check_decl.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. gb_internal void check_stmt(CheckerContext *ctx, Ast *node, u32 flags);
  2. // NOTE(bill): 'content_name' is for debugging and error messages
  3. gb_internal Type *check_init_variable(CheckerContext *ctx, Entity *e, Operand *operand, String context_name) {
  4. if (operand->mode == Addressing_Invalid ||
  5. operand->type == t_invalid ||
  6. e->type == t_invalid) {
  7. if (operand->mode == Addressing_Builtin) {
  8. ERROR_BLOCK();
  9. gbString expr_str = expr_to_string(operand->expr);
  10. error(operand->expr,
  11. "Cannot assign built-in procedure '%s' in %.*s",
  12. expr_str,
  13. LIT(context_name));
  14. error_line("\tBuilt-in procedures are implemented by the compiler and might not be actually instantiated procedure\n");
  15. operand->mode = Addressing_Invalid;
  16. gb_string_free(expr_str);
  17. }
  18. if (operand->mode == Addressing_ProcGroup) {
  19. if (e->type == nullptr) {
  20. error(operand->expr, "Cannot determine type from overloaded procedure '%.*s'", LIT(operand->proc_group->token.string));
  21. } else {
  22. check_assignment(ctx, operand, e->type, str_lit("variable assignment"));
  23. if (operand->mode != Addressing_Type) {
  24. return operand->type;
  25. }
  26. }
  27. }
  28. if (e->type == nullptr) {
  29. e->type = t_invalid;
  30. }
  31. return nullptr;
  32. }
  33. if (e->kind == Entity_Variable) {
  34. e->Variable.init_expr = operand->expr;
  35. }
  36. if (operand->mode == Addressing_Type) {
  37. if (e->type != nullptr && is_type_typeid(e->type) && !is_type_polymorphic(operand->type)) {
  38. add_type_info_type(ctx, operand->type);
  39. add_type_and_value(ctx, operand->expr, Addressing_Value, e->type, exact_value_typeid(operand->type));
  40. return e->type;
  41. } else {
  42. ERROR_BLOCK();
  43. gbString t = type_to_string(operand->type);
  44. defer (gb_string_free(t));
  45. if (is_type_polymorphic(operand->type)) {
  46. error(operand->expr, "Cannot assign a non-specialized polymorphic type '%s' to variable '%.*s'", t, LIT(e->token.string));
  47. } else {
  48. error(operand->expr, "Cannot assign a type '%s' to variable '%.*s'", t, LIT(e->token.string));
  49. }
  50. if (e->type == nullptr) {
  51. error_line("\tThe type of the variable '%.*s' cannot be inferred as a type does not have a default type\n", LIT(e->token.string));
  52. }
  53. e->type = operand->type;
  54. return nullptr;
  55. }
  56. }
  57. if (e->type == nullptr) {
  58. // NOTE(bill): Use the type of the operand
  59. Type *t = operand->type;
  60. if (is_type_untyped(t)) {
  61. if (is_type_untyped_uninit(t)) {
  62. error(e->token, "Invalid use of --- in %.*s", LIT(context_name));
  63. e->type = t_invalid;
  64. return nullptr;
  65. } else if (t == t_invalid || is_type_untyped_nil(t)) {
  66. error(e->token, "Invalid use of untyped nil in %.*s", LIT(context_name));
  67. e->type = t_invalid;
  68. return nullptr;
  69. }
  70. t = default_type(t);
  71. }
  72. if (is_type_asm_proc(t)) {
  73. error(e->token, "Invalid use of inline asm in %.*s", LIT(context_name));
  74. e->type = t_invalid;
  75. return nullptr;
  76. } else if (is_type_polymorphic(t)) {
  77. gbString str = type_to_string(t);
  78. defer (gb_string_free(str));
  79. error(e->token, "Invalid use of a polymorphic type '%s' in %.*s", str, LIT(context_name));
  80. e->type = t_invalid;
  81. return nullptr;
  82. } else if (is_type_empty_union(t)) {
  83. gbString str = type_to_string(t);
  84. defer (gb_string_free(str));
  85. error(e->token, "An empty union '%s' cannot be instantiated in %.*s", str, LIT(context_name));
  86. e->type = t_invalid;
  87. return nullptr;
  88. }
  89. GB_ASSERT(is_type_typed(t));
  90. e->type = t;
  91. }
  92. e->parent_proc_decl = ctx->curr_proc_decl;
  93. check_assignment(ctx, operand, e->type, context_name);
  94. if (operand->mode == Addressing_Invalid) {
  95. return nullptr;
  96. }
  97. return e->type;
  98. }
  99. gb_internal void check_init_variables(CheckerContext *ctx, Entity **lhs, isize lhs_count, Slice<Ast *> const &inits, String context_name) {
  100. if ((lhs == nullptr || lhs_count == 0) && inits.count == 0) {
  101. return;
  102. }
  103. // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be
  104. // an extra allocation
  105. TEMPORARY_ALLOCATOR_GUARD();
  106. auto operands = array_make<Operand>(temporary_allocator(), 0, 2*lhs_count);
  107. check_unpack_arguments(ctx, lhs, lhs_count, &operands, inits, UnpackFlag_AllowOk|UnpackFlag_AllowUndef);
  108. isize rhs_count = operands.count;
  109. isize max = gb_min(lhs_count, rhs_count);
  110. for (isize i = 0; i < max; i++) {
  111. Entity *e = lhs[i];
  112. DeclInfo *d = decl_info_of_entity(e);
  113. Operand *o = &operands[i];
  114. check_init_variable(ctx, e, o, context_name);
  115. if (d != nullptr) {
  116. d->init_expr = o->expr;
  117. }
  118. if (o->type && is_type_no_copy(o->type)) {
  119. begin_error_block();
  120. if (check_no_copy_assignment(*o, str_lit("initialization"))) {
  121. error_line("\tInitialization of a #no_copy type must be either implicitly zero, a constant literal, or a return value from a call expression");
  122. }
  123. end_error_block();
  124. }
  125. }
  126. if (rhs_count > 0 && lhs_count != rhs_count) {
  127. error(lhs[0]->token, "Assignment count mismatch '%td' = '%td'", lhs_count, rhs_count);
  128. }
  129. }
  130. gb_internal void check_init_constant(CheckerContext *ctx, Entity *e, Operand *operand) {
  131. if (operand->mode == Addressing_Invalid ||
  132. operand->type == t_invalid ||
  133. e->type == t_invalid) {
  134. if (e->type == nullptr) {
  135. e->type = t_invalid;
  136. }
  137. return;
  138. }
  139. if (operand->mode != Addressing_Constant) {
  140. gbString str = expr_to_string(operand->expr);
  141. error(operand->expr, "'%s' is not a compile-time known constant", str);
  142. gb_string_free(str);
  143. if (e->type == nullptr) {
  144. e->type = t_invalid;
  145. }
  146. return;
  147. }
  148. if (e->type == nullptr) { // NOTE(bill): type inference
  149. e->type = operand->type;
  150. }
  151. check_assignment(ctx, operand, e->type, str_lit("constant declaration"));
  152. if (operand->mode == Addressing_Invalid) {
  153. return;
  154. }
  155. if (is_type_proc(e->type)) {
  156. error(e->token, "Illegal declaration of a constant procedure value");
  157. }
  158. e->parent_proc_decl = ctx->curr_proc_decl;
  159. e->Constant.value = operand->value;
  160. }
  161. gb_internal bool is_type_distinct(Ast *node) {
  162. for (;;) {
  163. if (node == nullptr) {
  164. return false;
  165. }
  166. if (node->kind == Ast_ParenExpr) {
  167. node = node->ParenExpr.expr;
  168. } else if (node->kind == Ast_HelperType) {
  169. node = node->HelperType.type;
  170. } else {
  171. break;
  172. }
  173. }
  174. switch (node->kind) {
  175. case Ast_DistinctType:
  176. return true;
  177. case Ast_StructType:
  178. case Ast_UnionType:
  179. case Ast_EnumType:
  180. case Ast_ProcType:
  181. return true;
  182. case Ast_PointerType:
  183. case Ast_ArrayType:
  184. case Ast_DynamicArrayType:
  185. case Ast_MapType:
  186. return false;
  187. }
  188. return false;
  189. }
  190. gb_internal Ast *remove_type_alias_clutter(Ast *node) {
  191. for (;;) {
  192. if (node == nullptr) {
  193. return nullptr;
  194. }
  195. if (node->kind == Ast_ParenExpr) {
  196. node = node->ParenExpr.expr;
  197. } else if (node->kind == Ast_DistinctType) {
  198. node = node->DistinctType.type;
  199. } else {
  200. return node;
  201. }
  202. }
  203. }
  204. gb_internal Type *clone_enum_type(CheckerContext *ctx, Type *original_enum_type, Type *named_type) {
  205. // NOTE(bill, 2022-02-05): Stupid edge case for `distinct` declarations
  206. //
  207. // X :: enum {A, B, C}
  208. // Y :: distinct X
  209. //
  210. // To make Y be just like X, it will need to copy the elements of X and change their type
  211. // so that they match Y rather than X.
  212. GB_ASSERT(original_enum_type != nullptr);
  213. GB_ASSERT(named_type != nullptr);
  214. GB_ASSERT(original_enum_type->kind == Type_Enum);
  215. GB_ASSERT(named_type->kind == Type_Named);
  216. Scope *parent = original_enum_type->Enum.scope->parent;
  217. Scope *scope = create_scope(nullptr, parent);
  218. Type *et = alloc_type_enum();
  219. et->Enum.base_type = original_enum_type->Enum.base_type;
  220. et->Enum.min_value = original_enum_type->Enum.min_value;
  221. et->Enum.max_value = original_enum_type->Enum.max_value;
  222. et->Enum.min_value_index = original_enum_type->Enum.min_value_index;
  223. et->Enum.max_value_index = original_enum_type->Enum.max_value_index;
  224. et->Enum.scope = scope;
  225. auto fields = array_make<Entity *>(permanent_allocator(), original_enum_type->Enum.fields.count);
  226. for_array(i, fields) {
  227. Entity *old = original_enum_type->Enum.fields[i];
  228. Entity *e = alloc_entity_constant(scope, old->token, named_type, old->Constant.value);
  229. e->file = old->file;
  230. e->identifier = clone_ast(old->identifier);
  231. e->flags |= EntityFlag_Visited;
  232. e->state = EntityState_Resolved;
  233. e->Constant.flags = old->Constant.flags;
  234. e->Constant.docs = old->Constant.docs;
  235. e->Constant.comment = old->Constant.comment;
  236. fields[i] = e;
  237. add_entity(ctx, scope, nullptr, e);
  238. add_entity_use(ctx, e->identifier, e);
  239. }
  240. et->Enum.fields = fields;
  241. return et;
  242. }
  243. gb_internal void check_type_decl(CheckerContext *ctx, Entity *e, Ast *init_expr, Type *def) {
  244. GB_ASSERT(e->type == nullptr);
  245. DeclInfo *decl = decl_info_of_entity(e);
  246. bool is_distinct = is_type_distinct(init_expr);
  247. Ast *te = remove_type_alias_clutter(init_expr);
  248. e->type = t_invalid;
  249. String name = e->token.string;
  250. Type *named = alloc_type_named(name, nullptr, e);
  251. if (def != nullptr && def->kind == Type_Named) {
  252. def->Named.base = named;
  253. }
  254. e->type = named;
  255. check_type_path_push(ctx, e);
  256. Type *bt = check_type_expr(ctx, te, named);
  257. check_type_path_pop(ctx);
  258. Type *base = base_type(bt);
  259. if (is_distinct && bt->kind == Type_Named && base->kind == Type_Enum) {
  260. base = clone_enum_type(ctx, base, named);
  261. }
  262. named->Named.base = base;
  263. if (is_distinct) {
  264. if (is_type_typeid(e->type)) {
  265. error(init_expr, "'distinct' cannot be applied to 'typeid'");
  266. is_distinct = false;
  267. } else if (is_type_any(e->type)) {
  268. error(init_expr, "'distinct' cannot be applied to 'any'");
  269. is_distinct = false;
  270. } else if (is_type_simd_vector(e->type) || is_type_soa_pointer(e->type)) {
  271. gbString str = type_to_string(e->type);
  272. error(init_expr, "'distinct' cannot be applied to '%s'", str);
  273. gb_string_free(str);
  274. is_distinct = false;
  275. }
  276. } else {
  277. if (is_type_typeid(e->type)) {
  278. error(init_expr, "'typeid' cannot be aliased");
  279. } else if (is_type_any(e->type)) {
  280. error(init_expr, "'any' cannot be aliased");
  281. }
  282. }
  283. if (!is_distinct) {
  284. e->type = bt;
  285. named->Named.base = bt;
  286. e->TypeName.is_type_alias = true;
  287. }
  288. if (decl->type_expr != nullptr) {
  289. Type *t = check_type(ctx, decl->type_expr);
  290. if (t != nullptr && !is_type_typeid(t)) {
  291. Operand operand = {};
  292. operand.mode = Addressing_Type;
  293. operand.type = e->type;
  294. operand.expr = init_expr;
  295. check_assignment(ctx, &operand, t, str_lit("constant declaration"));
  296. }
  297. }
  298. if (decl != nullptr) {
  299. AttributeContext ac = {};
  300. check_decl_attributes(ctx, decl->attributes, type_decl_attribute, &ac);
  301. if (e->kind == Entity_TypeName && ac.objc_class != "") {
  302. e->TypeName.objc_class_name = ac.objc_class;
  303. if (type_size_of(e->type) > 0) {
  304. error(e->token, "@(objc_class) marked type must be of zero size");
  305. }
  306. }
  307. }
  308. // using decl
  309. if (decl->is_using) {
  310. error(init_expr, "'using' an enum declaration is not allowed, prefer using implicit selector expressions e.g. '.A'");
  311. }
  312. }
  313. gb_internal void override_entity_in_scope(Entity *original_entity, Entity *new_entity) {
  314. // NOTE(bill): The original_entity's scope may not be same scope that it was inserted into
  315. // e.g. file entity inserted into its package scope
  316. String original_name = original_entity->token.string;
  317. Scope *found_scope = nullptr;
  318. Entity *found_entity = nullptr;
  319. scope_lookup_parent(original_entity->scope, original_name, &found_scope, &found_entity);
  320. if (found_scope == nullptr) {
  321. return;
  322. }
  323. rw_mutex_lock(&found_scope->mutex);
  324. defer (rw_mutex_unlock(&found_scope->mutex));
  325. // IMPORTANT NOTE(bill, 2021-04-10): Overriding behaviour was flawed in that the
  326. // original entity was still used check checked, but the checking was only
  327. // relying on "constant" data such as the Entity.type and Entity.Constant.value
  328. //
  329. // Therefore two things can be done: the type can be assigned to state that it
  330. // has been "evaluated" and the variant data can be copied across
  331. string_map_set(&found_scope->elements, original_name, new_entity);
  332. original_entity->flags |= EntityFlag_Overridden;
  333. original_entity->type = new_entity->type;
  334. original_entity->aliased_of = new_entity;
  335. Ast *empty_ident = nullptr;
  336. original_entity->identifier.compare_exchange_strong(empty_ident, new_entity->identifier);
  337. if (original_entity->identifier.load() != nullptr &&
  338. original_entity->identifier.load()->kind == Ast_Ident) {
  339. original_entity->identifier.load()->Ident.entity = new_entity;
  340. }
  341. // IMPORTANT NOTE(bill, 2021-04-10): copy only the variants
  342. // This is most likely NEVER required, but it does not at all hurt to keep
  343. isize offset = cast(u8 *)&original_entity->Dummy.start - cast(u8 *)original_entity;
  344. isize size = gb_size_of(*original_entity) - offset;
  345. gb_memmove(cast(u8 *)original_entity, cast(u8 *)new_entity, size);
  346. }
  347. gb_internal void check_const_decl(CheckerContext *ctx, Entity *e, Ast *type_expr, Ast *init, Type *named_type) {
  348. GB_ASSERT(e->type == nullptr);
  349. GB_ASSERT(e->kind == Entity_Constant);
  350. init = unparen_expr(init);
  351. if (e->flags & EntityFlag_Visited) {
  352. e->type = t_invalid;
  353. return;
  354. }
  355. e->flags |= EntityFlag_Visited;
  356. if (type_expr) {
  357. e->type = check_type(ctx, type_expr);
  358. if (are_types_identical(e->type, t_typeid)) {
  359. e->type = nullptr;
  360. e->kind = Entity_TypeName;
  361. check_type_decl(ctx, e, init, named_type);
  362. return;
  363. }
  364. }
  365. Operand operand = {};
  366. if (init != nullptr) {
  367. Entity *entity = check_entity_from_ident_or_selector(ctx, init, false);
  368. if (entity != nullptr && entity->kind == Entity_TypeName) {
  369. // @TypeAliasingProblem
  370. // NOTE(bill, 2022-02-03): This is used to solve the problem caused by type aliases
  371. // being "confused" as constants
  372. //
  373. // A :: B
  374. // C :: proc "c" (^A)
  375. // B :: struct {x: C}
  376. //
  377. // A gets evaluated first, and then checks B.
  378. // B then checks C.
  379. // C then tries to check A which is unresolved but thought to be a constant.
  380. // Therefore within C's check, A errs as "not a type".
  381. //
  382. // This is because a const declaration may or may not be a type and this cannot
  383. // be determined from a syntactical standpoint.
  384. // This check allows the compiler to override the entity to be checked as a type.
  385. //
  386. // There is no problem if B is prefixed with the `#type` helper enforcing at
  387. // both a syntax and semantic level that B must be a type.
  388. //
  389. // A :: #type B
  390. //
  391. // This approach is not fool proof and can fail in case such as:
  392. //
  393. // X :: type_of(x)
  394. // X :: Foo(int).Type
  395. //
  396. // Since even these kind of declarations may cause weird checking cycles.
  397. // For the time being, these are going to be treated as an unfortunate error
  398. // until there is a proper delaying system to try declaration again if they
  399. // have failed.
  400. e->kind = Entity_TypeName;
  401. check_type_decl(ctx, e, init, named_type);
  402. return;
  403. }
  404. entity = nullptr;
  405. if (init->kind == Ast_Ident) {
  406. entity = check_ident(ctx, &operand, init, nullptr, e->type, true);
  407. } else if (init->kind == Ast_SelectorExpr) {
  408. entity = check_selector(ctx, &operand, init, e->type);
  409. } else {
  410. check_expr_or_type(ctx, &operand, init, e->type);
  411. }
  412. switch (operand.mode) {
  413. case Addressing_Type: {
  414. if (e->type != nullptr && !is_type_typeid(e->type)) {
  415. check_assignment(ctx, &operand, e->type, str_lit("constant declaration"));
  416. }
  417. e->kind = Entity_TypeName;
  418. e->type = nullptr;
  419. if (entity != nullptr && entity->type != nullptr &&
  420. is_type_polymorphic_record_unspecialized(entity->type)) {
  421. DeclInfo *decl = decl_info_of_entity(e);
  422. if (decl != nullptr) {
  423. if (decl->attributes.count > 0) {
  424. error(decl->attributes[0], "Constant alias declarations cannot have attributes");
  425. }
  426. }
  427. override_entity_in_scope(e, entity);
  428. return;
  429. }
  430. check_type_decl(ctx, e, ctx->decl->init_expr, named_type);
  431. return;
  432. }
  433. // NOTE(bill): Check to see if the expression it to be aliases
  434. case Addressing_Builtin:
  435. if (e->type != nullptr) {
  436. error(type_expr, "A constant alias of a built-in procedure may not have a type initializer");
  437. }
  438. e->kind = Entity_Builtin;
  439. e->Builtin.id = operand.builtin_id;
  440. e->type = t_invalid;
  441. return;
  442. case Addressing_ProcGroup:
  443. GB_ASSERT(operand.proc_group != nullptr);
  444. GB_ASSERT(operand.proc_group->kind == Entity_ProcGroup);
  445. // NOTE(bill, 2020-06-10): It is better to just clone the contents than overriding the entity in the scope
  446. // Thank goodness I made entities a tagged union to allow for this implace patching
  447. e->kind = Entity_ProcGroup;
  448. e->ProcGroup.entities = array_clone(heap_allocator(), operand.proc_group->ProcGroup.entities);
  449. return;
  450. }
  451. if (entity != nullptr) {
  452. if (e->type != nullptr) {
  453. Operand x = {};
  454. x.type = entity->type;
  455. x.mode = Addressing_Variable;
  456. if (!check_is_assignable_to(ctx, &x, e->type)) {
  457. gbString expr_str = expr_to_string(init);
  458. gbString op_type_str = type_to_string(entity->type);
  459. gbString type_str = type_to_string(e->type);
  460. error(e->token,
  461. "Cannot assign '%s' of type '%s' to '%s'",
  462. expr_str,
  463. op_type_str,
  464. type_str);
  465. gb_string_free(type_str);
  466. gb_string_free(op_type_str);
  467. gb_string_free(expr_str);
  468. }
  469. }
  470. // NOTE(bill): Override aliased entity
  471. switch (entity->kind) {
  472. case Entity_ProcGroup:
  473. case Entity_Procedure:
  474. case Entity_LibraryName:
  475. case Entity_ImportName:
  476. {
  477. DeclInfo *decl = decl_info_of_entity(e);
  478. if (decl != nullptr) {
  479. if (decl->attributes.count > 0) {
  480. error(decl->attributes[0], "Constant alias declarations cannot have attributes");
  481. }
  482. }
  483. override_entity_in_scope(e, entity);
  484. return;
  485. }
  486. }
  487. }
  488. }
  489. check_init_constant(ctx, e, &operand);
  490. if (operand.mode == Addressing_Invalid ||
  491. base_type(operand.type) == t_invalid) {
  492. gbString str = expr_to_string(init);
  493. error(init, "Invalid declaration value '%s'", str);
  494. gb_string_free(str);
  495. }
  496. DeclInfo *decl = decl_info_of_entity(e);
  497. if (decl != nullptr) {
  498. check_decl_attributes(ctx, decl->attributes, const_decl_attribute, nullptr);
  499. }
  500. }
  501. typedef bool TypeCheckSig(Type *t);
  502. gb_internal bool sig_compare(TypeCheckSig *a, Type *x, Type *y) {
  503. x = core_type(x);
  504. y = core_type(y);
  505. return (a(x) && a(y));
  506. }
  507. gb_internal bool sig_compare(TypeCheckSig *a, TypeCheckSig *b, Type *x, Type *y) {
  508. x = core_type(x);
  509. y = core_type(y);
  510. if (a == b) {
  511. return sig_compare(a, x, y);
  512. }
  513. return ((a(x) && b(y)) || (b(x) && a(y)));
  514. }
  515. gb_internal bool signature_parameter_similar_enough(Type *x, Type *y) {
  516. if (sig_compare(is_type_pointer, x, y)) {
  517. return true;
  518. }
  519. if (sig_compare(is_type_multi_pointer, x, y)) {
  520. return true;
  521. }
  522. if (sig_compare(is_type_proc, x, y)) {
  523. return true;
  524. }
  525. if (sig_compare(is_type_integer, x, y)) {
  526. GB_ASSERT(core_type(x)->kind == Type_Basic);
  527. GB_ASSERT(core_type(y)->kind == Type_Basic);
  528. i64 sx = type_size_of(x);
  529. i64 sy = type_size_of(y);
  530. if (sx == sy) return true;
  531. }
  532. if (sig_compare(is_type_integer, is_type_boolean, x, y)) {
  533. GB_ASSERT(core_type(x)->kind == Type_Basic);
  534. GB_ASSERT(core_type(y)->kind == Type_Basic);
  535. i64 sx = type_size_of(x);
  536. i64 sy = type_size_of(y);
  537. if (sx == sy) return true;
  538. }
  539. if (sig_compare(is_type_cstring, is_type_u8_ptr, x, y)) {
  540. return true;
  541. }
  542. if (sig_compare(is_type_cstring, is_type_u8_multi_ptr, x, y)) {
  543. return true;
  544. }
  545. if (sig_compare(is_type_uintptr, is_type_rawptr, x, y)) {
  546. return true;
  547. }
  548. if (sig_compare(is_type_proc, is_type_pointer, x, y)) {
  549. return true;
  550. }
  551. if (sig_compare(is_type_pointer, is_type_multi_pointer, x, y)) {
  552. return true;
  553. }
  554. if (sig_compare(is_type_proc, is_type_multi_pointer, x, y)) {
  555. return true;
  556. }
  557. return are_types_identical(x, y);
  558. }
  559. gb_internal bool are_signatures_similar_enough(Type *a_, Type *b_) {
  560. GB_ASSERT(a_->kind == Type_Proc);
  561. GB_ASSERT(b_->kind == Type_Proc);
  562. TypeProc *a = &a_->Proc;
  563. TypeProc *b = &b_->Proc;
  564. if (a->param_count != b->param_count) {
  565. return false;
  566. }
  567. if (a->result_count != b->result_count) {
  568. return false;
  569. }
  570. for (isize i = 0; i < a->param_count; i++) {
  571. Type *x = core_type(a->params->Tuple.variables[i]->type);
  572. Type *y = core_type(b->params->Tuple.variables[i]->type);
  573. if (!signature_parameter_similar_enough(x, y)) {
  574. return false;
  575. }
  576. }
  577. for (isize i = 0; i < a->result_count; i++) {
  578. Type *x = base_type(a->results->Tuple.variables[i]->type);
  579. Type *y = base_type(b->results->Tuple.variables[i]->type);
  580. if (!signature_parameter_similar_enough(x, y)) {
  581. return false;
  582. }
  583. }
  584. return true;
  585. }
  586. gb_internal Entity *init_entity_foreign_library(CheckerContext *ctx, Entity *e) {
  587. Ast *ident = nullptr;
  588. Entity **foreign_library = nullptr;
  589. switch (e->kind) {
  590. case Entity_Procedure:
  591. ident = e->Procedure.foreign_library_ident;
  592. foreign_library = &e->Procedure.foreign_library;
  593. break;
  594. case Entity_Variable:
  595. ident = e->Variable.foreign_library_ident;
  596. foreign_library = &e->Variable.foreign_library;
  597. break;
  598. default:
  599. return nullptr;
  600. }
  601. if (ident == nullptr) {
  602. error(e->token, "foreign entiies must declare which library they are from");
  603. } else if (ident->kind != Ast_Ident) {
  604. error(ident, "foreign library names must be an identifier");
  605. } else {
  606. String name = ident->Ident.token.string;
  607. Entity *found = scope_lookup(ctx->scope, name);
  608. if (found == nullptr) {
  609. if (is_blank_ident(name)) {
  610. // NOTE(bill): link against nothing
  611. } else {
  612. error(ident, "Undeclared name: %.*s", LIT(name));
  613. }
  614. } else if (found->kind != Entity_LibraryName) {
  615. error(ident, "'%.*s' cannot be used as a library name", LIT(name));
  616. } else {
  617. // TODO(bill): Extra stuff to do with library names?
  618. *foreign_library = found;
  619. found->flags |= EntityFlag_Used;
  620. add_entity_use(ctx, ident, found);
  621. return found;
  622. }
  623. }
  624. return nullptr;
  625. }
  626. gb_internal String handle_link_name(CheckerContext *ctx, Token token, String link_name, String link_prefix) {
  627. if (link_prefix.len > 0) {
  628. if (link_name.len > 0) {
  629. error(token, "'link_name' and 'link_prefix' cannot be used together");
  630. } else {
  631. isize len = link_prefix.len + token.string.len;
  632. u8 *name = gb_alloc_array(permanent_allocator(), u8, len+1);
  633. gb_memmove(name, &link_prefix[0], link_prefix.len);
  634. gb_memmove(name+link_prefix.len, &token.string[0], token.string.len);
  635. name[len] = 0;
  636. link_name = make_string(name, len);
  637. }
  638. }
  639. return link_name;
  640. }
  641. gb_internal void check_objc_methods(CheckerContext *ctx, Entity *e, AttributeContext const &ac) {
  642. if (!(ac.objc_name.len || ac.objc_is_class_method || ac.objc_type)) {
  643. return;
  644. }
  645. if (ac.objc_name.len == 0 && ac.objc_is_class_method) {
  646. error(e->token, "@(objc_name) is required with @(objc_is_class_method)");
  647. } else if (ac.objc_type == nullptr) {
  648. error(e->token, "@(objc_name) requires that @(objc_type) to be set");
  649. } else if (ac.objc_name.len == 0 && ac.objc_type) {
  650. error(e->token, "@(objc_name) is required with @(objc_type)");
  651. } else {
  652. Type *t = ac.objc_type;
  653. if (t->kind == Type_Named) {
  654. Entity *tn = t->Named.type_name;
  655. GB_ASSERT(tn->kind == Entity_TypeName);
  656. if (tn->scope != e->scope) {
  657. error(e->token, "@(objc_name) attribute may only be applied to procedures and types within the same scope");
  658. } else {
  659. mutex_lock(&global_type_name_objc_metadata_mutex);
  660. defer (mutex_unlock(&global_type_name_objc_metadata_mutex));
  661. if (!tn->TypeName.objc_metadata) {
  662. tn->TypeName.objc_metadata = create_type_name_obj_c_metadata();
  663. }
  664. auto *md = tn->TypeName.objc_metadata;
  665. mutex_lock(md->mutex);
  666. defer (mutex_unlock(md->mutex));
  667. if (!ac.objc_is_class_method) {
  668. bool ok = true;
  669. for (TypeNameObjCMetadataEntry const &entry : md->value_entries) {
  670. if (entry.name == ac.objc_name) {
  671. error(e->token, "Previous declaration of @(objc_name=\"%.*s\")", LIT(ac.objc_name));
  672. ok = false;
  673. break;
  674. }
  675. }
  676. if (ok) {
  677. array_add(&md->value_entries, TypeNameObjCMetadataEntry{ac.objc_name, e});
  678. }
  679. } else {
  680. bool ok = true;
  681. for (TypeNameObjCMetadataEntry const &entry : md->type_entries) {
  682. if (entry.name == ac.objc_name) {
  683. error(e->token, "Previous declaration of @(objc_name=\"%.*s\")", LIT(ac.objc_name));
  684. ok = false;
  685. break;
  686. }
  687. }
  688. if (ok) {
  689. array_add(&md->type_entries, TypeNameObjCMetadataEntry{ac.objc_name, e});
  690. }
  691. }
  692. }
  693. }
  694. }
  695. }
  696. gb_internal void check_proc_decl(CheckerContext *ctx, Entity *e, DeclInfo *d) {
  697. GB_ASSERT(e->type == nullptr);
  698. if (d->proc_lit->kind != Ast_ProcLit) {
  699. // TOOD(bill): Better error message
  700. error(d->proc_lit, "Expected a procedure to check");
  701. return;
  702. }
  703. Type *proc_type = e->type;
  704. if (d->gen_proc_type != nullptr) {
  705. proc_type = d->gen_proc_type;
  706. } else {
  707. proc_type = alloc_type_proc(e->scope, nullptr, 0, nullptr, 0, false, default_calling_convention());
  708. }
  709. e->type = proc_type;
  710. ast_node(pl, ProcLit, d->proc_lit);
  711. check_open_scope(ctx, pl->type);
  712. defer (check_close_scope(ctx));
  713. ctx->scope->procedure_entity = e;
  714. Type *decl_type = nullptr;
  715. if (d->type_expr != nullptr) {
  716. decl_type = check_type(ctx, d->type_expr);
  717. if (!is_type_proc(decl_type)) {
  718. gbString str = type_to_string(decl_type);
  719. error(d->type_expr, "Expected a procedure type, got '%s'", str);
  720. gb_string_free(str);
  721. }
  722. }
  723. auto tmp_ctx = *ctx;
  724. tmp_ctx.allow_polymorphic_types = true;
  725. if (decl_type != nullptr) {
  726. tmp_ctx.type_hint = decl_type;
  727. }
  728. check_procedure_type(&tmp_ctx, proc_type, pl->type);
  729. if (decl_type != nullptr) {
  730. Operand x = {};
  731. x.type = e->type;
  732. x.mode = Addressing_Variable;
  733. if (!check_is_assignable_to(ctx, &x, decl_type)) {
  734. gbString expr_str = expr_to_string(d->proc_lit);
  735. gbString op_type_str = type_to_string(e->type);
  736. gbString type_str = type_to_string(decl_type);
  737. error(e->token,
  738. "Cannot assign '%s' of type '%s' to '%s'",
  739. expr_str,
  740. op_type_str,
  741. type_str);
  742. gb_string_free(type_str);
  743. gb_string_free(op_type_str);
  744. gb_string_free(expr_str);
  745. }
  746. }
  747. TypeProc *pt = &proc_type->Proc;
  748. AttributeContext ac = make_attribute_context(e->Procedure.link_prefix);
  749. if (d != nullptr) {
  750. check_decl_attributes(ctx, d->attributes, proc_decl_attribute, &ac);
  751. }
  752. if (ac.test) {
  753. e->flags |= EntityFlag_Test;
  754. }
  755. if (ac.init && ac.fini) {
  756. error(e->token, "A procedure cannot be both declared as @(init) and @(fini)");
  757. } else if (ac.init) {
  758. e->flags |= EntityFlag_Init;
  759. } else if (ac.fini) {
  760. e->flags |= EntityFlag_Fini;
  761. }
  762. if (ac.set_cold) {
  763. e->flags |= EntityFlag_Cold;
  764. }
  765. e->Procedure.optimization_mode = cast(ProcedureOptimizationMode)ac.optimization_mode;
  766. check_objc_methods(ctx, e, ac);
  767. if (ac.require_target_feature.len != 0 && ac.enable_target_feature.len != 0) {
  768. error(e->token, "Attributes @(require_target_feature=...) and @(enable_target_feature=...) cannot be used together");
  769. } else if (ac.require_target_feature.len != 0) {
  770. if (check_target_feature_is_enabled(e->token.pos, ac.require_target_feature)) {
  771. e->Procedure.target_feature = ac.require_target_feature;
  772. } else {
  773. e->Procedure.target_feature_disabled = true;
  774. }
  775. } else if (ac.enable_target_feature.len != 0) {
  776. enable_target_feature(e->token.pos, ac.enable_target_feature);
  777. e->Procedure.target_feature = ac.enable_target_feature;
  778. }
  779. switch (e->Procedure.optimization_mode) {
  780. case ProcedureOptimizationMode_None:
  781. case ProcedureOptimizationMode_Minimal:
  782. if (pl->inlining == ProcInlining_inline) {
  783. error(e->token, "#force_inline cannot be used in conjunction with the attribute 'optimization_mode' with neither \"none\" nor \"minimal\"");
  784. }
  785. break;
  786. }
  787. e->Procedure.is_export = ac.is_export;
  788. e->deprecated_message = ac.deprecated_message;
  789. e->warning_message = ac.warning_message;
  790. ac.link_name = handle_link_name(ctx, e->token, ac.link_name, ac.link_prefix);
  791. if (ac.has_disabled_proc) {
  792. if (ac.disabled_proc) {
  793. e->flags |= EntityFlag_Disabled;
  794. }
  795. Type *t = base_type(e->type);
  796. GB_ASSERT(t->kind == Type_Proc);
  797. if (t->Proc.result_count != 0) {
  798. error(e->token, "Procedure with the 'disabled' attribute may not have any return values");
  799. }
  800. }
  801. bool is_foreign = e->Procedure.is_foreign;
  802. bool is_export = e->Procedure.is_export;
  803. if (ac.linkage.len != 0) {
  804. if (ac.linkage == "internal") { e->flags |= EntityFlag_CustomLinkage_Internal; }
  805. else if (ac.linkage == "strong") { e->flags |= EntityFlag_CustomLinkage_Strong; }
  806. else if (ac.linkage == "weak") { e->flags |= EntityFlag_CustomLinkage_Weak; }
  807. else if (ac.linkage == "link_once") { e->flags |= EntityFlag_CustomLinkage_LinkOnce; }
  808. if (is_foreign && (e->flags & EntityFlag_CustomLinkage_Internal)) {
  809. error(e->token, "A foreign procedure may not have an \"internal\" linkage");
  810. }
  811. }
  812. if (ac.require_declaration) {
  813. e->flags |= EntityFlag_Require;
  814. pl->inlining = ProcInlining_no_inline;
  815. }
  816. if (e->pkg != nullptr && e->token.string == "main") {
  817. if (e->pkg->kind != Package_Runtime) {
  818. if (pt->param_count != 0 ||
  819. pt->result_count != 0) {
  820. gbString str = type_to_string(proc_type);
  821. error(e->token, "Procedure type of 'main' was expected to be 'proc()', got %s", str);
  822. gb_string_free(str);
  823. }
  824. if (pt->calling_convention != default_calling_convention()) {
  825. error(e->token, "Procedure 'main' cannot have a custom calling convention");
  826. }
  827. pt->calling_convention = default_calling_convention();
  828. if (e->pkg->kind == Package_Init) {
  829. if (ctx->info->entry_point != nullptr) {
  830. error(e->token, "Redeclaration of the entry pointer procedure 'main'");
  831. } else {
  832. ctx->info->entry_point = e;
  833. }
  834. }
  835. }
  836. }
  837. if (is_foreign && is_export) {
  838. error(pl->type, "A foreign procedure cannot have an 'export' tag");
  839. }
  840. if (pt->is_polymorphic) {
  841. if (pl->body == nullptr) {
  842. error(e->token, "Polymorphic procedures must have a body");
  843. }
  844. if (is_foreign) {
  845. error(e->token, "A foreign procedure cannot be a polymorphic");
  846. return;
  847. }
  848. }
  849. if (pl->body != nullptr) {
  850. if (is_foreign) {
  851. error(pl->body, "A foreign procedure cannot have a body");
  852. }
  853. if (proc_type->Proc.c_vararg) {
  854. error(pl->body, "A procedure with a '#c_vararg' field cannot have a body and must be foreign");
  855. }
  856. d->scope = ctx->scope;
  857. GB_ASSERT(pl->body->kind == Ast_BlockStmt);
  858. if (!pt->is_polymorphic) {
  859. check_procedure_later(ctx->checker, ctx->file, e->token, d, proc_type, pl->body, pl->tags);
  860. }
  861. } else if (!is_foreign) {
  862. if (e->Procedure.is_export) {
  863. error(e->token, "Foreign export procedures must have a body");
  864. } else {
  865. error(e->token, "Only a foreign procedure cannot have a body");
  866. }
  867. }
  868. if (ac.require_results) {
  869. if (pt->result_count == 0) {
  870. error(pl->type, "'require_results' is not needed on a procedure with no results");
  871. } else {
  872. pt->require_results = true;
  873. }
  874. }
  875. if (ac.link_name.len > 0) {
  876. e->Procedure.link_name = ac.link_name;
  877. }
  878. if (ac.deferred_procedure.entity != nullptr) {
  879. e->Procedure.deferred_procedure = ac.deferred_procedure;
  880. mpsc_enqueue(&ctx->checker->procs_with_deferred_to_check, e);
  881. }
  882. if (is_foreign) {
  883. String name = e->token.string;
  884. if (e->Procedure.link_name.len > 0) {
  885. name = e->Procedure.link_name;
  886. }
  887. Entity *foreign_library = init_entity_foreign_library(ctx, e);
  888. if (is_arch_wasm() && foreign_library != nullptr) {
  889. String module_name = str_lit("env");
  890. GB_ASSERT (foreign_library->kind == Entity_LibraryName);
  891. if (foreign_library->LibraryName.paths.count != 1) {
  892. error(foreign_library->token, "'foreign import' for '%.*s' architecture may only have one path, got %td",
  893. LIT(target_arch_names[build_context.metrics.arch]), foreign_library->LibraryName.paths.count);
  894. }
  895. if (foreign_library->LibraryName.paths.count >= 1) {
  896. module_name = foreign_library->LibraryName.paths[0];
  897. }
  898. name = concatenate3_strings(permanent_allocator(), module_name, WASM_MODULE_NAME_SEPARATOR, name);
  899. }
  900. e->Procedure.is_foreign = true;
  901. e->Procedure.link_name = name;
  902. mutex_lock(&ctx->info->foreign_mutex);
  903. auto *fp = &ctx->info->foreigns;
  904. StringHashKey key = string_hash_string(name);
  905. Entity **found = string_map_get(fp, key);
  906. if (found && e != *found) {
  907. Entity *f = *found;
  908. TokenPos pos = f->token.pos;
  909. Type *this_type = base_type(e->type);
  910. Type *other_type = base_type(f->type);
  911. if (is_type_proc(this_type) && is_type_proc(other_type)) {
  912. if (!are_signatures_similar_enough(this_type, other_type)) {
  913. error(d->proc_lit,
  914. "Redeclaration of foreign procedure '%.*s' with different type signatures\n"
  915. "\tat %s",
  916. LIT(name), token_pos_to_string(pos));
  917. }
  918. } else if (!are_types_identical(this_type, other_type)) {
  919. error(d->proc_lit,
  920. "Foreign entity '%.*s' previously declared elsewhere with a different type\n"
  921. "\tat %s",
  922. LIT(name), token_pos_to_string(pos));
  923. }
  924. } else if (name == "main") {
  925. error(d->proc_lit, "The link name 'main' is reserved for internal use");
  926. } else {
  927. string_map_set(fp, key, e);
  928. }
  929. mutex_unlock(&ctx->info->foreign_mutex);
  930. } else {
  931. String name = e->token.string;
  932. if (e->Procedure.link_name.len > 0) {
  933. name = e->Procedure.link_name;
  934. }
  935. if (e->Procedure.link_name.len > 0 || is_export) {
  936. mutex_lock(&ctx->info->foreign_mutex);
  937. auto *fp = &ctx->info->foreigns;
  938. StringHashKey key = string_hash_string(name);
  939. Entity **found = string_map_get(fp, key);
  940. if (found) {
  941. Entity *f = *found;
  942. TokenPos pos = f->token.pos;
  943. // TODO(bill): Better error message?
  944. error(d->proc_lit,
  945. "Non unique linking name for procedure '%.*s'\n"
  946. "\tother at %s",
  947. LIT(name), token_pos_to_string(pos));
  948. } else if (name == "main") {
  949. if (d->entity->pkg->kind != Package_Runtime) {
  950. error(d->proc_lit, "The link name 'main' is reserved for internal use");
  951. }
  952. } else {
  953. string_map_set(fp, key, e);
  954. }
  955. mutex_unlock(&ctx->info->foreign_mutex);
  956. }
  957. }
  958. if (e->Procedure.link_name.len > 0 ) {
  959. e->flags |= EntityFlag_CustomLinkName;
  960. }
  961. }
  962. gb_internal void check_global_variable_decl(CheckerContext *ctx, Entity *&e, Ast *type_expr, Ast *init_expr) {
  963. GB_ASSERT(e->type == nullptr);
  964. GB_ASSERT(e->kind == Entity_Variable);
  965. if (e->flags & EntityFlag_Visited) {
  966. e->type = t_invalid;
  967. return;
  968. }
  969. e->flags |= EntityFlag_Visited;
  970. AttributeContext ac = make_attribute_context(e->Variable.link_prefix);
  971. ac.init_expr_list_count = init_expr != nullptr ? 1 : 0;
  972. DeclInfo *decl = decl_info_of_entity(e);
  973. GB_ASSERT(decl == ctx->decl);
  974. if (decl != nullptr) {
  975. check_decl_attributes(ctx, decl->attributes, var_decl_attribute, &ac);
  976. }
  977. if (ac.require_declaration) {
  978. e->flags |= EntityFlag_Require;
  979. mpsc_enqueue(&ctx->info->required_global_variable_queue, e);
  980. }
  981. e->Variable.thread_local_model = ac.thread_local_model;
  982. e->Variable.is_export = ac.is_export;
  983. e->flags &= ~EntityFlag_Static;
  984. if (ac.is_static) {
  985. error(e->token, "@(static) is not supported for global variables, nor required");
  986. }
  987. ac.link_name = handle_link_name(ctx, e->token, ac.link_name, ac.link_prefix);
  988. if (is_arch_wasm() && e->Variable.thread_local_model.len != 0) {
  989. e->Variable.thread_local_model.len = 0;
  990. // NOTE(bill): ignore this message for the time being
  991. // error(e->token, "@(thread_local) is not supported for this target platform");
  992. }
  993. if(build_context.no_thread_local) {
  994. e->Variable.thread_local_model.len = 0;
  995. }
  996. String context_name = str_lit("variable declaration");
  997. if (type_expr != nullptr) {
  998. e->type = check_type(ctx, type_expr);
  999. }
  1000. if (e->type != nullptr) {
  1001. if (is_type_polymorphic(base_type(e->type))) {
  1002. gbString str = type_to_string(e->type);
  1003. defer (gb_string_free(str));
  1004. error(e->token, "Invalid use of a polymorphic type '%s' in %.*s", str, LIT(context_name));
  1005. e->type = t_invalid;
  1006. } else if (is_type_empty_union(e->type)) {
  1007. gbString str = type_to_string(e->type);
  1008. defer (gb_string_free(str));
  1009. error(e->token, "An empty union '%s' cannot be instantiated in %.*s", str, LIT(context_name));
  1010. e->type = t_invalid;
  1011. }
  1012. }
  1013. if (e->Variable.is_foreign) {
  1014. if (init_expr != nullptr) {
  1015. error(e->token, "A foreign variable declaration cannot have a default value");
  1016. }
  1017. init_entity_foreign_library(ctx, e);
  1018. if (is_arch_wasm()) {
  1019. error(e->token, "A foreign variable declaration are not allowed for the '%.*s' architecture", LIT(target_arch_names[build_context.metrics.arch]));
  1020. }
  1021. }
  1022. if (ac.link_name.len > 0) {
  1023. e->Variable.link_name = ac.link_name;
  1024. }
  1025. if (ac.link_section.len > 0) {
  1026. e->Variable.link_section = ac.link_section;
  1027. }
  1028. if (e->Variable.is_foreign || e->Variable.is_export) {
  1029. String name = e->token.string;
  1030. if (e->Variable.link_name.len > 0) {
  1031. name = e->Variable.link_name;
  1032. }
  1033. auto *fp = &ctx->info->foreigns;
  1034. StringHashKey key = string_hash_string(name);
  1035. Entity **found = string_map_get(fp, key);
  1036. if (found) {
  1037. Entity *f = *found;
  1038. TokenPos pos = f->token.pos;
  1039. Type *this_type = base_type(e->type);
  1040. Type *other_type = base_type(f->type);
  1041. if (!are_types_identical(this_type, other_type)) {
  1042. error(e->token,
  1043. "Foreign entity '%.*s' previously declared elsewhere with a different type\n"
  1044. "\tat %s",
  1045. LIT(name), token_pos_to_string(pos));
  1046. }
  1047. } else {
  1048. string_map_set(fp, key, e);
  1049. }
  1050. }
  1051. if (e->Variable.link_name.len > 0) {
  1052. e->flags |= EntityFlag_CustomLinkName;
  1053. }
  1054. if (init_expr == nullptr) {
  1055. if (type_expr == nullptr) {
  1056. e->type = t_invalid;
  1057. }
  1058. return;
  1059. }
  1060. Operand o = {};
  1061. check_expr_with_type_hint(ctx, &o, init_expr, e->type);
  1062. check_init_variable(ctx, e, &o, str_lit("variable declaration"));
  1063. check_rtti_type_disallowed(e->token, e->type, "A variable declaration is using a type, %s, which has been disallowed");
  1064. }
  1065. gb_internal void check_proc_group_decl(CheckerContext *ctx, Entity *pg_entity, DeclInfo *d) {
  1066. GB_ASSERT(pg_entity->kind == Entity_ProcGroup);
  1067. auto *pge = &pg_entity->ProcGroup;
  1068. String proc_group_name = pg_entity->token.string;
  1069. ast_node(pg, ProcGroup, d->init_expr);
  1070. pge->entities = array_make<Entity*>(permanent_allocator(), 0, pg->args.count);
  1071. // NOTE(bill): This must be set here to prevent cycles in checking if someone
  1072. // places the entity within itself
  1073. pg_entity->type = t_invalid;
  1074. PtrSet<Entity *> entity_set = {};
  1075. ptr_set_init(&entity_set, 2*pg->args.count);
  1076. for (Ast *arg : pg->args) {
  1077. Entity *e = nullptr;
  1078. Operand o = {};
  1079. if (arg->kind == Ast_Ident) {
  1080. e = check_ident(ctx, &o, arg, nullptr, nullptr, true);
  1081. } else if (arg->kind == Ast_SelectorExpr) {
  1082. e = check_selector(ctx, &o, arg, nullptr);
  1083. }
  1084. if (e == nullptr) {
  1085. error(arg, "Expected a valid entity name in procedure group, got %.*s", LIT(ast_strings[arg->kind]));
  1086. continue;
  1087. }
  1088. if (e->kind == Entity_Variable) {
  1089. if (!is_type_proc(e->type)) {
  1090. gbString s = type_to_string(e->type);
  1091. defer (gb_string_free(s));
  1092. error(arg, "Expected a procedure, got %s", s);
  1093. continue;
  1094. }
  1095. } else if (e->kind != Entity_Procedure) {
  1096. error(arg, "Expected a procedure entity");
  1097. continue;
  1098. }
  1099. if (ptr_set_update(&entity_set, e)) {
  1100. error(arg, "Previous use of `%.*s` in procedure group", LIT(e->token.string));
  1101. continue;
  1102. }
  1103. array_add(&pge->entities, e);
  1104. }
  1105. ptr_set_destroy(&entity_set);
  1106. for (isize j = 0; j < pge->entities.count; j++) {
  1107. Entity *p = pge->entities[j];
  1108. if (p->type == t_invalid) {
  1109. // NOTE(bill): This invalid overload has already been handled
  1110. continue;
  1111. }
  1112. String name = p->token.string;
  1113. for (isize k = j+1; k < pge->entities.count; k++) {
  1114. Entity *q = pge->entities[k];
  1115. GB_ASSERT(p != q);
  1116. bool is_invalid = false;
  1117. TokenPos pos = q->token.pos;
  1118. if (q->type == nullptr || q->type == t_invalid) {
  1119. continue;
  1120. }
  1121. begin_error_block();
  1122. defer (end_error_block());
  1123. ProcTypeOverloadKind kind = are_proc_types_overload_safe(p->type, q->type);
  1124. bool both_have_where_clauses = false;
  1125. if (p->decl_info->proc_lit != nullptr && q->decl_info->proc_lit != nullptr) {
  1126. GB_ASSERT(p->decl_info->proc_lit->kind == Ast_ProcLit);
  1127. GB_ASSERT(q->decl_info->proc_lit->kind == Ast_ProcLit);
  1128. auto pl = &p->decl_info->proc_lit->ProcLit;
  1129. auto ql = &q->decl_info->proc_lit->ProcLit;
  1130. // Allow collisions if the procedures both have 'where' clauses and are both polymorphic
  1131. bool pw = pl->where_token.kind != Token_Invalid && is_type_polymorphic(p->type, true);
  1132. bool qw = ql->where_token.kind != Token_Invalid && is_type_polymorphic(q->type, true);
  1133. both_have_where_clauses = pw && qw;
  1134. }
  1135. if (!both_have_where_clauses) switch (kind) {
  1136. case ProcOverload_Identical:
  1137. error(p->token, "Overloaded procedure '%.*s' has the same type as another procedure in the procedure group '%.*s'", LIT(name), LIT(proc_group_name));
  1138. is_invalid = true;
  1139. break;
  1140. // case ProcOverload_CallingConvention:
  1141. // error(p->token, "Overloaded procedure '%.*s' has the same type as another procedure in the procedure group '%.*s'", LIT(name), LIT(proc_group_name));
  1142. // is_invalid = true;
  1143. // break;
  1144. case ProcOverload_ParamVariadic:
  1145. error(p->token, "Overloaded procedure '%.*s' has the same type as another procedure in the procedure group '%.*s'", LIT(name), LIT(proc_group_name));
  1146. is_invalid = true;
  1147. break;
  1148. case ProcOverload_ResultCount:
  1149. case ProcOverload_ResultTypes:
  1150. error(p->token, "Overloaded procedure '%.*s' has the same parameters but different results in the procedure group '%.*s'", LIT(name), LIT(proc_group_name));
  1151. is_invalid = true;
  1152. break;
  1153. case ProcOverload_Polymorphic:
  1154. break;
  1155. case ProcOverload_ParamCount:
  1156. case ProcOverload_ParamTypes:
  1157. // This is okay :)
  1158. break;
  1159. }
  1160. if (is_invalid) {
  1161. error_line("\tprevious procedure at %s\n", token_pos_to_string(pos));
  1162. q->type = t_invalid;
  1163. }
  1164. }
  1165. }
  1166. AttributeContext ac = {};
  1167. check_decl_attributes(ctx, d->attributes, proc_group_attribute, &ac);
  1168. check_objc_methods(ctx, pg_entity, ac);
  1169. }
  1170. gb_internal void check_entity_decl(CheckerContext *ctx, Entity *e, DeclInfo *d, Type *named_type) {
  1171. if (e->state == EntityState_Resolved) {
  1172. return;
  1173. }
  1174. if (e->flags & EntityFlag_Lazy) {
  1175. mutex_lock(&ctx->info->lazy_mutex);
  1176. }
  1177. String name = e->token.string;
  1178. if (e->type != nullptr || e->state != EntityState_Unresolved) {
  1179. error(e->token, "Illegal declaration cycle of `%.*s`", LIT(name));
  1180. } else {
  1181. GB_ASSERT(e->state == EntityState_Unresolved);
  1182. if (d == nullptr) {
  1183. d = decl_info_of_entity(e);
  1184. if (d == nullptr) {
  1185. // TODO(bill): Err here?
  1186. e->type = t_invalid;
  1187. e->state = EntityState_Resolved;
  1188. set_base_type(named_type, t_invalid);
  1189. goto end;
  1190. }
  1191. }
  1192. CheckerContext c = *ctx;
  1193. c.scope = d->scope;
  1194. c.decl = d;
  1195. c.type_level = 0;
  1196. e->parent_proc_decl = c.curr_proc_decl;
  1197. e->state = EntityState_InProgress;
  1198. switch (e->kind) {
  1199. case Entity_Variable:
  1200. check_global_variable_decl(&c, e, d->type_expr, d->init_expr);
  1201. break;
  1202. case Entity_Constant:
  1203. check_const_decl(&c, e, d->type_expr, d->init_expr, named_type);
  1204. break;
  1205. case Entity_TypeName: {
  1206. check_type_decl(&c, e, d->init_expr, named_type);
  1207. break;
  1208. }
  1209. case Entity_Procedure:
  1210. check_proc_decl(&c, e, d);
  1211. break;
  1212. case Entity_ProcGroup:
  1213. check_proc_group_decl(&c, e, d);
  1214. break;
  1215. }
  1216. e->state = EntityState_Resolved;
  1217. }
  1218. end:;
  1219. // NOTE(bill): Add it to the list of checked entities
  1220. if (e->flags & EntityFlag_Lazy) {
  1221. array_add(&ctx->info->entities, e);
  1222. mutex_unlock(&ctx->info->lazy_mutex);
  1223. }
  1224. }
  1225. gb_internal void add_deps_from_child_to_parent(DeclInfo *decl) {
  1226. if (decl && decl->parent) {
  1227. Scope *ps = decl->parent->scope;
  1228. if (ps->flags & (ScopeFlag_File & ScopeFlag_Pkg & ScopeFlag_Global)) {
  1229. return;
  1230. } else {
  1231. // NOTE(bill): Add the dependencies from the procedure literal (lambda)
  1232. // But only at the procedure level
  1233. rw_mutex_shared_lock(&decl->deps_mutex);
  1234. rw_mutex_lock(&decl->parent->deps_mutex);
  1235. for (Entity *e : decl->deps) {
  1236. ptr_set_add(&decl->parent->deps, e);
  1237. }
  1238. rw_mutex_unlock(&decl->parent->deps_mutex);
  1239. rw_mutex_shared_unlock(&decl->deps_mutex);
  1240. rw_mutex_shared_lock(&decl->type_info_deps_mutex);
  1241. rw_mutex_lock(&decl->parent->type_info_deps_mutex);
  1242. for (Type *t : decl->type_info_deps) {
  1243. ptr_set_add(&decl->parent->type_info_deps, t);
  1244. }
  1245. rw_mutex_unlock(&decl->parent->type_info_deps_mutex);
  1246. rw_mutex_shared_unlock(&decl->type_info_deps_mutex);
  1247. }
  1248. }
  1249. }
  1250. struct ProcUsingVar {
  1251. Entity *e;
  1252. Entity *uvar;
  1253. };
  1254. gb_internal bool check_proc_body(CheckerContext *ctx_, Token token, DeclInfo *decl, Type *type, Ast *body) {
  1255. if (body == nullptr) {
  1256. return false;
  1257. }
  1258. GB_ASSERT(body->kind == Ast_BlockStmt);
  1259. String proc_name = {};
  1260. if (token.kind == Token_Ident) {
  1261. proc_name = token.string;
  1262. } else {
  1263. // TODO(bill): Better name
  1264. proc_name = str_lit("(anonymous-procedure)");
  1265. }
  1266. CheckerContext new_ctx = *ctx_;
  1267. CheckerContext *ctx = &new_ctx;
  1268. GB_ASSERT(type->kind == Type_Proc);
  1269. ctx->scope = decl->scope;
  1270. ctx->decl = decl;
  1271. ctx->proc_name = proc_name;
  1272. ctx->curr_proc_decl = decl;
  1273. ctx->curr_proc_sig = type;
  1274. ctx->curr_proc_calling_convention = type->Proc.calling_convention;
  1275. if (ctx->pkg->name != "runtime") {
  1276. switch (type->Proc.calling_convention) {
  1277. case ProcCC_None:
  1278. error(body, "Procedures with the calling convention \"none\" are not allowed a body");
  1279. break;
  1280. }
  1281. }
  1282. ast_node(bs, BlockStmt, body);
  1283. Array<ProcUsingVar> using_entities = {};
  1284. using_entities.allocator = heap_allocator();
  1285. defer (array_free(&using_entities));
  1286. {
  1287. if (type->Proc.param_count > 0) {
  1288. TypeTuple *params = &type->Proc.params->Tuple;
  1289. for (Entity *e : params->variables) {
  1290. if (e->kind != Entity_Variable) {
  1291. continue;
  1292. }
  1293. if (!(e->flags & EntityFlag_Using)) {
  1294. continue;
  1295. }
  1296. if (is_blank_ident(e->token)) {
  1297. error(e->token, "'using' a procedure parameter requires a non blank identifier");
  1298. break;
  1299. }
  1300. bool is_value = (e->flags & EntityFlag_Value) != 0 && !is_type_pointer(e->type);
  1301. String name = e->token.string;
  1302. Type *t = base_type(type_deref(e->type));
  1303. if (t->kind == Type_Struct) {
  1304. Scope *scope = t->Struct.scope;
  1305. GB_ASSERT(scope != nullptr);
  1306. rw_mutex_lock(&scope->mutex);
  1307. for (auto const &entry : scope->elements) {
  1308. Entity *f = entry.value;
  1309. if (f->kind == Entity_Variable) {
  1310. Entity *uvar = alloc_entity_using_variable(e, f->token, f->type, nullptr);
  1311. if (is_value) uvar->flags |= EntityFlag_Value;
  1312. ProcUsingVar puv = {e, uvar};
  1313. array_add(&using_entities, puv);
  1314. }
  1315. }
  1316. rw_mutex_unlock(&scope->mutex);
  1317. } else {
  1318. error(e->token, "'using' can only be applied to variables of type struct");
  1319. break;
  1320. }
  1321. }
  1322. }
  1323. }
  1324. rw_mutex_lock(&ctx->scope->mutex);
  1325. for (auto const &entry : using_entities) {
  1326. Entity *e = entry.e;
  1327. Entity *uvar = entry.uvar;
  1328. Entity *prev = scope_insert_no_mutex(ctx->scope, uvar);
  1329. if (prev != nullptr) {
  1330. error(e->token, "Namespace collision while 'using' procedure argument '%.*s' of: %.*s", LIT(e->token.string), LIT(prev->token.string));
  1331. error_line("%.*s != %.*s\n", LIT(uvar->token.string), LIT(prev->token.string));
  1332. break;
  1333. }
  1334. }
  1335. rw_mutex_unlock(&ctx->scope->mutex);
  1336. bool where_clause_ok = evaluate_where_clauses(ctx, nullptr, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !decl->where_clauses_evaluated);
  1337. if (!where_clause_ok) {
  1338. // NOTE(bill, 2019-08-31): Don't check the body as the where clauses failed
  1339. return false;
  1340. }
  1341. check_open_scope(ctx, body);
  1342. {
  1343. for (auto const &entry : using_entities) {
  1344. Entity *uvar = entry.uvar;
  1345. Entity *prev = scope_insert(ctx->scope, uvar);
  1346. gb_unused(prev);
  1347. // NOTE(bill): Don't err here
  1348. }
  1349. GB_ASSERT(decl->proc_checked_state != ProcCheckedState_Checked);
  1350. if (decl->defer_use_checked) {
  1351. GB_ASSERT(is_type_polymorphic(type, true));
  1352. error(token, "Defer Use Checked: %.*s", LIT(decl->entity->token.string));
  1353. GB_ASSERT(decl->defer_use_checked == false);
  1354. }
  1355. check_stmt_list(ctx, bs->stmts, Stmt_CheckScopeDecls);
  1356. decl->defer_use_checked = true;
  1357. for (Ast *stmt : bs->stmts) {
  1358. if (stmt->kind == Ast_ValueDecl) {
  1359. ast_node(vd, ValueDecl, stmt);
  1360. for (Ast *name : vd->names) {
  1361. if (!is_blank_ident(name)) {
  1362. if (name->kind == Ast_Ident) {
  1363. GB_ASSERT(name->Ident.entity != nullptr);
  1364. }
  1365. }
  1366. }
  1367. }
  1368. }
  1369. if (type->Proc.result_count > 0) {
  1370. if (!check_is_terminating(body, str_lit(""))) {
  1371. if (token.kind == Token_Ident) {
  1372. error(bs->close, "Missing return statement at the end of the procedure '%.*s'", LIT(token.string));
  1373. } else {
  1374. // NOTE(bill): Anonymous procedure (lambda)
  1375. error(bs->close, "Missing return statement at the end of the procedure");
  1376. }
  1377. }
  1378. } else if (type->Proc.diverging) {
  1379. if (!check_is_terminating(body, str_lit(""))) {
  1380. if (token.kind == Token_Ident) {
  1381. error(bs->close, "Missing diverging call at the end of the procedure '%.*s'", LIT(token.string));
  1382. } else {
  1383. // NOTE(bill): Anonymous procedure (lambda)
  1384. error(bs->close, "Missing diverging call at the end of the procedure");
  1385. }
  1386. }
  1387. }
  1388. }
  1389. check_close_scope(ctx);
  1390. check_scope_usage(ctx->checker, ctx->scope, check_vet_flags(body));
  1391. add_deps_from_child_to_parent(decl);
  1392. return true;
  1393. }