check_stmt.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403
  1. bool is_diverging_expr(Ast *expr) {
  2. expr = unparen_expr(expr);
  3. if (expr->kind != Ast_CallExpr) {
  4. return false;
  5. }
  6. if (expr->CallExpr.proc->kind == Ast_BasicDirective) {
  7. String name = expr->CallExpr.proc->BasicDirective.name.string;
  8. return name == "panic";
  9. }
  10. Ast *proc = unparen_expr(expr->CallExpr.proc);
  11. TypeAndValue tv = proc->tav;
  12. if (tv.mode == Addressing_Builtin) {
  13. Entity *e = entity_of_node(proc);
  14. BuiltinProcId id = BuiltinProc_Invalid;
  15. if (e != nullptr) {
  16. id = cast(BuiltinProcId)e->Builtin.id;
  17. } else {
  18. id = BuiltinProc_DIRECTIVE;
  19. }
  20. return builtin_procs[id].diverging;
  21. }
  22. Type *t = tv.type;
  23. t = base_type(t);
  24. return t != nullptr && t->kind == Type_Proc && t->Proc.diverging;
  25. }
  26. bool is_diverging_stmt(Ast *stmt) {
  27. if (stmt->kind != Ast_ExprStmt) {
  28. return false;
  29. }
  30. return is_diverging_expr(stmt->ExprStmt.expr);
  31. }
  32. bool contains_deferred_call(Ast *node) {
  33. if (node->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  34. return true;
  35. }
  36. switch (node->kind) {
  37. case Ast_ExprStmt:
  38. return contains_deferred_call(node->ExprStmt.expr);
  39. case Ast_AssignStmt:
  40. for_array(i, node->AssignStmt.rhs) {
  41. if (contains_deferred_call(node->AssignStmt.rhs[i])) {
  42. return true;
  43. }
  44. }
  45. for_array(i, node->AssignStmt.lhs) {
  46. if (contains_deferred_call(node->AssignStmt.lhs[i])) {
  47. return true;
  48. }
  49. }
  50. break;
  51. case Ast_ValueDecl:
  52. for_array(i, node->ValueDecl.values) {
  53. if (contains_deferred_call(node->ValueDecl.values[i])) {
  54. return true;
  55. }
  56. }
  57. break;
  58. }
  59. return false;
  60. }
  61. void check_stmt_list(CheckerContext *ctx, Slice<Ast *> const &stmts, u32 flags) {
  62. if (stmts.count == 0) {
  63. return;
  64. }
  65. if (flags&Stmt_CheckScopeDecls) {
  66. check_scope_decls(ctx, stmts, cast(isize)(1.2*stmts.count));
  67. }
  68. bool ft_ok = (flags & Stmt_FallthroughAllowed) != 0;
  69. flags &= ~Stmt_FallthroughAllowed;
  70. isize max = stmts.count;
  71. for (isize i = stmts.count-1; i >= 0; i--) {
  72. if (stmts[i]->kind != Ast_EmptyStmt) {
  73. break;
  74. }
  75. max--;
  76. }
  77. isize max_non_constant_declaration = stmts.count;
  78. for (isize i = stmts.count-1; i >= 0; i--) {
  79. if (stmts[i]->kind == Ast_EmptyStmt) {
  80. // Okay
  81. } else if (stmts[i]->kind == Ast_ValueDecl && !stmts[i]->ValueDecl.is_mutable) {
  82. // Okay
  83. } else {
  84. break;
  85. }
  86. max_non_constant_declaration--;
  87. }
  88. for (isize i = 0; i < max; i++) {
  89. Ast *n = stmts[i];
  90. if (n->kind == Ast_EmptyStmt) {
  91. continue;
  92. }
  93. u32 new_flags = flags;
  94. if (ft_ok && i+1 == max) {
  95. new_flags |= Stmt_FallthroughAllowed;
  96. }
  97. check_stmt(ctx, n, new_flags);
  98. if (i+1 < max_non_constant_declaration) {
  99. switch (n->kind) {
  100. case Ast_ReturnStmt:
  101. error(n, "Statements after this 'return' are never executed");
  102. break;
  103. case Ast_BranchStmt:
  104. error(n, "Statements after this '%.*s' are never executed", LIT(n->BranchStmt.token.string));
  105. break;
  106. case Ast_ExprStmt:
  107. if (is_diverging_stmt(n)) {
  108. error(n, "Statements after a diverging procedure call are never executed");
  109. }
  110. break;
  111. }
  112. } else if (i+1 == max_non_constant_declaration) {
  113. if (is_diverging_stmt(n)) {
  114. for (isize j = 0; j < i; j++) {
  115. Ast *stmt = stmts[j];
  116. if (stmt->kind == Ast_ValueDecl && !stmt->ValueDecl.is_mutable) {
  117. } else if (stmt->kind == Ast_DeferStmt) {
  118. error(stmt, "Unreachable defer statement due to diverging procedure call at the end of the current scope");
  119. } else if (contains_deferred_call(stmt)) {
  120. error(stmt, "Unreachable deferred procedure call due to a diverging procedure call at the end of the current scope");
  121. }
  122. }
  123. }
  124. }
  125. }
  126. }
  127. bool check_is_terminating_list(Slice<Ast *> const &stmts, String const &label) {
  128. // Iterate backwards
  129. for (isize n = stmts.count-1; n >= 0; n--) {
  130. Ast *stmt = stmts[n];
  131. if (stmt->kind == Ast_EmptyStmt) {
  132. // Okay
  133. } else if (stmt->kind == Ast_ValueDecl && !stmt->ValueDecl.is_mutable) {
  134. // Okay
  135. } else if (is_diverging_stmt(stmt)) {
  136. return true;
  137. } else {
  138. return check_is_terminating(stmt, label);
  139. }
  140. }
  141. return false;
  142. }
  143. bool check_has_break_list(Slice<Ast *> const &stmts, String const &label, bool implicit) {
  144. for_array(i, stmts) {
  145. Ast *stmt = stmts[i];
  146. if (check_has_break(stmt, label, implicit)) {
  147. return true;
  148. }
  149. }
  150. return false;
  151. }
  152. bool check_has_break(Ast *stmt, String const &label, bool implicit) {
  153. switch (stmt->kind) {
  154. case Ast_BranchStmt:
  155. if (stmt->BranchStmt.token.kind == Token_break) {
  156. if (stmt->BranchStmt.label == nullptr) {
  157. return implicit;
  158. }
  159. if (stmt->BranchStmt.label->kind == Ast_Ident &&
  160. stmt->BranchStmt.label->Ident.token.string == label) {
  161. return true;
  162. }
  163. }
  164. break;
  165. case Ast_BlockStmt:
  166. return check_has_break_list(stmt->BlockStmt.stmts, label, implicit);
  167. case Ast_IfStmt:
  168. if (check_has_break(stmt->IfStmt.body, label, implicit) ||
  169. (stmt->IfStmt.else_stmt != nullptr && check_has_break(stmt->IfStmt.else_stmt, label, implicit))) {
  170. return true;
  171. }
  172. break;
  173. case Ast_CaseClause:
  174. return check_has_break_list(stmt->CaseClause.stmts, label, implicit);
  175. case Ast_SwitchStmt:
  176. if (label != "" && check_has_break(stmt->SwitchStmt.body, label, false)) {
  177. return true;
  178. }
  179. break;
  180. case Ast_TypeSwitchStmt:
  181. if (label != "" && check_has_break(stmt->TypeSwitchStmt.body, label, false)) {
  182. return true;
  183. }
  184. break;
  185. case Ast_ForStmt:
  186. if (label != "" && check_has_break(stmt->ForStmt.body, label, false)) {
  187. return true;
  188. }
  189. break;
  190. case Ast_RangeStmt:
  191. if (label != "" && check_has_break(stmt->RangeStmt.body, label, false)) {
  192. return true;
  193. }
  194. break;
  195. }
  196. return false;
  197. }
  198. // NOTE(bill): The last expression has to be a 'return' statement
  199. // TODO(bill): This is a mild hack and should be probably handled properly
  200. bool check_is_terminating(Ast *node, String const &label) {
  201. switch (node->kind) {
  202. case_ast_node(rs, ReturnStmt, node);
  203. return true;
  204. case_end;
  205. case_ast_node(bs, BlockStmt, node);
  206. return check_is_terminating_list(bs->stmts, label);
  207. case_end;
  208. case_ast_node(es, ExprStmt, node);
  209. return check_is_terminating(unparen_expr(es->expr), label);
  210. case_end;
  211. case_ast_node(is, IfStmt, node);
  212. if (is->else_stmt != nullptr) {
  213. if (check_is_terminating(is->body, label) &&
  214. check_is_terminating(is->else_stmt, label)) {
  215. return true;
  216. }
  217. }
  218. case_end;
  219. case_ast_node(ws, WhenStmt, node);
  220. // TODO(bill): Is this logic correct for when statements?
  221. auto const &tv = ws->cond->tav;
  222. if (tv.mode != Addressing_Constant) {
  223. // NOTE(bill): Check the things regardless as a bug occurred earlier
  224. if (ws->else_stmt != nullptr) {
  225. if (check_is_terminating(ws->body, label) &&
  226. check_is_terminating(ws->else_stmt, label)) {
  227. return true;
  228. }
  229. }
  230. return false;
  231. }
  232. if (tv.value.kind == ExactValue_Bool) {
  233. if (tv.value.value_bool) {
  234. return check_is_terminating(ws->body, label);
  235. } else {
  236. if (ws->else_stmt == nullptr) {
  237. return false;
  238. }
  239. return check_is_terminating(ws->else_stmt, label);
  240. }
  241. }
  242. case_end;
  243. case_ast_node(fs, ForStmt, node);
  244. if (fs->cond == nullptr && !check_has_break(fs->body, label, true)) {
  245. return true;
  246. }
  247. case_end;
  248. case_ast_node(rs, UnrollRangeStmt, node);
  249. return false;
  250. case_end;
  251. case_ast_node(rs, RangeStmt, node);
  252. return false;
  253. case_end;
  254. case_ast_node(ss, SwitchStmt, node);
  255. bool has_default = false;
  256. for_array(i, ss->body->BlockStmt.stmts) {
  257. Ast *clause = ss->body->BlockStmt.stmts[i];
  258. ast_node(cc, CaseClause, clause);
  259. if (cc->list.count == 0) {
  260. has_default = true;
  261. }
  262. if (!check_is_terminating_list(cc->stmts, label) ||
  263. check_has_break_list(cc->stmts, label, true)) {
  264. return false;
  265. }
  266. }
  267. return has_default;
  268. case_end;
  269. case_ast_node(ss, TypeSwitchStmt, node);
  270. bool has_default = false;
  271. for_array(i, ss->body->BlockStmt.stmts) {
  272. Ast *clause = ss->body->BlockStmt.stmts[i];
  273. ast_node(cc, CaseClause, clause);
  274. if (cc->list.count == 0) {
  275. has_default = true;
  276. }
  277. if (!check_is_terminating_list(cc->stmts, label) ||
  278. check_has_break_list(cc->stmts, label, true)) {
  279. return false;
  280. }
  281. }
  282. return has_default;
  283. case_end;
  284. }
  285. return false;
  286. }
  287. Type *check_assignment_variable(CheckerContext *ctx, Operand *lhs, Operand *rhs) {
  288. if (rhs->mode == Addressing_Invalid) {
  289. return nullptr;
  290. }
  291. if (rhs->type == t_invalid &&
  292. rhs->mode != Addressing_ProcGroup &&
  293. rhs->mode != Addressing_Builtin) {
  294. return nullptr;
  295. }
  296. Ast *node = unparen_expr(lhs->expr);
  297. // NOTE(bill): Ignore assignments to '_'
  298. if (is_blank_ident(node)) {
  299. check_assignment(ctx, rhs, nullptr, str_lit("assignment to '_' identifier"));
  300. if (rhs->mode == Addressing_Invalid) {
  301. return nullptr;
  302. }
  303. return rhs->type;
  304. }
  305. Entity *e = nullptr;
  306. bool used = false;
  307. if (lhs->mode == Addressing_Invalid ||
  308. (lhs->type == t_invalid &&
  309. lhs->mode != Addressing_ProcGroup &&
  310. lhs->mode != Addressing_Builtin)) {
  311. return nullptr;
  312. }
  313. if (rhs->mode == Addressing_ProcGroup) {
  314. Array<Entity *> procs = proc_group_entities(ctx, *rhs);
  315. GB_ASSERT(procs.count > 0);
  316. // NOTE(bill): These should be done
  317. for_array(i, procs) {
  318. Type *t = base_type(procs[i]->type);
  319. if (t == t_invalid) {
  320. continue;
  321. }
  322. Operand x = {};
  323. x.mode = Addressing_Value;
  324. x.type = t;
  325. if (check_is_assignable_to(ctx, &x, lhs->type)) {
  326. e = procs[i];
  327. add_entity_use(ctx, rhs->expr, e);
  328. break;
  329. }
  330. }
  331. if (e != nullptr) {
  332. // HACK TODO(bill): Should the entities be freed as it's technically a leak
  333. rhs->mode = Addressing_Value;
  334. rhs->type = e->type;
  335. rhs->proc_group = nullptr;
  336. }
  337. } else {
  338. if (node->kind == Ast_Ident) {
  339. ast_node(i, Ident, node);
  340. e = scope_lookup(ctx->scope, i->token.string);
  341. if (e != nullptr && e->kind == Entity_Variable) {
  342. used = (e->flags & EntityFlag_Used) != 0; // TODO(bill): Make backup just in case
  343. }
  344. }
  345. }
  346. if (e != nullptr && used) {
  347. e->flags |= EntityFlag_Used;
  348. }
  349. Type *assignment_type = lhs->type;
  350. switch (lhs->mode) {
  351. case Addressing_Invalid:
  352. return nullptr;
  353. case Addressing_Variable:
  354. break;
  355. case Addressing_MapIndex: {
  356. Ast *ln = unparen_expr(lhs->expr);
  357. if (ln->kind == Ast_IndexExpr) {
  358. Ast *x = ln->IndexExpr.expr;
  359. TypeAndValue tav = x->tav;
  360. GB_ASSERT(tav.mode != Addressing_Invalid);
  361. if (tav.mode != Addressing_Variable) {
  362. if (!is_type_pointer(tav.type)) {
  363. gbString str = expr_to_string(lhs->expr);
  364. error(lhs->expr, "Cannot assign to the value of a map '%s'", str);
  365. gb_string_free(str);
  366. return nullptr;
  367. }
  368. }
  369. }
  370. break;
  371. }
  372. case Addressing_Context: {
  373. break;
  374. }
  375. case Addressing_SoaVariable:
  376. break;
  377. case Addressing_SwizzleVariable:
  378. break;
  379. default: {
  380. if (lhs->expr->kind == Ast_SelectorExpr) {
  381. // NOTE(bill): Extra error checks
  382. Operand op_c = {Addressing_Invalid};
  383. ast_node(se, SelectorExpr, lhs->expr);
  384. check_expr(ctx, &op_c, se->expr);
  385. if (op_c.mode == Addressing_MapIndex) {
  386. gbString str = expr_to_string(lhs->expr);
  387. error(lhs->expr, "Cannot assign to struct field '%s' in map", str);
  388. gb_string_free(str);
  389. return nullptr;
  390. }
  391. }
  392. Entity *e = entity_of_node(lhs->expr);
  393. gbString str = expr_to_string(lhs->expr);
  394. if (e != nullptr && e->flags & EntityFlag_Param) {
  395. if (e->flags & EntityFlag_Using) {
  396. error(lhs->expr, "Cannot assign to '%s' which is from a 'using' procedure parameter", str);
  397. } else {
  398. error(lhs->expr, "Cannot assign to '%s' which is a procedure parameter", str);
  399. }
  400. } else {
  401. error(lhs->expr, "Cannot assign to '%s'", str);
  402. }
  403. gb_string_free(str);
  404. break;
  405. }
  406. }
  407. check_assignment(ctx, rhs, assignment_type, str_lit("assignment"));
  408. if (rhs->mode == Addressing_Invalid) {
  409. return nullptr;
  410. }
  411. return rhs->type;
  412. }
  413. void check_stmt_internal(CheckerContext *ctx, Ast *node, u32 flags);
  414. void check_stmt(CheckerContext *ctx, Ast *node, u32 flags) {
  415. u32 prev_state_flags = ctx->state_flags;
  416. if (node->state_flags != 0) {
  417. u32 in = node->state_flags;
  418. u32 out = ctx->state_flags;
  419. if (in & StateFlag_no_bounds_check) {
  420. out |= StateFlag_no_bounds_check;
  421. out &= ~StateFlag_bounds_check;
  422. } else if (in & StateFlag_bounds_check) {
  423. out |= StateFlag_bounds_check;
  424. out &= ~StateFlag_no_bounds_check;
  425. }
  426. if (in & StateFlag_no_type_assert) {
  427. out |= StateFlag_no_type_assert;
  428. out &= ~StateFlag_type_assert;
  429. } else if (in & StateFlag_type_assert) {
  430. out |= StateFlag_type_assert;
  431. out &= ~StateFlag_no_type_assert;
  432. }
  433. ctx->state_flags = out;
  434. }
  435. check_stmt_internal(ctx, node, flags);
  436. ctx->state_flags = prev_state_flags;
  437. }
  438. void check_when_stmt(CheckerContext *ctx, AstWhenStmt *ws, u32 flags) {
  439. Operand operand = {Addressing_Invalid};
  440. check_expr(ctx, &operand, ws->cond);
  441. if (operand.mode != Addressing_Constant || !is_type_boolean(operand.type)) {
  442. error(ws->cond, "Non-constant boolean 'when' condition");
  443. return;
  444. }
  445. if (ws->body == nullptr || ws->body->kind != Ast_BlockStmt) {
  446. error(ws->cond, "Invalid body for 'when' statement");
  447. return;
  448. }
  449. if (operand.value.kind == ExactValue_Bool &&
  450. operand.value.value_bool) {
  451. check_stmt_list(ctx, ws->body->BlockStmt.stmts, flags);
  452. } else if (ws->else_stmt) {
  453. switch (ws->else_stmt->kind) {
  454. case Ast_BlockStmt:
  455. check_stmt_list(ctx, ws->else_stmt->BlockStmt.stmts, flags);
  456. break;
  457. case Ast_WhenStmt:
  458. check_when_stmt(ctx, &ws->else_stmt->WhenStmt, flags);
  459. break;
  460. default:
  461. error(ws->else_stmt, "Invalid 'else' statement in 'when' statement");
  462. break;
  463. }
  464. }
  465. }
  466. void check_label(CheckerContext *ctx, Ast *label, Ast *parent) {
  467. if (label == nullptr) {
  468. return;
  469. }
  470. ast_node(l, Label, label);
  471. if (l->name->kind != Ast_Ident) {
  472. error(l->name, "A label's name must be an identifier");
  473. return;
  474. }
  475. String name = l->name->Ident.token.string;
  476. if (is_blank_ident(name)) {
  477. error(l->name, "A label's name cannot be a blank identifier");
  478. return;
  479. }
  480. if (ctx->curr_proc_decl == nullptr) {
  481. error(l->name, "A label is only allowed within a procedure");
  482. return;
  483. }
  484. GB_ASSERT(ctx->decl != nullptr);
  485. bool ok = true;
  486. for_array(i, ctx->decl->labels) {
  487. BlockLabel bl = ctx->decl->labels[i];
  488. if (bl.name == name) {
  489. error(label, "Duplicate label with the name '%.*s'", LIT(name));
  490. ok = false;
  491. break;
  492. }
  493. }
  494. Entity *e = alloc_entity_label(ctx->scope, l->name->Ident.token, t_invalid, label, parent);
  495. add_entity(ctx, ctx->scope, l->name, e);
  496. e->parent_proc_decl = ctx->curr_proc_decl;
  497. if (ok) {
  498. BlockLabel bl = {name, label};
  499. array_add(&ctx->decl->labels, bl);
  500. }
  501. }
  502. // Returns 'true' for 'continue', 'false' for 'return'
  503. bool check_using_stmt_entity(CheckerContext *ctx, AstUsingStmt *us, Ast *expr, bool is_selector, Entity *e) {
  504. if (e == nullptr) {
  505. error(us->token, "'using' applied to an unknown entity");
  506. return true;
  507. }
  508. add_entity_use(ctx, expr, e);
  509. ERROR_BLOCK();
  510. switch (e->kind) {
  511. case Entity_TypeName: {
  512. Type *t = base_type(e->type);
  513. if (t->kind == Type_Enum) {
  514. for_array(i, t->Enum.fields) {
  515. Entity *f = t->Enum.fields[i];
  516. if (!is_entity_exported(f)) continue;
  517. Entity *found = scope_insert(ctx->scope, f);
  518. if (found != nullptr) {
  519. gbString expr_str = expr_to_string(expr);
  520. error(us->token, "Namespace collision while 'using' enum '%s' of: %.*s", expr_str, LIT(found->token.string));
  521. gb_string_free(expr_str);
  522. return false;
  523. }
  524. f->using_parent = e;
  525. }
  526. } else {
  527. error(us->token, "'using' can be only applied to enum type entities");
  528. }
  529. break;
  530. }
  531. case Entity_ImportName: {
  532. Scope *scope = e->ImportName.scope;
  533. MUTEX_GUARD_BLOCK(scope->mutex) for_array(i, scope->elements.entries) {
  534. String name = scope->elements.entries[i].key.string;
  535. Entity *decl = scope->elements.entries[i].value;
  536. if (!is_entity_exported(decl)) continue;
  537. Entity *found = scope_insert_with_name(ctx->scope, name, decl);
  538. if (found != nullptr) {
  539. gbString expr_str = expr_to_string(expr);
  540. error(us->token,
  541. "Namespace collision while 'using' import name '%s' of: %.*s\n"
  542. "\tat %s\n"
  543. "\tat %s",
  544. expr_str, LIT(found->token.string),
  545. token_pos_to_string(found->token.pos),
  546. token_pos_to_string(decl->token.pos)
  547. );
  548. gb_string_free(expr_str);
  549. return false;
  550. }
  551. }
  552. break;
  553. }
  554. case Entity_Variable: {
  555. bool is_ptr = is_type_pointer(e->type);
  556. Type *t = base_type(type_deref(e->type));
  557. if (t->kind == Type_Struct) {
  558. Scope *found = t->Struct.scope;
  559. GB_ASSERT(found != nullptr);
  560. for_array(i, found->elements.entries) {
  561. Entity *f = found->elements.entries[i].value;
  562. if (f->kind == Entity_Variable) {
  563. Entity *uvar = alloc_entity_using_variable(e, f->token, f->type, expr);
  564. if (!is_ptr && e->flags & EntityFlag_Value) uvar->flags |= EntityFlag_Value;
  565. if (e->flags & EntityFlag_Param) uvar->flags |= EntityFlag_Param;
  566. Entity *prev = scope_insert(ctx->scope, uvar);
  567. if (prev != nullptr) {
  568. gbString expr_str = expr_to_string(expr);
  569. error(us->token, "Namespace collision while using '%s' of: '%.*s'", expr_str, LIT(prev->token.string));
  570. gb_string_free(expr_str);
  571. return false;
  572. }
  573. }
  574. }
  575. } else {
  576. error(us->token, "'using' can only be applied to variables of type 'struct'");
  577. return false;
  578. }
  579. break;
  580. }
  581. case Entity_Constant:
  582. error(us->token, "'using' cannot be applied to a constant");
  583. break;
  584. case Entity_Procedure:
  585. case Entity_ProcGroup:
  586. case Entity_Builtin:
  587. error(us->token, "'using' cannot be applied to a procedure");
  588. break;
  589. case Entity_Nil:
  590. error(us->token, "'using' cannot be applied to 'nil'");
  591. break;
  592. case Entity_Label:
  593. error(us->token, "'using' cannot be applied to a label");
  594. break;
  595. case Entity_Invalid:
  596. error(us->token, "'using' cannot be applied to an invalid entity");
  597. break;
  598. default:
  599. GB_PANIC("TODO(bill): 'using' other expressions?");
  600. }
  601. return true;
  602. }
  603. void check_inline_range_stmt(CheckerContext *ctx, Ast *node, u32 mod_flags) {
  604. ast_node(irs, UnrollRangeStmt, node);
  605. check_open_scope(ctx, node);
  606. Type *val0 = nullptr;
  607. Type *val1 = nullptr;
  608. Entity *entities[2] = {};
  609. isize entity_count = 0;
  610. Ast *expr = unparen_expr(irs->expr);
  611. ExactValue inline_for_depth = exact_value_i64(0);
  612. if (is_ast_range(expr)) {
  613. ast_node(ie, BinaryExpr, expr);
  614. Operand x = {};
  615. Operand y = {};
  616. bool ok = check_range(ctx, expr, &x, &y, &inline_for_depth);
  617. if (!ok) {
  618. goto skip_expr;
  619. }
  620. val0 = x.type;
  621. val1 = t_int;
  622. } else {
  623. Operand operand = {Addressing_Invalid};
  624. check_expr_or_type(ctx, &operand, irs->expr);
  625. if (operand.mode == Addressing_Type) {
  626. if (!is_type_enum(operand.type)) {
  627. gbString t = type_to_string(operand.type);
  628. error(operand.expr, "Cannot iterate over the type '%s'", t);
  629. gb_string_free(t);
  630. goto skip_expr;
  631. } else {
  632. val0 = operand.type;
  633. val1 = t_int;
  634. add_type_info_type(ctx, operand.type);
  635. Type *bt = base_type(operand.type);
  636. inline_for_depth = exact_value_i64(bt->Enum.fields.count);
  637. goto skip_expr;
  638. }
  639. } else if (operand.mode != Addressing_Invalid) {
  640. Type *t = base_type(operand.type);
  641. switch (t->kind) {
  642. case Type_Basic:
  643. if (is_type_string(t) && t->Basic.kind != Basic_cstring) {
  644. val0 = t_rune;
  645. val1 = t_int;
  646. inline_for_depth = exact_value_i64(operand.value.value_string.len);
  647. }
  648. break;
  649. case Type_Array:
  650. val0 = t->Array.elem;
  651. val1 = t_int;
  652. inline_for_depth = exact_value_i64(t->Array.count);
  653. break;
  654. case Type_EnumeratedArray:
  655. val0 = t->EnumeratedArray.elem;
  656. val1 = t->EnumeratedArray.index;
  657. inline_for_depth = exact_value_i64(t->EnumeratedArray.count);
  658. break;
  659. }
  660. }
  661. if (val0 == nullptr) {
  662. gbString s = expr_to_string(operand.expr);
  663. gbString t = type_to_string(operand.type);
  664. error(operand.expr, "Cannot iterate over '%s' of type '%s' in an '#unroll for' statement", s, t);
  665. gb_string_free(t);
  666. gb_string_free(s);
  667. } else if (operand.mode != Addressing_Constant) {
  668. error(operand.expr, "An '#unroll for' expression must be known at compile time");
  669. }
  670. }
  671. skip_expr:; // NOTE(zhiayang): again, declaring a variable immediately after a label... weird.
  672. Ast * lhs[2] = {irs->val0, irs->val1};
  673. Type *rhs[2] = {val0, val1};
  674. for (isize i = 0; i < 2; i++) {
  675. if (lhs[i] == nullptr) {
  676. continue;
  677. }
  678. Ast * name = lhs[i];
  679. Type *type = rhs[i];
  680. Entity *entity = nullptr;
  681. if (name->kind == Ast_Ident) {
  682. Token token = name->Ident.token;
  683. String str = token.string;
  684. Entity *found = nullptr;
  685. if (!is_blank_ident(str)) {
  686. found = scope_lookup_current(ctx->scope, str);
  687. }
  688. if (found == nullptr) {
  689. entity = alloc_entity_variable(ctx->scope, token, type, EntityState_Resolved);
  690. entity->flags |= EntityFlag_Value;
  691. add_entity_definition(&ctx->checker->info, name, entity);
  692. } else {
  693. TokenPos pos = found->token.pos;
  694. error(token,
  695. "Redeclaration of '%.*s' in this scope\n"
  696. "\tat %s", LIT(str), token_pos_to_string(pos));
  697. entity = found;
  698. }
  699. } else {
  700. error(name, "A variable declaration must be an identifier");
  701. }
  702. if (entity == nullptr) {
  703. entity = alloc_entity_dummy_variable(builtin_pkg->scope, ast_token(name));
  704. }
  705. entities[entity_count++] = entity;
  706. if (type == nullptr) {
  707. entity->type = t_invalid;
  708. entity->flags |= EntityFlag_Used;
  709. }
  710. }
  711. for (isize i = 0; i < entity_count; i++) {
  712. add_entity(ctx, ctx->scope, entities[i]->identifier, entities[i]);
  713. }
  714. // NOTE(bill): Minimize the amount of nesting of an '#unroll for'
  715. i64 prev_inline_for_depth = ctx->inline_for_depth;
  716. defer (ctx->inline_for_depth = prev_inline_for_depth);
  717. {
  718. i64 v = exact_value_to_i64(inline_for_depth);
  719. if (v <= 0) {
  720. // Do nothing
  721. } else {
  722. ctx->inline_for_depth = gb_max(ctx->inline_for_depth, 1) * v;
  723. }
  724. if (ctx->inline_for_depth >= MAX_INLINE_FOR_DEPTH && prev_inline_for_depth < MAX_INLINE_FOR_DEPTH) {
  725. if (prev_inline_for_depth > 0) {
  726. error(node, "Nested '#unroll for' loop cannot be inlined as it exceeds the maximum '#unroll for' depth (%lld levels >= %lld maximum levels)", v, MAX_INLINE_FOR_DEPTH);
  727. } else {
  728. error(node, "'#unroll for' loop cannot be inlined as it exceeds the maximum '#unroll for' depth (%lld levels >= %lld maximum levels)", v, MAX_INLINE_FOR_DEPTH);
  729. }
  730. error_line("\tUse a normal 'for' loop instead by removing the 'inline' prefix\n");
  731. ctx->inline_for_depth = MAX_INLINE_FOR_DEPTH;
  732. }
  733. }
  734. check_stmt(ctx, irs->body, mod_flags);
  735. check_close_scope(ctx);
  736. }
  737. void check_switch_stmt(CheckerContext *ctx, Ast *node, u32 mod_flags) {
  738. ast_node(ss, SwitchStmt, node);
  739. Operand x = {};
  740. mod_flags |= Stmt_BreakAllowed | Stmt_FallthroughAllowed;
  741. check_open_scope(ctx, node);
  742. defer (check_close_scope(ctx));
  743. check_label(ctx, ss->label, node); // TODO(bill): What should the label's "scope" be?
  744. if (ss->init != nullptr) {
  745. check_stmt(ctx, ss->init, 0);
  746. }
  747. if (ss->tag != nullptr) {
  748. check_expr(ctx, &x, ss->tag);
  749. check_assignment(ctx, &x, nullptr, str_lit("switch expression"));
  750. } else {
  751. x.mode = Addressing_Constant;
  752. x.type = t_bool;
  753. x.value = exact_value_bool(true);
  754. Token token = {};
  755. token.pos = ast_token(ss->body).pos;
  756. token.string = str_lit("true");
  757. x.expr = alloc_ast_node(nullptr, Ast_Ident);
  758. x.expr->Ident.token = token;
  759. }
  760. // NOTE(bill): Check for multiple defaults
  761. Ast *first_default = nullptr;
  762. ast_node(bs, BlockStmt, ss->body);
  763. for_array(i, bs->stmts) {
  764. Ast *stmt = bs->stmts[i];
  765. Ast *default_stmt = nullptr;
  766. if (stmt->kind == Ast_CaseClause) {
  767. ast_node(cc, CaseClause, stmt);
  768. if (cc->list.count == 0) {
  769. default_stmt = stmt;
  770. }
  771. } else {
  772. error(stmt, "Invalid AST - expected case clause");
  773. }
  774. if (default_stmt != nullptr) {
  775. if (first_default != nullptr) {
  776. TokenPos pos = ast_token(first_default).pos;
  777. error(stmt,
  778. "multiple default clauses\n"
  779. "\tfirst at %s", token_pos_to_string(pos));
  780. } else {
  781. first_default = default_stmt;
  782. }
  783. }
  784. }
  785. bool is_partial = ss->partial;
  786. if (is_partial) {
  787. if (!is_type_enum(x.type)) {
  788. error(x.expr, "#partial switch statement can be only used with an enum type");
  789. }
  790. }
  791. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  792. map_init(&seen, heap_allocator());
  793. defer (map_destroy(&seen));
  794. for_array(stmt_index, bs->stmts) {
  795. Ast *stmt = bs->stmts[stmt_index];
  796. if (stmt->kind != Ast_CaseClause) {
  797. // NOTE(bill): error handled by above multiple default checker
  798. continue;
  799. }
  800. ast_node(cc, CaseClause, stmt);
  801. for_array(j, cc->list) {
  802. Ast *expr = unparen_expr(cc->list[j]);
  803. if (is_ast_range(expr)) {
  804. ast_node(be, BinaryExpr, expr);
  805. Operand lhs = {};
  806. Operand rhs = {};
  807. check_expr_with_type_hint(ctx, &lhs, be->left, x.type);
  808. if (x.mode == Addressing_Invalid) {
  809. continue;
  810. }
  811. if (lhs.mode == Addressing_Invalid) {
  812. continue;
  813. }
  814. check_expr_with_type_hint(ctx, &rhs, be->right, x.type);
  815. if (rhs.mode == Addressing_Invalid) {
  816. continue;
  817. }
  818. if (!is_type_ordered(x.type)) {
  819. gbString str = type_to_string(x.type);
  820. error(expr, "Unordered type '%s', is invalid for an interval expression", str);
  821. gb_string_free(str);
  822. continue;
  823. }
  824. TokenKind upper_op = Token_Invalid;
  825. switch (be->op.kind) {
  826. case Token_Ellipsis: upper_op = Token_LtEq; break;
  827. case Token_RangeFull: upper_op = Token_LtEq; break;
  828. case Token_RangeHalf: upper_op = Token_Lt; break;
  829. default: GB_PANIC("Invalid range operator"); break;
  830. }
  831. Operand a = lhs;
  832. Operand b = rhs;
  833. check_comparison(ctx, &a, &x, Token_LtEq);
  834. if (a.mode == Addressing_Invalid) {
  835. continue;
  836. }
  837. check_comparison(ctx, &b, &x, upper_op);
  838. if (b.mode == Addressing_Invalid) {
  839. continue;
  840. }
  841. Operand a1 = lhs;
  842. Operand b1 = rhs;
  843. check_comparison(ctx, &a1, &b1, Token_LtEq);
  844. add_to_seen_map(ctx, &seen, upper_op, x, lhs, rhs);
  845. if (is_type_string(x.type)) {
  846. // NOTE(bill): Force dependency for strings here
  847. add_package_dependency(ctx, "runtime", "string_le");
  848. add_package_dependency(ctx, "runtime", "string_lt");
  849. }
  850. } else {
  851. Operand y = {};
  852. if (is_type_typeid(x.type)) {
  853. check_expr_or_type(ctx, &y, expr, x.type);
  854. } else {
  855. check_expr_with_type_hint(ctx, &y, expr, x.type);
  856. }
  857. if (x.mode == Addressing_Invalid ||
  858. y.mode == Addressing_Invalid) {
  859. continue;
  860. }
  861. if (y.mode == Addressing_Type) {
  862. Type *t = y.type;
  863. if (t == nullptr || t == t_invalid || is_type_polymorphic(t)) {
  864. error(y.expr, "Invalid type for case clause");
  865. continue;
  866. }
  867. t = default_type(t);
  868. add_type_info_type(ctx, t);
  869. } else {
  870. convert_to_typed(ctx, &y, x.type);
  871. if (y.mode == Addressing_Invalid) {
  872. continue;
  873. }
  874. // NOTE(bill): the ordering here matters
  875. Operand z = y;
  876. check_comparison(ctx, &z, &x, Token_CmpEq);
  877. if (z.mode == Addressing_Invalid) {
  878. continue;
  879. }
  880. if (y.mode != Addressing_Constant) {
  881. continue;
  882. }
  883. update_untyped_expr_type(ctx, z.expr, x.type, !is_type_untyped(x.type));
  884. add_to_seen_map(ctx, &seen, y);
  885. }
  886. }
  887. }
  888. check_open_scope(ctx, stmt);
  889. check_stmt_list(ctx, cc->stmts, mod_flags);
  890. check_close_scope(ctx);
  891. }
  892. if (!is_partial && is_type_enum(x.type)) {
  893. Type *et = base_type(x.type);
  894. GB_ASSERT(is_type_enum(et));
  895. auto fields = et->Enum.fields;
  896. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  897. for_array(i, fields) {
  898. Entity *f = fields[i];
  899. if (f->kind != Entity_Constant) {
  900. continue;
  901. }
  902. ExactValue v = f->Constant.value;
  903. auto found = map_get(&seen, hash_exact_value(v));
  904. if (!found) {
  905. array_add(&unhandled, f);
  906. }
  907. }
  908. if (unhandled.count > 0) {
  909. begin_error_block();
  910. defer (end_error_block());
  911. if (unhandled.count == 1) {
  912. error_no_newline(node, "Unhandled switch case: %.*s", LIT(unhandled[0]->token.string));
  913. } else {
  914. error(node, "Unhandled switch cases:");
  915. for_array(i, unhandled) {
  916. Entity *f = unhandled[i];
  917. error_line("\t%.*s\n", LIT(f->token.string));
  918. }
  919. }
  920. error_line("\n");
  921. error_line("\tSuggestion: Was '#partial switch' wanted?\n");
  922. }
  923. }
  924. }
  925. enum TypeSwitchKind {
  926. TypeSwitch_Invalid,
  927. TypeSwitch_Union,
  928. TypeSwitch_Any,
  929. };
  930. TypeSwitchKind check_valid_type_switch_type(Type *type) {
  931. type = type_deref(type);
  932. if (is_type_union(type)) {
  933. return TypeSwitch_Union;
  934. }
  935. if (is_type_any(type)) {
  936. return TypeSwitch_Any;
  937. }
  938. return TypeSwitch_Invalid;
  939. }
  940. void check_type_switch_stmt(CheckerContext *ctx, Ast *node, u32 mod_flags) {
  941. ast_node(ss, TypeSwitchStmt, node);
  942. Operand x = {};
  943. mod_flags |= Stmt_BreakAllowed | Stmt_TypeSwitch;
  944. check_open_scope(ctx, node);
  945. defer (check_close_scope(ctx));
  946. check_label(ctx, ss->label, node); // TODO(bill): What should the label's "scope" be?
  947. if (ss->tag->kind != Ast_AssignStmt) {
  948. error(ss->tag, "Expected an 'in' assignment for this type switch statement");
  949. return;
  950. }
  951. ast_node(as, AssignStmt, ss->tag);
  952. Token as_token = ast_token(ss->tag);
  953. if (as->lhs.count != 1) {
  954. syntax_error(as_token, "Expected 1 name before 'in'");
  955. return;
  956. }
  957. if (as->rhs.count != 1) {
  958. syntax_error(as_token, "Expected 1 expression after 'in'");
  959. return;
  960. }
  961. Ast *lhs = as->lhs[0];
  962. Ast *rhs = as->rhs[0];
  963. check_expr(ctx, &x, rhs);
  964. check_assignment(ctx, &x, nullptr, str_lit("type switch expression"));
  965. add_type_info_type(ctx, x.type);
  966. TypeSwitchKind switch_kind = check_valid_type_switch_type(x.type);
  967. if (switch_kind == TypeSwitch_Invalid) {
  968. gbString str = type_to_string(x.type);
  969. error(x.expr, "Invalid type for this type switch expression, got '%s'", str);
  970. gb_string_free(str);
  971. return;
  972. }
  973. bool is_partial = ss->partial;
  974. if (is_partial) {
  975. if (switch_kind != TypeSwitch_Union) {
  976. error(node, "#partial switch statement may only be used with a union");
  977. }
  978. }
  979. bool is_ptr = is_type_pointer(x.type);
  980. // NOTE(bill): Check for multiple defaults
  981. Ast *first_default = nullptr;
  982. ast_node(bs, BlockStmt, ss->body);
  983. for_array(i, bs->stmts) {
  984. Ast *stmt = bs->stmts[i];
  985. Ast *default_stmt = nullptr;
  986. if (stmt->kind == Ast_CaseClause) {
  987. ast_node(cc, CaseClause, stmt);
  988. if (cc->list.count == 0) {
  989. default_stmt = stmt;
  990. }
  991. } else {
  992. error(stmt, "Invalid AST - expected case clause");
  993. }
  994. if (default_stmt != nullptr) {
  995. if (first_default != nullptr) {
  996. TokenPos pos = ast_token(first_default).pos;
  997. error(stmt,
  998. "Multiple default clauses\n"
  999. "\tfirst at %s", token_pos_to_string(pos));
  1000. } else {
  1001. first_default = default_stmt;
  1002. }
  1003. }
  1004. }
  1005. if (lhs->kind != Ast_Ident) {
  1006. error(rhs, "Expected an identifier, got '%.*s'", LIT(ast_strings[rhs->kind]));
  1007. return;
  1008. }
  1009. PtrSet<Type *> seen = {};
  1010. ptr_set_init(&seen, heap_allocator());
  1011. defer (ptr_set_destroy(&seen));
  1012. for_array(i, bs->stmts) {
  1013. Ast *stmt = bs->stmts[i];
  1014. if (stmt->kind != Ast_CaseClause) {
  1015. // NOTE(bill): error handled by above multiple default checker
  1016. continue;
  1017. }
  1018. ast_node(cc, CaseClause, stmt);
  1019. // TODO(bill): Make robust
  1020. Type *bt = base_type(type_deref(x.type));
  1021. Type *case_type = nullptr;
  1022. for_array(type_index, cc->list) {
  1023. Ast *type_expr = cc->list[type_index];
  1024. if (type_expr != nullptr) { // Otherwise it's a default expression
  1025. Operand y = {};
  1026. check_expr_or_type(ctx, &y, type_expr);
  1027. if (y.mode != Addressing_Type) {
  1028. gbString str = expr_to_string(type_expr);
  1029. error(type_expr, "Expected a type as a case, got %s", str);
  1030. gb_string_free(str);
  1031. continue;
  1032. }
  1033. if (switch_kind == TypeSwitch_Union) {
  1034. GB_ASSERT(is_type_union(bt));
  1035. bool tag_type_found = false;
  1036. for_array(j, bt->Union.variants) {
  1037. Type *vt = bt->Union.variants[j];
  1038. if (are_types_identical(vt, y.type)) {
  1039. tag_type_found = true;
  1040. break;
  1041. }
  1042. }
  1043. if (!tag_type_found) {
  1044. gbString type_str = type_to_string(y.type);
  1045. error(y.expr, "Unknown variant type, got '%s'", type_str);
  1046. gb_string_free(type_str);
  1047. continue;
  1048. }
  1049. case_type = y.type;
  1050. add_type_info_type(ctx, y.type);
  1051. } else if (switch_kind == TypeSwitch_Any) {
  1052. case_type = y.type;
  1053. add_type_info_type(ctx, y.type);
  1054. } else {
  1055. GB_PANIC("Unknown type to type switch statement");
  1056. }
  1057. if (type_ptr_set_exists(&seen, y.type)) {
  1058. TokenPos pos = cc->token.pos;
  1059. gbString expr_str = expr_to_string(y.expr);
  1060. error(y.expr,
  1061. "Duplicate type case '%s'\n"
  1062. "\tprevious type case at %s",
  1063. expr_str,
  1064. token_pos_to_string(pos));
  1065. gb_string_free(expr_str);
  1066. break;
  1067. }
  1068. ptr_set_add(&seen, y.type);
  1069. }
  1070. }
  1071. bool is_reference = false;
  1072. if (is_ptr &&
  1073. cc->list.count == 1 &&
  1074. case_type != nullptr) {
  1075. is_reference = true;
  1076. }
  1077. if (cc->list.count > 1) {
  1078. case_type = nullptr;
  1079. }
  1080. if (case_type == nullptr) {
  1081. case_type = x.type;
  1082. }
  1083. add_type_info_type(ctx, case_type);
  1084. check_open_scope(ctx, stmt);
  1085. {
  1086. Entity *tag_var = alloc_entity_variable(ctx->scope, lhs->Ident.token, case_type, EntityState_Resolved);
  1087. tag_var->flags |= EntityFlag_Used;
  1088. if (!is_reference) {
  1089. tag_var->flags |= EntityFlag_Value;
  1090. tag_var->flags |= EntityFlag_SwitchValue;
  1091. }
  1092. add_entity(ctx, ctx->scope, lhs, tag_var);
  1093. add_entity_use(ctx, lhs, tag_var);
  1094. add_implicit_entity(ctx, stmt, tag_var);
  1095. }
  1096. check_stmt_list(ctx, cc->stmts, mod_flags);
  1097. check_close_scope(ctx);
  1098. }
  1099. if (!is_partial && is_type_union(type_deref(x.type))) {
  1100. Type *ut = base_type(type_deref(x.type));
  1101. GB_ASSERT(is_type_union(ut));
  1102. auto variants = ut->Union.variants;
  1103. auto unhandled = array_make<Type *>(temporary_allocator(), 0, variants.count);
  1104. for_array(i, variants) {
  1105. Type *t = variants[i];
  1106. if (!type_ptr_set_exists(&seen, t)) {
  1107. array_add(&unhandled, t);
  1108. }
  1109. }
  1110. if (unhandled.count > 0) {
  1111. if (unhandled.count == 1) {
  1112. gbString s = type_to_string(unhandled[0]);
  1113. error_no_newline(node, "Unhandled switch case: %s", s);
  1114. gb_string_free(s);
  1115. } else {
  1116. error_no_newline(node, "Unhandled switch cases:\n");
  1117. for_array(i, unhandled) {
  1118. Type *t = unhandled[i];
  1119. gbString s = type_to_string(t);
  1120. error_line("\t%s\n", s);
  1121. gb_string_free(s);
  1122. }
  1123. }
  1124. error_line("\n");
  1125. error_line("\tSuggestion: Was '#partial switch' wanted?\n");
  1126. }
  1127. }
  1128. }
  1129. void check_block_stmt_for_errors(CheckerContext *ctx, Ast *body) {
  1130. if (body->kind != Ast_BlockStmt) {
  1131. return;
  1132. }
  1133. ast_node(bs, BlockStmt, body);
  1134. // NOTE(bill, 2020-09-23): This logic is prevent common erros with block statements
  1135. // e.g. if cond { x := 123; } // this is an error
  1136. if (bs->scope != nullptr && bs->scope->elements.entries.count > 0) {
  1137. if (bs->scope->parent->node != nullptr) {
  1138. switch (bs->scope->parent->node->kind) {
  1139. case Ast_IfStmt:
  1140. case Ast_ForStmt:
  1141. case Ast_RangeStmt:
  1142. case Ast_UnrollRangeStmt:
  1143. case Ast_SwitchStmt:
  1144. case Ast_TypeSwitchStmt:
  1145. // TODO(bill): Is this a correct checking system?
  1146. break;
  1147. default:
  1148. return;
  1149. }
  1150. }
  1151. isize stmt_count = 0;
  1152. Ast *the_stmt = nullptr;
  1153. for_array(i, bs->stmts) {
  1154. Ast *stmt = bs->stmts[i];
  1155. GB_ASSERT(stmt != nullptr);
  1156. switch (stmt->kind) {
  1157. case_ast_node(es, EmptyStmt, stmt);
  1158. case_end;
  1159. case_ast_node(bs, BadStmt, stmt);
  1160. case_end;
  1161. case_ast_node(bd, BadDecl, stmt);
  1162. case_end;
  1163. default:
  1164. the_stmt = stmt;
  1165. stmt_count += 1;
  1166. break;
  1167. }
  1168. }
  1169. if (stmt_count == 1) {
  1170. if (the_stmt->kind == Ast_ValueDecl) {
  1171. for_array(i, the_stmt->ValueDecl.names) {
  1172. Ast *name = the_stmt->ValueDecl.names[i];
  1173. if (name->kind != Ast_Ident) {
  1174. continue;
  1175. }
  1176. String n = name->Ident.token.string;
  1177. if (n != "_") {
  1178. error(name, "'%.*s' declared but not used", LIT(n));
  1179. }
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. bool all_operands_valid(Array<Operand> const &operands) {
  1186. if (any_errors()) {
  1187. for_array(i, operands) {
  1188. if (operands[i].type == t_invalid) {
  1189. return false;
  1190. }
  1191. }
  1192. }
  1193. return true;
  1194. }
  1195. bool check_stmt_internal_builtin_proc_id(Ast *expr, BuiltinProcId *id_) {
  1196. BuiltinProcId id = BuiltinProc_Invalid;
  1197. Entity *e = entity_of_node(expr);
  1198. if (e != nullptr && e->kind == Entity_Builtin) {
  1199. if (e->Builtin.id && e->Builtin.id != BuiltinProc_DIRECTIVE) {
  1200. id = cast(BuiltinProcId)e->Builtin.id;
  1201. }
  1202. }
  1203. if (id_) *id_ = id;
  1204. return id != BuiltinProc_Invalid;
  1205. }
  1206. bool check_expr_is_stack_variable(Ast *expr) {
  1207. expr = unparen_expr(expr);
  1208. Entity *e = entity_of_node(expr);
  1209. if (e && e->kind == Entity_Variable) {
  1210. if (e->flags & (EntityFlag_Static|EntityFlag_Using|EntityFlag_ImplicitReference|EntityFlag_ForValue)) {
  1211. // okay
  1212. } else if (e->Variable.thread_local_model.len != 0) {
  1213. // okay
  1214. } else if (e->scope) {
  1215. if ((e->scope->flags & (ScopeFlag_Global|ScopeFlag_File|ScopeFlag_Type)) == 0) {
  1216. return true;
  1217. }
  1218. }
  1219. }
  1220. return false;
  1221. }
  1222. void check_stmt_internal(CheckerContext *ctx, Ast *node, u32 flags) {
  1223. u32 mod_flags = flags & (~Stmt_FallthroughAllowed);
  1224. switch (node->kind) {
  1225. case_ast_node(_, EmptyStmt, node); case_end;
  1226. case_ast_node(_, BadStmt, node); case_end;
  1227. case_ast_node(_, BadDecl, node); case_end;
  1228. case_ast_node(es, ExprStmt, node)
  1229. Operand operand = {Addressing_Invalid};
  1230. ExprKind kind = check_expr_base(ctx, &operand, es->expr, nullptr);
  1231. switch (operand.mode) {
  1232. case Addressing_Type: {
  1233. gbString str = type_to_string(operand.type);
  1234. error(node, "'%s' is not an expression", str);
  1235. gb_string_free(str);
  1236. break;
  1237. }
  1238. case Addressing_NoValue:
  1239. return;
  1240. default: {
  1241. if (kind == Expr_Stmt) {
  1242. return;
  1243. }
  1244. Ast *expr = strip_or_return_expr(operand.expr);
  1245. if (expr->kind == Ast_CallExpr) {
  1246. BuiltinProcId builtin_id = BuiltinProc_Invalid;
  1247. bool do_require = false;
  1248. AstCallExpr *ce = &expr->CallExpr;
  1249. Type *t = base_type(type_of_expr(ce->proc));
  1250. if (t->kind == Type_Proc) {
  1251. do_require = t->Proc.require_results;
  1252. } else if (check_stmt_internal_builtin_proc_id(ce->proc, &builtin_id)) {
  1253. auto const &bp = builtin_procs[builtin_id];
  1254. do_require = bp.kind == Expr_Expr && !bp.ignore_results;
  1255. }
  1256. if (do_require) {
  1257. gbString expr_str = expr_to_string(ce->proc);
  1258. error(node, "'%s' requires that its results must be handled", expr_str);
  1259. gb_string_free(expr_str);
  1260. }
  1261. return;
  1262. } else if (expr->kind == Ast_SelectorCallExpr) {
  1263. BuiltinProcId builtin_id = BuiltinProc_Invalid;
  1264. bool do_require = false;
  1265. AstSelectorCallExpr *se = &expr->SelectorCallExpr;
  1266. ast_node(ce, CallExpr, se->call);
  1267. Type *t = base_type(type_of_expr(ce->proc));
  1268. if (t == nullptr) {
  1269. gbString expr_str = expr_to_string(ce->proc);
  1270. error(node, "'%s' is not a value field nor procedure", expr_str);
  1271. gb_string_free(expr_str);
  1272. return;
  1273. }
  1274. if (t->kind == Type_Proc) {
  1275. do_require = t->Proc.require_results;
  1276. } else if (check_stmt_internal_builtin_proc_id(ce->proc, &builtin_id)) {
  1277. auto const &bp = builtin_procs[builtin_id];
  1278. do_require = bp.kind == Expr_Expr && !bp.ignore_results;
  1279. }
  1280. if (do_require) {
  1281. gbString expr_str = expr_to_string(ce->proc);
  1282. error(node, "'%s' requires that its results must be handled", expr_str);
  1283. gb_string_free(expr_str);
  1284. }
  1285. return;
  1286. }
  1287. gbString expr_str = expr_to_string(operand.expr);
  1288. error(node, "Expression is not used: '%s'", expr_str);
  1289. gb_string_free(expr_str);
  1290. if (operand.expr->kind == Ast_BinaryExpr) {
  1291. ast_node(be, BinaryExpr, operand.expr);
  1292. if (be->op.kind != Token_CmpEq) {
  1293. break;
  1294. }
  1295. switch (be->left->tav.mode) {
  1296. case Addressing_Context:
  1297. case Addressing_Variable:
  1298. case Addressing_MapIndex:
  1299. case Addressing_SoaVariable:
  1300. {
  1301. gbString lhs = expr_to_string(be->left);
  1302. gbString rhs = expr_to_string(be->right);
  1303. error_line("\tSuggestion: Did you mean to do an assignment?\n", lhs, rhs);
  1304. error_line("\t '%s = %s;'\n", lhs, rhs);
  1305. gb_string_free(rhs);
  1306. gb_string_free(lhs);
  1307. }
  1308. break;
  1309. }
  1310. }
  1311. break;
  1312. }
  1313. }
  1314. case_end;
  1315. case_ast_node(ts, TagStmt, node);
  1316. // TODO(bill): Tag Statements
  1317. error(node, "Tag statements are not supported yet");
  1318. check_stmt(ctx, ts->stmt, flags);
  1319. case_end;
  1320. case_ast_node(as, AssignStmt, node);
  1321. switch (as->op.kind) {
  1322. case Token_Eq: {
  1323. // a, b, c = 1, 2, 3; // Multisided
  1324. isize lhs_count = as->lhs.count;
  1325. if (lhs_count == 0) {
  1326. error(as->op, "Missing lhs in assignment statement");
  1327. return;
  1328. }
  1329. // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be
  1330. // an extra allocation
  1331. auto lhs_operands = array_make<Operand>(temporary_allocator(), lhs_count);
  1332. auto rhs_operands = array_make<Operand>(temporary_allocator(), 0, 2*lhs_count);
  1333. for_array(i, as->lhs) {
  1334. if (is_blank_ident(as->lhs[i])) {
  1335. Operand *o = &lhs_operands[i];
  1336. o->expr = as->lhs[i];
  1337. o->mode = Addressing_Value;
  1338. } else {
  1339. ctx->assignment_lhs_hint = unparen_expr(as->lhs[i]);
  1340. check_expr(ctx, &lhs_operands[i], as->lhs[i]);
  1341. }
  1342. }
  1343. ctx->assignment_lhs_hint = nullptr; // Reset the assignment_lhs_hint
  1344. check_assignment_arguments(ctx, lhs_operands, &rhs_operands, as->rhs);
  1345. isize rhs_count = rhs_operands.count;
  1346. for_array(i, rhs_operands) {
  1347. if (rhs_operands[i].mode == Addressing_Invalid) {
  1348. // TODO(bill): Should I ignore invalid parameters?
  1349. // rhs_count--;
  1350. }
  1351. }
  1352. auto lhs_to_ignore = array_make<bool>(temporary_allocator(), lhs_count);
  1353. isize max = gb_min(lhs_count, rhs_count);
  1354. for (isize i = 0; i < max; i++) {
  1355. if (lhs_to_ignore[i]) {
  1356. continue;
  1357. }
  1358. check_assignment_variable(ctx, &lhs_operands[i], &rhs_operands[i]);
  1359. }
  1360. if (lhs_count != rhs_count) {
  1361. error(as->lhs[0], "Assignment count mismatch '%td' = '%td'", lhs_count, rhs_count);
  1362. }
  1363. break;
  1364. }
  1365. default: {
  1366. // a += 1; // Single-sided
  1367. Token op = as->op;
  1368. if (as->lhs.count != 1 || as->rhs.count != 1) {
  1369. error(op, "Assignment operation '%.*s' requires single-valued expressions", LIT(op.string));
  1370. return;
  1371. }
  1372. if (!gb_is_between(op.kind, Token__AssignOpBegin+1, Token__AssignOpEnd-1)) {
  1373. error(op, "Unknown Assignment operation '%.*s'", LIT(op.string));
  1374. return;
  1375. }
  1376. Operand lhs = {Addressing_Invalid};
  1377. Operand rhs = {Addressing_Invalid};
  1378. Ast *binary_expr = alloc_ast_node(node->file(), Ast_BinaryExpr);
  1379. ast_node(be, BinaryExpr, binary_expr);
  1380. be->op = op;
  1381. be->op.kind = cast(TokenKind)(cast(i32)be->op.kind - (Token_AddEq - Token_Add));
  1382. // NOTE(bill): Only use the first one will be used
  1383. be->left = as->lhs[0];
  1384. be->right = as->rhs[0];
  1385. check_expr(ctx, &lhs, as->lhs[0]);
  1386. check_binary_expr(ctx, &rhs, binary_expr, nullptr, true);
  1387. if (rhs.mode == Addressing_Invalid) {
  1388. return;
  1389. }
  1390. // NOTE(bill): Only use the first one will be used
  1391. check_assignment_variable(ctx, &lhs, &rhs);
  1392. break;
  1393. }
  1394. }
  1395. case_end;
  1396. case_ast_node(bs, BlockStmt, node);
  1397. check_open_scope(ctx, node);
  1398. check_label(ctx, bs->label, node);
  1399. check_stmt_list(ctx, bs->stmts, flags);
  1400. check_block_stmt_for_errors(ctx, node);
  1401. check_close_scope(ctx);
  1402. case_end;
  1403. case_ast_node(is, IfStmt, node);
  1404. check_open_scope(ctx, node);
  1405. check_label(ctx, is->label, node);
  1406. if (is->init != nullptr) {
  1407. check_stmt(ctx, is->init, 0);
  1408. }
  1409. Operand operand = {Addressing_Invalid};
  1410. check_expr(ctx, &operand, is->cond);
  1411. if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) {
  1412. error(is->cond, "Non-boolean condition in 'if' statement");
  1413. }
  1414. check_stmt(ctx, is->body, mod_flags);
  1415. if (is->else_stmt != nullptr) {
  1416. switch (is->else_stmt->kind) {
  1417. case Ast_IfStmt:
  1418. case Ast_BlockStmt:
  1419. check_stmt(ctx, is->else_stmt, mod_flags);
  1420. break;
  1421. default:
  1422. error(is->else_stmt, "Invalid 'else' statement in 'if' statement");
  1423. break;
  1424. }
  1425. }
  1426. check_close_scope(ctx);
  1427. case_end;
  1428. case_ast_node(ws, WhenStmt, node);
  1429. check_when_stmt(ctx, ws, flags);
  1430. case_end;
  1431. case_ast_node(rs, ReturnStmt, node);
  1432. GB_ASSERT(ctx->curr_proc_sig != nullptr);
  1433. if (ctx->in_defer) {
  1434. error(rs->token, "'return' cannot be used within a defer statement");
  1435. break;
  1436. }
  1437. Type *proc_type = ctx->curr_proc_sig;
  1438. GB_ASSERT(proc_type != nullptr);
  1439. GB_ASSERT(proc_type->kind == Type_Proc);
  1440. TypeProc *pt = &proc_type->Proc;
  1441. if (pt->diverging) {
  1442. error(rs->token, "Diverging procedures may not return");
  1443. break;
  1444. }
  1445. Entity **result_entities = nullptr;
  1446. isize result_count = 0;
  1447. bool has_named_results = pt->has_named_results;
  1448. if (pt->results) {
  1449. result_entities = proc_type->Proc.results->Tuple.variables.data;
  1450. result_count = proc_type->Proc.results->Tuple.variables.count;
  1451. }
  1452. auto operands = array_make<Operand>(heap_allocator(), 0, 2*rs->results.count);
  1453. defer (array_free(&operands));
  1454. check_unpack_arguments(ctx, result_entities, result_count, &operands, rs->results, true, false);
  1455. if (result_count == 0 && rs->results.count > 0) {
  1456. error(rs->results[0], "No return values expected");
  1457. } else if (has_named_results && operands.count == 0) {
  1458. // Okay
  1459. } else if (operands.count != result_count) {
  1460. // Ignore error message as it has most likely already been reported
  1461. if (all_operands_valid(operands)) {
  1462. error(node, "Expected %td return values, got %td", result_count, operands.count);
  1463. }
  1464. } else {
  1465. for (isize i = 0; i < result_count; i++) {
  1466. Entity *e = pt->results->Tuple.variables[i];
  1467. Operand *o = &operands[i];
  1468. check_assignment(ctx, o, e->type, str_lit("return statement"));
  1469. if (is_type_untyped(o->type)) {
  1470. update_untyped_expr_type(ctx, o->expr, e->type, true);
  1471. }
  1472. // NOTE(bill): This is very basic escape analysis
  1473. // This needs to be improved tremendously, and a lot of it done during the
  1474. // middle-end (or LLVM side) to improve checks and error messages
  1475. Ast *expr = unparen_expr(o->expr);
  1476. if (expr->kind == Ast_UnaryExpr && expr->UnaryExpr.op.kind == Token_And) {
  1477. Ast *x = unparen_expr(expr->UnaryExpr.expr);
  1478. if (x->kind == Ast_CompoundLit) {
  1479. error(expr, "Cannot return the address to a stack value from a procedure");
  1480. } else if (x->kind == Ast_IndexExpr) {
  1481. Ast *array = x->IndexExpr.expr;
  1482. if (is_type_array_like(type_of_expr(array)) && check_expr_is_stack_variable(array)) {
  1483. gbString t = type_to_string(type_of_expr(array));
  1484. error(expr, "Cannot return the address to an element of stack variable from a procedure, of type %s", t);
  1485. gb_string_free(t);
  1486. }
  1487. } else {
  1488. if (check_expr_is_stack_variable(x)) {
  1489. error(expr, "Cannot return the address to a stack variable from a procedure");
  1490. }
  1491. }
  1492. }
  1493. }
  1494. }
  1495. case_end;
  1496. case_ast_node(fs, ForStmt, node);
  1497. u32 new_flags = mod_flags | Stmt_BreakAllowed | Stmt_ContinueAllowed;
  1498. check_open_scope(ctx, node);
  1499. check_label(ctx, fs->label, node); // TODO(bill): What should the label's "scope" be?
  1500. if (fs->init != nullptr) {
  1501. check_stmt(ctx, fs->init, 0);
  1502. }
  1503. if (fs->cond != nullptr) {
  1504. Operand o = {Addressing_Invalid};
  1505. check_expr(ctx, &o, fs->cond);
  1506. if (o.mode != Addressing_Invalid && !is_type_boolean(o.type)) {
  1507. error(fs->cond, "Non-boolean condition in 'for' statement");
  1508. }
  1509. }
  1510. if (fs->post != nullptr) {
  1511. check_stmt(ctx, fs->post, 0);
  1512. if (fs->post->kind != Ast_AssignStmt) {
  1513. error(fs->post, "'for' statement post statement must be a simple statement");
  1514. }
  1515. }
  1516. check_stmt(ctx, fs->body, new_flags);
  1517. check_close_scope(ctx);
  1518. case_end;
  1519. case_ast_node(rs, RangeStmt, node);
  1520. u32 new_flags = mod_flags | Stmt_BreakAllowed | Stmt_ContinueAllowed;
  1521. check_open_scope(ctx, node);
  1522. check_label(ctx, rs->label, node);
  1523. auto vals = array_make<Type *>(temporary_allocator(), 0, 2);
  1524. auto entities = array_make<Entity *>(temporary_allocator(), 0, 2);
  1525. bool is_map = false;
  1526. bool use_by_reference_for_value = false;
  1527. bool is_soa = false;
  1528. Ast *expr = unparen_expr(rs->expr);
  1529. isize max_val_count = 2;
  1530. if (is_ast_range(expr)) {
  1531. ast_node(ie, BinaryExpr, expr);
  1532. Operand x = {};
  1533. Operand y = {};
  1534. bool ok = check_range(ctx, expr, &x, &y, nullptr);
  1535. if (!ok) {
  1536. goto skip_expr_range_stmt;
  1537. }
  1538. array_add(&vals, x.type);
  1539. array_add(&vals, t_int);
  1540. } else {
  1541. Operand operand = {Addressing_Invalid};
  1542. check_expr_base(ctx, &operand, expr, nullptr);
  1543. error_operand_no_value(&operand);
  1544. if (operand.mode == Addressing_Type) {
  1545. if (!is_type_enum(operand.type)) {
  1546. gbString t = type_to_string(operand.type);
  1547. error(operand.expr, "Cannot iterate over the type '%s'", t);
  1548. gb_string_free(t);
  1549. goto skip_expr_range_stmt;
  1550. } else {
  1551. array_add(&vals, operand.type);
  1552. array_add(&vals, t_int);
  1553. add_type_info_type(ctx, operand.type);
  1554. goto skip_expr_range_stmt;
  1555. }
  1556. } else if (operand.mode != Addressing_Invalid) {
  1557. bool is_ptr = is_type_pointer(operand.type);
  1558. Type *t = base_type(type_deref(operand.type));
  1559. switch (t->kind) {
  1560. case Type_Basic:
  1561. if (is_type_string(t) && t->Basic.kind != Basic_cstring) {
  1562. array_add(&vals, t_rune);
  1563. array_add(&vals, t_int);
  1564. add_package_dependency(ctx, "runtime", "string_decode_rune");
  1565. }
  1566. break;
  1567. case Type_EnumeratedArray:
  1568. if (is_ptr) use_by_reference_for_value = true;
  1569. array_add(&vals, t->EnumeratedArray.elem);
  1570. array_add(&vals, t->EnumeratedArray.index);
  1571. break;
  1572. case Type_Array:
  1573. if (is_ptr) use_by_reference_for_value = true;
  1574. array_add(&vals, t->Array.elem);
  1575. array_add(&vals, t_int);
  1576. break;
  1577. case Type_DynamicArray:
  1578. if (is_ptr) use_by_reference_for_value = true;
  1579. array_add(&vals, t->DynamicArray.elem);
  1580. array_add(&vals, t_int);
  1581. break;
  1582. case Type_Slice:
  1583. if (is_ptr) use_by_reference_for_value = true;
  1584. array_add(&vals, t->Slice.elem);
  1585. array_add(&vals, t_int);
  1586. break;
  1587. case Type_Map:
  1588. if (is_ptr) use_by_reference_for_value = true;
  1589. is_map = true;
  1590. array_add(&vals, t->Map.key);
  1591. array_add(&vals, t->Map.value);
  1592. break;
  1593. case Type_Tuple:
  1594. {
  1595. isize count = t->Tuple.variables.count;
  1596. if (count < 1 || count > 3) {
  1597. check_not_tuple(ctx, &operand);
  1598. error_line("\tMultiple return valued parameters in a range statement are limited to a maximum of 2 usable values with a trailing boolean for the conditional\n");
  1599. break;
  1600. }
  1601. Type *cond_type = t->Tuple.variables[count-1]->type;
  1602. if (!is_type_boolean(cond_type)) {
  1603. gbString s = type_to_string(cond_type);
  1604. error(operand.expr, "The final type of %td-valued expression must be a boolean, got %s", count, s);
  1605. gb_string_free(s);
  1606. break;
  1607. }
  1608. for_array(ti, t->Tuple.variables) {
  1609. array_add(&vals, t->Tuple.variables[ti]->type);
  1610. }
  1611. if (rs->vals.count > 1 && rs->vals[1] != nullptr && count < 3) {
  1612. gbString s = type_to_string(t);
  1613. error(operand.expr, "Expected a 3-valued expression on the rhs, got (%s)", s);
  1614. gb_string_free(s);
  1615. break;
  1616. }
  1617. if (rs->vals.count > 0 && rs->vals[0] != nullptr && count < 2) {
  1618. gbString s = type_to_string(t);
  1619. error(operand.expr, "Expected at least a 2-valued expression on the rhs, got (%s)", s);
  1620. gb_string_free(s);
  1621. break;
  1622. }
  1623. }
  1624. break;
  1625. case Type_Struct:
  1626. if (t->Struct.soa_kind != StructSoa_None) {
  1627. is_soa = true;
  1628. if (is_ptr) use_by_reference_for_value = true;
  1629. array_add(&vals, t->Struct.soa_elem);
  1630. array_add(&vals, t_int);
  1631. }
  1632. break;
  1633. }
  1634. }
  1635. if (vals.count == 0 || vals[0] == nullptr) {
  1636. gbString s = expr_to_string(operand.expr);
  1637. gbString t = type_to_string(operand.type);
  1638. defer (gb_string_free(s));
  1639. defer (gb_string_free(t));
  1640. error(operand.expr, "Cannot iterate over '%s' of type '%s'", s, t);
  1641. if (rs->vals.count == 1) {
  1642. Type *t = type_deref(operand.type);
  1643. if (is_type_map(t) || is_type_bit_set(t)) {
  1644. gbString v = expr_to_string(rs->vals[0]);
  1645. defer (gb_string_free(v));
  1646. error_line("\tSuggestion: place parentheses around the expression\n");
  1647. error_line("\t for (%s in %s) {\n", v, s);
  1648. }
  1649. }
  1650. }
  1651. }
  1652. skip_expr_range_stmt:; // NOTE(zhiayang): again, declaring a variable immediately after a label... weird.
  1653. if (rs->vals.count > max_val_count) {
  1654. error(rs->vals[max_val_count], "Expected a maximum of %td identifier%s, got %td", max_val_count, max_val_count == 1 ? "" : "s", rs->vals.count);
  1655. }
  1656. auto rhs = slice_from_array(vals);
  1657. auto lhs = slice_make<Ast *>(temporary_allocator(), rhs.count);
  1658. slice_copy(&lhs, rs->vals);
  1659. isize addressable_index = cast(isize)is_map;
  1660. for_array(i, rhs) {
  1661. if (lhs[i] == nullptr) {
  1662. continue;
  1663. }
  1664. Ast * name = lhs[i];
  1665. Type *type = rhs[i];
  1666. Entity *entity = nullptr;
  1667. if (name->kind == Ast_Ident) {
  1668. Token token = name->Ident.token;
  1669. String str = token.string;
  1670. Entity *found = nullptr;
  1671. if (!is_blank_ident(str)) {
  1672. found = scope_lookup_current(ctx->scope, str);
  1673. }
  1674. if (found == nullptr) {
  1675. entity = alloc_entity_variable(ctx->scope, token, type, EntityState_Resolved);
  1676. entity->flags |= EntityFlag_ForValue;
  1677. entity->flags |= EntityFlag_Value;
  1678. if (i == addressable_index && use_by_reference_for_value) {
  1679. entity->flags &= ~EntityFlag_Value;
  1680. }
  1681. if (is_soa) {
  1682. if (i == 0) {
  1683. entity->flags |= EntityFlag_SoaPtrField;
  1684. }
  1685. }
  1686. add_entity_definition(&ctx->checker->info, name, entity);
  1687. } else {
  1688. TokenPos pos = found->token.pos;
  1689. error(token,
  1690. "Redeclaration of '%.*s' in this scope\n"
  1691. "\tat %s",
  1692. LIT(str), token_pos_to_string(pos));
  1693. entity = found;
  1694. }
  1695. } else {
  1696. error(name, "A variable declaration must be an identifier");
  1697. }
  1698. if (entity == nullptr) {
  1699. entity = alloc_entity_dummy_variable(builtin_pkg->scope, ast_token(name));
  1700. }
  1701. array_add(&entities, entity);
  1702. if (type == nullptr) {
  1703. entity->type = t_invalid;
  1704. entity->flags |= EntityFlag_Used;
  1705. }
  1706. }
  1707. for_array(i, entities) {
  1708. Entity *e = entities[i];
  1709. DeclInfo *d = decl_info_of_entity(e);
  1710. GB_ASSERT(d == nullptr);
  1711. add_entity(ctx, ctx->scope, e->identifier, e);
  1712. d = make_decl_info(ctx->scope, ctx->decl);
  1713. add_entity_and_decl_info(ctx, e->identifier, e, d);
  1714. }
  1715. check_stmt(ctx, rs->body, new_flags);
  1716. check_close_scope(ctx);
  1717. case_end;
  1718. case_ast_node(irs, UnrollRangeStmt, node);
  1719. check_inline_range_stmt(ctx, node, mod_flags);
  1720. case_end;
  1721. case_ast_node(ss, SwitchStmt, node);
  1722. check_switch_stmt(ctx, node, mod_flags);
  1723. case_end;
  1724. case_ast_node(ss, TypeSwitchStmt, node);
  1725. check_type_switch_stmt(ctx, node, mod_flags);
  1726. case_end;
  1727. case_ast_node(ds, DeferStmt, node);
  1728. if (is_ast_decl(ds->stmt)) {
  1729. error(ds->token, "You cannot defer a declaration");
  1730. } else {
  1731. bool out_in_defer = ctx->in_defer;
  1732. ctx->in_defer = true;
  1733. check_stmt(ctx, ds->stmt, 0);
  1734. ctx->in_defer = out_in_defer;
  1735. }
  1736. case_end;
  1737. case_ast_node(bs, BranchStmt, node);
  1738. Token token = bs->token;
  1739. switch (token.kind) {
  1740. case Token_break:
  1741. if ((flags & Stmt_BreakAllowed) == 0 && bs->label == nullptr) {
  1742. error(token, "'break' only allowed in non-inline loops or 'switch' statements");
  1743. }
  1744. break;
  1745. case Token_continue:
  1746. if ((flags & Stmt_ContinueAllowed) == 0 && bs->label == nullptr) {
  1747. error(token, "'continue' only allowed in non-inline loops");
  1748. }
  1749. break;
  1750. case Token_fallthrough:
  1751. if ((flags & Stmt_FallthroughAllowed) == 0) {
  1752. if ((flags & Stmt_TypeSwitch) != 0) {
  1753. error(token, "'fallthrough' statement not allowed within a type switch statement");
  1754. } else {
  1755. error(token, "'fallthrough' statement in illegal position, expected at the end of a 'case' block");
  1756. }
  1757. } else if (bs->label != nullptr) {
  1758. error(token, "'fallthrough' cannot have a label");
  1759. }
  1760. break;
  1761. default:
  1762. error(token, "Invalid AST: Branch Statement '%.*s'", LIT(token.string));
  1763. break;
  1764. }
  1765. if (bs->label != nullptr) {
  1766. if (bs->label->kind != Ast_Ident) {
  1767. error(bs->label, "A branch statement's label name must be an identifier");
  1768. return;
  1769. }
  1770. Ast *ident = bs->label;
  1771. String name = ident->Ident.token.string;
  1772. Operand o = {};
  1773. Entity *e = check_ident(ctx, &o, ident, nullptr, nullptr, false);
  1774. if (e == nullptr) {
  1775. error(ident, "Undeclared label name: %.*s", LIT(name));
  1776. return;
  1777. }
  1778. add_entity_use(ctx, ident, e);
  1779. if (e->kind != Entity_Label) {
  1780. error(ident, "'%.*s' is not a label", LIT(name));
  1781. return;
  1782. }
  1783. Ast *parent = e->Label.parent;
  1784. GB_ASSERT(parent != nullptr);
  1785. switch (parent->kind) {
  1786. case Ast_BlockStmt:
  1787. case Ast_IfStmt:
  1788. case Ast_SwitchStmt:
  1789. if (token.kind != Token_break) {
  1790. error(bs->label, "Label '%.*s' can only be used with 'break'", LIT(e->token.string));
  1791. }
  1792. break;
  1793. case Ast_RangeStmt:
  1794. case Ast_ForStmt:
  1795. if ((token.kind != Token_break) && (token.kind != Token_continue)) {
  1796. error(bs->label, "Label '%.*s' can only be used with 'break' and 'continue'", LIT(e->token.string));
  1797. }
  1798. break;
  1799. }
  1800. }
  1801. case_end;
  1802. case_ast_node(us, UsingStmt, node);
  1803. if (us->list.count == 0) {
  1804. error(us->token, "Empty 'using' list");
  1805. return;
  1806. }
  1807. for_array(i, us->list) {
  1808. Ast *expr = unparen_expr(us->list[i]);
  1809. Entity *e = nullptr;
  1810. bool is_selector = false;
  1811. Operand o = {};
  1812. switch (expr->kind) {
  1813. case Ast_Ident:
  1814. e = check_ident(ctx, &o, expr, nullptr, nullptr, true);
  1815. break;
  1816. case Ast_SelectorExpr:
  1817. e = check_selector(ctx, &o, expr, nullptr);
  1818. is_selector = true;
  1819. break;
  1820. case Ast_Implicit:
  1821. error(us->token, "'using' applied to an implicit value");
  1822. continue;
  1823. default:
  1824. error(us->token, "'using' can only be applied to an entity, got %.*s", LIT(ast_strings[expr->kind]));
  1825. continue;
  1826. }
  1827. if (!check_using_stmt_entity(ctx, us, expr, is_selector, e)) {
  1828. return;
  1829. }
  1830. }
  1831. case_end;
  1832. case_ast_node(fb, ForeignBlockDecl, node);
  1833. Ast *foreign_library = fb->foreign_library;
  1834. CheckerContext c = *ctx;
  1835. if (foreign_library->kind != Ast_Ident) {
  1836. error(foreign_library, "foreign library name must be an identifier");
  1837. } else {
  1838. c.foreign_context.curr_library = foreign_library;
  1839. c.foreign_context.default_cc = ProcCC_CDecl;
  1840. }
  1841. check_decl_attributes(&c, fb->attributes, foreign_block_decl_attribute, nullptr);
  1842. ast_node(block, BlockStmt, fb->body);
  1843. for_array(i, block->stmts) {
  1844. Ast *decl = block->stmts[i];
  1845. if (decl->kind == Ast_ValueDecl && decl->ValueDecl.is_mutable) {
  1846. check_stmt(&c, decl, flags);
  1847. }
  1848. }
  1849. case_end;
  1850. case_ast_node(vd, ValueDecl, node);
  1851. if (vd->is_mutable) {
  1852. Entity **entities = gb_alloc_array(permanent_allocator(), Entity *, vd->names.count);
  1853. isize entity_count = 0;
  1854. isize new_name_count = 0;
  1855. for_array(i, vd->names) {
  1856. Ast *name = vd->names[i];
  1857. Entity *entity = nullptr;
  1858. if (name->kind != Ast_Ident) {
  1859. error(name, "A variable declaration must be an identifier");
  1860. } else {
  1861. Token token = name->Ident.token;
  1862. String str = token.string;
  1863. Entity *found = nullptr;
  1864. // NOTE(bill): Ignore assignments to '_'
  1865. if (!is_blank_ident(str)) {
  1866. found = scope_lookup_current(ctx->scope, str);
  1867. new_name_count += 1;
  1868. }
  1869. if (found == nullptr) {
  1870. entity = alloc_entity_variable(ctx->scope, token, nullptr);
  1871. entity->identifier = name;
  1872. Ast *fl = ctx->foreign_context.curr_library;
  1873. if (fl != nullptr) {
  1874. GB_ASSERT(fl->kind == Ast_Ident);
  1875. entity->Variable.is_foreign = true;
  1876. entity->Variable.foreign_library_ident = fl;
  1877. }
  1878. } else {
  1879. TokenPos pos = found->token.pos;
  1880. error(token,
  1881. "Redeclaration of '%.*s' in this scope\n"
  1882. "\tat %s",
  1883. LIT(str), token_pos_to_string(pos));
  1884. entity = found;
  1885. }
  1886. }
  1887. if (entity == nullptr) {
  1888. entity = alloc_entity_dummy_variable(builtin_pkg->scope, ast_token(name));
  1889. }
  1890. entity->parent_proc_decl = ctx->curr_proc_decl;
  1891. entities[entity_count++] = entity;
  1892. if (name->kind == Ast_Ident) {
  1893. name->Ident.entity = entity;
  1894. }
  1895. }
  1896. if (new_name_count == 0) {
  1897. begin_error_block();
  1898. error(node, "No new declarations on the left hand side");
  1899. bool all_underscore = true;
  1900. for_array(i, vd->names) {
  1901. Ast *name = vd->names[i];
  1902. if (name->kind == Ast_Ident) {
  1903. if (!is_blank_ident(name)) {
  1904. all_underscore = false;
  1905. break;
  1906. }
  1907. } else {
  1908. all_underscore = false;
  1909. break;
  1910. }
  1911. }
  1912. if (all_underscore) {
  1913. error_line("\tSuggestion: Try changing the declaration (:=) to an assignment (=)\n");
  1914. }
  1915. end_error_block();
  1916. }
  1917. Type *init_type = nullptr;
  1918. if (vd->type != nullptr) {
  1919. init_type = check_type(ctx, vd->type);
  1920. if (init_type == nullptr) {
  1921. init_type = t_invalid;
  1922. } else if (is_type_polymorphic(base_type(init_type))) {
  1923. gbString str = type_to_string(init_type);
  1924. error(vd->type, "Invalid use of a polymorphic type '%s' in variable declaration", str);
  1925. gb_string_free(str);
  1926. init_type = t_invalid;
  1927. }
  1928. }
  1929. // TODO NOTE(bill): This technically checks things multple times
  1930. AttributeContext ac = make_attribute_context(ctx->foreign_context.link_prefix);
  1931. check_decl_attributes(ctx, vd->attributes, var_decl_attribute, &ac);
  1932. for (isize i = 0; i < entity_count; i++) {
  1933. Entity *e = entities[i];
  1934. GB_ASSERT(e != nullptr);
  1935. if (e->flags & EntityFlag_Visited) {
  1936. e->type = t_invalid;
  1937. continue;
  1938. }
  1939. e->flags |= EntityFlag_Visited;
  1940. e->state = EntityState_InProgress;
  1941. if (e->type == nullptr) {
  1942. e->type = init_type;
  1943. e->state = EntityState_Resolved;
  1944. }
  1945. ac.link_name = handle_link_name(ctx, e->token, ac.link_name, ac.link_prefix);
  1946. if (ac.link_name.len > 0) {
  1947. e->Variable.link_name = ac.link_name;
  1948. }
  1949. e->flags &= ~EntityFlag_Static;
  1950. if (ac.is_static) {
  1951. String name = e->token.string;
  1952. if (name == "_") {
  1953. error(e->token, "The 'static' attribute is not allowed to be applied to '_'");
  1954. } else {
  1955. e->flags |= EntityFlag_Static;
  1956. if (ctx->in_defer) {
  1957. error(e->token, "'static' variables cannot be declared within a defer statement");
  1958. }
  1959. }
  1960. }
  1961. if (ac.thread_local_model != "") {
  1962. String name = e->token.string;
  1963. if (name == "_") {
  1964. error(e->token, "The 'thread_local' attribute is not allowed to be applied to '_'");
  1965. } else {
  1966. e->flags |= EntityFlag_Static;
  1967. if (ctx->in_defer) {
  1968. error(e->token, "'thread_local' variables cannot be declared within a defer statement");
  1969. }
  1970. }
  1971. e->Variable.thread_local_model = ac.thread_local_model;
  1972. }
  1973. if (is_arch_wasm() && e->Variable.thread_local_model.len != 0) {
  1974. error(e->token, "@(thread_local) is not supported for this target platform");
  1975. }
  1976. if (ac.is_static && ac.thread_local_model != "") {
  1977. error(e->token, "The 'static' attribute is not needed if 'thread_local' is applied");
  1978. }
  1979. }
  1980. check_init_variables(ctx, entities, entity_count, vd->values, str_lit("variable declaration"));
  1981. check_arity_match(ctx, vd, false);
  1982. for (isize i = 0; i < entity_count; i++) {
  1983. Entity *e = entities[i];
  1984. if (e->Variable.is_foreign) {
  1985. if (vd->values.count > 0) {
  1986. error(e->token, "A foreign variable declaration cannot have a default value");
  1987. }
  1988. String name = e->token.string;
  1989. if (e->Variable.link_name.len > 0) {
  1990. name = e->Variable.link_name;
  1991. }
  1992. if (vd->values.count > 0) {
  1993. error(e->token, "A foreign variable declaration cannot have a default value");
  1994. }
  1995. init_entity_foreign_library(ctx, e);
  1996. auto *fp = &ctx->checker->info.foreigns;
  1997. StringHashKey key = string_hash_string(name);
  1998. Entity **found = string_map_get(fp, key);
  1999. if (found) {
  2000. Entity *f = *found;
  2001. TokenPos pos = f->token.pos;
  2002. Type *this_type = base_type(e->type);
  2003. Type *other_type = base_type(f->type);
  2004. if (!are_types_identical(this_type, other_type)) {
  2005. error(e->token,
  2006. "Foreign entity '%.*s' previously declared elsewhere with a different type\n"
  2007. "\tat %s",
  2008. LIT(name), token_pos_to_string(pos));
  2009. }
  2010. } else {
  2011. string_map_set(fp, key, e);
  2012. }
  2013. } else if (e->flags & EntityFlag_Static) {
  2014. if (vd->values.count > 0) {
  2015. if (entity_count != vd->values.count) {
  2016. error(e->token, "A static variable declaration with a default value must be constant");
  2017. } else {
  2018. Ast *value = vd->values[i];
  2019. if (value->tav.mode != Addressing_Constant) {
  2020. error(e->token, "A static variable declaration with a default value must be constant");
  2021. }
  2022. }
  2023. }
  2024. }
  2025. add_entity(ctx, ctx->scope, e->identifier, e);
  2026. }
  2027. if (vd->is_using != 0) {
  2028. Token token = ast_token(node);
  2029. if (vd->type != nullptr && entity_count > 1) {
  2030. error(token, "'using' can only be applied to one variable of the same type");
  2031. // TODO(bill): Should a 'continue' happen here?
  2032. }
  2033. for (isize entity_index = 0; entity_index < 1; entity_index++) {
  2034. Entity *e = entities[entity_index];
  2035. if (e == nullptr) {
  2036. continue;
  2037. }
  2038. if (e->kind != Entity_Variable) {
  2039. continue;
  2040. }
  2041. String name = e->token.string;
  2042. Type *t = base_type(type_deref(e->type));
  2043. if (is_blank_ident(name)) {
  2044. error(token, "'using' cannot be applied variable declared as '_'");
  2045. } else if (is_type_struct(t) || is_type_raw_union(t)) {
  2046. ERROR_BLOCK();
  2047. Scope *scope = t->Struct.scope;
  2048. GB_ASSERT(scope != nullptr);
  2049. for_array(i, scope->elements.entries) {
  2050. Entity *f = scope->elements.entries[i].value;
  2051. if (f->kind == Entity_Variable) {
  2052. Entity *uvar = alloc_entity_using_variable(e, f->token, f->type, nullptr);
  2053. uvar->flags |= (e->flags & EntityFlag_Value);
  2054. Entity *prev = scope_insert(ctx->scope, uvar);
  2055. if (prev != nullptr) {
  2056. error(token, "Namespace collision while 'using' '%.*s' of: %.*s", LIT(name), LIT(prev->token.string));
  2057. return;
  2058. }
  2059. }
  2060. }
  2061. add_entity_use(ctx, nullptr, e);
  2062. } else {
  2063. // NOTE(bill): skip the rest to remove extra errors
  2064. error(token, "'using' can only be applied to variables of type struct or raw_union");
  2065. return;
  2066. }
  2067. }
  2068. }
  2069. } else {
  2070. // constant value declaration
  2071. // NOTE(bill): Check `_` declarations
  2072. for_array(i, vd->names) {
  2073. Ast *name = vd->names[i];
  2074. if (is_blank_ident(name)) {
  2075. Entity *e = name->Ident.entity;
  2076. DeclInfo *d = decl_info_of_entity(e);
  2077. if (d != nullptr) {
  2078. check_entity_decl(ctx, e, d, nullptr);
  2079. }
  2080. }
  2081. }
  2082. }
  2083. case_end;
  2084. }
  2085. }