checker.cpp 86 KB

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