checker.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057
  1. #include "entity.cpp"
  2. #include "types.cpp"
  3. void check_expr(Checker *c, Operand *operand, AstNode *expression);
  4. bool is_operand_value(Operand o) {
  5. switch (o.mode) {
  6. case Addressing_Value:
  7. case Addressing_Variable:
  8. case Addressing_Immutable:
  9. case Addressing_Constant:
  10. case Addressing_MapIndex:
  11. return true;
  12. }
  13. return false;
  14. }
  15. bool is_operand_nil(Operand o) {
  16. return o.mode == Addressing_Value && o.type == t_untyped_nil;
  17. }
  18. bool is_operand_undef(Operand o) {
  19. return o.mode == Addressing_Value && o.type == t_untyped_undef;
  20. }
  21. gb_global Scope *universal_scope = nullptr;
  22. void scope_reset(Scope *scope) {
  23. if (scope == nullptr) return;
  24. scope->first_child = nullptr;
  25. scope->last_child = nullptr;
  26. map_clear (&scope->elements);
  27. ptr_set_clear(&scope->implicit);
  28. ptr_set_clear(&scope->imported);
  29. ptr_set_clear(&scope->exported);
  30. }
  31. i32 is_scope_an_ancestor(Scope *parent, Scope *child) {
  32. i32 i = 0;
  33. while (child != nullptr) {
  34. if (parent == child) {
  35. return i;
  36. }
  37. child = child->parent;
  38. i++;
  39. }
  40. return -1;
  41. }
  42. void entity_graph_node_set_destroy(EntityGraphNodeSet *s) {
  43. if (s->hashes.data != nullptr) {
  44. ptr_set_destroy(s);
  45. }
  46. }
  47. void entity_graph_node_set_add(EntityGraphNodeSet *s, EntityGraphNode *n) {
  48. if (s->hashes.data == nullptr) {
  49. ptr_set_init(s, heap_allocator());
  50. }
  51. ptr_set_add(s, n);
  52. }
  53. bool entity_graph_node_set_exists(EntityGraphNodeSet *s, EntityGraphNode *n) {
  54. return ptr_set_exists(s, n);
  55. }
  56. void entity_graph_node_set_remove(EntityGraphNodeSet *s, EntityGraphNode *n) {
  57. ptr_set_remove(s, n);
  58. }
  59. void entity_graph_node_destroy(EntityGraphNode *n, gbAllocator a) {
  60. entity_graph_node_set_destroy(&n->pred);
  61. entity_graph_node_set_destroy(&n->succ);
  62. gb_free(a, n);
  63. }
  64. int entity_graph_node_cmp(EntityGraphNode **data, isize i, isize j) {
  65. EntityGraphNode *x = data[i];
  66. EntityGraphNode *y = data[j];
  67. isize a = x->entity->order_in_src;
  68. isize b = y->entity->order_in_src;
  69. if (x->dep_count < y->dep_count) return -1;
  70. if (x->dep_count > y->dep_count) return +1;
  71. return a < b ? -1 : b > a;
  72. }
  73. void entity_graph_node_swap(EntityGraphNode **data, isize i, isize j) {
  74. EntityGraphNode *x = data[i];
  75. EntityGraphNode *y = data[j];
  76. data[i] = y;
  77. data[j] = x;
  78. x->index = j;
  79. y->index = i;
  80. }
  81. void import_graph_node_set_destroy(ImportGraphNodeSet *s) {
  82. if (s->hashes.data != nullptr) {
  83. ptr_set_destroy(s);
  84. }
  85. }
  86. void import_graph_node_set_add(ImportGraphNodeSet *s, ImportGraphNode *n) {
  87. if (s->hashes.data == nullptr) {
  88. ptr_set_init(s, heap_allocator());
  89. }
  90. ptr_set_add(s, n);
  91. }
  92. bool import_graph_node_set_exists(ImportGraphNodeSet *s, ImportGraphNode *n) {
  93. return ptr_set_exists(s, n);
  94. }
  95. void import_graph_node_set_remove(ImportGraphNodeSet *s, ImportGraphNode *n) {
  96. ptr_set_remove(s, n);
  97. }
  98. ImportGraphNode *import_graph_node_create(gbAllocator a, Scope *scope) {
  99. ImportGraphNode *n = gb_alloc_item(a, ImportGraphNode);
  100. n->scope = scope;
  101. n->path = scope->package->fullpath;
  102. n->package_id = scope->package->id;
  103. return n;
  104. }
  105. void import_graph_node_destroy(ImportGraphNode *n, gbAllocator a) {
  106. import_graph_node_set_destroy(&n->pred);
  107. import_graph_node_set_destroy(&n->succ);
  108. gb_free(a, n);
  109. }
  110. int import_graph_node_cmp(ImportGraphNode **data, isize i, isize j) {
  111. ImportGraphNode *x = data[i];
  112. ImportGraphNode *y = data[j];
  113. GB_ASSERT(x != y);
  114. GB_ASSERT(x->scope != y->scope);
  115. bool xg = x->scope->is_global;
  116. bool yg = y->scope->is_global;
  117. if (xg != yg) return xg ? -1 : +1;
  118. if (xg && yg) return x->package_id < y->package_id ? +1 : -1;
  119. if (x->dep_count < y->dep_count) return -1;
  120. if (x->dep_count > y->dep_count) return +1;
  121. return 0;
  122. }
  123. void import_graph_node_swap(ImportGraphNode **data, isize i, isize j) {
  124. ImportGraphNode *x = data[i];
  125. ImportGraphNode *y = data[j];
  126. data[i] = y;
  127. data[j] = x;
  128. x->index = j;
  129. y->index = i;
  130. }
  131. GB_COMPARE_PROC(ast_node_cmp) {
  132. AstNode *x = *cast(AstNode **)a;
  133. AstNode *y = *cast(AstNode **)b;
  134. Token i = ast_node_token(x);
  135. Token j = ast_node_token(y);
  136. return token_pos_cmp(i.pos, j.pos);
  137. }
  138. void init_decl_info(DeclInfo *d, Scope *scope, DeclInfo *parent) {
  139. d->parent = parent;
  140. d->scope = scope;
  141. ptr_set_init(&d->deps, heap_allocator());
  142. ptr_set_init(&d->type_info_deps, heap_allocator());
  143. array_init (&d->labels, heap_allocator());
  144. }
  145. DeclInfo *make_decl_info(gbAllocator a, Scope *scope, DeclInfo *parent) {
  146. DeclInfo *d = gb_alloc_item(a, DeclInfo);
  147. init_decl_info(d, scope, parent);
  148. return d;
  149. }
  150. void destroy_declaration_info(DeclInfo *d) {
  151. ptr_set_destroy(&d->deps);
  152. array_free(&d->labels);
  153. }
  154. bool decl_info_has_init(DeclInfo *d) {
  155. if (d->init_expr != nullptr) {
  156. return true;
  157. }
  158. if (d->proc_lit != nullptr) {
  159. switch (d->proc_lit->kind) {
  160. case_ast_node(pl, ProcLit, d->proc_lit);
  161. if (pl->body != nullptr) {
  162. return true;
  163. }
  164. case_end;
  165. }
  166. }
  167. return false;
  168. }
  169. Scope *create_scope(Scope *parent, gbAllocator allocator) {
  170. Scope *s = gb_alloc_item(allocator, Scope);
  171. s->parent = parent;
  172. map_init(&s->elements, heap_allocator());
  173. ptr_set_init(&s->implicit, heap_allocator());
  174. ptr_set_init(&s->imported, heap_allocator());
  175. ptr_set_init(&s->exported, heap_allocator());
  176. s->delayed_imports.allocator = heap_allocator();
  177. s->delayed_asserts.allocator = heap_allocator();
  178. if (parent != nullptr && parent != universal_scope) {
  179. DLIST_APPEND(parent->first_child, parent->last_child, s);
  180. }
  181. return s;
  182. }
  183. Scope *create_scope_from_file(Checker *c, AstFile *f) {
  184. GB_ASSERT(f != nullptr);
  185. GB_ASSERT(f->package != nullptr);
  186. GB_ASSERT(f->package->scope != nullptr);
  187. Scope *s = create_scope(f->package->scope, c->allocator);
  188. s->is_file = true;
  189. s->file = f;
  190. f->scope = s;
  191. return s;
  192. }
  193. Scope *create_scope_from_package(Checker *c, AstPackage *p) {
  194. GB_ASSERT(p != nullptr);
  195. Scope *s = create_scope(universal_scope, c->allocator);
  196. s->is_package = true;
  197. s->package = p;
  198. p->scope = s;
  199. if (p->fullpath == c->parser->init_fullpath) {
  200. s->is_init = true;
  201. } else {
  202. s->is_init = p->kind == Package_Init;
  203. }
  204. if (p->kind == Package_Builtin) {
  205. s->is_global = true;
  206. universal_scope->shared = s;
  207. }
  208. if (s->is_init || s->is_global) {
  209. s->has_been_imported = true;
  210. }
  211. return s;
  212. }
  213. void destroy_scope(Scope *scope) {
  214. for_array(i, scope->elements.entries) {
  215. Entity *e =scope->elements.entries[i].value;
  216. if (e->kind == Entity_Variable) {
  217. if (!(e->flags & EntityFlag_Used)) {
  218. #if 0
  219. warning(e->token, "Unused variable '%.*s'", LIT(e->token.string));
  220. #endif
  221. }
  222. }
  223. }
  224. for (Scope *child = scope->first_child; child != nullptr; child = child->next) {
  225. destroy_scope(child);
  226. }
  227. map_destroy(&scope->elements);
  228. array_free(&scope->delayed_imports);
  229. array_free(&scope->delayed_asserts);
  230. ptr_set_destroy(&scope->implicit);
  231. ptr_set_destroy(&scope->imported);
  232. ptr_set_destroy(&scope->exported);
  233. // NOTE(bill): No need to free scope as it "should" be allocated in an arena (except for the global scope)
  234. }
  235. void add_scope(Checker *c, AstNode *node, Scope *scope) {
  236. GB_ASSERT(node != nullptr);
  237. GB_ASSERT(scope != nullptr);
  238. scope->node = node;
  239. node->scope = scope;
  240. }
  241. void check_open_scope(Checker *c, AstNode *node) {
  242. node = unparen_expr(node);
  243. GB_ASSERT(node->kind == AstNode_Invalid ||
  244. is_ast_node_stmt(node) ||
  245. is_ast_node_type(node));
  246. Scope *scope = create_scope(c->context.scope, c->allocator);
  247. add_scope(c, node, scope);
  248. switch (node->kind) {
  249. case AstNode_ProcType:
  250. scope->is_proc = true;
  251. break;
  252. case AstNode_StructType:
  253. case AstNode_EnumType:
  254. case AstNode_UnionType:
  255. scope->is_struct = true;
  256. break;
  257. }
  258. c->context.scope = scope;
  259. c->context.stmt_state_flags |= StmtStateFlag_bounds_check;
  260. }
  261. void check_close_scope(Checker *c) {
  262. c->context.scope = c->context.scope->parent;
  263. }
  264. Entity *current_scope_lookup_entity(Scope *s, String name) {
  265. HashKey key = hash_string(name);
  266. Entity **found = map_get(&s->elements, key);
  267. if (found) {
  268. return *found;
  269. }
  270. return nullptr;
  271. }
  272. void scope_lookup_parent_entity(Scope *scope, String name, Scope **scope_, Entity **entity_) {
  273. bool gone_thru_proc = false;
  274. bool gone_thru_package = false;
  275. HashKey key = hash_string(name);
  276. for (Scope *s = scope; s != nullptr; s = s->parent) {
  277. Entity **found = map_get(&s->elements, key);
  278. if (found) {
  279. Entity *e = *found;
  280. if (gone_thru_proc) {
  281. // IMPORTANT TODO(bill): Is this correct?!
  282. if (e->kind == Entity_Label) {
  283. continue;
  284. }
  285. if (e->kind == Entity_Variable &&
  286. !e->scope->is_file) {
  287. continue;
  288. }
  289. }
  290. if (entity_) *entity_ = e;
  291. if (scope_) *scope_ = s;
  292. return;
  293. }
  294. if (s->is_proc) {
  295. gone_thru_proc = true;
  296. } else if (s->shared) {
  297. Entity **found = map_get(&s->shared->elements, key);
  298. if (found) {
  299. Entity *e = *found;
  300. if (e->kind == Entity_Variable &&
  301. !e->scope->is_file) {
  302. continue;
  303. }
  304. if (e->scope->parent != s->shared) {
  305. continue;
  306. }
  307. if ((e->kind == Entity_ImportName ||
  308. e->kind == Entity_LibraryName)
  309. && gone_thru_package) {
  310. continue;
  311. }
  312. if (entity_) *entity_ = e;
  313. if (scope_) *scope_ = s->shared;
  314. return;
  315. }
  316. }
  317. if (s->is_package) {
  318. gone_thru_package = true;
  319. }
  320. }
  321. if (entity_) *entity_ = nullptr;
  322. if (scope_) *scope_ = nullptr;
  323. }
  324. Entity *scope_lookup_entity(Scope *s, String name) {
  325. Entity *entity = nullptr;
  326. scope_lookup_parent_entity(s, name, nullptr, &entity);
  327. return entity;
  328. }
  329. Entity *scope_insert_entity(Scope *s, Entity *entity) {
  330. String name = entity->token.string;
  331. if (name == "") {
  332. return nullptr;
  333. }
  334. HashKey key = hash_string(name);
  335. Entity **found = map_get(&s->elements, key);
  336. if (found) {
  337. return *found;
  338. }
  339. map_set(&s->elements, key, entity);
  340. if (entity->scope == nullptr) {
  341. entity->scope = s;
  342. }
  343. return nullptr;
  344. }
  345. GB_COMPARE_PROC(entity_variable_pos_cmp) {
  346. Entity *x = *cast(Entity **)a;
  347. Entity *y = *cast(Entity **)b;
  348. return token_pos_cmp(x->token.pos, y->token.pos);
  349. }
  350. void check_scope_usage(Checker *c, Scope *scope) {
  351. // TODO(bill): Use this?
  352. #if 0
  353. Array<Entity *> unused = {};
  354. array_init(&unused, heap_allocator());
  355. defer (array_free(&unused));
  356. for_array(i, scope->elements.entries) {
  357. Entity *e = scope->elements.entries[i].value;
  358. if (e != nullptr && e->kind == Entity_Variable && (e->flags&EntityFlag_Used) == 0) {
  359. array_add(&unused, e);
  360. }
  361. }
  362. gb_sort_array(unused.data, unused.count, entity_variable_pos_cmp);
  363. for_array(i, unused) {
  364. Entity *e = unused[i];
  365. error(e->token, "'%.*s' declared but not used", LIT(e->token.string));
  366. }
  367. for (Scope *child = scope->first_child;
  368. child != nullptr;
  369. child = child->next) {
  370. if (!child->is_proc && !child->is_struct && !child->is_file) {
  371. check_scope_usage(c, child);
  372. }
  373. }
  374. #endif
  375. }
  376. void add_dependency(DeclInfo *d, Entity *e) {
  377. ptr_set_add(&d->deps, e);
  378. }
  379. void add_type_info_dependency(DeclInfo *d, Type *type) {
  380. if (d == nullptr) {
  381. GB_ASSERT(type == t_invalid);
  382. return;
  383. }
  384. ptr_set_add(&d->type_info_deps, type);
  385. }
  386. void add_preload_dependency(Checker *c, char *name) {
  387. String n = make_string_c(name);
  388. Entity *e = scope_lookup_entity(c->builtin_package->scope, n);
  389. GB_ASSERT(e != nullptr);
  390. ptr_set_add(&c->context.decl->deps, e);
  391. // add_type_info_type(c, e->type);
  392. }
  393. void add_declaration_dependency(Checker *c, Entity *e) {
  394. if (e == nullptr) {
  395. return;
  396. }
  397. if (c->context.decl != nullptr) {
  398. // DeclInfo *decl = decl_info_of_entity(&c->info, e);
  399. add_dependency(c->context.decl, e);
  400. }
  401. }
  402. Entity *add_global_entity(Entity *entity) {
  403. String name = entity->token.string;
  404. if (gb_memchr(name.text, ' ', name.len)) {
  405. return entity; // NOTE(bill): 'untyped thing'
  406. }
  407. if (scope_insert_entity(universal_scope, entity)) {
  408. compiler_error("double declaration");
  409. }
  410. entity->state = EntityState_Resolved;
  411. return entity;
  412. }
  413. void add_global_constant(String name, Type *type, ExactValue value) {
  414. Entity *entity = alloc_entity(Entity_Constant, nullptr, make_token_ident(name), type);
  415. entity->Constant.value = value;
  416. add_global_entity(entity);
  417. }
  418. void add_global_string_constant(String name, String value) {
  419. add_global_constant(name, t_untyped_string, exact_value_string(value));
  420. }
  421. void add_global_type_entity(String name, Type *type) {
  422. add_global_entity(alloc_entity_type_name(nullptr, make_token_ident(name), type));
  423. }
  424. void init_universal_scope(void) {
  425. BuildContext *bc = &build_context;
  426. // NOTE(bill): No need to free these
  427. gbAllocator a = heap_allocator();
  428. universal_scope = create_scope(nullptr, a);
  429. universal_scope->is_package = true;
  430. // Types
  431. for (isize i = 0; i < gb_count_of(basic_types); i++) {
  432. add_global_type_entity(basic_types[i].Basic.name, &basic_types[i]);
  433. }
  434. add_global_type_entity(str_lit("byte"), &basic_types[Basic_u8]);
  435. // Constants
  436. add_global_constant(str_lit("true"), t_untyped_bool, exact_value_bool(true));
  437. add_global_constant(str_lit("false"), t_untyped_bool, exact_value_bool(false));
  438. add_global_entity(alloc_entity_nil(str_lit("nil"), t_untyped_nil));
  439. add_global_entity(alloc_entity_library_name(universal_scope,
  440. make_token_ident(str_lit("__llvm_core")), t_invalid,
  441. str_lit(""), str_lit("__llvm_core")));
  442. // TODO(bill): Set through flags in the compiler
  443. // add_global_string_constant(str_lit("ODIN_OS"), bc->ODIN_OS);
  444. // add_global_string_constant(str_lit("ODIN_ARCH"), bc->ODIN_ARCH);
  445. // add_global_string_constant(str_lit("ODIN_ENDIAN"), bc->ODIN_ENDIAN);
  446. add_global_string_constant(str_lit("ODIN_VENDOR"), bc->ODIN_VENDOR);
  447. add_global_string_constant(str_lit("ODIN_VERSION"), bc->ODIN_VERSION);
  448. add_global_string_constant(str_lit("ODIN_ROOT"), bc->ODIN_ROOT);
  449. add_global_constant(str_lit("ODIN_DEBUG"), t_untyped_bool, exact_value_bool(bc->ODIN_DEBUG));
  450. // Builtin Procedures
  451. for (isize i = 0; i < gb_count_of(builtin_procs); i++) {
  452. BuiltinProcId id = cast(BuiltinProcId)i;
  453. String name = builtin_procs[i].name;
  454. if (name != "") {
  455. Entity *entity = alloc_entity(Entity_Builtin, nullptr, make_token_ident(name), t_invalid);
  456. entity->Builtin.id = id;
  457. add_global_entity(entity);
  458. }
  459. }
  460. t_u8_ptr = alloc_type_pointer(t_u8);
  461. t_int_ptr = alloc_type_pointer(t_int);
  462. t_i64_ptr = alloc_type_pointer(t_i64);
  463. t_f64_ptr = alloc_type_pointer(t_f64);
  464. t_u8_slice = alloc_type_slice(t_u8);
  465. t_string_slice = alloc_type_slice(t_string);
  466. }
  467. void init_checker_info(CheckerInfo *i) {
  468. gbAllocator a = heap_allocator();
  469. map_init(&i->types, a);
  470. array_init(&i->definitions, a);
  471. array_init(&i->entities, a);
  472. map_init(&i->untyped, a);
  473. map_init(&i->foreigns, a);
  474. map_init(&i->gen_procs, a);
  475. map_init(&i->gen_types, a);
  476. array_init(&i->type_info_types, a);
  477. map_init(&i->type_info_map, a);
  478. map_init(&i->files, a);
  479. map_init(&i->packages, a);
  480. array_init(&i->variable_init_order, a);
  481. }
  482. void destroy_checker_info(CheckerInfo *i) {
  483. map_destroy(&i->types);
  484. array_free(&i->definitions);
  485. array_free(&i->entities);
  486. map_destroy(&i->untyped);
  487. map_destroy(&i->foreigns);
  488. map_destroy(&i->gen_procs);
  489. map_destroy(&i->gen_types);
  490. array_free(&i->type_info_types);
  491. map_destroy(&i->type_info_map);
  492. map_destroy(&i->files);
  493. map_destroy(&i->packages);
  494. array_free(&i->variable_init_order);
  495. }
  496. void init_checker(Checker *c, Parser *parser) {
  497. if (global_error_collector.count > 0) {
  498. gb_exit(1);
  499. }
  500. gbAllocator a = heap_allocator();
  501. c->parser = parser;
  502. init_checker_info(&c->info);
  503. gb_mutex_init(&c->mutex);
  504. array_init(&c->proc_stack, a);
  505. array_init(&c->procs, a);
  506. // NOTE(bill): Is this big enough or too small?
  507. isize item_size = gb_max3(gb_size_of(Entity), gb_size_of(Type), gb_size_of(Scope));
  508. isize total_token_count = c->parser->total_token_count;
  509. isize arena_size = 2 * item_size * total_token_count;
  510. gb_arena_init_from_allocator(&c->tmp_arena, a, arena_size);
  511. gb_arena_init_from_allocator(&c->arena, a, arena_size);
  512. // c->allocator = pool_allocator(&c->pool);
  513. c->allocator = heap_allocator();
  514. // c->allocator = gb_arena_allocator(&c->arena);
  515. c->tmp_allocator = gb_arena_allocator(&c->tmp_arena);
  516. map_init(&c->package_scopes, heap_allocator());
  517. array_init(&c->package_order, heap_allocator(), 0, c->parser->packages.count);
  518. // Init context
  519. c->context.scope = universal_scope;
  520. c->context.type_path = new_checker_type_path();
  521. c->context.type_level = 0;
  522. }
  523. void destroy_checker(Checker *c) {
  524. destroy_checker_info(&c->info);
  525. gb_mutex_destroy(&c->mutex);
  526. array_free(&c->proc_stack);
  527. array_free(&c->procs);
  528. gb_arena_free(&c->tmp_arena);
  529. map_destroy(&c->package_scopes);
  530. array_free(&c->package_order);
  531. destroy_checker_type_path(c->context.type_path);
  532. }
  533. Entity *entity_of_ident(CheckerInfo *i, AstNode *identifier) {
  534. if (identifier->kind == AstNode_Ident) {
  535. return identifier->Ident.entity;
  536. }
  537. return nullptr;
  538. }
  539. TypeAndValue type_and_value_of_expr(CheckerInfo *i, AstNode *expr) {
  540. TypeAndValue result = {};
  541. TypeAndValue *found = map_get(&i->types, hash_node(expr));
  542. if (found) result = *found;
  543. return result;
  544. }
  545. Type *type_of_expr(CheckerInfo *i, AstNode *expr) {
  546. TypeAndValue tav = type_and_value_of_expr(i, expr);
  547. if (tav.mode != Addressing_Invalid) {
  548. return tav.type;
  549. }
  550. if (expr->kind == AstNode_Ident) {
  551. Entity *entity = entity_of_ident(i, expr);
  552. if (entity) {
  553. return entity->type;
  554. }
  555. }
  556. return nullptr;
  557. }
  558. Entity *implicit_entity_of_node(CheckerInfo *i, AstNode *clause) {
  559. // Entity **found = map_get(&i->implicits, hash_node(clause));
  560. // if (found != nullptr) {
  561. // return *found;
  562. // }
  563. if (clause->kind == AstNode_CaseClause) {
  564. return clause->CaseClause.implicit_entity;
  565. }
  566. return nullptr;
  567. }
  568. bool is_entity_implicitly_imported(Entity *import_name, Entity *e) {
  569. GB_ASSERT(import_name->kind == Entity_ImportName);
  570. return ptr_set_exists(&import_name->ImportName.scope->implicit, e);
  571. }
  572. // Will return nullptr if not found
  573. Entity *entity_of_node(CheckerInfo *i, AstNode *expr) {
  574. expr = unparen_expr(expr);
  575. switch (expr->kind) {
  576. case_ast_node(ident, Ident, expr);
  577. return entity_of_ident(i, expr);
  578. case_end;
  579. case_ast_node(se, SelectorExpr, expr);
  580. AstNode *s = unselector_expr(se->selector);
  581. if (s->kind == AstNode_Ident) {
  582. return entity_of_ident(i, s);
  583. }
  584. case_end;
  585. case_ast_node(cc, CaseClause, expr);
  586. return cc->implicit_entity;
  587. case_end;
  588. }
  589. return nullptr;
  590. }
  591. DeclInfo *decl_info_of_entity(CheckerInfo *i, Entity *e) {
  592. if (e != nullptr) {
  593. return e->decl_info;
  594. }
  595. return nullptr;
  596. }
  597. DeclInfo *decl_info_of_ident(CheckerInfo *i, AstNode *ident) {
  598. return decl_info_of_entity(i, entity_of_ident(i, ident));
  599. }
  600. AstFile *ast_file_of_filename(CheckerInfo *i, String filename) {
  601. AstFile **found = map_get(&i->files, hash_string(filename));
  602. if (found != nullptr) {
  603. return *found;
  604. }
  605. return nullptr;
  606. }
  607. Scope *scope_of_node(CheckerInfo *i, AstNode *node) {
  608. return node->scope;
  609. }
  610. ExprInfo *check_get_expr_info(CheckerInfo *i, AstNode *expr) {
  611. return map_get(&i->untyped, hash_node(expr));
  612. }
  613. void check_set_expr_info(CheckerInfo *i, AstNode *expr, ExprInfo info) {
  614. map_set(&i->untyped, hash_node(expr), info);
  615. }
  616. void check_remove_expr_info(CheckerInfo *i, AstNode *expr) {
  617. map_remove(&i->untyped, hash_node(expr));
  618. }
  619. isize type_info_index(CheckerInfo *info, Type *type, bool error_on_failure) {
  620. type = default_type(type);
  621. if (type == t_llvm_bool) {
  622. type = t_bool;
  623. }
  624. isize entry_index = -1;
  625. HashKey key = hash_type(type);
  626. isize *found_entry_index = map_get(&info->type_info_map, key);
  627. if (found_entry_index) {
  628. entry_index = *found_entry_index;
  629. }
  630. if (entry_index < 0) {
  631. // NOTE(bill): Do manual search
  632. // TODO(bill): This is O(n) and can be very slow
  633. for_array(i, info->type_info_map.entries){
  634. auto *e = &info->type_info_map.entries[i];
  635. Type *prev_type = cast(Type *)e->key.ptr;
  636. if (are_types_identical(prev_type, type)) {
  637. entry_index = e->value;
  638. // NOTE(bill): Add it to the search map
  639. map_set(&info->type_info_map, key, entry_index);
  640. break;
  641. }
  642. }
  643. }
  644. if (error_on_failure && entry_index < 0) {
  645. compiler_error("TypeInfo for '%s' could not be found", type_to_string(type));
  646. }
  647. return entry_index;
  648. }
  649. void add_untyped(CheckerInfo *i, AstNode *expression, bool lhs, AddressingMode mode, Type *type, ExactValue value) {
  650. if (expression == nullptr) {
  651. return;
  652. }
  653. if (mode == Addressing_Invalid) {
  654. return;
  655. }
  656. if (mode == Addressing_Constant && type == t_invalid) {
  657. compiler_error("add_untyped - invalid type: %s", type_to_string(type));
  658. }
  659. map_set(&i->untyped, hash_node(expression), make_expr_info(mode, type, value, lhs));
  660. }
  661. void add_type_and_value(CheckerInfo *i, AstNode *expression, AddressingMode mode, Type *type, ExactValue value) {
  662. if (expression == nullptr) {
  663. return;
  664. }
  665. if (mode == Addressing_Invalid) {
  666. return;
  667. }
  668. if (mode == Addressing_Constant && type == t_invalid) {
  669. compiler_error("add_type_and_value - invalid type: %s", type_to_string(type));
  670. }
  671. TypeAndValue tv = {};
  672. tv.type = type;
  673. tv.value = value;
  674. tv.mode = mode;
  675. map_set(&i->types, hash_node(expression), tv);
  676. }
  677. void add_entity_definition(CheckerInfo *i, AstNode *identifier, Entity *entity) {
  678. GB_ASSERT(identifier != nullptr);
  679. GB_ASSERT(identifier->kind == AstNode_Ident);
  680. if (is_blank_ident(identifier)) {
  681. return;
  682. }
  683. if (identifier->Ident.entity != nullptr) {
  684. // NOTE(bill): Identifier has already been handled
  685. return;
  686. }
  687. GB_ASSERT(entity != nullptr);
  688. identifier->Ident.entity = entity;
  689. entity->identifier = identifier;
  690. array_add(&i->definitions, entity);
  691. }
  692. bool add_entity(Checker *c, Scope *scope, AstNode *identifier, Entity *entity) {
  693. if (scope == nullptr) {
  694. return false;
  695. }
  696. String name = entity->token.string;
  697. if (!is_blank_ident(name)) {
  698. Entity *ie = scope_insert_entity(scope, entity);
  699. if (ie != nullptr) {
  700. TokenPos pos = ie->token.pos;
  701. Entity *up = ie->using_parent;
  702. if (up != nullptr) {
  703. if (pos == up->token.pos) {
  704. // NOTE(bill): Error should have been handled already
  705. return false;
  706. }
  707. error(entity->token,
  708. "Redeclaration of '%.*s' in this scope through 'using'\n"
  709. "\tat %.*s(%td:%td)",
  710. LIT(name),
  711. LIT(up->token.pos.file), up->token.pos.line, up->token.pos.column);
  712. return false;
  713. } else {
  714. if (pos == entity->token.pos) {
  715. // NOTE(bill): Error should have been handled already
  716. return false;
  717. }
  718. error(entity->token,
  719. "Redeclaration of '%.*s' in this scope\n"
  720. "\tat %.*s(%td:%td)",
  721. LIT(name),
  722. LIT(pos.file), pos.line, pos.column);
  723. return false;
  724. }
  725. }
  726. }
  727. if (identifier != nullptr) {
  728. add_entity_definition(&c->info, identifier, entity);
  729. }
  730. return true;
  731. }
  732. void add_entity_use(Checker *c, AstNode *identifier, Entity *entity) {
  733. GB_ASSERT(identifier != nullptr);
  734. if (identifier->kind != AstNode_Ident) {
  735. return;
  736. }
  737. if (entity == nullptr) {
  738. return;
  739. }
  740. if (entity->identifier == nullptr) {
  741. entity->identifier = identifier;
  742. }
  743. identifier->Ident.entity = entity;
  744. add_declaration_dependency(c, entity); // TODO(bill): Should this be here?
  745. String dmsg = entity->deprecated_message;
  746. if (dmsg.len > 0) {
  747. warning(identifier, "%.*s is deprecated: %.*s", LIT(entity->token.string), LIT(dmsg));
  748. }
  749. }
  750. void add_entity_and_decl_info(Checker *c, AstNode *identifier, Entity *e, DeclInfo *d) {
  751. GB_ASSERT(identifier->kind == AstNode_Ident);
  752. GB_ASSERT(e != nullptr && d != nullptr);
  753. GB_ASSERT(identifier->Ident.token.string == e->token.string);
  754. if (e->scope != nullptr) {
  755. Scope *scope = e->scope;
  756. if (scope->is_file) {
  757. switch (e->kind) {
  758. case Entity_ImportName:
  759. case Entity_LibraryName:
  760. // NOTE(bill): Entities local to file rather than package
  761. break;
  762. default: {
  763. AstPackage *p = scope->file->package;
  764. GB_ASSERT(p->scope == scope->parent);
  765. scope = p->scope;
  766. if (e->package != nullptr) {
  767. GB_ASSERT(e->package == p);
  768. }
  769. e->package = p;
  770. break;
  771. }
  772. }
  773. }
  774. add_entity(c, scope, identifier, e);
  775. }
  776. add_entity_definition(&c->info, identifier, e);
  777. GB_ASSERT(e->decl_info == nullptr);
  778. e->decl_info = d;
  779. array_add(&c->info.entities, e);
  780. e->order_in_src = c->info.entities.count;
  781. }
  782. void add_implicit_entity(Checker *c, AstNode *clause, Entity *e) {
  783. GB_ASSERT(clause != nullptr);
  784. GB_ASSERT(e != nullptr);
  785. GB_ASSERT(clause->kind == AstNode_CaseClause);
  786. clause->CaseClause.implicit_entity = e;
  787. }
  788. void add_type_info_type(Checker *c, Type *t) {
  789. if (t == nullptr) {
  790. return;
  791. }
  792. t = default_type(t);
  793. if (is_type_bit_field_value(t)) {
  794. t = default_bit_field_value_type(t);
  795. }
  796. if (is_type_untyped(t)) {
  797. return; // Could be nil
  798. }
  799. if (is_type_polymorphic(base_type(t))) {
  800. return;
  801. }
  802. auto found = map_get(&c->info.type_info_map, hash_type(t));
  803. if (found != nullptr) {
  804. // Types have already been added
  805. add_type_info_dependency(c->context.decl, t);
  806. return;
  807. }
  808. bool prev = false;
  809. isize ti_index = -1;
  810. for_array(i, c->info.type_info_map.entries) {
  811. auto *e = &c->info.type_info_map.entries[i];
  812. Type *prev_type = cast(Type *)e->key.ptr;
  813. if (are_types_identical(t, prev_type)) {
  814. // Duplicate entry
  815. ti_index = e->value;
  816. prev = true;
  817. break;
  818. }
  819. }
  820. if (ti_index < 0) {
  821. // Unique entry
  822. // NOTE(bill): map entries grow linearly and in order
  823. ti_index = c->info.type_info_types.count;
  824. array_add(&c->info.type_info_types, t);
  825. }
  826. map_set(&c->info.type_info_map, hash_type(t), ti_index);
  827. if (prev) {
  828. // NOTE(bill): If a previous one exists already, no need to continue
  829. add_type_info_dependency(c->context.decl, t);
  830. return;
  831. }
  832. // Add nested types
  833. if (t->kind == Type_Named) {
  834. // NOTE(bill): Just in case
  835. add_type_info_type(c, t->Named.base);
  836. return;
  837. }
  838. Type *bt = base_type(t);
  839. add_type_info_type(c, bt);
  840. switch (bt->kind) {
  841. case Type_Basic:
  842. switch (bt->Basic.kind) {
  843. case Basic_string:
  844. add_type_info_type(c, t_u8_ptr);
  845. add_type_info_type(c, t_int);
  846. break;
  847. case Basic_any:
  848. add_type_info_type(c, t_type_info_ptr);
  849. add_type_info_type(c, t_rawptr);
  850. break;
  851. case Basic_typeid:
  852. break;
  853. case Basic_complex64:
  854. add_type_info_type(c, t_type_info_float);
  855. add_type_info_type(c, t_f32);
  856. break;
  857. case Basic_complex128:
  858. add_type_info_type(c, t_type_info_float);
  859. add_type_info_type(c, t_f64);
  860. break;
  861. }
  862. break;
  863. case Type_Pointer:
  864. add_type_info_type(c, bt->Pointer.elem);
  865. break;
  866. case Type_Array:
  867. add_type_info_type(c, bt->Array.elem);
  868. add_type_info_type(c, alloc_type_pointer(bt->Array.elem));
  869. add_type_info_type(c, t_int);
  870. break;
  871. case Type_DynamicArray:
  872. add_type_info_type(c, bt->DynamicArray.elem);
  873. add_type_info_type(c, alloc_type_pointer(bt->DynamicArray.elem));
  874. add_type_info_type(c, t_int);
  875. add_type_info_type(c, t_allocator);
  876. break;
  877. case Type_Slice:
  878. add_type_info_type(c, bt->Slice.elem);
  879. add_type_info_type(c, alloc_type_pointer(bt->Slice.elem));
  880. add_type_info_type(c, t_int);
  881. break;
  882. case Type_Enum:
  883. add_type_info_type(c, bt->Enum.base_type);
  884. break;
  885. case Type_Union:
  886. add_type_info_type(c, t_int);
  887. add_type_info_type(c, t_type_info_ptr);
  888. for_array(i, bt->Union.variants) {
  889. add_type_info_type(c, bt->Union.variants[i]);
  890. }
  891. break;
  892. case Type_Struct:
  893. if (bt->Struct.scope != nullptr) {
  894. for_array(i, bt->Struct.scope->elements.entries) {
  895. Entity *e = bt->Struct.scope->elements.entries[i].value;
  896. add_type_info_type(c, e->type);
  897. }
  898. }
  899. for_array(i, bt->Struct.fields) {
  900. Entity *f = bt->Struct.fields[i];
  901. add_type_info_type(c, f->type);
  902. }
  903. break;
  904. case Type_Map:
  905. init_map_internal_types(bt);
  906. add_type_info_type(c, bt->Map.key);
  907. add_type_info_type(c, bt->Map.value);
  908. add_type_info_type(c, bt->Map.generated_struct_type);
  909. break;
  910. case Type_Tuple:
  911. for_array(i, bt->Tuple.variables) {
  912. Entity *var = bt->Tuple.variables[i];
  913. add_type_info_type(c, var->type);
  914. }
  915. break;
  916. case Type_Proc:
  917. add_type_info_type(c, bt->Proc.params);
  918. add_type_info_type(c, bt->Proc.results);
  919. break;
  920. }
  921. }
  922. void check_procedure_later(Checker *c, ProcedureInfo info) {
  923. GB_ASSERT(info.decl != nullptr);
  924. array_add(&c->procs, info);
  925. }
  926. void check_procedure_later(Checker *c, AstFile *file, Token token, DeclInfo *decl, Type *type, AstNode *body, u64 tags) {
  927. ProcedureInfo info = {};
  928. info.file = file;
  929. info.token = token;
  930. info.decl = decl;
  931. info.type = type;
  932. info.body = body;
  933. info.tags = tags;
  934. check_procedure_later(c, info);
  935. }
  936. void push_procedure(Checker *c, Type *type) {
  937. array_add(&c->proc_stack, type);
  938. }
  939. void pop_procedure(Checker *c) {
  940. array_pop(&c->proc_stack);
  941. }
  942. Type *const curr_procedure_type(Checker *c) {
  943. isize count = c->proc_stack.count;
  944. if (count > 0) {
  945. return c->proc_stack[count-1];
  946. }
  947. return nullptr;
  948. }
  949. void add_curr_ast_file(Checker *c, AstFile *file) {
  950. if (file != nullptr) {
  951. TokenPos zero_pos = {};
  952. global_error_collector.prev = zero_pos;
  953. c->curr_ast_file = file;
  954. c->context.decl = file->package->decl_info;
  955. c->context.scope = file->scope;
  956. c->context.package_scope = file->package->scope;
  957. }
  958. }
  959. void add_min_dep_type_info(Checker *c, Type *t) {
  960. if (t == nullptr) {
  961. return;
  962. }
  963. t = default_type(t);
  964. if (is_type_bit_field_value(t)) {
  965. t = default_bit_field_value_type(t);
  966. }
  967. if (is_type_untyped(t)) {
  968. return; // Could be nil
  969. }
  970. if (is_type_polymorphic(base_type(t))) {
  971. return;
  972. }
  973. auto *set = &c->info.minimum_dependency_type_info_set;
  974. isize ti_index = type_info_index(&c->info, t);
  975. if (ptr_set_exists(set, ti_index)) {
  976. // Type Already exists
  977. return;
  978. }
  979. ptr_set_add(set, ti_index);
  980. // Add nested types
  981. if (t->kind == Type_Named) {
  982. // NOTE(bill): Just in case
  983. add_min_dep_type_info(c, t->Named.base);
  984. return;
  985. }
  986. Type *bt = base_type(t);
  987. add_min_dep_type_info(c, bt);
  988. switch (bt->kind) {
  989. case Type_Basic:
  990. switch (bt->Basic.kind) {
  991. case Basic_string:
  992. add_min_dep_type_info(c, t_u8_ptr);
  993. add_min_dep_type_info(c, t_int);
  994. break;
  995. case Basic_any:
  996. add_min_dep_type_info(c, t_type_info_ptr);
  997. add_min_dep_type_info(c, t_rawptr);
  998. break;
  999. case Basic_complex64:
  1000. add_min_dep_type_info(c, t_type_info_float);
  1001. add_min_dep_type_info(c, t_f32);
  1002. break;
  1003. case Basic_complex128:
  1004. add_min_dep_type_info(c, t_type_info_float);
  1005. add_min_dep_type_info(c, t_f64);
  1006. break;
  1007. }
  1008. break;
  1009. case Type_Pointer:
  1010. add_min_dep_type_info(c, bt->Pointer.elem);
  1011. break;
  1012. case Type_Array:
  1013. add_min_dep_type_info(c, bt->Array.elem);
  1014. add_min_dep_type_info(c, alloc_type_pointer(bt->Array.elem));
  1015. add_min_dep_type_info(c, t_int);
  1016. break;
  1017. case Type_DynamicArray:
  1018. add_min_dep_type_info(c, bt->DynamicArray.elem);
  1019. add_min_dep_type_info(c, alloc_type_pointer(bt->DynamicArray.elem));
  1020. add_min_dep_type_info(c, t_int);
  1021. add_min_dep_type_info(c, t_allocator);
  1022. break;
  1023. case Type_Slice:
  1024. add_min_dep_type_info(c, bt->Slice.elem);
  1025. add_min_dep_type_info(c, alloc_type_pointer(bt->Slice.elem));
  1026. add_min_dep_type_info(c, t_int);
  1027. break;
  1028. case Type_Enum:
  1029. add_min_dep_type_info(c, bt->Enum.base_type);
  1030. break;
  1031. case Type_Union:
  1032. add_min_dep_type_info(c, t_int);
  1033. add_min_dep_type_info(c, t_type_info_ptr);
  1034. for_array(i, bt->Union.variants) {
  1035. add_min_dep_type_info(c, bt->Union.variants[i]);
  1036. }
  1037. break;
  1038. case Type_Struct:
  1039. if (bt->Struct.scope != nullptr) {
  1040. for_array(i, bt->Struct.scope->elements.entries) {
  1041. Entity *e = bt->Struct.scope->elements.entries[i].value;
  1042. add_min_dep_type_info(c, e->type);
  1043. }
  1044. }
  1045. for_array(i, bt->Struct.fields) {
  1046. Entity *f = bt->Struct.fields[i];
  1047. add_min_dep_type_info(c, f->type);
  1048. }
  1049. break;
  1050. case Type_Map:
  1051. init_map_internal_types(bt);
  1052. add_min_dep_type_info(c, bt->Map.key);
  1053. add_min_dep_type_info(c, bt->Map.value);
  1054. add_min_dep_type_info(c, bt->Map.generated_struct_type);
  1055. break;
  1056. case Type_Tuple:
  1057. for_array(i, bt->Tuple.variables) {
  1058. Entity *var = bt->Tuple.variables[i];
  1059. add_min_dep_type_info(c, var->type);
  1060. }
  1061. break;
  1062. case Type_Proc:
  1063. add_min_dep_type_info(c, bt->Proc.params);
  1064. add_min_dep_type_info(c, bt->Proc.results);
  1065. break;
  1066. }
  1067. }
  1068. void add_dependency_to_set(Checker *c, Entity *entity) {
  1069. if (entity == nullptr) {
  1070. return;
  1071. }
  1072. CheckerInfo *info = &c->info;
  1073. auto *set = &info->minimum_dependency_set;
  1074. String name = entity->token.string;
  1075. if (entity->type != nullptr &&
  1076. is_type_polymorphic(entity->type)) {
  1077. DeclInfo *decl = decl_info_of_entity(&c->info, entity);
  1078. if (decl != nullptr && decl->gen_proc_type == nullptr) {
  1079. return;
  1080. }
  1081. }
  1082. if (ptr_set_exists(set, entity)) {
  1083. return;
  1084. }
  1085. ptr_set_add(set, entity);
  1086. DeclInfo *decl = decl_info_of_entity(info, entity);
  1087. if (decl == nullptr) {
  1088. return;
  1089. }
  1090. for_array(i, decl->type_info_deps.entries) {
  1091. Type *type = decl->type_info_deps.entries[i].ptr;
  1092. add_min_dep_type_info(c, type);
  1093. }
  1094. for_array(i, decl->deps.entries) {
  1095. Entity *e = decl->deps.entries[i].ptr;
  1096. add_dependency_to_set(c, e);
  1097. if (e->kind == Entity_Procedure && e->Procedure.is_foreign) {
  1098. Entity *fl = e->Procedure.foreign_library;
  1099. if (fl != nullptr) {
  1100. GB_ASSERT_MSG(fl->kind == Entity_LibraryName &&
  1101. fl->LibraryName.used,
  1102. "%.*s", LIT(name));
  1103. add_dependency_to_set(c, fl);
  1104. }
  1105. }
  1106. if (e->kind == Entity_Variable && e->Variable.is_foreign) {
  1107. Entity *fl = e->Variable.foreign_library;
  1108. if (fl != nullptr) {
  1109. GB_ASSERT_MSG(fl->kind == Entity_LibraryName &&
  1110. fl->LibraryName.used,
  1111. "%.*s", LIT(name));
  1112. add_dependency_to_set(c, fl);
  1113. }
  1114. }
  1115. }
  1116. }
  1117. void generate_minimum_dependency_set(Checker *c, Entity *start) {
  1118. ptr_set_init(&c->info.minimum_dependency_set, heap_allocator());
  1119. ptr_set_init(&c->info.minimum_dependency_type_info_set, heap_allocator());
  1120. String required_entities[] = {
  1121. str_lit("__mem_zero"),
  1122. str_lit("__init_context"),
  1123. str_lit("default_allocator"),
  1124. str_lit("__args__"),
  1125. str_lit("__type_table"),
  1126. str_lit("Type_Info"),
  1127. str_lit("Source_Code_Location"),
  1128. str_lit("Allocator"),
  1129. str_lit("Context"),
  1130. };
  1131. for (isize i = 0; i < gb_count_of(required_entities); i++) {
  1132. add_dependency_to_set(c, scope_lookup_entity(c->builtin_package->scope, required_entities[i]));
  1133. }
  1134. if (!build_context.no_bounds_check) {
  1135. String bounds_check_entities[] = {
  1136. str_lit("__bounds_check_error"),
  1137. str_lit("__slice_expr_error"),
  1138. str_lit("__dynamic_array_expr_error"),
  1139. };
  1140. for (isize i = 0; i < gb_count_of(bounds_check_entities); i++) {
  1141. add_dependency_to_set(c, scope_lookup_entity(c->builtin_package->scope, bounds_check_entities[i]));
  1142. }
  1143. }
  1144. for_array(i, c->info.definitions) {
  1145. Entity *e = c->info.definitions[i];
  1146. // if (e->scope->is_global && !is_type_poly_proc(e->type)) { // TODO(bill): is the check enough?
  1147. if (e->scope == universal_scope) { // TODO(bill): is the check enough?
  1148. if (e->type == nullptr || !is_type_poly_proc(e->type)) {
  1149. add_dependency_to_set(c, e);
  1150. }
  1151. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  1152. add_dependency_to_set(c, e);
  1153. } else if (e->kind == Entity_Variable && e->Procedure.is_export) {
  1154. add_dependency_to_set(c, e);
  1155. }
  1156. }
  1157. add_dependency_to_set(c, start);
  1158. }
  1159. bool is_entity_a_dependency(Entity *e) {
  1160. if (e == nullptr) return false;
  1161. switch (e->kind) {
  1162. case Entity_Procedure:
  1163. case Entity_Variable:
  1164. case Entity_Constant:
  1165. return true;
  1166. }
  1167. return false;
  1168. }
  1169. Array<EntityGraphNode *> generate_entity_dependency_graph(CheckerInfo *info) {
  1170. gbAllocator a = heap_allocator();
  1171. Map<EntityGraphNode *> M = {}; // Key: Entity *
  1172. map_init(&M, a, info->entities.count);
  1173. defer (map_destroy(&M));
  1174. for_array(i, info->entities) {
  1175. Entity *e = info->entities[i];
  1176. DeclInfo *d = e->decl_info;
  1177. if (is_entity_a_dependency(e)) {
  1178. EntityGraphNode *n = gb_alloc_item(a, EntityGraphNode);
  1179. n->entity = e;
  1180. map_set(&M, hash_pointer(e), n);
  1181. }
  1182. }
  1183. // Calculate edges for graph M
  1184. for_array(i, M.entries) {
  1185. Entity * e = cast(Entity *)M.entries[i].key.ptr;
  1186. EntityGraphNode *n = M.entries[i].value;
  1187. DeclInfo *decl = decl_info_of_entity(info, e);
  1188. if (decl != nullptr) {
  1189. for_array(j, decl->deps.entries) {
  1190. auto entry = decl->deps.entries[j];
  1191. Entity *dep = entry.ptr;
  1192. if (dep && is_entity_a_dependency(dep)) {
  1193. EntityGraphNode **m_ = map_get(&M, hash_pointer(dep));
  1194. if (m_ != nullptr) {
  1195. EntityGraphNode *m = *m_;
  1196. entity_graph_node_set_add(&n->succ, m);
  1197. entity_graph_node_set_add(&m->pred, n);
  1198. }
  1199. }
  1200. }
  1201. }
  1202. }
  1203. auto G = array_make<EntityGraphNode *>(a, 0, M.entries.count);
  1204. for_array(i, M.entries) {
  1205. auto *entry = &M.entries[i];
  1206. auto *e = cast(Entity *)entry->key.ptr;
  1207. EntityGraphNode *n = entry->value;
  1208. if (e->kind == Entity_Procedure) {
  1209. // Connect each pred 'p' of 'n' with each succ 's' and from
  1210. // the procedure node
  1211. for_array(j, n->pred.entries) {
  1212. EntityGraphNode *p = n->pred.entries[j].ptr;
  1213. // Ignore self-cycles
  1214. if (p != n) {
  1215. // Each succ 's' of 'n' becomes a succ of 'p', and
  1216. // each pred 'p' of 'n' becomes a pred of 's'
  1217. for_array(k, n->succ.entries) {
  1218. EntityGraphNode *s = n->succ.entries[k].ptr;
  1219. // Ignore self-cycles
  1220. if (s != n) {
  1221. entity_graph_node_set_add(&p->succ, s);
  1222. entity_graph_node_set_add(&s->pred, p);
  1223. // Remove edge to 'n'
  1224. entity_graph_node_set_remove(&s->pred, n);
  1225. }
  1226. }
  1227. // Remove edge to 'n'
  1228. entity_graph_node_set_remove(&p->succ, n);
  1229. }
  1230. }
  1231. } else {
  1232. array_add(&G, n);
  1233. }
  1234. }
  1235. for_array(i, G) {
  1236. EntityGraphNode *n = G[i];
  1237. n->index = i;
  1238. n->dep_count = n->succ.entries.count;
  1239. GB_ASSERT(n->dep_count >= 0);
  1240. }
  1241. return G;
  1242. }
  1243. Entity *find_core_entity(Checker *c, String name) {
  1244. Entity *e = current_scope_lookup_entity(c->builtin_package->scope, name);
  1245. if (e == nullptr) {
  1246. compiler_error("Could not find type declaration for '%.*s'\n"
  1247. "Is '_preload.odin' missing from the 'core' directory relative to odin.exe?", LIT(name));
  1248. // NOTE(bill): This will exit the program as it's cannot continue without it!
  1249. }
  1250. return e;
  1251. }
  1252. Type *find_core_type(Checker *c, String name) {
  1253. Entity *e = current_scope_lookup_entity(c->builtin_package->scope, name);
  1254. if (e == nullptr) {
  1255. compiler_error("Could not find type declaration for '%.*s'\n"
  1256. "Is '_preload.odin' missing from the 'core' directory relative to odin.exe?", LIT(name));
  1257. // NOTE(bill): This will exit the program as it's cannot continue without it!
  1258. }
  1259. return e->type;
  1260. }
  1261. CheckerTypePath *new_checker_type_path() {
  1262. gbAllocator a = heap_allocator();
  1263. auto *tp = gb_alloc_item(a, CheckerTypePath);
  1264. array_init(tp, a, 0, 16);
  1265. return tp;
  1266. }
  1267. void destroy_checker_type_path(CheckerTypePath *tp) {
  1268. array_free(tp);
  1269. gb_free(heap_allocator(), tp);
  1270. }
  1271. void check_type_path_push(Checker *c, Entity *e) {
  1272. GB_ASSERT(c->context.type_path != nullptr);
  1273. GB_ASSERT(e != nullptr);
  1274. array_add(c->context.type_path, e);
  1275. }
  1276. Entity *check_type_path_pop(Checker *c) {
  1277. GB_ASSERT(c->context.type_path != nullptr);
  1278. return array_pop(c->context.type_path);
  1279. }
  1280. void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type);
  1281. Array<Entity *> proc_group_entities(Checker *c, Operand o) {
  1282. Array<Entity *> procs = {};
  1283. if (o.mode == Addressing_ProcGroup) {
  1284. GB_ASSERT(o.proc_group != nullptr);
  1285. if (o.proc_group->kind == Entity_ProcGroup) {
  1286. check_entity_decl(c, o.proc_group, nullptr, nullptr);
  1287. return o.proc_group->ProcGroup.entities;
  1288. }
  1289. }
  1290. return procs;
  1291. }
  1292. void init_preload(Checker *c) {
  1293. if (t_type_info == nullptr) {
  1294. Entity *type_info_entity = find_core_entity(c, str_lit("Type_Info"));
  1295. t_type_info = type_info_entity->type;
  1296. t_type_info_ptr = alloc_type_pointer(t_type_info);
  1297. GB_ASSERT(is_type_struct(type_info_entity->type));
  1298. TypeStruct *tis = &base_type(type_info_entity->type)->Struct;
  1299. Entity *type_info_enum_value = find_core_entity(c, str_lit("Type_Info_Enum_Value"));
  1300. t_type_info_enum_value = type_info_enum_value->type;
  1301. t_type_info_enum_value_ptr = alloc_type_pointer(t_type_info_enum_value);
  1302. GB_ASSERT(tis->fields.count == 4);
  1303. Entity *type_info_variant = tis->fields[3];
  1304. Type *tiv_type = type_info_variant->type;
  1305. GB_ASSERT(is_type_union(tiv_type));
  1306. t_type_info_named = find_core_type(c, str_lit("Type_Info_Named"));
  1307. t_type_info_integer = find_core_type(c, str_lit("Type_Info_Integer"));
  1308. t_type_info_rune = find_core_type(c, str_lit("Type_Info_Rune"));
  1309. t_type_info_float = find_core_type(c, str_lit("Type_Info_Float"));
  1310. t_type_info_complex = find_core_type(c, str_lit("Type_Info_Complex"));
  1311. t_type_info_string = find_core_type(c, str_lit("Type_Info_String"));
  1312. t_type_info_boolean = find_core_type(c, str_lit("Type_Info_Boolean"));
  1313. t_type_info_any = find_core_type(c, str_lit("Type_Info_Any"));
  1314. t_type_info_typeid = find_core_type(c, str_lit("Type_Info_Type_Id"));
  1315. t_type_info_pointer = find_core_type(c, str_lit("Type_Info_Pointer"));
  1316. t_type_info_procedure = find_core_type(c, str_lit("Type_Info_Procedure"));
  1317. t_type_info_array = find_core_type(c, str_lit("Type_Info_Array"));
  1318. t_type_info_dynamic_array = find_core_type(c, str_lit("Type_Info_Dynamic_Array"));
  1319. t_type_info_slice = find_core_type(c, str_lit("Type_Info_Slice"));
  1320. t_type_info_tuple = find_core_type(c, str_lit("Type_Info_Tuple"));
  1321. t_type_info_struct = find_core_type(c, str_lit("Type_Info_Struct"));
  1322. t_type_info_union = find_core_type(c, str_lit("Type_Info_Union"));
  1323. t_type_info_enum = find_core_type(c, str_lit("Type_Info_Enum"));
  1324. t_type_info_map = find_core_type(c, str_lit("Type_Info_Map"));
  1325. t_type_info_bit_field = find_core_type(c, str_lit("Type_Info_Bit_Field"));
  1326. t_type_info_named_ptr = alloc_type_pointer(t_type_info_named);
  1327. t_type_info_integer_ptr = alloc_type_pointer(t_type_info_integer);
  1328. t_type_info_rune_ptr = alloc_type_pointer(t_type_info_rune);
  1329. t_type_info_float_ptr = alloc_type_pointer(t_type_info_float);
  1330. t_type_info_complex_ptr = alloc_type_pointer(t_type_info_complex);
  1331. t_type_info_string_ptr = alloc_type_pointer(t_type_info_string);
  1332. t_type_info_boolean_ptr = alloc_type_pointer(t_type_info_boolean);
  1333. t_type_info_any_ptr = alloc_type_pointer(t_type_info_any);
  1334. t_type_info_typeid_ptr = alloc_type_pointer(t_type_info_typeid);
  1335. t_type_info_pointer_ptr = alloc_type_pointer(t_type_info_pointer);
  1336. t_type_info_procedure_ptr = alloc_type_pointer(t_type_info_procedure);
  1337. t_type_info_array_ptr = alloc_type_pointer(t_type_info_array);
  1338. t_type_info_dynamic_array_ptr = alloc_type_pointer(t_type_info_dynamic_array);
  1339. t_type_info_slice_ptr = alloc_type_pointer(t_type_info_slice);
  1340. t_type_info_tuple_ptr = alloc_type_pointer(t_type_info_tuple);
  1341. t_type_info_struct_ptr = alloc_type_pointer(t_type_info_struct);
  1342. t_type_info_union_ptr = alloc_type_pointer(t_type_info_union);
  1343. t_type_info_enum_ptr = alloc_type_pointer(t_type_info_enum);
  1344. t_type_info_map_ptr = alloc_type_pointer(t_type_info_map);
  1345. t_type_info_bit_field_ptr = alloc_type_pointer(t_type_info_bit_field);
  1346. }
  1347. if (t_allocator == nullptr) {
  1348. Entity *e = find_core_entity(c, str_lit("Allocator"));
  1349. t_allocator = e->type;
  1350. t_allocator_ptr = alloc_type_pointer(t_allocator);
  1351. }
  1352. if (t_context == nullptr) {
  1353. Entity *e = find_core_entity(c, str_lit("Context"));
  1354. e_context = e;
  1355. t_context = e->type;
  1356. t_context_ptr = alloc_type_pointer(t_context);
  1357. }
  1358. if (t_source_code_location == nullptr) {
  1359. Entity *e = find_core_entity(c, str_lit("Source_Code_Location"));
  1360. t_source_code_location = e->type;
  1361. t_source_code_location_ptr = alloc_type_pointer(t_allocator);
  1362. }
  1363. if (t_map_key == nullptr) {
  1364. Entity *e = find_core_entity(c, str_lit("__Map_Key"));
  1365. t_map_key = e->type;
  1366. }
  1367. if (t_map_header == nullptr) {
  1368. Entity *e = find_core_entity(c, str_lit("__Map_Header"));
  1369. t_map_header = e->type;
  1370. }
  1371. {
  1372. String _global = str_lit("_global");
  1373. Entity *type_info_entity = find_core_entity(c, str_lit("Type_Info"));
  1374. Scope *preload_scope = type_info_entity->scope;
  1375. Entity *e = alloc_entity_import_name(preload_scope, make_token_ident(_global), t_invalid,
  1376. str_lit(""), _global,
  1377. preload_scope);
  1378. add_entity(c, universal_scope, nullptr, e);
  1379. }
  1380. c->done_preload = true;
  1381. }
  1382. DECL_ATTRIBUTE_PROC(foreign_block_decl_attribute) {
  1383. if (name == "default_calling_convention") {
  1384. if (value.kind == ExactValue_String) {
  1385. auto cc = string_to_calling_convention(value.value_string);
  1386. if (cc == ProcCC_Invalid) {
  1387. error(elem, "Unknown procedure calling convention: '%.*s'\n", LIT(value.value_string));
  1388. } else {
  1389. c->context.foreign_context.default_cc = cc;
  1390. }
  1391. } else {
  1392. error(elem, "Expected a string value for '%.*s'", LIT(name));
  1393. }
  1394. return true;
  1395. } else if (name == "link_prefix") {
  1396. if (value.kind == ExactValue_String) {
  1397. String link_prefix = value.value_string;
  1398. if (!is_foreign_name_valid(link_prefix)) {
  1399. error(elem, "Invalid link prefix: '%.*s'\n", LIT(link_prefix));
  1400. } else {
  1401. c->context.foreign_context.link_prefix = link_prefix;
  1402. }
  1403. } else {
  1404. error(elem, "Expected a string value for '%.*s'", LIT(name));
  1405. }
  1406. return true;
  1407. }
  1408. return false;
  1409. }
  1410. DECL_ATTRIBUTE_PROC(proc_decl_attribute) {
  1411. if (name == "link_name") {
  1412. if (value.kind == ExactValue_String) {
  1413. ac->link_name = value.value_string;
  1414. if (!is_foreign_name_valid(ac->link_name)) {
  1415. error(elem, "Invalid link name: %.*s", LIT(ac->link_name));
  1416. }
  1417. } else {
  1418. error(elem, "Expected a string value for '%.*s'", LIT(name));
  1419. }
  1420. return true;
  1421. } else if (name == "link_prefix") {
  1422. if (value.kind == ExactValue_String) {
  1423. ac->link_prefix = value.value_string;
  1424. if (!is_foreign_name_valid(ac->link_prefix)) {
  1425. error(elem, "Invalid link prefix: %.*s", LIT(ac->link_prefix));
  1426. }
  1427. } else {
  1428. error(elem, "Expected a string value for '%.*s'", LIT(name));
  1429. }
  1430. return true;
  1431. } else if (name == "deprecated") {
  1432. if (value.kind == ExactValue_String) {
  1433. String msg = value.value_string;
  1434. if (msg.len == 0) {
  1435. error(elem, "Deprecation message cannot be an empty string");
  1436. } else {
  1437. ac->deprecated_message = msg;
  1438. }
  1439. } else {
  1440. error(elem, "Expected a string value for '%.*s'", LIT(name));
  1441. }
  1442. return true;
  1443. }
  1444. return false;
  1445. }
  1446. DECL_ATTRIBUTE_PROC(var_decl_attribute) {
  1447. if (c->context.curr_proc_decl != nullptr) {
  1448. error(elem, "Only a variable at file scope can have a '%.*s'", LIT(name));
  1449. return true;
  1450. }
  1451. if (name == "link_name") {
  1452. if (value.kind == ExactValue_String) {
  1453. ac->link_name = value.value_string;
  1454. if (!is_foreign_name_valid(ac->link_name)) {
  1455. error(elem, "Invalid link name: %.*s", LIT(ac->link_name));
  1456. }
  1457. } else {
  1458. error(elem, "Expected a string value for '%.*s'", LIT(name));
  1459. }
  1460. return true;
  1461. } else if (name == "link_prefix") {
  1462. if (value.kind == ExactValue_String) {
  1463. ac->link_prefix = value.value_string;
  1464. if (!is_foreign_name_valid(ac->link_prefix)) {
  1465. error(elem, "Invalid link prefix: %.*s", LIT(ac->link_prefix));
  1466. }
  1467. } else {
  1468. error(elem, "Expected a string value for '%.*s'", LIT(name));
  1469. }
  1470. return true;
  1471. } else if (name == "thread_local") {
  1472. if (ac->init_expr_list_count > 0) {
  1473. error(elem, "A thread local variable declaration cannot have initialization values");
  1474. } else if (c->context.foreign_context.curr_library || c->context.foreign_context.in_export) {
  1475. error(elem, "A foreign block variable cannot be thread local");
  1476. } else if (value.kind == ExactValue_Invalid) {
  1477. ac->thread_local_model = str_lit("default");
  1478. } else if (value.kind == ExactValue_String) {
  1479. String model = value.value_string;
  1480. if (model == "localdynamic" ||
  1481. model == "initialexec" ||
  1482. model == "localexec") {
  1483. ac->thread_local_model = model;
  1484. } else {
  1485. error(elem, "Invalid thread local model '%.*s'", LIT(model));
  1486. }
  1487. } else {
  1488. error(elem, "Expected either no value or a string for '%.*s'", LIT(name));
  1489. }
  1490. return true;
  1491. }
  1492. return false;
  1493. }
  1494. #include "check_expr.cpp"
  1495. #include "check_type.cpp"
  1496. #include "check_decl.cpp"
  1497. #include "check_stmt.cpp"
  1498. void check_decl_attributes(Checker *c, Array<AstNode *> attributes, DeclAttributeProc *proc, AttributeContext *ac) {
  1499. if (attributes.count == 0) return;
  1500. String original_link_prefix = {};
  1501. if (ac) {
  1502. original_link_prefix = ac->link_prefix;
  1503. }
  1504. StringSet set = {};
  1505. string_set_init(&set, heap_allocator());
  1506. defer (string_set_destroy(&set));
  1507. for_array(i, attributes) {
  1508. AstNode *attr = attributes[i];
  1509. if (attr->kind != AstNode_Attribute) continue;
  1510. for_array(j, attr->Attribute.elems) {
  1511. AstNode *elem = attr->Attribute.elems[j];
  1512. String name = {};
  1513. AstNode *value = nullptr;
  1514. switch (elem->kind) {
  1515. case_ast_node(i, Ident, elem);
  1516. name = i->token.string;
  1517. case_end;
  1518. case_ast_node(fv, FieldValue, elem);
  1519. GB_ASSERT(fv->field->kind == AstNode_Ident);
  1520. name = fv->field->Ident.token.string;
  1521. value = fv->value;
  1522. case_end;
  1523. default:
  1524. error(elem, "Invalid attribute element");
  1525. continue;
  1526. }
  1527. ExactValue ev = {};
  1528. if (value != nullptr) {
  1529. Operand op = {};
  1530. check_expr(c, &op, value);
  1531. if (op.mode) {
  1532. if (op.mode != Addressing_Constant) {
  1533. error(value, "An attribute element must be constant");
  1534. } else {
  1535. ev = op.value;
  1536. }
  1537. }
  1538. }
  1539. if (string_set_exists(&set, name)) {
  1540. error(elem, "Previous declaration of '%.*s'", LIT(name));
  1541. continue;
  1542. } else {
  1543. string_set_add(&set, name);
  1544. }
  1545. if (!proc(c, elem, name, ev, ac)) {
  1546. error(elem, "Unknown attribute element name '%.*s'", LIT(name));
  1547. }
  1548. }
  1549. }
  1550. if (ac) {
  1551. if (ac->link_prefix.text == original_link_prefix.text) {
  1552. if (ac->link_name.len > 0) {
  1553. ac->link_prefix.text = nullptr;
  1554. ac->link_prefix.len = 0;
  1555. }
  1556. }
  1557. }
  1558. }
  1559. bool check_arity_match(Checker *c, AstNodeValueDecl *vd, bool is_global) {
  1560. isize lhs = vd->names.count;
  1561. isize rhs = vd->values.count;
  1562. if (rhs == 0) {
  1563. if (vd->type == nullptr) {
  1564. error(vd->names[0], "Missing type or initial expression");
  1565. return false;
  1566. }
  1567. } else if (lhs < rhs) {
  1568. if (lhs < vd->values.count) {
  1569. AstNode *n = vd->values[lhs];
  1570. gbString str = expr_to_string(n);
  1571. error(n, "Extra initial expression '%s'", str);
  1572. gb_string_free(str);
  1573. } else {
  1574. error(vd->names[0], "Extra initial expression");
  1575. }
  1576. return false;
  1577. } else if (lhs > rhs) {
  1578. if (!is_global && rhs != 1) {
  1579. AstNode *n = vd->names[rhs];
  1580. gbString str = expr_to_string(n);
  1581. error(n, "Missing expression for '%s'", str);
  1582. gb_string_free(str);
  1583. return false;
  1584. } else if (is_global) {
  1585. AstNode *n = vd->values[rhs-1];
  1586. error(n, "Expected %td expressions on the right hand side, got %td", lhs, rhs);
  1587. return false;
  1588. }
  1589. }
  1590. return true;
  1591. }
  1592. void check_collect_entities_from_when_stmt(Checker *c, AstNodeWhenStmt *ws) {
  1593. Operand operand = {Addressing_Invalid};
  1594. if (!ws->is_cond_determined) {
  1595. check_expr(c, &operand, ws->cond);
  1596. if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) {
  1597. error(ws->cond, "Non-boolean condition in 'when' statement");
  1598. }
  1599. if (operand.mode != Addressing_Constant) {
  1600. error(ws->cond, "Non-constant condition in 'when' statement");
  1601. }
  1602. ws->is_cond_determined = true;
  1603. ws->determined_cond = operand.value.kind == ExactValue_Bool && operand.value.value_bool;
  1604. }
  1605. if (ws->body == nullptr || ws->body->kind != AstNode_BlockStmt) {
  1606. error(ws->cond, "Invalid body for 'when' statement");
  1607. } else {
  1608. if (ws->determined_cond) {
  1609. check_collect_entities(c, ws->body->BlockStmt.stmts);
  1610. } else if (ws->else_stmt) {
  1611. switch (ws->else_stmt->kind) {
  1612. case AstNode_BlockStmt:
  1613. check_collect_entities(c, ws->else_stmt->BlockStmt.stmts);
  1614. break;
  1615. case AstNode_WhenStmt:
  1616. check_collect_entities_from_when_stmt(c, &ws->else_stmt->WhenStmt);
  1617. break;
  1618. default:
  1619. error(ws->else_stmt, "Invalid 'else' statement in 'when' statement");
  1620. break;
  1621. }
  1622. }
  1623. }
  1624. }
  1625. void check_collect_value_decl(Checker *c, AstNode *decl) {
  1626. ast_node(vd, ValueDecl, decl);
  1627. if (vd->been_handled) return;
  1628. vd->been_handled = true;
  1629. if (vd->is_mutable) {
  1630. if (!c->context.scope->is_file) {
  1631. // NOTE(bill): local scope -> handle later and in order
  1632. return;
  1633. }
  1634. // NOTE(bill): You need to store the entity information here unline a constant declaration
  1635. isize entity_cap = vd->names.count;
  1636. isize entity_count = 0;
  1637. Entity **entities = gb_alloc_array(c->allocator, Entity *, entity_cap);
  1638. DeclInfo *di = nullptr;
  1639. if (vd->values.count > 0) {
  1640. di = make_decl_info(heap_allocator(), c->context.scope, c->context.decl);
  1641. di->entities = entities;
  1642. di->type_expr = vd->type;
  1643. di->init_expr = vd->values[0];
  1644. di->init_expr_list = vd->values;
  1645. }
  1646. for_array(i, vd->names) {
  1647. AstNode *name = vd->names[i];
  1648. AstNode *value = nullptr;
  1649. if (i < vd->values.count) {
  1650. value = vd->values[i];
  1651. }
  1652. if (name->kind != AstNode_Ident) {
  1653. error(name, "A declaration's name must be an identifier, got %.*s", LIT(ast_node_strings[name->kind]));
  1654. continue;
  1655. }
  1656. Entity *e = alloc_entity_variable(c->context.scope, name->Ident.token, nullptr, false);
  1657. e->identifier = name;
  1658. if (vd->is_using) {
  1659. vd->is_using = false; // NOTE(bill): This error will be only caught once
  1660. error(name, "'using' is not allowed at the file scope");
  1661. }
  1662. AstNode *fl = c->context.foreign_context.curr_library;
  1663. if (fl != nullptr) {
  1664. GB_ASSERT(fl->kind == AstNode_Ident);
  1665. e->Variable.is_foreign = true;
  1666. e->Variable.foreign_library_ident = fl;
  1667. e->Variable.link_prefix = c->context.foreign_context.link_prefix;
  1668. } else if (c->context.foreign_context.in_export) {
  1669. e->Variable.is_export = true;
  1670. }
  1671. entities[entity_count++] = e;
  1672. DeclInfo *d = di;
  1673. if (d == nullptr || i > 0) {
  1674. AstNode *init_expr = value;
  1675. d = make_decl_info(heap_allocator(), e->scope, c->context.decl);
  1676. d->type_expr = vd->type;
  1677. d->init_expr = init_expr;
  1678. }
  1679. d->attributes = vd->attributes;
  1680. add_entity_and_decl_info(c, name, e, d);
  1681. }
  1682. if (di != nullptr) {
  1683. di->entity_count = entity_count;
  1684. }
  1685. check_arity_match(c, vd, true);
  1686. } else {
  1687. for_array(i, vd->names) {
  1688. AstNode *name = vd->names[i];
  1689. if (name->kind != AstNode_Ident) {
  1690. error(name, "A declaration's name must be an identifier, got %.*s", LIT(ast_node_strings[name->kind]));
  1691. continue;
  1692. }
  1693. AstNode *init = unparen_expr(vd->values[i]);
  1694. if (init == nullptr) {
  1695. error(name, "Expected a value for this constant value declaration");
  1696. continue;
  1697. }
  1698. Token token = name->Ident.token;
  1699. AstNode *fl = c->context.foreign_context.curr_library;
  1700. DeclInfo *d = make_decl_info(c->allocator, c->context.scope, c->context.decl);
  1701. Entity *e = nullptr;
  1702. d->attributes = vd->attributes;
  1703. if (is_ast_node_type(init) ||
  1704. (vd->type != nullptr && vd->type->kind == AstNode_TypeType)) {
  1705. e = alloc_entity_type_name(d->scope, token, nullptr);
  1706. if (vd->type != nullptr) {
  1707. error(name, "A type declaration cannot have an type parameter");
  1708. }
  1709. d->type_expr = init;
  1710. d->init_expr = init;
  1711. } else if (init->kind == AstNode_ProcLit) {
  1712. if (c->context.scope->is_struct) {
  1713. error(name, "Procedure declarations are not allowed within a struct");
  1714. continue;
  1715. }
  1716. ast_node(pl, ProcLit, init);
  1717. e = alloc_entity_procedure(d->scope, token, nullptr, pl->tags);
  1718. if (fl != nullptr) {
  1719. GB_ASSERT(fl->kind == AstNode_Ident);
  1720. e->Procedure.foreign_library_ident = fl;
  1721. e->Procedure.is_foreign = true;
  1722. GB_ASSERT(pl->type->kind == AstNode_ProcType);
  1723. auto cc = pl->type->ProcType.calling_convention;
  1724. if (cc == ProcCC_ForeignBlockDefault) {
  1725. cc = ProcCC_CDecl;
  1726. if (c->context.foreign_context.default_cc > 0) {
  1727. cc = c->context.foreign_context.default_cc;
  1728. }
  1729. }
  1730. e->Procedure.link_prefix = c->context.foreign_context.link_prefix;
  1731. GB_ASSERT(cc != ProcCC_Invalid);
  1732. pl->type->ProcType.calling_convention = cc;
  1733. } else if (c->context.foreign_context.in_export) {
  1734. e->Procedure.is_export = true;
  1735. }
  1736. d->proc_lit = init;
  1737. d->type_expr = pl->type;
  1738. } else if (init->kind == AstNode_ProcGroup) {
  1739. ast_node(pg, ProcGroup, init);
  1740. e = alloc_entity_proc_group(d->scope, token, nullptr);
  1741. if (fl != nullptr) {
  1742. error(name, "Procedure groups are not allowed within a foreign block");
  1743. }
  1744. d->init_expr = init;
  1745. } else {
  1746. e = alloc_entity_constant(d->scope, token, nullptr, empty_exact_value);
  1747. d->type_expr = vd->type;
  1748. d->init_expr = init;
  1749. }
  1750. e->identifier = name;
  1751. if (e->kind != Entity_Procedure) {
  1752. if (fl != nullptr || c->context.foreign_context.in_export) {
  1753. AstNodeKind kind = init->kind;
  1754. error(name, "Only procedures and variables are allowed to be in a foreign block, got %.*s", LIT(ast_node_strings[kind]));
  1755. if (kind == AstNode_ProcType) {
  1756. gb_printf_err("\tDid you forget to append '---' to the procedure?\n");
  1757. }
  1758. }
  1759. }
  1760. add_entity_and_decl_info(c, name, e, d);
  1761. }
  1762. check_arity_match(c, vd, true);
  1763. }
  1764. }
  1765. void check_add_foreign_block_decl(Checker *c, AstNode *decl) {
  1766. ast_node(fb, ForeignBlockDecl, decl);
  1767. if (fb->been_handled) return;
  1768. fb->been_handled = true;
  1769. AstNode *foreign_library = fb->foreign_library;
  1770. CheckerContext prev_context = c->context;
  1771. if (foreign_library->kind == AstNode_Ident) {
  1772. c->context.foreign_context.curr_library = foreign_library;
  1773. } else if (foreign_library->kind == AstNode_Implicit && foreign_library->Implicit.kind == Token_export) {
  1774. c->context.foreign_context.in_export = true;
  1775. } else {
  1776. error(foreign_library, "Foreign block name must be an identifier or 'export'");
  1777. c->context.foreign_context.curr_library = nullptr;
  1778. }
  1779. check_decl_attributes(c, fb->attributes, foreign_block_decl_attribute, nullptr);
  1780. check_collect_entities(c, fb->decls);
  1781. c->context = prev_context;
  1782. }
  1783. // NOTE(bill): If file_scopes == nullptr, this will act like a local scope
  1784. void check_collect_entities(Checker *c, Array<AstNode *> nodes) {
  1785. for_array(decl_index, nodes) {
  1786. AstNode *decl = nodes[decl_index];
  1787. if (!is_ast_node_decl(decl) && !is_ast_node_when_stmt(decl)) {
  1788. continue;
  1789. }
  1790. switch (decl->kind) {
  1791. case_ast_node(bd, BadDecl, decl);
  1792. case_end;
  1793. case_ast_node(ws, WhenStmt, decl);
  1794. // Will be handled later
  1795. case_end;
  1796. case_ast_node(vd, ValueDecl, decl);
  1797. check_collect_value_decl(c, decl);
  1798. case_end;
  1799. case_ast_node(id, ImportDecl, decl);
  1800. if (!c->context.scope->is_file) {
  1801. error(decl, "import declarations are only allowed in the file scope");
  1802. // NOTE(bill): _Should_ be caught by the parser
  1803. // TODO(bill): Better error handling if it isn't
  1804. continue;
  1805. }
  1806. array_add(&c->context.scope->delayed_imports, decl);
  1807. case_end;
  1808. case_ast_node(fl, ForeignImportDecl, decl);
  1809. if (!c->context.scope->is_file) {
  1810. error(decl, "%.*s declarations are only allowed in the file scope", LIT(fl->token.string));
  1811. // NOTE(bill): _Should_ be caught by the parser
  1812. // TODO(bill): Better error handling if it isn't
  1813. continue;
  1814. }
  1815. check_add_foreign_import_decl(c, decl);
  1816. case_end;
  1817. case_ast_node(fb, ForeignBlockDecl, decl);
  1818. check_add_foreign_block_decl(c, decl);
  1819. case_end;
  1820. case_ast_node(ce, CallExpr, decl);
  1821. if (c->context.scope->is_file &&
  1822. ce->proc->kind == AstNode_BasicDirective &&
  1823. ce->proc->BasicDirective.name == "assert") {
  1824. array_add(&c->context.scope->delayed_asserts, decl);
  1825. } else {
  1826. goto error_case;
  1827. }
  1828. case_end;
  1829. error_case:
  1830. default:
  1831. if (c->context.scope->is_file) {
  1832. error(decl, "Only declarations are allowed at file scope");
  1833. }
  1834. break;
  1835. }
  1836. }
  1837. // NOTE(bill): 'when' stmts need to be handled after the other as the condition may refer to something
  1838. // declared after this stmt in source
  1839. if (!c->context.scope->is_file) {
  1840. for_array(i, nodes) {
  1841. AstNode *node = nodes[i];
  1842. switch (node->kind) {
  1843. case_ast_node(ws, WhenStmt, node);
  1844. check_collect_entities_from_when_stmt(c, ws);
  1845. case_end;
  1846. }
  1847. }
  1848. }
  1849. }
  1850. void check_all_global_entities(Checker *c) {
  1851. Scope *prev_file = nullptr;
  1852. bool processing_preload = true;
  1853. for_array(i, c->info.entities) {
  1854. Entity *e = c->info.entities[i];
  1855. DeclInfo *d = e->decl_info;
  1856. if (d->scope != e->scope) {
  1857. continue;
  1858. }
  1859. GB_ASSERT(d->scope->is_file);
  1860. AstFile *file = d->scope->file;
  1861. add_curr_ast_file(c, file);
  1862. Scope *package_scope = file->package->scope;
  1863. if (e->token.string == "main") {
  1864. if (e->kind != Entity_Procedure) {
  1865. if (package_scope->is_init) {
  1866. error(e->token, "'main' is reserved as the entry point procedure in the initial scope");
  1867. continue;
  1868. }
  1869. } else if (package_scope->is_global) {
  1870. error(e->token, "'main' is reserved as the entry point procedure in the initial scope");
  1871. continue;
  1872. }
  1873. }
  1874. CheckerContext prev_context = c->context;
  1875. c->context.decl = d;
  1876. c->context.scope = d->scope;
  1877. check_entity_decl(c, e, d, nullptr);
  1878. c->context = prev_context;
  1879. if (!package_scope->is_global) {
  1880. processing_preload = false;
  1881. }
  1882. if (!processing_preload) {
  1883. init_preload(c);
  1884. }
  1885. }
  1886. }
  1887. bool is_string_an_identifier(String s) {
  1888. isize offset = 0;
  1889. if (s.len < 1) {
  1890. return false;
  1891. }
  1892. while (offset < s.len) {
  1893. bool ok = false;
  1894. Rune r = -1;
  1895. isize size = gb_utf8_decode(s.text+offset, s.len-offset, &r);
  1896. if (offset == 0) {
  1897. ok = rune_is_letter(r);
  1898. } else {
  1899. ok = rune_is_letter(r) || rune_is_digit(r);
  1900. }
  1901. if (!ok) {
  1902. return false;
  1903. }
  1904. offset += size;
  1905. }
  1906. return offset == s.len;
  1907. }
  1908. String path_to_entity_name(String name, String fullpath) {
  1909. if (name.len != 0) {
  1910. return name;
  1911. }
  1912. // NOTE(bill): use file name (without extension) as the identifier
  1913. // If it is a valid identifier
  1914. String filename = fullpath;
  1915. isize slash = 0;
  1916. isize dot = 0;
  1917. for (isize i = filename.len-1; i >= 0; i--) {
  1918. u8 c = filename[i];
  1919. if (c == '/' || c == '\\') {
  1920. break;
  1921. }
  1922. slash = i;
  1923. }
  1924. filename = substring(filename, slash, filename.len);
  1925. dot = filename.len;
  1926. while (dot --> 0) {
  1927. u8 c = filename[dot];
  1928. if (c == '.') {
  1929. break;
  1930. }
  1931. }
  1932. filename = substring(filename, 0, dot);
  1933. if (is_string_an_identifier(filename)) {
  1934. return filename;
  1935. } else {
  1936. return str_lit("_");
  1937. }
  1938. }
  1939. #if 1
  1940. void add_import_dependency_node(Checker *c, AstNode *decl, Map<ImportGraphNode *> *M) {
  1941. Scope *parent_package_scope = decl->file->package->scope;
  1942. switch (decl->kind) {
  1943. case_ast_node(id, ImportDecl, decl);
  1944. String path = id->fullpath;
  1945. HashKey key = hash_string(path);
  1946. Scope **found = map_get(&c->package_scopes, key);
  1947. if (found == nullptr) {
  1948. for_array(scope_index, c->package_scopes.entries) {
  1949. Scope *scope = c->package_scopes.entries[scope_index].value;
  1950. gb_printf_err("%.*s\n", LIT(scope->package->fullpath));
  1951. }
  1952. Token token = ast_node_token(decl);
  1953. gb_printf_err("%.*s(%td:%td)\n", LIT(token.pos.file), token.pos.line, token.pos.column);
  1954. GB_PANIC("Unable to find scope for file: %.*s", LIT(path));
  1955. }
  1956. Scope *scope = *found;
  1957. GB_ASSERT(scope != nullptr);
  1958. id->package = scope->package;
  1959. ImportGraphNode **found_node = nullptr;
  1960. ImportGraphNode *m = nullptr;
  1961. ImportGraphNode *n = nullptr;
  1962. found_node = map_get(M, hash_pointer(scope));
  1963. GB_ASSERT(found_node != nullptr);
  1964. m = *found_node;
  1965. found_node = map_get(M, hash_pointer(parent_package_scope));
  1966. GB_ASSERT(found_node != nullptr);
  1967. n = *found_node;
  1968. // TODO(bill): How should the edges be attched for 'import'?
  1969. import_graph_node_set_add(&n->succ, m);
  1970. import_graph_node_set_add(&m->pred, n);
  1971. ptr_set_add(&m->scope->imported, n->scope);
  1972. if (id->is_using) {
  1973. ptr_set_add(&m->scope->exported, n->scope);
  1974. }
  1975. case_end;
  1976. case_ast_node(ws, WhenStmt, decl);
  1977. if (ws->body != nullptr) {
  1978. auto stmts = ws->body->BlockStmt.stmts;
  1979. for_array(i, stmts) {
  1980. add_import_dependency_node(c, stmts[i], M);
  1981. }
  1982. }
  1983. if (ws->else_stmt != nullptr) {
  1984. switch (ws->else_stmt->kind) {
  1985. case AstNode_BlockStmt: {
  1986. auto stmts = ws->else_stmt->BlockStmt.stmts;
  1987. for_array(i, stmts) {
  1988. add_import_dependency_node(c, stmts[i], M);
  1989. }
  1990. break;
  1991. }
  1992. case AstNode_WhenStmt:
  1993. add_import_dependency_node(c, ws->else_stmt, M);
  1994. break;
  1995. }
  1996. }
  1997. case_end;
  1998. }
  1999. }
  2000. Array<ImportGraphNode *> generate_import_dependency_graph(Checker *c) {
  2001. gbAllocator a = heap_allocator();
  2002. Map<ImportGraphNode *> M = {}; // Key: Scope *
  2003. map_init(&M, a);
  2004. defer (map_destroy(&M));
  2005. for_array(i, c->parser->packages) {
  2006. Scope *scope = c->parser->packages[i]->scope;
  2007. ImportGraphNode *n = import_graph_node_create(heap_allocator(), scope);
  2008. map_set(&M, hash_pointer(scope), n);
  2009. }
  2010. // Calculate edges for graph M
  2011. for_array(i, c->parser->packages) {
  2012. AstPackage *p = c->parser->packages[i];
  2013. for_array(j, p->files.entries) {
  2014. AstFile *f = p->files.entries[j].value;
  2015. for_array(k, f->decls) {
  2016. AstNode *decl = f->decls[k];
  2017. add_import_dependency_node(c, decl, &M);
  2018. }
  2019. }
  2020. }
  2021. Array<ImportGraphNode *> G = {};
  2022. array_init(&G, a);
  2023. for_array(i, M.entries) {
  2024. array_add(&G, M.entries[i].value);
  2025. }
  2026. for_array(i, G) {
  2027. ImportGraphNode *n = G[i];
  2028. n->index = i;
  2029. n->dep_count = n->succ.entries.count;
  2030. GB_ASSERT(n->dep_count >= 0);
  2031. }
  2032. return G;
  2033. }
  2034. struct ImportPathItem {
  2035. Scope * scope;
  2036. AstNode *decl;
  2037. };
  2038. Array<ImportPathItem> find_import_path(Checker *c, Scope *start, Scope *end, PtrSet<Scope *> *visited) {
  2039. Array<ImportPathItem> empty_path = {};
  2040. if (ptr_set_exists(visited, start)) {
  2041. return empty_path;
  2042. }
  2043. ptr_set_add(visited, start);
  2044. String path = start->package->fullpath;
  2045. HashKey key = hash_string(path);
  2046. Scope **found = map_get(&c->package_scopes, key);
  2047. if (found) {
  2048. AstPackage *p = (*found)->package;
  2049. GB_ASSERT(p != nullptr);
  2050. for_array(i, p->files.entries) {
  2051. AstFile *f = p->files.entries[i].value;
  2052. for_array(j, f->imports) {
  2053. Scope *s = nullptr;
  2054. AstNode *decl = f->imports[j];
  2055. if (decl->kind == AstNode_ImportDecl) {
  2056. s = decl->ImportDecl.package->scope;
  2057. } else {
  2058. continue;
  2059. }
  2060. GB_ASSERT(s != nullptr && s->is_package);
  2061. ImportPathItem item = {s, decl};
  2062. if (s == end) {
  2063. auto path = array_make<ImportPathItem>(heap_allocator());
  2064. array_add(&path, item);
  2065. return path;
  2066. }
  2067. auto next_path = find_import_path(c, s, end, visited);
  2068. if (next_path.count > 0) {
  2069. array_add(&next_path, item);
  2070. return next_path;
  2071. }
  2072. }
  2073. }
  2074. }
  2075. return empty_path;
  2076. }
  2077. #endif
  2078. void check_add_import_decl(Checker *c, AstNodeImportDecl *id) {
  2079. if (id->been_handled) return;
  2080. id->been_handled = true;
  2081. Scope *parent_scope = c->context.scope;
  2082. GB_ASSERT(parent_scope->is_file);
  2083. Token token = id->relpath;
  2084. HashKey key = hash_string(id->fullpath);
  2085. Scope **found = map_get(&c->package_scopes, key);
  2086. if (found == nullptr) {
  2087. for_array(scope_index, c->package_scopes.entries) {
  2088. Scope *scope = c->package_scopes.entries[scope_index].value;
  2089. gb_printf_err("%.*s\n", LIT(scope->package->fullpath));
  2090. }
  2091. gb_printf_err("%.*s(%td:%td)\n", LIT(token.pos.file), token.pos.line, token.pos.column);
  2092. GB_PANIC("Unable to find scope for package: %.*s", LIT(id->fullpath));
  2093. }
  2094. Scope *scope = *found;
  2095. GB_ASSERT(scope->is_package && scope->package != nullptr);
  2096. if (scope->is_global) {
  2097. error(token, "Importing a built-in package is disallowed and unnecessary");
  2098. return;
  2099. }
  2100. if (ptr_set_exists(&parent_scope->imported, scope)) {
  2101. // error(token, "Multiple import of the same file within this scope");
  2102. } else {
  2103. ptr_set_add(&parent_scope->imported, scope);
  2104. }
  2105. if (id->using_in_list.count == 0) {
  2106. String import_name = id->import_name.string;
  2107. if (import_name.len == 0) {
  2108. import_name = scope->package->name;
  2109. }
  2110. if (is_blank_ident(import_name)) {
  2111. if (id->is_using) {
  2112. // TODO(bill): Should this be a warning?
  2113. } else {
  2114. error(token, "Import name, %.*s, cannot be use as an import name as it is not a valid identifier", LIT(id->import_name.string));
  2115. }
  2116. } else {
  2117. GB_ASSERT(id->import_name.pos.line != 0);
  2118. id->import_name.string = import_name;
  2119. Entity *e = alloc_entity_import_name(parent_scope, id->import_name, t_invalid,
  2120. id->fullpath, id->import_name.string,
  2121. scope);
  2122. add_entity(c, parent_scope, nullptr, e);
  2123. }
  2124. }
  2125. if (id->is_using) {
  2126. if (parent_scope->is_global) {
  2127. error(id->import_name, "'builtin' package imports cannot use using");
  2128. return;
  2129. }
  2130. // NOTE(bill): Add imported entities to this file's scope
  2131. if (id->using_in_list.count > 0) {
  2132. for_array(list_index, id->using_in_list) {
  2133. AstNode *node = id->using_in_list[list_index];
  2134. ast_node(ident, Ident, node);
  2135. String name = ident->token.string;
  2136. Entity *e = scope_lookup_entity(scope, name);
  2137. if (e == nullptr) {
  2138. if (is_blank_ident(name)) {
  2139. error(node, "'_' cannot be used as a value");
  2140. } else {
  2141. error(node, "Undeclared name in this importation: '%.*s'", LIT(name));
  2142. }
  2143. continue;
  2144. }
  2145. if (e->scope == parent_scope) {
  2146. continue;
  2147. }
  2148. bool implicit_is_found = ptr_set_exists(&scope->implicit, e);
  2149. if (is_entity_exported(e) && !implicit_is_found) {
  2150. add_entity_use(c, node, e);
  2151. bool ok = add_entity(c, parent_scope, e->identifier, e);
  2152. if (ok) ptr_set_add(&parent_scope->implicit, e);
  2153. } else {
  2154. error(node, "'%.*s' is exported from this scope", LIT(name));
  2155. continue;
  2156. }
  2157. }
  2158. } else {
  2159. for_array(elem_index, scope->elements.entries) {
  2160. Entity *e = scope->elements.entries[elem_index].value;
  2161. if (e->scope == parent_scope) continue;
  2162. bool implicit_is_found = ptr_set_exists(&scope->implicit, e);
  2163. if (is_entity_exported(e) && !implicit_is_found) {
  2164. Entity *prev = scope_lookup_entity(parent_scope, e->token.string);
  2165. // if (prev) gb_printf_err("%.*s\n", LIT(prev->token.string));
  2166. bool ok = add_entity(c, parent_scope, e->identifier, e);
  2167. if (ok) ptr_set_add(&parent_scope->implicit, e);
  2168. }
  2169. }
  2170. }
  2171. }
  2172. scope->has_been_imported = true;
  2173. }
  2174. void check_add_foreign_import_decl(Checker *c, AstNode *decl) {
  2175. ast_node(fl, ForeignImportDecl, decl);
  2176. if (fl->been_handled) return;
  2177. fl->been_handled = true;
  2178. Scope *parent_scope = c->context.scope;
  2179. GB_ASSERT(parent_scope->is_file);
  2180. String fullpath = fl->fullpath;
  2181. String library_name = path_to_entity_name(fl->library_name.string, fullpath);
  2182. if (is_blank_ident(library_name)) {
  2183. error(fl->token, "File name, %.*s, cannot be as a library name as it is not a valid identifier", LIT(fl->library_name.string));
  2184. return;
  2185. }
  2186. if (fl->collection_name != "system") {
  2187. char *c_str = gb_alloc_array(heap_allocator(), char, fullpath.len+1);
  2188. defer (gb_free(heap_allocator(), c_str));
  2189. gb_memcopy(c_str, fullpath.text, fullpath.len);
  2190. c_str[fullpath.len] = '\0';
  2191. gbFile f = {};
  2192. gbFileError file_err = gb_file_open(&f, c_str);
  2193. defer (gb_file_close(&f));
  2194. switch (file_err) {
  2195. case gbFileError_Invalid:
  2196. error(decl, "Invalid file or cannot be found ('%.*s')", LIT(fullpath));
  2197. return;
  2198. case gbFileError_NotExists:
  2199. error(decl, "File cannot be found ('%.*s')", LIT(fullpath));
  2200. return;
  2201. }
  2202. }
  2203. GB_ASSERT(fl->library_name.pos.line != 0);
  2204. fl->library_name.string = library_name;
  2205. Entity *e = alloc_entity_library_name(parent_scope, fl->library_name, t_invalid,
  2206. fl->fullpath, library_name);
  2207. add_entity(c, parent_scope, nullptr, e);
  2208. }
  2209. void check_import_entities(Checker *c) {
  2210. Array<ImportGraphNode *> dep_graph = generate_import_dependency_graph(c);
  2211. defer ({
  2212. for_array(i, dep_graph) {
  2213. import_graph_node_destroy(dep_graph[i], heap_allocator());
  2214. }
  2215. array_free(&dep_graph);
  2216. });
  2217. // NOTE(bill): Priority queue
  2218. auto pq = priority_queue_create(dep_graph, import_graph_node_cmp, import_graph_node_swap);
  2219. PtrSet<Scope *> emitted = {};
  2220. ptr_set_init(&emitted, heap_allocator());
  2221. defer (ptr_set_destroy(&emitted));
  2222. while (pq.queue.count > 0) {
  2223. ImportGraphNode *n = priority_queue_pop(&pq);
  2224. Scope *s = n->scope;
  2225. if (n->dep_count > 0) {
  2226. PtrSet<Scope *> visited = {};
  2227. ptr_set_init(&visited, heap_allocator());
  2228. defer (ptr_set_destroy(&visited));
  2229. auto path = find_import_path(c, s, s, &visited);
  2230. defer (array_free(&path));
  2231. // TODO(bill): This needs better TokenPos finding
  2232. auto const fn = [](ImportPathItem item) -> String {
  2233. Scope *s = item.scope;
  2234. // return remove_directory_from_path(s->package->fullpath);
  2235. return s->package->name;
  2236. };
  2237. if (path.count == 1) {
  2238. // TODO(bill): Should this be allowed or disabled?
  2239. #if 0
  2240. ImportPathItem item = path[0];
  2241. String filename = fn(item);
  2242. error(item.decl, "Self importation of '%.*s'", LIT(filename));
  2243. #endif
  2244. } else if (path.count > 0) {
  2245. ImportPathItem item = path[path.count-1];
  2246. String filename = fn(item);
  2247. error(item.decl, "Cyclic importation of '%.*s'", LIT(filename));
  2248. for (isize i = 0; i < path.count; i++) {
  2249. error(item.decl, "'%.*s' refers to", LIT(filename));
  2250. item = path[i];
  2251. filename = fn(item);
  2252. }
  2253. error(item.decl, "'%.*s'", LIT(filename));
  2254. }
  2255. }
  2256. for_array(i, n->pred.entries) {
  2257. ImportGraphNode *p = n->pred.entries[i].ptr;
  2258. p->dep_count = gb_max(p->dep_count-1, 0);
  2259. // p->dep_count -= 1;
  2260. priority_queue_fix(&pq, p->index);
  2261. }
  2262. if (s == nullptr) {
  2263. continue;
  2264. }
  2265. if (ptr_set_exists(&emitted, s)) {
  2266. continue;
  2267. }
  2268. ptr_set_add(&emitted, s);
  2269. array_add(&c->package_order, n);
  2270. }
  2271. for_array(i, c->package_order) {
  2272. ImportGraphNode *node = c->package_order[i];
  2273. GB_ASSERT(node->scope->is_package);
  2274. AstPackage *p = node->scope->package;
  2275. for_array(i, p->files.entries) {
  2276. AstFile *f = p->files.entries[i].value;
  2277. CheckerContext prev_context = c->context;
  2278. defer (c->context = prev_context);
  2279. add_curr_ast_file(c, f);
  2280. check_collect_entities(c, f->decls);
  2281. }
  2282. for_array(i, p->files.entries) {
  2283. AstFile *f = p->files.entries[i].value;
  2284. CheckerContext prev_context = c->context;
  2285. defer (c->context = prev_context);
  2286. add_curr_ast_file(c, f);
  2287. for_array(j, f->scope->delayed_imports) {
  2288. AstNode *decl = f->scope->delayed_imports[j];
  2289. ast_node(id, ImportDecl, decl);
  2290. check_add_import_decl(c, id);
  2291. }
  2292. }
  2293. for_array(i, p->files.entries) {
  2294. AstFile *f = p->files.entries[i].value;
  2295. CheckerContext prev_context = c->context;
  2296. defer (c->context = prev_context);
  2297. add_curr_ast_file(c, f);
  2298. for_array(j, f->scope->delayed_asserts) {
  2299. AstNode *expr = f->scope->delayed_asserts[j];
  2300. Operand o = {};
  2301. check_expr(c, &o, expr);
  2302. }
  2303. }
  2304. }
  2305. // gb_printf_err("End here!\n");
  2306. // gb_exit(1);
  2307. }
  2308. Array<Entity *> find_entity_path(Entity *start, Entity *end, Map<Entity *> *visited = nullptr) {
  2309. Map<Entity *> visited_ = {};
  2310. bool made_visited = false;
  2311. if (visited == nullptr) {
  2312. made_visited = true;
  2313. map_init(&visited_, heap_allocator());
  2314. visited = &visited_;
  2315. }
  2316. defer (if (made_visited) {
  2317. map_destroy(&visited_);
  2318. });
  2319. Array<Entity *> empty_path = {};
  2320. HashKey key = hash_pointer(start);
  2321. if (map_get(visited, key) != nullptr) {
  2322. return empty_path;
  2323. }
  2324. map_set(visited, key, start);
  2325. DeclInfo *decl = start->decl_info;
  2326. if (decl) {
  2327. for_array(i, decl->deps.entries) {
  2328. Entity *dep = decl->deps.entries[i].ptr;
  2329. if (dep == end) {
  2330. auto path = array_make<Entity *>(heap_allocator());
  2331. array_add(&path, dep);
  2332. return path;
  2333. }
  2334. auto next_path = find_entity_path(dep, end, visited);
  2335. if (next_path.count > 0) {
  2336. array_add(&next_path, dep);
  2337. return next_path;
  2338. }
  2339. }
  2340. }
  2341. return empty_path;
  2342. }
  2343. void calculate_global_init_order(Checker *c) {
  2344. #if 0
  2345. Timings timings = {};
  2346. timings_init(&timings, str_lit("calculate_global_init_order"), 16);
  2347. defer ({
  2348. timings_print_all(&timings);
  2349. timings_destroy(&timings);
  2350. });
  2351. #define TIME_SECTION(str) timings_start_section(&timings, str_lit(str))
  2352. #else
  2353. #define TIME_SECTION(str)
  2354. #endif
  2355. CheckerInfo *info = &c->info;
  2356. TIME_SECTION("generate entity dependency graph");
  2357. Array<EntityGraphNode *> dep_graph = generate_entity_dependency_graph(info);
  2358. defer ({
  2359. for_array(i, dep_graph) {
  2360. entity_graph_node_destroy(dep_graph[i], heap_allocator());
  2361. }
  2362. array_free(&dep_graph);
  2363. });
  2364. TIME_SECTION("priority queue create");
  2365. // NOTE(bill): Priority queue
  2366. auto pq = priority_queue_create(dep_graph, entity_graph_node_cmp, entity_graph_node_swap);
  2367. PtrSet<DeclInfo *> emitted = {};
  2368. ptr_set_init(&emitted, heap_allocator());
  2369. defer (ptr_set_destroy(&emitted));
  2370. TIME_SECTION("queue sort");
  2371. while (pq.queue.count > 0) {
  2372. EntityGraphNode *n = priority_queue_pop(&pq);
  2373. Entity *e = n->entity;
  2374. if (n->dep_count > 0) {
  2375. auto path = find_entity_path(e, e);
  2376. defer (array_free(&path));
  2377. if (path.count > 0) {
  2378. Entity *e = path[0];
  2379. error(e->token, "Cyclic initialization of '%.*s'", LIT(e->token.string));
  2380. for (isize i = path.count-1; i >= 0; i--) {
  2381. error(e->token, "\t'%.*s' refers to", LIT(e->token.string));
  2382. e = path[i];
  2383. }
  2384. error(e->token, "\t'%.*s'", LIT(e->token.string));
  2385. }
  2386. }
  2387. for_array(i, n->pred.entries) {
  2388. EntityGraphNode *p = n->pred.entries[i].ptr;
  2389. p->dep_count -= 1;
  2390. priority_queue_fix(&pq, p->index);
  2391. }
  2392. if (e == nullptr || e->kind != Entity_Variable) {
  2393. continue;
  2394. }
  2395. DeclInfo *d = decl_info_of_entity(info, e);
  2396. if (ptr_set_exists(&emitted, d)) {
  2397. continue;
  2398. }
  2399. ptr_set_add(&emitted, d);
  2400. if (d->entities == nullptr) {
  2401. d->entities = gb_alloc_array(c->allocator, Entity *, 1);
  2402. d->entities[0] = e;
  2403. d->entity_count = 1;
  2404. }
  2405. array_add(&info->variable_init_order, d);
  2406. }
  2407. if (false) {
  2408. gb_printf("Variable Initialization Order:\n");
  2409. for_array(i, info->variable_init_order) {
  2410. DeclInfo *d = info->variable_init_order[i];
  2411. for (isize j = 0; j < d->entity_count; j++) {
  2412. Entity *e = d->entities[j];
  2413. if (j == 0) gb_printf("\t");
  2414. if (j > 0) gb_printf(", ");
  2415. gb_printf("'%.*s' %td", LIT(e->token.string), e->order_in_src);
  2416. }
  2417. gb_printf("\n");
  2418. }
  2419. gb_printf("\n");
  2420. }
  2421. #undef TIME_SECTION
  2422. }
  2423. void check_parsed_files(Checker *c) {
  2424. #if 0
  2425. Timings timings = {};
  2426. timings_init(&timings, str_lit("check_parsed_files"), 16);
  2427. defer ({
  2428. timings_print_all(&timings);
  2429. timings_destroy(&timings);
  2430. });
  2431. #define TIME_SECTION(str) timings_start_section(&timings, str_lit(str))
  2432. #else
  2433. #define TIME_SECTION(str)
  2434. #endif
  2435. TIME_SECTION("map full filepaths to scope");
  2436. add_type_info_type(c, t_invalid);
  2437. // Map full filepaths to Scopes
  2438. for_array(i, c->parser->packages) {
  2439. AstPackage *p = c->parser->packages[i];
  2440. Scope *scope = create_scope_from_package(c, p);
  2441. p->decl_info = make_decl_info(c->allocator, scope, c->context.decl);
  2442. HashKey key = hash_string(p->fullpath);
  2443. map_set(&c->package_scopes, key, scope);
  2444. map_set(&c->info.packages, key, p);
  2445. if (scope->is_init) {
  2446. c->info.init_scope = scope;
  2447. }
  2448. if (p->kind == Package_Builtin) {
  2449. GB_ASSERT(c->builtin_package == nullptr);
  2450. c->builtin_package = p;
  2451. }
  2452. }
  2453. TIME_SECTION("collect entities");
  2454. // Collect Entities
  2455. for_array(i, c->parser->packages) {
  2456. AstPackage *p = c->parser->packages[i];
  2457. CheckerContext prev_context = c->context;
  2458. for_array(j, p->files.entries) {
  2459. AstFile *f = p->files.entries[j].value;
  2460. create_scope_from_file(c, f);
  2461. HashKey key = hash_string(f->fullpath);
  2462. map_set(&c->info.files, key, f);
  2463. add_curr_ast_file(c, f);
  2464. check_collect_entities(c, f->decls);
  2465. }
  2466. c->context = prev_context;
  2467. }
  2468. TIME_SECTION("import entities");
  2469. check_import_entities(c);
  2470. TIME_SECTION("check all global entities");
  2471. check_all_global_entities(c);
  2472. TIME_SECTION("init preload");
  2473. init_preload(c); // NOTE(bill): This could be setup previously through the use of 'type_info_of'
  2474. TIME_SECTION("check procedure bodies");
  2475. // Check procedure bodies
  2476. // NOTE(bill): Nested procedures bodies will be added to this "queue"
  2477. for_array(i, c->procs) {
  2478. ProcedureInfo *pi = &c->procs[i];
  2479. if (pi->type == nullptr) {
  2480. continue;
  2481. }
  2482. CheckerContext prev_context = c->context;
  2483. defer (c->context = prev_context);
  2484. TypeProc *pt = &pi->type->Proc;
  2485. String name = pi->token.string;
  2486. if (pt->is_polymorphic) {
  2487. GB_ASSERT_MSG(pt->is_poly_specialized, "%.*s", LIT(name));
  2488. }
  2489. add_curr_ast_file(c, pi->file);
  2490. bool bounds_check = (pi->tags & ProcTag_bounds_check) != 0;
  2491. bool no_bounds_check = (pi->tags & ProcTag_no_bounds_check) != 0;
  2492. if (bounds_check) {
  2493. c->context.stmt_state_flags |= StmtStateFlag_bounds_check;
  2494. c->context.stmt_state_flags &= ~StmtStateFlag_no_bounds_check;
  2495. } else if (no_bounds_check) {
  2496. c->context.stmt_state_flags |= StmtStateFlag_no_bounds_check;
  2497. c->context.stmt_state_flags &= ~StmtStateFlag_bounds_check;
  2498. }
  2499. check_proc_body(c, pi->token, pi->decl, pi->type, pi->body);
  2500. }
  2501. TIME_SECTION("generate minimum dependency set");
  2502. generate_minimum_dependency_set(c, c->info.entry_point);
  2503. TIME_SECTION("calculate global init order");
  2504. // Calculate initialization order of global variables
  2505. calculate_global_init_order(c);
  2506. TIME_SECTION("add untyped expression values");
  2507. // Add untyped expression values
  2508. for_array(i, c->info.untyped.entries) {
  2509. auto *entry = &c->info.untyped.entries[i];
  2510. HashKey key = entry->key;
  2511. AstNode *expr = cast(AstNode *)key.ptr;
  2512. ExprInfo *info = &entry->value;
  2513. if (info != nullptr && expr != nullptr) {
  2514. if (is_type_typed(info->type)) {
  2515. compiler_error("%s (type %s) is typed!", expr_to_string(expr), type_to_string(info->type));
  2516. }
  2517. add_type_and_value(&c->info, expr, info->mode, info->type, info->value);
  2518. }
  2519. }
  2520. // TODO(bill): Check for unused imports (and remove) or even warn/err
  2521. // TODO(bill): Any other checks?
  2522. TIME_SECTION("add type information");
  2523. // Add "Basic" type information
  2524. for (isize i = 0; i < Basic_COUNT; i++) {
  2525. Type *t = &basic_types[i];
  2526. if (t->Basic.size > 0 &&
  2527. (t->Basic.flags & BasicFlag_LLVM) == 0) {
  2528. add_type_info_type(c, t);
  2529. }
  2530. }
  2531. // NOTE(bill): Check for illegal cyclic type declarations
  2532. for_array(i, c->info.definitions) {
  2533. Entity *e = c->info.definitions[i];
  2534. if (e->kind == Entity_TypeName && e->type != nullptr) {
  2535. // i64 size = type_size_of(c->allocator, e->type);
  2536. i64 align = type_align_of(e->type);
  2537. if (align > 0 && ptr_set_exists(&c->info.minimum_dependency_set, e)) {
  2538. add_type_info_type(c, e->type);
  2539. }
  2540. }
  2541. }
  2542. TIME_SECTION("check entry point");
  2543. if (!build_context.is_dll) {
  2544. Scope *s = c->info.init_scope;
  2545. GB_ASSERT(s != nullptr);
  2546. GB_ASSERT(s->is_init);
  2547. Entity *e = current_scope_lookup_entity(s, str_lit("main"));
  2548. if (e == nullptr) {
  2549. Token token = {};
  2550. token.pos.file = s->package->fullpath;
  2551. token.pos.line = 1;
  2552. token.pos.column = 1;
  2553. if (s->package->files.entries.count > 0) {
  2554. AstFile *f = s->package->files.entries[0].value;
  2555. if (f->tokens.count > 0) {
  2556. token = f->tokens[0];
  2557. }
  2558. }
  2559. error(token, "Undefined entry point procedure 'main'");
  2560. }
  2561. }
  2562. #undef TIME_SECTION
  2563. }