authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2024-12-31 14:35:28+00:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-12-31 14:35:28+00:00
log0df1f3df2f25bf12071f11e9b738a356dfbd214d
treefd7830fb82c95f52a79fd9984af4caacb090f3fe
parent6d67658965bc298a697dc756a4e06bda144427de
parent106df881d3a3fe3b744f0563b99cff88d7ef6549
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #22352 from mlugg/zir-comptime-reason

Zir: attach reason to `block_comptime` and improve corresponding error reporting

39 files changed, 1157 insertions(+), 839 deletions(-)

lib/std/zig.zig+159
...@@ -718,6 +718,165 @@ pub const EnvVar = enum {...@@ -718,6 +718,165 @@ pub const EnvVar = enum {
718 }718 }
719};719};
720720
721pub const SimpleComptimeReason = enum(u32) {
722 // Evaluating at comptime because a builtin operand must be comptime-known.
723 // These messages all mention a specific builtin.
724 operand_Type,
725 operand_setEvalBranchQuota,
726 operand_setFloatMode,
727 operand_branchHint,
728 operand_setRuntimeSafety,
729 operand_embedFile,
730 operand_cImport,
731 operand_cDefine_macro_name,
732 operand_cDefine_macro_value,
733 operand_cInclude_file_name,
734 operand_cUndef_macro_name,
735 operand_shuffle_mask,
736 operand_atomicRmw_operation,
737 operand_reduce_operation,
738
739 // Evaluating at comptime because an operand must be comptime-known.
740 // These messages do not mention a specific builtin (and may not be about a builtin at all).
741 export_target,
742 export_options,
743 extern_options,
744 prefetch_options,
745 call_modifier,
746 compile_error_string,
747 inline_assembly_code,
748 atomic_order,
749 array_mul_factor,
750 slice_cat_operand,
751 comptime_call_target,
752 wasm_memory_index,
753 work_group_dim_index,
754
755 // Evaluating at comptime because types must be comptime-known.
756 // Reasons other than `.type` are just more specific messages.
757 type,
758 array_sentinel,
759 pointer_sentinel,
760 slice_sentinel,
761 array_length,
762 vector_length,
763 error_set_contents,
764 struct_fields,
765 enum_fields,
766 union_fields,
767 function_ret_ty,
768 function_parameters,
769
770 // Evaluating at comptime because decl/field name must be comptime-known.
771 decl_name,
772 field_name,
773 struct_field_name,
774 enum_field_name,
775 union_field_name,
776 tuple_field_name,
777 tuple_field_index,
778
779 // Evaluating at comptime because it is an attribute of a global declaration.
780 container_var_init,
781 @"callconv",
782 @"align",
783 @"addrspace",
784 @"linksection",
785
786 // Miscellaneous reasons.
787 comptime_keyword,
788 comptime_call_modifier,
789 switch_item,
790 tuple_field_default_value,
791 struct_field_default_value,
792 enum_field_tag_value,
793 slice_single_item_ptr_bounds,
794 comptime_param_arg,
795 stored_to_comptime_field,
796 stored_to_comptime_var,
797 casted_to_comptime_enum,
798 casted_to_comptime_int,
799 casted_to_comptime_float,
800 panic_handler,
801
802 pub fn message(r: SimpleComptimeReason) []const u8 {
803 return switch (r) {
804 // zig fmt: off
805 .operand_Type => "operand to '@Type' must be comptime-known",
806 .operand_setEvalBranchQuota => "operand to '@setEvalBranchQuota' must be comptime-known",
807 .operand_setFloatMode => "operand to '@setFloatMode' must be comptime-known",
808 .operand_branchHint => "operand to '@branchHint' must be comptime-known",
809 .operand_setRuntimeSafety => "operand to '@setRuntimeSafety' must be comptime-known",
810 .operand_embedFile => "operand to '@embedFile' must be comptime-known",
811 .operand_cImport => "operand to '@cImport' is evaluated at comptime",
812 .operand_cDefine_macro_name => "'@cDefine' macro name must be comptime-known",
813 .operand_cDefine_macro_value => "'@cDefine' macro value must be comptime-known",
814 .operand_cInclude_file_name => "'@cInclude' file name must be comptime-known",
815 .operand_cUndef_macro_name => "'@cUndef' macro name must be comptime-known",
816 .operand_shuffle_mask => "'@shuffle' mask must be comptime-known",
817 .operand_atomicRmw_operation => "'@atomicRmw' operation must be comptime-known",
818 .operand_reduce_operation => "'@reduce' operation must be comptime-known",
819
820 .export_target => "export target must be comptime-known",
821 .export_options => "export options must be comptime-known",
822 .extern_options => "extern options must be comptime-known",
823 .prefetch_options => "prefetch options must be comptime-known",
824 .call_modifier => "call modifier must be comptime-known",
825 .compile_error_string => "compile error string must be comptime-known",
826 .inline_assembly_code => "inline assembly code must be comptime-known",
827 .atomic_order => "atomic order must be comptime-known",
828 .array_mul_factor => "array multiplication factor must be comptime-known",
829 .slice_cat_operand => "slice being concatenated must be comptime-known",
830 .comptime_call_target => "function being called at comptime must be comptime-known",
831 .wasm_memory_index => "wasm memory index must be comptime-known",
832 .work_group_dim_index => "work group dimension index must be comptime-known",
833
834 .type => "types must be comptime-known",
835 .array_sentinel => "array sentinel value must be comptime-known",
836 .pointer_sentinel => "pointer sentinel value must be comptime-known",
837 .slice_sentinel => "slice sentinel value must be comptime-known",
838 .array_length => "array length must be comptime-known",
839 .vector_length => "vector length must be comptime-known",
840 .error_set_contents => "error set contents must be comptime-known",
841 .struct_fields => "struct fields must be comptime-known",
842 .enum_fields => "enum fields must be comptime-known",
843 .union_fields => "union fields must be comptime-known",
844 .function_ret_ty => "function return type must be comptime-known",
845 .function_parameters => "function parameters must be comptime-known",
846
847 .decl_name => "declaration name must be comptime-known",
848 .field_name => "field name must be comptime-known",
849 .struct_field_name => "struct field name must be comptime-known",
850 .enum_field_name => "enum field name must be comptime-known",
851 .union_field_name => "union field name must be comptime-known",
852 .tuple_field_name => "tuple field name must be comptime-known",
853 .tuple_field_index => "tuple field index must be comptime-known",
854
855 .container_var_init => "initializer of container-level variable must be comptime-known",
856 .@"callconv" => "calling convention must be comptime-known",
857 .@"align" => "alignment must be comptime-known",
858 .@"addrspace" => "address space must be comptime-known",
859 .@"linksection" => "linksection must be comptime-known",
860
861 .comptime_keyword => "'comptime' keyword forces comptime evaluation",
862 .comptime_call_modifier => "'.compile_time' call modifier forces comptime evaluation",
863 .switch_item => "switch prong values must be comptime-known",
864 .tuple_field_default_value => "tuple field default value must be comptime-known",
865 .struct_field_default_value => "struct field default value must be comptime-known",
866 .enum_field_tag_value => "enum field tag value must be comptime-known",
867 .slice_single_item_ptr_bounds => "slice of single-item pointer must have comptime-known bounds",
868 .comptime_param_arg => "argument to comptime parameter must be comptime-known",
869 .stored_to_comptime_field => "value stored to a comptime field must be comptime-known",
870 .stored_to_comptime_var => "value stored to a comptime variable must be comptime-known",
871 .casted_to_comptime_enum => "value casted to enum with 'comptime_int' tag type must be comptime-known",
872 .casted_to_comptime_int => "value casted to 'comptime_int' must be comptime-known",
873 .casted_to_comptime_float => "value casted to 'comptime_float' must be comptime-known",
874 .panic_handler => "panic handler must be comptime-known",
875 // zig fmt: on
876 };
877 }
878};
879
721test {880test {
722 _ = Ast;881 _ = Ast;
723 _ = AstRlAnnotate;882 _ = AstRlAnnotate;
lib/std/zig/AstGen.zig+241-86
...@@ -97,6 +97,7 @@ fn setExtra(astgen: *AstGen, index: usize, extra: anytype) void {...@@ -97,6 +97,7 @@ fn setExtra(astgen: *AstGen, index: usize, extra: anytype) void {
97 Zir.Inst.Ref,97 Zir.Inst.Ref,
98 Zir.Inst.Index,98 Zir.Inst.Index,
99 Zir.Inst.Declaration.Name,99 Zir.Inst.Declaration.Name,
100 std.zig.SimpleComptimeReason,
100 Zir.NullTerminatedString,101 Zir.NullTerminatedString,
101 => @intFromEnum(@field(extra, field.name)),102 => @intFromEnum(@field(extra, field.name)),
102103
...@@ -379,7 +380,7 @@ const coerced_type_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .type_type } };...@@ -379,7 +380,7 @@ const coerced_type_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .type_type } };
379const coerced_bool_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .bool_type } };380const coerced_bool_ri: ResultInfo = .{ .rl = .{ .coerced_ty = .bool_type } };
380381
381fn typeExpr(gz: *GenZir, scope: *Scope, type_node: Ast.Node.Index) InnerError!Zir.Inst.Ref {382fn typeExpr(gz: *GenZir, scope: *Scope, type_node: Ast.Node.Index) InnerError!Zir.Inst.Ref {
382 return comptimeExpr(gz, scope, coerced_type_ri, type_node);383 return comptimeExpr(gz, scope, coerced_type_ri, type_node, .type);
383}384}
384385
385fn reachableTypeExpr(386fn reachableTypeExpr(
...@@ -388,7 +389,7 @@ fn reachableTypeExpr(...@@ -388,7 +389,7 @@ fn reachableTypeExpr(
388 type_node: Ast.Node.Index,389 type_node: Ast.Node.Index,
389 reachable_node: Ast.Node.Index,390 reachable_node: Ast.Node.Index,
390) InnerError!Zir.Inst.Ref {391) InnerError!Zir.Inst.Ref {
391 return reachableExprComptime(gz, scope, coerced_type_ri, type_node, reachable_node, true);392 return reachableExprComptime(gz, scope, coerced_type_ri, type_node, reachable_node, .type);
392}393}
393394
394/// Same as `expr` but fails with a compile error if the result type is `noreturn`.395/// Same as `expr` but fails with a compile error if the result type is `noreturn`.
...@@ -399,7 +400,7 @@ fn reachableExpr(...@@ -399,7 +400,7 @@ fn reachableExpr(
399 node: Ast.Node.Index,400 node: Ast.Node.Index,
400 reachable_node: Ast.Node.Index,401 reachable_node: Ast.Node.Index,
401) InnerError!Zir.Inst.Ref {402) InnerError!Zir.Inst.Ref {
402 return reachableExprComptime(gz, scope, ri, node, reachable_node, false);403 return reachableExprComptime(gz, scope, ri, node, reachable_node, null);
403}404}
404405
405fn reachableExprComptime(406fn reachableExprComptime(
...@@ -408,10 +409,11 @@ fn reachableExprComptime(...@@ -408,10 +409,11 @@ fn reachableExprComptime(
408 ri: ResultInfo,409 ri: ResultInfo,
409 node: Ast.Node.Index,410 node: Ast.Node.Index,
410 reachable_node: Ast.Node.Index,411 reachable_node: Ast.Node.Index,
411 force_comptime: bool,412 /// If `null`, the expression is not evaluated in a comptime context.
413 comptime_reason: ?std.zig.SimpleComptimeReason,
412) InnerError!Zir.Inst.Ref {414) InnerError!Zir.Inst.Ref {
413 const result_inst = if (force_comptime)415 const result_inst = if (comptime_reason) |r|
414 try comptimeExpr(gz, scope, ri, node)416 try comptimeExpr(gz, scope, ri, node, r)
415 else417 else
416 try expr(gz, scope, ri, node);418 try expr(gz, scope, ri, node);
417419
...@@ -782,13 +784,22 @@ fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerE...@@ -782,13 +784,22 @@ fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerE
782 const result = try gz.addPlNode(.array_mul, node, Zir.Inst.ArrayMul{784 const result = try gz.addPlNode(.array_mul, node, Zir.Inst.ArrayMul{
783 .res_ty = if (try ri.rl.resultType(gz, node)) |t| t else .none,785 .res_ty = if (try ri.rl.resultType(gz, node)) |t| t else .none,
784 .lhs = try expr(gz, scope, .{ .rl = .none }, node_datas[node].lhs),786 .lhs = try expr(gz, scope, .{ .rl = .none }, node_datas[node].lhs),
785 .rhs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, node_datas[node].rhs),787 .rhs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, node_datas[node].rhs, .array_mul_factor),
786 });788 });
787 return rvalue(gz, ri, result, node);789 return rvalue(gz, ri, result, node);
788 },790 },
789791
790 .error_union => return simpleBinOp(gz, scope, ri, node, .error_union_type),792 .error_union, .merge_error_sets => |tag| {
791 .merge_error_sets => return simpleBinOp(gz, scope, ri, node, .merge_error_sets),793 const inst_tag: Zir.Inst.Tag = switch (tag) {
794 .error_union => .error_union_type,
795 .merge_error_sets => .merge_error_sets,
796 else => unreachable,
797 };
798 const lhs = try reachableTypeExpr(gz, scope, node_datas[node].lhs, node);
799 const rhs = try reachableTypeExpr(gz, scope, node_datas[node].rhs, node);
800 const result = try gz.addPlNode(inst_tag, node, Zir.Inst.Bin{ .lhs = lhs, .rhs = rhs });
801 return rvalue(gz, ri, result, node);
802 },
792803
793 .bool_and => return boolBinOp(gz, scope, ri, node, .bool_br_and),804 .bool_and => return boolBinOp(gz, scope, ri, node, .bool_br_and),
794 .bool_or => return boolBinOp(gz, scope, ri, node, .bool_br_or),805 .bool_or => return boolBinOp(gz, scope, ri, node, .bool_br_or),
...@@ -799,7 +810,7 @@ fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerE...@@ -799,7 +810,7 @@ fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerE
799 .negation => return negation(gz, scope, ri, node),810 .negation => return negation(gz, scope, ri, node),
800 .negation_wrap => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none }, node_datas[node].lhs, .negate_wrap),811 .negation_wrap => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none }, node_datas[node].lhs, .negate_wrap),
801812
802 .identifier => return identifier(gz, scope, ri, node),813 .identifier => return identifier(gz, scope, ri, node, null),
803814
804 .asm_simple,815 .asm_simple,
805 .@"asm",816 .@"asm",
...@@ -1364,6 +1375,7 @@ fn fnProtoExprInner(...@@ -1364,6 +1375,7 @@ fn fnProtoExprInner(
1364 assert(param_type_node != 0);1375 assert(param_type_node != 0);
1365 var param_gz = block_scope.makeSubBlock(scope);1376 var param_gz = block_scope.makeSubBlock(scope);
1366 defer param_gz.unstack();1377 defer param_gz.unstack();
1378 param_gz.is_comptime = true;
1367 const param_type = try fullBodyExpr(&param_gz, scope, coerced_type_ri, param_type_node, .normal);1379 const param_type = try fullBodyExpr(&param_gz, scope, coerced_type_ri, param_type_node, .normal);
1368 const param_inst_expected: Zir.Inst.Index = @enumFromInt(astgen.instructions.len + 1);1380 const param_inst_expected: Zir.Inst.Index = @enumFromInt(astgen.instructions.len + 1);
1369 _ = try param_gz.addBreakWithSrcNode(.break_inline, param_inst_expected, param_type, param_type_node);1381 _ = try param_gz.addBreakWithSrcNode(.break_inline, param_inst_expected, param_type, param_type_node);
...@@ -1380,18 +1392,19 @@ fn fnProtoExprInner(...@@ -1380,18 +1392,19 @@ fn fnProtoExprInner(
1380 };1392 };
13811393
1382 const cc: Zir.Inst.Ref = if (fn_proto.ast.callconv_expr != 0)1394 const cc: Zir.Inst.Ref = if (fn_proto.ast.callconv_expr != 0)
1383 try expr(1395 try comptimeExpr(
1384 &block_scope,1396 &block_scope,
1385 scope,1397 scope,
1386 .{ .rl = .{ .coerced_ty = try block_scope.addBuiltinValue(fn_proto.ast.callconv_expr, .calling_convention) } },1398 .{ .rl = .{ .coerced_ty = try block_scope.addBuiltinValue(fn_proto.ast.callconv_expr, .calling_convention) } },
1387 fn_proto.ast.callconv_expr,1399 fn_proto.ast.callconv_expr,
1400 .@"callconv",
1388 )1401 )
1389 else if (implicit_ccc)1402 else if (implicit_ccc)
1390 try block_scope.addBuiltinValue(node, .calling_convention_c)1403 try block_scope.addBuiltinValue(node, .calling_convention_c)
1391 else1404 else
1392 .none;1405 .none;
13931406
1394 const ret_ty = try expr(&block_scope, scope, coerced_type_ri, fn_proto.ast.return_type);1407 const ret_ty = try comptimeExpr(&block_scope, scope, coerced_type_ri, fn_proto.ast.return_type, .function_ret_ty);
13951408
1396 const result = try block_scope.addFunc(.{1409 const result = try block_scope.addFunc(.{
1397 .src_node = fn_proto.ast.proto_node,1410 .src_node = fn_proto.ast.proto_node,
...@@ -1453,7 +1466,7 @@ fn arrayInitExpr(...@@ -1453,7 +1466,7 @@ fn arrayInitExpr(
1453 });1466 });
1454 break :inst .{ array_type_inst, elem_type };1467 break :inst .{ array_type_inst, elem_type };
1455 } else {1468 } else {
1456 const sentinel = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = elem_type } }, array_type.ast.sentinel);1469 const sentinel = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = elem_type } }, array_type.ast.sentinel, .array_sentinel);
1457 const array_type_inst = try gz.addPlNode(1470 const array_type_inst = try gz.addPlNode(
1458 .array_type_sentinel,1471 .array_type_sentinel,
1459 array_init.ast.type_expr,1472 array_init.ast.type_expr,
...@@ -1721,7 +1734,7 @@ fn structInitExpr(...@@ -1721,7 +1734,7 @@ fn structInitExpr(
1721 .rhs = elem_type,1734 .rhs = elem_type,
1722 });1735 });
1723 } else blk: {1736 } else blk: {
1724 const sentinel = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = elem_type } }, array_type.ast.sentinel);1737 const sentinel = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = elem_type } }, array_type.ast.sentinel, .array_sentinel);
1725 break :blk try gz.addPlNode(1738 break :blk try gz.addPlNode(
1726 .array_type_sentinel,1739 .array_type_sentinel,
1727 struct_init.ast.type_expr,1740 struct_init.ast.type_expr,
...@@ -1966,6 +1979,20 @@ fn comptimeExpr(...@@ -1966,6 +1979,20 @@ fn comptimeExpr(
1966 scope: *Scope,1979 scope: *Scope,
1967 ri: ResultInfo,1980 ri: ResultInfo,
1968 node: Ast.Node.Index,1981 node: Ast.Node.Index,
1982 reason: std.zig.SimpleComptimeReason,
1983) InnerError!Zir.Inst.Ref {
1984 return comptimeExpr2(gz, scope, ri, node, node, reason);
1985}
1986
1987/// Like `comptimeExpr`, but draws a distinction between `node`, the expression to evaluate at comptime,
1988/// and `src_node`, the node to attach to the `block_comptime`.
1989fn comptimeExpr2(
1990 gz: *GenZir,
1991 scope: *Scope,
1992 ri: ResultInfo,
1993 node: Ast.Node.Index,
1994 src_node: Ast.Node.Index,
1995 reason: std.zig.SimpleComptimeReason,
1969) InnerError!Zir.Inst.Ref {1996) InnerError!Zir.Inst.Ref {
1970 if (gz.is_comptime) {1997 if (gz.is_comptime) {
1971 // No need to change anything!1998 // No need to change anything!
...@@ -1979,19 +2006,50 @@ fn comptimeExpr(...@@ -1979,19 +2006,50 @@ fn comptimeExpr(
1979 const main_tokens = tree.nodes.items(.main_token);2006 const main_tokens = tree.nodes.items(.main_token);
1980 const node_tags = tree.nodes.items(.tag);2007 const node_tags = tree.nodes.items(.tag);
1981 switch (node_tags[node]) {2008 switch (node_tags[node]) {
1982 // Any identifier in `primitive_instrs` is trivially comptime. In particular, this includes
1983 // some common types, so we can elide `block_comptime` for a few common type annotations.
1984 .identifier => {2009 .identifier => {
1985 const ident_token = main_tokens[node];2010 // Many identifiers can be handled without a `block_comptime`, so `AstGen.identifier` has
1986 const ident_name_raw = tree.tokenSlice(ident_token);2011 // special handling for this case.
1987 if (primitive_instrs.get(ident_name_raw)) |zir_const_ref| {2012 return identifier(gz, scope, ri, node, .{ .src_node = src_node, .reason = reason });
1988 // No need to worry about result location here, we're not creating a comptime block!
1989 return rvalue(gz, ri, zir_const_ref, node);
1990 }
1991 },2013 },
19922014
1993 // We can also avoid the block for a few trivial AST tags which are always comptime-known.2015 // These are leaf nodes which are always comptime-known.
1994 .number_literal, .string_literal, .multiline_string_literal, .enum_literal, .error_value => {2016 .number_literal,
2017 .char_literal,
2018 .string_literal,
2019 .multiline_string_literal,
2020 .enum_literal,
2021 .error_value,
2022 .anyframe_literal,
2023 .error_set_decl,
2024 // These nodes are not leaves, but will force comptime evaluation of all sub-expressions, and
2025 // hence behave the same regardless of whether they're in a comptime scope.
2026 .error_union,
2027 .merge_error_sets,
2028 .optional_type,
2029 .anyframe_type,
2030 .ptr_type_aligned,
2031 .ptr_type_sentinel,
2032 .ptr_type,
2033 .ptr_type_bit_range,
2034 .array_type,
2035 .array_type_sentinel,
2036 .fn_proto_simple,
2037 .fn_proto_multi,
2038 .fn_proto_one,
2039 .fn_proto,
2040 .container_decl,
2041 .container_decl_trailing,
2042 .container_decl_arg,
2043 .container_decl_arg_trailing,
2044 .container_decl_two,
2045 .container_decl_two_trailing,
2046 .tagged_union,
2047 .tagged_union_trailing,
2048 .tagged_union_enum_tag,
2049 .tagged_union_enum_tag_trailing,
2050 .tagged_union_two,
2051 .tagged_union_two_trailing,
2052 => {
1995 // No need to worry about result location here, we're not creating a comptime block!2053 // No need to worry about result location here, we're not creating a comptime block!
1996 return expr(gz, scope, ri, node);2054 return expr(gz, scope, ri, node);
1997 },2055 },
...@@ -2049,23 +2107,23 @@ fn comptimeExpr(...@@ -2049,23 +2107,23 @@ fn comptimeExpr(
2049 block_scope.is_comptime = true;2107 block_scope.is_comptime = true;
2050 defer block_scope.unstack();2108 defer block_scope.unstack();
20512109
2052 const block_inst = try gz.makeBlockInst(.block_comptime, node);2110 const block_inst = try gz.makeBlockInst(.block_comptime, src_node);
2053 // Replace result location and copy back later - see above.2111 // Replace result location and copy back later - see above.
2054 const ty_only_ri: ResultInfo = .{2112 const ty_only_ri: ResultInfo = .{
2055 .ctx = ri.ctx,2113 .ctx = ri.ctx,
2056 .rl = if (try ri.rl.resultType(gz, node)) |res_ty|2114 .rl = if (try ri.rl.resultType(gz, src_node)) |res_ty|
2057 .{ .coerced_ty = res_ty }2115 .{ .coerced_ty = res_ty }
2058 else2116 else
2059 .none,2117 .none,
2060 };2118 };
2061 const block_result = try fullBodyExpr(&block_scope, scope, ty_only_ri, node, .normal);2119 const block_result = try fullBodyExpr(&block_scope, scope, ty_only_ri, node, .normal);
2062 if (!gz.refIsNoReturn(block_result)) {2120 if (!gz.refIsNoReturn(block_result)) {
2063 _ = try block_scope.addBreak(.@"break", block_inst, block_result);2121 _ = try block_scope.addBreak(.break_inline, block_inst, block_result);
2064 }2122 }
2065 try block_scope.setBlockBody(block_inst);2123 try block_scope.setBlockComptimeBody(block_inst, reason);
2066 try gz.instructions.append(gz.astgen.gpa, block_inst);2124 try gz.instructions.append(gz.astgen.gpa, block_inst);
20672125
2068 return rvalue(gz, ri, block_inst.toRef(), node);2126 return rvalue(gz, ri, block_inst.toRef(), src_node);
2069}2127}
20702128
2071/// This one is for an actual `comptime` syntax, and will emit a compile error if2129/// This one is for an actual `comptime` syntax, and will emit a compile error if
...@@ -2084,7 +2142,7 @@ fn comptimeExprAst(...@@ -2084,7 +2142,7 @@ fn comptimeExprAst(
2084 const tree = astgen.tree;2142 const tree = astgen.tree;
2085 const node_datas = tree.nodes.items(.data);2143 const node_datas = tree.nodes.items(.data);
2086 const body_node = node_datas[node].lhs;2144 const body_node = node_datas[node].lhs;
2087 return comptimeExpr(gz, scope, ri, body_node);2145 return comptimeExpr2(gz, scope, ri, body_node, node, .comptime_keyword);
2088}2146}
20892147
2090/// Restore the error return trace index. Performs the restore only if the result is a non-error or2148/// Restore the error return trace index. Performs the restore only if the result is a non-error or
...@@ -2494,10 +2552,10 @@ fn labeledBlockExpr(...@@ -2494,10 +2552,10 @@ fn labeledBlockExpr(
24942552
2495 // Reserve the Block ZIR instruction index so that we can put it into the GenZir struct2553 // Reserve the Block ZIR instruction index so that we can put it into the GenZir struct
2496 // so that break statements can reference it.2554 // so that break statements can reference it.
2497 const block_tag: Zir.Inst.Tag = if (force_comptime) .block_comptime else .block;2555 const block_inst = try gz.makeBlockInst(if (force_comptime) .block_comptime else .block, block_node);
2498 const block_inst = try gz.makeBlockInst(block_tag, block_node);
2499 try gz.instructions.append(astgen.gpa, block_inst);2556 try gz.instructions.append(astgen.gpa, block_inst);
2500 var block_scope = gz.makeSubBlock(parent_scope);2557 var block_scope = gz.makeSubBlock(parent_scope);
2558 block_scope.is_inline = force_comptime;
2501 block_scope.label = GenZir.Label{2559 block_scope.label = GenZir.Label{
2502 .token = label_token,2560 .token = label_token,
2503 .block_inst = block_inst,2561 .block_inst = block_inst,
...@@ -2511,14 +2569,20 @@ fn labeledBlockExpr(...@@ -2511,14 +2569,20 @@ fn labeledBlockExpr(
2511 // As our last action before the return, "pop" the error trace if needed2569 // As our last action before the return, "pop" the error trace if needed
2512 _ = try gz.addRestoreErrRetIndex(.{ .block = block_inst }, .always, block_node);2570 _ = try gz.addRestoreErrRetIndex(.{ .block = block_inst }, .always, block_node);
2513 const result = try rvalue(gz, block_scope.break_result_info, .void_value, block_node);2571 const result = try rvalue(gz, block_scope.break_result_info, .void_value, block_node);
2514 _ = try block_scope.addBreak(.@"break", block_inst, result);2572 const break_tag: Zir.Inst.Tag = if (force_comptime) .break_inline else .@"break";
2573 _ = try block_scope.addBreak(break_tag, block_inst, result);
2515 }2574 }
25162575
2517 if (!block_scope.label.?.used) {2576 if (!block_scope.label.?.used) {
2518 try astgen.appendErrorTok(label_token, "unused block label", .{});2577 try astgen.appendErrorTok(label_token, "unused block label", .{});
2519 }2578 }
25202579
2521 try block_scope.setBlockBody(block_inst);2580 if (force_comptime) {
2581 try block_scope.setBlockComptimeBody(block_inst, .comptime_keyword);
2582 } else {
2583 try block_scope.setBlockBody(block_inst);
2584 }
2585
2522 if (need_result_rvalue) {2586 if (need_result_rvalue) {
2523 return rvalue(gz, ri, block_inst.toRef(), block_node);2587 return rvalue(gz, ri, block_inst.toRef(), block_node);
2524 } else {2588 } else {
...@@ -2941,6 +3005,7 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As...@@ -2941,6 +3005,7 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As
2941 .validate_array_init_result_ty,3005 .validate_array_init_result_ty,
2942 .validate_ptr_array_init,3006 .validate_ptr_array_init,
2943 .validate_ref_ty,3007 .validate_ref_ty,
3008 .validate_const,
2944 .try_operand_ty,3009 .try_operand_ty,
2945 .try_ref_operand_ty,3010 .try_ref_operand_ty,
2946 => break :b true,3011 => break :b true,
...@@ -3255,9 +3320,10 @@ fn varDecl(...@@ -3255,9 +3320,10 @@ fn varDecl(
3255 } else .{ .rl = .none, .ctx = .const_init };3320 } else .{ .rl = .none, .ctx = .const_init };
3256 const prev_anon_name_strategy = gz.anon_name_strategy;3321 const prev_anon_name_strategy = gz.anon_name_strategy;
3257 gz.anon_name_strategy = .dbg_var;3322 gz.anon_name_strategy = .dbg_var;
3258 const init_inst = try reachableExprComptime(gz, scope, result_info, var_decl.ast.init_node, node, force_comptime);3323 const init_inst = try reachableExprComptime(gz, scope, result_info, var_decl.ast.init_node, node, if (force_comptime) .comptime_keyword else null);
3259 gz.anon_name_strategy = prev_anon_name_strategy;3324 gz.anon_name_strategy = prev_anon_name_strategy;
32603325
3326 _ = try gz.addUnNode(.validate_const, init_inst, var_decl.ast.init_node);
3261 try gz.addDbgVar(.dbg_var_val, ident_name, init_inst);3327 try gz.addDbgVar(.dbg_var_val, ident_name, init_inst);
32623328
3263 // The const init expression may have modified the error return trace, so signal3329 // The const init expression may have modified the error return trace, so signal
...@@ -3321,7 +3387,7 @@ fn varDecl(...@@ -3321,7 +3387,7 @@ fn varDecl(
3321 const prev_anon_name_strategy = gz.anon_name_strategy;3387 const prev_anon_name_strategy = gz.anon_name_strategy;
3322 gz.anon_name_strategy = .dbg_var;3388 gz.anon_name_strategy = .dbg_var;
3323 defer gz.anon_name_strategy = prev_anon_name_strategy;3389 defer gz.anon_name_strategy = prev_anon_name_strategy;
3324 const init_inst = try reachableExprComptime(gz, scope, init_result_info, var_decl.ast.init_node, node, force_comptime);3390 const init_inst = try reachableExprComptime(gz, scope, init_result_info, var_decl.ast.init_node, node, if (force_comptime) .comptime_keyword else null);
33253391
3326 // The const init expression may have modified the error return trace, so signal3392 // The const init expression may have modified the error return trace, so signal
3327 // to Sema that it should save the new index for restoring later.3393 // to Sema that it should save the new index for restoring later.
...@@ -3393,7 +3459,14 @@ fn varDecl(...@@ -3393,7 +3459,14 @@ fn varDecl(
3393 };3459 };
3394 const prev_anon_name_strategy = gz.anon_name_strategy;3460 const prev_anon_name_strategy = gz.anon_name_strategy;
3395 gz.anon_name_strategy = .dbg_var;3461 gz.anon_name_strategy = .dbg_var;
3396 _ = try reachableExprComptime(gz, scope, result_info, var_decl.ast.init_node, node, is_comptime);3462 _ = try reachableExprComptime(
3463 gz,
3464 scope,
3465 result_info,
3466 var_decl.ast.init_node,
3467 node,
3468 if (var_decl.comptime_token != null) .comptime_keyword else null,
3469 );
3397 gz.anon_name_strategy = prev_anon_name_strategy;3470 gz.anon_name_strategy = prev_anon_name_strategy;
3398 const final_ptr: Zir.Inst.Ref = if (resolve_inferred) ptr: {3471 const final_ptr: Zir.Inst.Ref = if (resolve_inferred) ptr: {
3399 break :ptr try gz.addUnNode(.resolve_inferred_alloc, alloc, node);3472 break :ptr try gz.addUnNode(.resolve_inferred_alloc, alloc, node);
...@@ -3501,8 +3574,8 @@ fn assignDestructure(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerErro...@@ -3501,8 +3574,8 @@ fn assignDestructure(gz: *GenZir, scope: *Scope, node: Ast.Node.Index) InnerErro
35013574
3502 if (full.comptime_token) |_| {3575 if (full.comptime_token) |_| {
3503 const comptime_block_inst = try gz.makeBlockInst(.block_comptime, node);3576 const comptime_block_inst = try gz.makeBlockInst(.block_comptime, node);
3504 _ = try inner_gz.addBreak(.@"break", comptime_block_inst, .void_value);3577 _ = try inner_gz.addBreak(.break_inline, comptime_block_inst, .void_value);
3505 try inner_gz.setBlockBody(comptime_block_inst);3578 try inner_gz.setBlockComptimeBody(comptime_block_inst, .comptime_keyword);
3506 try gz.instructions.append(gz.astgen.gpa, comptime_block_inst);3579 try gz.instructions.append(gz.astgen.gpa, comptime_block_inst);
3507 }3580 }
3508}3581}
...@@ -3673,8 +3746,8 @@ fn assignDestructureMaybeDecls(...@@ -3673,8 +3746,8 @@ fn assignDestructureMaybeDecls(
3673 // Finish the block_comptime. Inferred alloc resolution etc will occur3746 // Finish the block_comptime. Inferred alloc resolution etc will occur
3674 // in the parent block.3747 // in the parent block.
3675 const comptime_block_inst = try gz.makeBlockInst(.block_comptime, node);3748 const comptime_block_inst = try gz.makeBlockInst(.block_comptime, node);
3676 _ = try inner_gz.addBreak(.@"break", comptime_block_inst, .void_value);3749 _ = try inner_gz.addBreak(.break_inline, comptime_block_inst, .void_value);
3677 try inner_gz.setBlockBody(comptime_block_inst);3750 try inner_gz.setBlockComptimeBody(comptime_block_inst, .comptime_keyword);
3678 try gz.instructions.append(gz.astgen.gpa, comptime_block_inst);3751 try gz.instructions.append(gz.astgen.gpa, comptime_block_inst);
3679 }3752 }
36803753
...@@ -3867,7 +3940,16 @@ fn ptrType(...@@ -3867,7 +3940,16 @@ fn ptrType(
3867 gz.astgen.source_line = source_line;3940 gz.astgen.source_line = source_line;
3868 gz.astgen.source_column = source_column;3941 gz.astgen.source_column = source_column;
38693942
3870 sentinel_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = elem_type } }, ptr_info.ast.sentinel);3943 sentinel_ref = try comptimeExpr(
3944 gz,
3945 scope,
3946 .{ .rl = .{ .ty = elem_type } },
3947 ptr_info.ast.sentinel,
3948 switch (ptr_info.size) {
3949 .Slice => .slice_sentinel,
3950 else => .pointer_sentinel,
3951 },
3952 );
3871 trailing_count += 1;3953 trailing_count += 1;
3872 }3954 }
3873 if (ptr_info.ast.addrspace_node != 0) {3955 if (ptr_info.ast.addrspace_node != 0) {
...@@ -3876,7 +3958,7 @@ fn ptrType(...@@ -3876,7 +3958,7 @@ fn ptrType(
3876 gz.astgen.source_column = source_column;3958 gz.astgen.source_column = source_column;
38773959
3878 const addrspace_ty = try gz.addBuiltinValue(ptr_info.ast.addrspace_node, .address_space);3960 const addrspace_ty = try gz.addBuiltinValue(ptr_info.ast.addrspace_node, .address_space);
3879 addrspace_ref = try expr(gz, scope, .{ .rl = .{ .coerced_ty = addrspace_ty } }, ptr_info.ast.addrspace_node);3961 addrspace_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = addrspace_ty } }, ptr_info.ast.addrspace_node, .@"addrspace");
3880 trailing_count += 1;3962 trailing_count += 1;
3881 }3963 }
3882 if (ptr_info.ast.align_node != 0) {3964 if (ptr_info.ast.align_node != 0) {
...@@ -3884,13 +3966,13 @@ fn ptrType(...@@ -3884,13 +3966,13 @@ fn ptrType(
3884 gz.astgen.source_line = source_line;3966 gz.astgen.source_line = source_line;
3885 gz.astgen.source_column = source_column;3967 gz.astgen.source_column = source_column;
38863968
3887 align_ref = try expr(gz, scope, coerced_align_ri, ptr_info.ast.align_node);3969 align_ref = try comptimeExpr(gz, scope, coerced_align_ri, ptr_info.ast.align_node, .@"align");
3888 trailing_count += 1;3970 trailing_count += 1;
3889 }3971 }
3890 if (ptr_info.ast.bit_range_start != 0) {3972 if (ptr_info.ast.bit_range_start != 0) {
3891 assert(ptr_info.ast.bit_range_end != 0);3973 assert(ptr_info.ast.bit_range_end != 0);
3892 bit_start_ref = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .u16_type } }, ptr_info.ast.bit_range_start);3974 bit_start_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u16_type } }, ptr_info.ast.bit_range_start, .type);
3893 bit_end_ref = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .u16_type } }, ptr_info.ast.bit_range_end);3975 bit_end_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u16_type } }, ptr_info.ast.bit_range_end, .type);
3894 trailing_count += 2;3976 trailing_count += 2;
3895 }3977 }
38963978
...@@ -3953,7 +4035,7 @@ fn arrayType(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) !...@@ -3953,7 +4035,7 @@ fn arrayType(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) !
3953 {4035 {
3954 return astgen.failNode(len_node, "unable to infer array size", .{});4036 return astgen.failNode(len_node, "unable to infer array size", .{});
3955 }4037 }
3956 const len = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, len_node);4038 const len = try reachableExprComptime(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, len_node, node, .type);
3957 const elem_type = try typeExpr(gz, scope, node_datas[node].rhs);4039 const elem_type = try typeExpr(gz, scope, node_datas[node].rhs);
39584040
3959 const result = try gz.addPlNode(.array_type, node, Zir.Inst.Bin{4041 const result = try gz.addPlNode(.array_type, node, Zir.Inst.Bin{
...@@ -3977,9 +4059,9 @@ fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node....@@ -3977,9 +4059,9 @@ fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.
3977 {4059 {
3978 return astgen.failNode(len_node, "unable to infer array size", .{});4060 return astgen.failNode(len_node, "unable to infer array size", .{});
3979 }4061 }
3980 const len = try reachableExpr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, len_node, node);4062 const len = try reachableExprComptime(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, len_node, node, .array_length);
3981 const elem_type = try typeExpr(gz, scope, extra.elem_type);4063 const elem_type = try typeExpr(gz, scope, extra.elem_type);
3982 const sentinel = try reachableExprComptime(gz, scope, .{ .rl = .{ .coerced_ty = elem_type } }, extra.sentinel, node, true);4064 const sentinel = try reachableExprComptime(gz, scope, .{ .rl = .{ .coerced_ty = elem_type } }, extra.sentinel, node, .array_sentinel);
39834065
3984 const result = try gz.addPlNode(.array_type_sentinel, node, Zir.Inst.ArrayTypeSentinel{4066 const result = try gz.addPlNode(.array_type_sentinel, node, Zir.Inst.ArrayTypeSentinel{
3985 .len = len,4067 .len = len,
...@@ -5321,7 +5403,7 @@ fn tupleDecl(...@@ -5321,7 +5403,7 @@ fn tupleDecl(
5321 astgen.scratch.appendAssumeCapacity(@intFromEnum(field_type_ref));5403 astgen.scratch.appendAssumeCapacity(@intFromEnum(field_type_ref));
53225404
5323 if (field.ast.value_expr != 0) {5405 if (field.ast.value_expr != 0) {
5324 const field_init_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_type_ref } }, field.ast.value_expr);5406 const field_init_ref = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = field_type_ref } }, field.ast.value_expr, .tuple_field_default_value);
5325 astgen.scratch.appendAssumeCapacity(@intFromEnum(field_init_ref));5407 astgen.scratch.appendAssumeCapacity(@intFromEnum(field_init_ref));
5326 } else {5408 } else {
5327 astgen.scratch.appendAssumeCapacity(@intFromEnum(Zir.Inst.Ref.none));5409 astgen.scratch.appendAssumeCapacity(@intFromEnum(Zir.Inst.Ref.none));
...@@ -5693,7 +5775,7 @@ fn containerDecl(...@@ -5693,7 +5775,7 @@ fn containerDecl(
5693 namespace.base.tag = .namespace;5775 namespace.base.tag = .namespace;
56945776
5695 const arg_inst: Zir.Inst.Ref = if (container_decl.ast.arg != 0)5777 const arg_inst: Zir.Inst.Ref = if (container_decl.ast.arg != 0)
5696 try comptimeExpr(&block_scope, &namespace.base, coerced_type_ri, container_decl.ast.arg)5778 try comptimeExpr(&block_scope, &namespace.base, coerced_type_ri, container_decl.ast.arg, .type)
5697 else5779 else
5698 .none;5780 .none;
56995781
...@@ -7573,7 +7655,7 @@ fn switchExprErrUnion(...@@ -7573,7 +7655,7 @@ fn switchExprErrUnion(
7573 if (node_tags[item_node] == .switch_range) continue;7655 if (node_tags[item_node] == .switch_range) continue;
7574 items_len += 1;7656 items_len += 1;
75757657
7576 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node);7658 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node, .switch_item);
7577 try payloads.append(gpa, @intFromEnum(item_inst));7659 try payloads.append(gpa, @intFromEnum(item_inst));
7578 }7660 }
75797661
...@@ -7583,8 +7665,8 @@ fn switchExprErrUnion(...@@ -7583,8 +7665,8 @@ fn switchExprErrUnion(
7583 if (node_tags[range] != .switch_range) continue;7665 if (node_tags[range] != .switch_range) continue;
7584 ranges_len += 1;7666 ranges_len += 1;
75857667
7586 const first = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].lhs);7668 const first = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].lhs, .switch_item);
7587 const last = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].rhs);7669 const last = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].rhs, .switch_item);
7588 try payloads.appendSlice(gpa, &[_]u32{7670 try payloads.appendSlice(gpa, &[_]u32{
7589 @intFromEnum(first), @intFromEnum(last),7671 @intFromEnum(first), @intFromEnum(last),
7590 });7672 });
...@@ -7602,7 +7684,7 @@ fn switchExprErrUnion(...@@ -7602,7 +7684,7 @@ fn switchExprErrUnion(
7602 scalar_case_index += 1;7684 scalar_case_index += 1;
7603 try payloads.resize(gpa, header_index + 2); // item, body_len7685 try payloads.resize(gpa, header_index + 2); // item, body_len
7604 const item_node = case.ast.values[0];7686 const item_node = case.ast.values[0];
7605 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node);7687 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node, .switch_item);
7606 payloads.items[header_index] = @intFromEnum(item_inst);7688 payloads.items[header_index] = @intFromEnum(item_inst);
7607 break :blk header_index + 1;7689 break :blk header_index + 1;
7608 };7690 };
...@@ -8046,7 +8128,7 @@ fn switchExpr(...@@ -8046,7 +8128,7 @@ fn switchExpr(
8046 if (node_tags[item_node] == .switch_range) continue;8128 if (node_tags[item_node] == .switch_range) continue;
8047 items_len += 1;8129 items_len += 1;
80488130
8049 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node);8131 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node, .switch_item);
8050 try payloads.append(gpa, @intFromEnum(item_inst));8132 try payloads.append(gpa, @intFromEnum(item_inst));
8051 }8133 }
80528134
...@@ -8056,8 +8138,8 @@ fn switchExpr(...@@ -8056,8 +8138,8 @@ fn switchExpr(
8056 if (node_tags[range] != .switch_range) continue;8138 if (node_tags[range] != .switch_range) continue;
8057 ranges_len += 1;8139 ranges_len += 1;
80588140
8059 const first = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].lhs);8141 const first = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].lhs, .switch_item);
8060 const last = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].rhs);8142 const last = try comptimeExpr(parent_gz, scope, item_ri, node_datas[range].rhs, .switch_item);
8061 try payloads.appendSlice(gpa, &[_]u32{8143 try payloads.appendSlice(gpa, &[_]u32{
8062 @intFromEnum(first), @intFromEnum(last),8144 @intFromEnum(first), @intFromEnum(last),
8063 });8145 });
...@@ -8075,7 +8157,7 @@ fn switchExpr(...@@ -8075,7 +8157,7 @@ fn switchExpr(
8075 scalar_case_index += 1;8157 scalar_case_index += 1;
8076 try payloads.resize(gpa, header_index + 2); // item, body_len8158 try payloads.resize(gpa, header_index + 2); // item, body_len
8077 const item_node = case.ast.values[0];8159 const item_node = case.ast.values[0];
8078 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node);8160 const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node, .switch_item);
8079 payloads.items[header_index] = @intFromEnum(item_inst);8161 payloads.items[header_index] = @intFromEnum(item_inst);
8080 break :blk header_index + 1;8162 break :blk header_index + 1;
8081 };8163 };
...@@ -8339,11 +8421,17 @@ fn parseBitCount(buf: []const u8) std.fmt.ParseIntError!u16 {...@@ -8339,11 +8421,17 @@ fn parseBitCount(buf: []const u8) std.fmt.ParseIntError!u16 {
8339 return x;8421 return x;
8340}8422}
83418423
8424const ComptimeBlockInfo = struct {
8425 src_node: Ast.Node.Index,
8426 reason: std.zig.SimpleComptimeReason,
8427};
8428
8342fn identifier(8429fn identifier(
8343 gz: *GenZir,8430 gz: *GenZir,
8344 scope: *Scope,8431 scope: *Scope,
8345 ri: ResultInfo,8432 ri: ResultInfo,
8346 ident: Ast.Node.Index,8433 ident: Ast.Node.Index,
8434 force_comptime: ?ComptimeBlockInfo,
8347) InnerError!Zir.Inst.Ref {8435) InnerError!Zir.Inst.Ref {
8348 const astgen = gz.astgen;8436 const astgen = gz.astgen;
8349 const tree = astgen.tree;8437 const tree = astgen.tree;
...@@ -8362,6 +8450,7 @@ fn identifier(...@@ -8362,6 +8450,7 @@ fn identifier(
8362 }8450 }
83638451
8364 if (ident_name_raw.len >= 2) integer: {8452 if (ident_name_raw.len >= 2) integer: {
8453 // Keep in sync with logic in `comptimeExpr2`.
8365 const first_c = ident_name_raw[0];8454 const first_c = ident_name_raw[0];
8366 if (first_c == 'i' or first_c == 'u') {8455 if (first_c == 'i' or first_c == 'u') {
8367 const signedness: std.builtin.Signedness = switch (first_c == 'i') {8456 const signedness: std.builtin.Signedness = switch (first_c == 'i') {
...@@ -8396,8 +8485,31 @@ fn identifier(...@@ -8396,8 +8485,31 @@ fn identifier(
8396 }8485 }
8397 }8486 }
83988487
8399 // Local variables, including function parameters.8488 // Local variables, including function parameters, and container-level declarations.
8400 return localVarRef(gz, scope, ri, ident, ident_token);8489
8490 if (force_comptime) |fc| {
8491 // Mirrors the logic at the end of `comptimeExpr2`.
8492 const block_inst = try gz.makeBlockInst(.block_comptime, fc.src_node);
8493
8494 var comptime_gz = gz.makeSubBlock(scope);
8495 comptime_gz.is_comptime = true;
8496 defer comptime_gz.unstack();
8497
8498 const sub_ri: ResultInfo = .{
8499 .ctx = ri.ctx,
8500 .rl = .none, // no point providing a result type, it won't change anything
8501 };
8502 const block_result = try localVarRef(&comptime_gz, scope, sub_ri, ident, ident_token);
8503 assert(!comptime_gz.endsWithNoReturn());
8504 _ = try comptime_gz.addBreak(.break_inline, block_inst, block_result);
8505
8506 try comptime_gz.setBlockComptimeBody(block_inst, fc.reason);
8507 try gz.instructions.append(astgen.gpa, block_inst);
8508
8509 return rvalue(gz, ri, block_inst.toRef(), fc.src_node);
8510 } else {
8511 return localVarRef(gz, scope, ri, ident, ident_token);
8512 }
8401}8513}
84028514
8403fn localVarRef(8515fn localVarRef(
...@@ -8836,7 +8948,7 @@ fn asmExpr(...@@ -8836,7 +8948,7 @@ fn asmExpr(
8836 },8948 },
8837 else => .{8949 else => .{
8838 .tag = .asm_expr,8950 .tag = .asm_expr,
8839 .tmpl = @enumFromInt(@intFromEnum(try comptimeExpr(gz, scope, .{ .rl = .none }, full.ast.template))),8951 .tmpl = @enumFromInt(@intFromEnum(try comptimeExpr(gz, scope, .{ .rl = .none }, full.ast.template, .inline_assembly_code))),
8840 },8952 },
8841 };8953 };
88428954
...@@ -8973,7 +9085,7 @@ fn unionInit(...@@ -8973,7 +9085,7 @@ fn unionInit(
8973 params: []const Ast.Node.Index,9085 params: []const Ast.Node.Index,
8974) InnerError!Zir.Inst.Ref {9086) InnerError!Zir.Inst.Ref {
8975 const union_type = try typeExpr(gz, scope, params[0]);9087 const union_type = try typeExpr(gz, scope, params[0]);
8976 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1]);9088 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .union_field_name);
8977 const field_type = try gz.addPlNode(.field_type_ref, node, Zir.Inst.FieldTypeRef{9089 const field_type = try gz.addPlNode(.field_type_ref, node, Zir.Inst.FieldTypeRef{
8978 .container_type = union_type,9090 .container_type = union_type,
8979 .field_name = field_name,9091 .field_name = field_name,
...@@ -9078,7 +9190,7 @@ fn ptrCast(...@@ -9078,7 +9190,7 @@ fn ptrCast(
9078 const flags_int: FlagsInt = @bitCast(flags);9190 const flags_int: FlagsInt = @bitCast(flags);
9079 const cursor = maybeAdvanceSourceCursorToMainToken(gz, root_node);9191 const cursor = maybeAdvanceSourceCursorToMainToken(gz, root_node);
9080 const parent_ptr_type = try ri.rl.resultTypeForCast(gz, root_node, "@alignCast");9192 const parent_ptr_type = try ri.rl.resultTypeForCast(gz, root_node, "@alignCast");
9081 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, node_datas[node].lhs);9193 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, node_datas[node].lhs, .field_name);
9082 const field_ptr = try expr(gz, scope, .{ .rl = .none }, node_datas[node].rhs);9194 const field_ptr = try expr(gz, scope, .{ .rl = .none }, node_datas[node].rhs);
9083 try emitDbgStmt(gz, cursor);9195 try emitDbgStmt(gz, cursor);
9084 const result = try gz.addExtendedPayloadSmall(.field_parent_ptr, flags_int, Zir.Inst.FieldParentPtr{9196 const result = try gz.addExtendedPayloadSmall(.field_parent_ptr, flags_int, Zir.Inst.FieldParentPtr{
...@@ -9279,7 +9391,7 @@ fn builtinCall(...@@ -9279,7 +9391,7 @@ fn builtinCall(
9279 return astgen.failNode(node, "'@branchHint' must appear as the first statement in a function or conditional branch", .{});9391 return astgen.failNode(node, "'@branchHint' must appear as the first statement in a function or conditional branch", .{});
9280 }9392 }
9281 const hint_ty = try gz.addBuiltinValue(node, .branch_hint);9393 const hint_ty = try gz.addBuiltinValue(node, .branch_hint);
9282 const hint_val = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = hint_ty } }, params[0]);9394 const hint_val = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = hint_ty } }, params[0], .operand_branchHint);
9283 _ = try gz.addExtendedPayload(.branch_hint, Zir.Inst.UnNode{9395 _ = try gz.addExtendedPayload(.branch_hint, Zir.Inst.UnNode{
9284 .node = gz.nodeIndexToRelative(node),9396 .node = gz.nodeIndexToRelative(node),
9285 .operand = hint_val,9397 .operand = hint_val,
...@@ -9326,18 +9438,18 @@ fn builtinCall(...@@ -9326,18 +9438,18 @@ fn builtinCall(
9326 if (ri.rl == .ref or ri.rl == .ref_coerced_ty) {9438 if (ri.rl == .ref or ri.rl == .ref_coerced_ty) {
9327 return gz.addPlNode(.field_ptr_named, node, Zir.Inst.FieldNamed{9439 return gz.addPlNode(.field_ptr_named, node, Zir.Inst.FieldNamed{
9328 .lhs = try expr(gz, scope, .{ .rl = .ref }, params[0]),9440 .lhs = try expr(gz, scope, .{ .rl = .ref }, params[0]),
9329 .field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1]),9441 .field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .field_name),
9330 });9442 });
9331 }9443 }
9332 const result = try gz.addPlNode(.field_val_named, node, Zir.Inst.FieldNamed{9444 const result = try gz.addPlNode(.field_val_named, node, Zir.Inst.FieldNamed{
9333 .lhs = try expr(gz, scope, .{ .rl = .none }, params[0]),9445 .lhs = try expr(gz, scope, .{ .rl = .none }, params[0]),
9334 .field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1]),9446 .field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .field_name),
9335 });9447 });
9336 return rvalue(gz, ri, result, node);9448 return rvalue(gz, ri, result, node);
9337 },9449 },
9338 .FieldType => {9450 .FieldType => {
9339 const ty_inst = try typeExpr(gz, scope, params[0]);9451 const ty_inst = try typeExpr(gz, scope, params[0]);
9340 const name_inst = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1]);9452 const name_inst = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[1], .field_name);
9341 const result = try gz.addPlNode(.field_type_ref, node, Zir.Inst.FieldTypeRef{9453 const result = try gz.addPlNode(.field_type_ref, node, Zir.Inst.FieldTypeRef{
9342 .container_type = ty_inst,9454 .container_type = ty_inst,
9343 .field_name = name_inst,9455 .field_name = name_inst,
...@@ -9358,7 +9470,7 @@ fn builtinCall(...@@ -9358,7 +9470,7 @@ fn builtinCall(
9358 .@"export" => {9470 .@"export" => {
9359 const exported = try expr(gz, scope, .{ .rl = .none }, params[0]);9471 const exported = try expr(gz, scope, .{ .rl = .none }, params[0]);
9360 const export_options_ty = try gz.addBuiltinValue(node, .export_options);9472 const export_options_ty = try gz.addBuiltinValue(node, .export_options);
9361 const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = export_options_ty } }, params[1]);9473 const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = export_options_ty } }, params[1], .export_options);
9362 _ = try gz.addPlNode(.@"export", node, Zir.Inst.Export{9474 _ = try gz.addPlNode(.@"export", node, Zir.Inst.Export{
9363 .exported = exported,9475 .exported = exported,
9364 .options = options,9476 .options = options,
...@@ -9368,7 +9480,7 @@ fn builtinCall(...@@ -9368,7 +9480,7 @@ fn builtinCall(
9368 .@"extern" => {9480 .@"extern" => {
9369 const type_inst = try typeExpr(gz, scope, params[0]);9481 const type_inst = try typeExpr(gz, scope, params[0]);
9370 const extern_options_ty = try gz.addBuiltinValue(node, .extern_options);9482 const extern_options_ty = try gz.addBuiltinValue(node, .extern_options);
9371 const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = extern_options_ty } }, params[1]);9483 const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = extern_options_ty } }, params[1], .extern_options);
9372 const result = try gz.addExtendedPayload(.builtin_extern, Zir.Inst.BinNode{9484 const result = try gz.addExtendedPayload(.builtin_extern, Zir.Inst.BinNode{
9373 .node = gz.nodeIndexToRelative(node),9485 .node = gz.nodeIndexToRelative(node),
9374 .lhs = type_inst,9486 .lhs = type_inst,
...@@ -9560,7 +9672,7 @@ fn builtinCall(...@@ -9560,7 +9672,7 @@ fn builtinCall(
9560 // zig fmt: on9672 // zig fmt: on
95619673
9562 .wasm_memory_size => {9674 .wasm_memory_size => {
9563 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0]);9675 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .wasm_memory_index);
9564 const result = try gz.addExtendedPayload(.wasm_memory_size, Zir.Inst.UnNode{9676 const result = try gz.addExtendedPayload(.wasm_memory_size, Zir.Inst.UnNode{
9565 .node = gz.nodeIndexToRelative(node),9677 .node = gz.nodeIndexToRelative(node),
9566 .operand = operand,9678 .operand = operand,
...@@ -9568,7 +9680,7 @@ fn builtinCall(...@@ -9568,7 +9680,7 @@ fn builtinCall(
9568 return rvalue(gz, ri, result, node);9680 return rvalue(gz, ri, result, node);
9569 },9681 },
9570 .wasm_memory_grow => {9682 .wasm_memory_grow => {
9571 const index_arg = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0]);9683 const index_arg = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .wasm_memory_index);
9572 const delta_arg = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, params[1]);9684 const delta_arg = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, params[1]);
9573 const result = try gz.addExtendedPayload(.wasm_memory_grow, Zir.Inst.BinNode{9685 const result = try gz.addExtendedPayload(.wasm_memory_grow, Zir.Inst.BinNode{
9574 .node = gz.nodeIndexToRelative(node),9686 .node = gz.nodeIndexToRelative(node),
...@@ -9579,8 +9691,8 @@ fn builtinCall(...@@ -9579,8 +9691,8 @@ fn builtinCall(
9579 },9691 },
9580 .c_define => {9692 .c_define => {
9581 if (!gz.c_import) return gz.astgen.failNode(node, "C define valid only inside C import block", .{});9693 if (!gz.c_import) return gz.astgen.failNode(node, "C define valid only inside C import block", .{});
9582 const name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[0]);9694 const name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[0], .operand_cDefine_macro_name);
9583 const value = try comptimeExpr(gz, scope, .{ .rl = .none }, params[1]);9695 const value = try comptimeExpr(gz, scope, .{ .rl = .none }, params[1], .operand_cDefine_macro_value);
9584 const result = try gz.addExtendedPayload(.c_define, Zir.Inst.BinNode{9696 const result = try gz.addExtendedPayload(.c_define, Zir.Inst.BinNode{
9585 .node = gz.nodeIndexToRelative(node),9697 .node = gz.nodeIndexToRelative(node),
9586 .lhs = name,9698 .lhs = name,
...@@ -9666,7 +9778,7 @@ fn builtinCall(...@@ -9666,7 +9778,7 @@ fn builtinCall(
9666 },9778 },
9667 .call => {9779 .call => {
9668 const call_modifier_ty = try gz.addBuiltinValue(node, .call_modifier);9780 const call_modifier_ty = try gz.addBuiltinValue(node, .call_modifier);
9669 const modifier = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = call_modifier_ty } }, params[0]);9781 const modifier = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = call_modifier_ty } }, params[0], .call_modifier);
9670 const callee = try expr(gz, scope, .{ .rl = .none }, params[1]);9782 const callee = try expr(gz, scope, .{ .rl = .none }, params[1]);
9671 const args = try expr(gz, scope, .{ .rl = .none }, params[2]);9783 const args = try expr(gz, scope, .{ .rl = .none }, params[2]);
9672 const result = try gz.addPlNode(.builtin_call, node, Zir.Inst.BuiltinCall{9784 const result = try gz.addPlNode(.builtin_call, node, Zir.Inst.BuiltinCall{
...@@ -9682,7 +9794,7 @@ fn builtinCall(...@@ -9682,7 +9794,7 @@ fn builtinCall(
9682 },9794 },
9683 .field_parent_ptr => {9795 .field_parent_ptr => {
9684 const parent_ptr_type = try ri.rl.resultTypeForCast(gz, node, builtin_name);9796 const parent_ptr_type = try ri.rl.resultTypeForCast(gz, node, builtin_name);
9685 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[0]);9797 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[0], .field_name);
9686 const result = try gz.addExtendedPayloadSmall(.field_parent_ptr, 0, Zir.Inst.FieldParentPtr{9798 const result = try gz.addExtendedPayloadSmall(.field_parent_ptr, 0, Zir.Inst.FieldParentPtr{
9687 .src_node = gz.nodeIndexToRelative(node),9799 .src_node = gz.nodeIndexToRelative(node),
9688 .parent_ptr_type = parent_ptr_type,9800 .parent_ptr_type = parent_ptr_type,
...@@ -9713,7 +9825,7 @@ fn builtinCall(...@@ -9713,7 +9825,7 @@ fn builtinCall(
9713 .elem_type = try typeExpr(gz, scope, params[0]),9825 .elem_type = try typeExpr(gz, scope, params[0]),
9714 .a = try expr(gz, scope, .{ .rl = .none }, params[1]),9826 .a = try expr(gz, scope, .{ .rl = .none }, params[1]),
9715 .b = try expr(gz, scope, .{ .rl = .none }, params[2]),9827 .b = try expr(gz, scope, .{ .rl = .none }, params[2]),
9716 .mask = try comptimeExpr(gz, scope, .{ .rl = .none }, params[3]),9828 .mask = try comptimeExpr(gz, scope, .{ .rl = .none }, params[3], .operand_shuffle_mask),
9717 });9829 });
9718 return rvalue(gz, ri, result, node);9830 return rvalue(gz, ri, result, node);
9719 },9831 },
...@@ -9739,7 +9851,7 @@ fn builtinCall(...@@ -9739,7 +9851,7 @@ fn builtinCall(
9739 },9851 },
9740 .Vector => {9852 .Vector => {
9741 const result = try gz.addPlNode(.vector_type, node, Zir.Inst.Bin{9853 const result = try gz.addPlNode(.vector_type, node, Zir.Inst.Bin{
9742 .lhs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0]),9854 .lhs = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .type),
9743 .rhs = try typeExpr(gz, scope, params[1]),9855 .rhs = try typeExpr(gz, scope, params[1]),
9744 });9856 });
9745 return rvalue(gz, ri, result, node);9857 return rvalue(gz, ri, result, node);
...@@ -9747,7 +9859,7 @@ fn builtinCall(...@@ -9747,7 +9859,7 @@ fn builtinCall(
9747 .prefetch => {9859 .prefetch => {
9748 const prefetch_options_ty = try gz.addBuiltinValue(node, .prefetch_options);9860 const prefetch_options_ty = try gz.addBuiltinValue(node, .prefetch_options);
9749 const ptr = try expr(gz, scope, .{ .rl = .none }, params[0]);9861 const ptr = try expr(gz, scope, .{ .rl = .none }, params[0]);
9750 const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = prefetch_options_ty } }, params[1]);9862 const options = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = prefetch_options_ty } }, params[1], .prefetch_options);
9751 _ = try gz.addExtendedPayload(.prefetch, Zir.Inst.BinNode{9863 _ = try gz.addExtendedPayload(.prefetch, Zir.Inst.BinNode{
9752 .node = gz.nodeIndexToRelative(node),9864 .node = gz.nodeIndexToRelative(node),
9753 .lhs = ptr,9865 .lhs = ptr,
...@@ -9785,7 +9897,7 @@ fn builtinCall(...@@ -9785,7 +9897,7 @@ fn builtinCall(
9785 },9897 },
97869898
9787 .work_item_id => {9899 .work_item_id => {
9788 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0]);9900 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .work_group_dim_index);
9789 const result = try gz.addExtendedPayload(.work_item_id, Zir.Inst.UnNode{9901 const result = try gz.addExtendedPayload(.work_item_id, Zir.Inst.UnNode{
9790 .node = gz.nodeIndexToRelative(node),9902 .node = gz.nodeIndexToRelative(node),
9791 .operand = operand,9903 .operand = operand,
...@@ -9793,7 +9905,7 @@ fn builtinCall(...@@ -9793,7 +9905,7 @@ fn builtinCall(
9793 return rvalue(gz, ri, result, node);9905 return rvalue(gz, ri, result, node);
9794 },9906 },
9795 .work_group_size => {9907 .work_group_size => {
9796 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0]);9908 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .work_group_dim_index);
9797 const result = try gz.addExtendedPayload(.work_group_size, Zir.Inst.UnNode{9909 const result = try gz.addExtendedPayload(.work_group_size, Zir.Inst.UnNode{
9798 .node = gz.nodeIndexToRelative(node),9910 .node = gz.nodeIndexToRelative(node),
9799 .operand = operand,9911 .operand = operand,
...@@ -9801,7 +9913,7 @@ fn builtinCall(...@@ -9801,7 +9913,7 @@ fn builtinCall(
9801 return rvalue(gz, ri, result, node);9913 return rvalue(gz, ri, result, node);
9802 },9914 },
9803 .work_group_id => {9915 .work_group_id => {
9804 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0]);9916 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .u32_type } }, params[0], .work_group_dim_index);
9805 const result = try gz.addExtendedPayload(.work_group_id, Zir.Inst.UnNode{9917 const result = try gz.addExtendedPayload(.work_group_id, Zir.Inst.UnNode{
9806 .node = gz.nodeIndexToRelative(node),9918 .node = gz.nodeIndexToRelative(node),
9807 .operand = operand,9919 .operand = operand,
...@@ -9821,7 +9933,13 @@ fn hasDeclOrField(...@@ -9821,7 +9933,13 @@ fn hasDeclOrField(
9821 tag: Zir.Inst.Tag,9933 tag: Zir.Inst.Tag,
9822) InnerError!Zir.Inst.Ref {9934) InnerError!Zir.Inst.Ref {
9823 const container_type = try typeExpr(gz, scope, lhs_node);9935 const container_type = try typeExpr(gz, scope, lhs_node);
9824 const name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, rhs_node);9936 const name = try comptimeExpr(
9937 gz,
9938 scope,
9939 .{ .rl = .{ .coerced_ty = .slice_const_u8_type } },
9940 rhs_node,
9941 if (tag == .has_decl) .decl_name else .field_name,
9942 );
9825 const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{9943 const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
9826 .lhs = container_type,9944 .lhs = container_type,
9827 .rhs = name,9945 .rhs = name,
...@@ -9874,7 +9992,7 @@ fn simpleUnOp(...@@ -9874,7 +9992,7 @@ fn simpleUnOp(
9874) InnerError!Zir.Inst.Ref {9992) InnerError!Zir.Inst.Ref {
9875 const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);9993 const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
9876 const operand = if (tag == .compile_error)9994 const operand = if (tag == .compile_error)
9877 try comptimeExpr(gz, scope, operand_ri, operand_node)9995 try comptimeExpr(gz, scope, operand_ri, operand_node, .compile_error_string)
9878 else9996 else
9879 try expr(gz, scope, operand_ri, operand_node);9997 try expr(gz, scope, operand_ri, operand_node);
9880 switch (tag) {9998 switch (tag) {
...@@ -9972,7 +10090,13 @@ fn simpleCBuiltin(...@@ -9972,7 +10090,13 @@ fn simpleCBuiltin(
9972) InnerError!Zir.Inst.Ref {10090) InnerError!Zir.Inst.Ref {
9973 const name: []const u8 = if (tag == .c_undef) "C undef" else "C include";10091 const name: []const u8 = if (tag == .c_undef) "C undef" else "C include";
9974 if (!gz.c_import) return gz.astgen.failNode(node, "{s} valid only inside C import block", .{name});10092 if (!gz.c_import) return gz.astgen.failNode(node, "{s} valid only inside C import block", .{name});
9975 const operand = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, operand_node);10093 const operand = try comptimeExpr(
10094 gz,
10095 scope,
10096 .{ .rl = .{ .coerced_ty = .slice_const_u8_type } },
10097 operand_node,
10098 if (tag == .c_undef) .operand_cUndef_macro_name else .operand_cInclude_file_name,
10099 );
9976 _ = try gz.addExtendedPayload(tag, Zir.Inst.UnNode{10100 _ = try gz.addExtendedPayload(tag, Zir.Inst.UnNode{
9977 .node = gz.nodeIndexToRelative(node),10101 .node = gz.nodeIndexToRelative(node),
9978 .operand = operand,10102 .operand = operand,
...@@ -9990,7 +10114,7 @@ fn offsetOf(...@@ -9990,7 +10114,7 @@ fn offsetOf(
9990 tag: Zir.Inst.Tag,10114 tag: Zir.Inst.Tag,
9991) InnerError!Zir.Inst.Ref {10115) InnerError!Zir.Inst.Ref {
9992 const type_inst = try typeExpr(gz, scope, lhs_node);10116 const type_inst = try typeExpr(gz, scope, lhs_node);
9993 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, rhs_node);10117 const field_name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, rhs_node, .field_name);
9994 const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{10118 const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
9995 .lhs = type_inst,10119 .lhs = type_inst,
9996 .rhs = field_name,10120 .rhs = field_name,
...@@ -11996,11 +12120,16 @@ const GenZir = struct {...@@ -11996,11 +12120,16 @@ const GenZir = struct {
11996 }12120 }
1199712121
11998 /// Assumes nothing stacked on `gz`. Unstacks `gz`.12122 /// Assumes nothing stacked on `gz`. Unstacks `gz`.
12123 /// Asserts `inst` is not a `block_comptime`.
11999 fn setBlockBody(gz: *GenZir, inst: Zir.Inst.Index) !void {12124 fn setBlockBody(gz: *GenZir, inst: Zir.Inst.Index) !void {
12000 const astgen = gz.astgen;12125 const astgen = gz.astgen;
12001 const gpa = astgen.gpa;12126 const gpa = astgen.gpa;
12002 const body = gz.instructionsSlice();12127 const body = gz.instructionsSlice();
12003 const body_len = astgen.countBodyLenAfterFixups(body);12128 const body_len = astgen.countBodyLenAfterFixups(body);
12129
12130 const zir_tags = astgen.instructions.items(.tag);
12131 assert(zir_tags[@intFromEnum(inst)] != .block_comptime); // use `setComptimeBlockBody` instead
12132
12004 try astgen.extra.ensureUnusedCapacity(12133 try astgen.extra.ensureUnusedCapacity(
12005 gpa,12134 gpa,
12006 @typeInfo(Zir.Inst.Block).@"struct".fields.len + body_len,12135 @typeInfo(Zir.Inst.Block).@"struct".fields.len + body_len,
...@@ -12013,6 +12142,32 @@ const GenZir = struct {...@@ -12013,6 +12142,32 @@ const GenZir = struct {
12013 gz.unstack();12142 gz.unstack();
12014 }12143 }
1201512144
12145 /// Assumes nothing stacked on `gz`. Unstacks `gz`.
12146 /// Asserts `inst` is a `block_comptime`.
12147 fn setBlockComptimeBody(gz: *GenZir, inst: Zir.Inst.Index, comptime_reason: std.zig.SimpleComptimeReason) !void {
12148 const astgen = gz.astgen;
12149 const gpa = astgen.gpa;
12150 const body = gz.instructionsSlice();
12151 const body_len = astgen.countBodyLenAfterFixups(body);
12152
12153 const zir_tags = astgen.instructions.items(.tag);
12154 assert(zir_tags[@intFromEnum(inst)] == .block_comptime); // use `setBlockBody` instead
12155
12156 try astgen.extra.ensureUnusedCapacity(
12157 gpa,
12158 @typeInfo(Zir.Inst.BlockComptime).@"struct".fields.len + body_len,
12159 );
12160 const zir_datas = astgen.instructions.items(.data);
12161 zir_datas[@intFromEnum(inst)].pl_node.payload_index = astgen.addExtraAssumeCapacity(
12162 Zir.Inst.BlockComptime{
12163 .reason = comptime_reason,
12164 .body_len = body_len,
12165 },
12166 );
12167 astgen.appendBodyWithFixups(body);
12168 gz.unstack();
12169 }
12170
12016 /// Assumes nothing stacked on `gz`. Unstacks `gz`.12171 /// Assumes nothing stacked on `gz`. Unstacks `gz`.
12017 fn setTryBody(gz: *GenZir, inst: Zir.Inst.Index, operand: Zir.Inst.Ref) !void {12172 fn setTryBody(gz: *GenZir, inst: Zir.Inst.Index, operand: Zir.Inst.Ref) !void {
12018 const astgen = gz.astgen;12173 const astgen = gz.astgen;
lib/std/zig/Zir.zig+26-2
...@@ -78,6 +78,7 @@ pub fn extraData(code: Zir, comptime T: type, index: usize) ExtraData(T) {...@@ -78,6 +78,7 @@ pub fn extraData(code: Zir, comptime T: type, index: usize) ExtraData(T) {
78 Inst.Ref,78 Inst.Ref,
79 Inst.Index,79 Inst.Index,
80 Inst.Declaration.Name,80 Inst.Declaration.Name,
81 std.zig.SimpleComptimeReason,
81 NullTerminatedString,82 NullTerminatedString,
82 => @enumFromInt(code.extra[i]),83 => @enumFromInt(code.extra[i]),
8384
...@@ -291,7 +292,8 @@ pub const Inst = struct {...@@ -291,7 +292,8 @@ pub const Inst = struct {
291 /// Uses the `pl_node` union field. Payload is `Block`.292 /// Uses the `pl_node` union field. Payload is `Block`.
292 block,293 block,
293 /// Like `block`, but forces full evaluation of its contents at compile-time.294 /// Like `block`, but forces full evaluation of its contents at compile-time.
294 /// Uses the `pl_node` union field. Payload is `Block`.295 /// Exited with `break_inline`.
296 /// Uses the `pl_node` union field. Payload is `BlockComptime`.
295 block_comptime,297 block_comptime,
296 /// A list of instructions which are analyzed in the parent context, without298 /// A list of instructions which are analyzed in the parent context, without
297 /// generating a runtime block. Must terminate with an "inline" variant of299 /// generating a runtime block. Must terminate with an "inline" variant of
...@@ -709,6 +711,12 @@ pub const Inst = struct {...@@ -709,6 +711,12 @@ pub const Inst = struct {
709 /// operator. Emit a compile error if not.711 /// operator. Emit a compile error if not.
710 /// Uses the `un_tok` union field. Token is the `&` operator. Operand is the type.712 /// Uses the `un_tok` union field. Token is the `&` operator. Operand is the type.
711 validate_ref_ty,713 validate_ref_ty,
714 /// Given a value, check whether it is a valid local constant in this scope.
715 /// In a runtime scope, this is always a nop.
716 /// In a comptime scope, raises a compile error if the value is runtime-known.
717 /// Result is always void.
718 /// Uses the `un_node` union field. Node is the initializer. Operand is the initializer value.
719 validate_const,
712 /// Given a type `T`, construct the type `E!T`, where `E` is this function's error set, to be used720 /// Given a type `T`, construct the type `E!T`, where `E` is this function's error set, to be used
713 /// as the result type of a `try` operand. Generic poison is propagated.721 /// as the result type of a `try` operand. Generic poison is propagated.
714 /// Uses the `un_node` union field. Node is the `try` expression. Operand is the type `T`.722 /// Uses the `un_node` union field. Node is the `try` expression. Operand is the type `T`.
...@@ -1291,6 +1299,7 @@ pub const Inst = struct {...@@ -1291,6 +1299,7 @@ pub const Inst = struct {
1291 .array_init_elem_type,1299 .array_init_elem_type,
1292 .array_init_elem_ptr,1300 .array_init_elem_ptr,
1293 .validate_ref_ty,1301 .validate_ref_ty,
1302 .validate_const,
1294 .try_operand_ty,1303 .try_operand_ty,
1295 .try_ref_operand_ty,1304 .try_ref_operand_ty,
1296 .restore_err_ret_index_unconditional,1305 .restore_err_ret_index_unconditional,
...@@ -1351,6 +1360,7 @@ pub const Inst = struct {...@@ -1351,6 +1360,7 @@ pub const Inst = struct {
1351 .validate_array_init_result_ty,1360 .validate_array_init_result_ty,
1352 .validate_ptr_array_init,1361 .validate_ptr_array_init,
1353 .validate_ref_ty,1362 .validate_ref_ty,
1363 .validate_const,
1354 .try_operand_ty,1364 .try_operand_ty,
1355 .try_ref_operand_ty,1365 .try_ref_operand_ty,
1356 => true,1366 => true,
...@@ -1734,6 +1744,7 @@ pub const Inst = struct {...@@ -1734,6 +1744,7 @@ pub const Inst = struct {
1734 .opt_eu_base_ptr_init = .un_node,1744 .opt_eu_base_ptr_init = .un_node,
1735 .coerce_ptr_elem_ty = .pl_node,1745 .coerce_ptr_elem_ty = .pl_node,
1736 .validate_ref_ty = .un_tok,1746 .validate_ref_ty = .un_tok,
1747 .validate_const = .un_node,
1737 .try_operand_ty = .un_node,1748 .try_operand_ty = .un_node,
1738 .try_ref_operand_ty = .un_node,1749 .try_ref_operand_ty = .un_node,
17391750
...@@ -2547,6 +2558,13 @@ pub const Inst = struct {...@@ -2547,6 +2558,13 @@ pub const Inst = struct {
2547 body_len: u32,2558 body_len: u32,
2548 };2559 };
25492560
2561 /// Trailing:
2562 /// * inst: Index // for each `body_len`
2563 pub const BlockComptime = struct {
2564 reason: std.zig.SimpleComptimeReason,
2565 body_len: u32,
2566 };
2567
2550 /// Trailing:2568 /// Trailing:
2551 /// * inst: Index // for each `body_len`2569 /// * inst: Index // for each `body_len`
2552 pub const BoolBr = struct {2570 pub const BoolBr = struct {
...@@ -4134,6 +4152,7 @@ fn findTrackableInner(...@@ -4134,6 +4152,7 @@ fn findTrackableInner(
4134 .opt_eu_base_ptr_init,4152 .opt_eu_base_ptr_init,
4135 .coerce_ptr_elem_ty,4153 .coerce_ptr_elem_ty,
4136 .validate_ref_ty,4154 .validate_ref_ty,
4155 .validate_const,
4137 .try_operand_ty,4156 .try_operand_ty,
4138 .try_ref_operand_ty,4157 .try_ref_operand_ty,
4139 .struct_init_empty,4158 .struct_init_empty,
...@@ -4517,7 +4536,6 @@ fn findTrackableInner(...@@ -4517,7 +4536,6 @@ fn findTrackableInner(
4517 // Block instructions, recurse over the bodies.4536 // Block instructions, recurse over the bodies.
45184537
4519 .block,4538 .block,
4520 .block_comptime,
4521 .block_inline,4539 .block_inline,
4522 .c_import,4540 .c_import,
4523 .typeof_builtin,4541 .typeof_builtin,
...@@ -4528,6 +4546,12 @@ fn findTrackableInner(...@@ -4528,6 +4546,12 @@ fn findTrackableInner(
4528 const body = zir.bodySlice(extra.end, extra.data.body_len);4546 const body = zir.bodySlice(extra.end, extra.data.body_len);
4529 return zir.findTrackableBody(gpa, contents, defers, body);4547 return zir.findTrackableBody(gpa, contents, defers, body);
4530 },4548 },
4549 .block_comptime => {
4550 const inst_data = datas[@intFromEnum(inst)].pl_node;
4551 const extra = zir.extraData(Inst.BlockComptime, inst_data.payload_index);
4552 const body = zir.bodySlice(extra.end, extra.data.body_len);
4553 return zir.findTrackableBody(gpa, contents, defers, body);
4554 },
4531 .condbr, .condbr_inline => {4555 .condbr, .condbr_inline => {
4532 const inst_data = datas[@intFromEnum(inst)].pl_node;4556 const inst_data = datas[@intFromEnum(inst)].pl_node;
4533 const extra = zir.extraData(Inst.CondBr, inst_data.payload_index);4557 const extra = zir.extraData(Inst.CondBr, inst_data.payload_index);
src/Compilation.zig+5-1
...@@ -3435,6 +3435,7 @@ pub fn addModuleErrorMsg(...@@ -3435,6 +3435,7 @@ pub fn addModuleErrorMsg(
3435 var notes: std.ArrayHashMapUnmanaged(ErrorBundle.ErrorMessage, void, ErrorNoteHashContext, true) = .empty;3435 var notes: std.ArrayHashMapUnmanaged(ErrorBundle.ErrorMessage, void, ErrorNoteHashContext, true) = .empty;
3436 defer notes.deinit(gpa);3436 defer notes.deinit(gpa);
34373437
3438 var last_note_loc: ?std.zig.Loc = null;
3438 for (module_err_msg.notes) |module_note| {3439 for (module_err_msg.notes) |module_note| {
3439 const note_src_loc = module_note.src_loc.upgrade(zcu);3440 const note_src_loc = module_note.src_loc.upgrade(zcu);
3440 const source = try note_src_loc.file_scope.getSource(gpa);3441 const source = try note_src_loc.file_scope.getSource(gpa);
...@@ -3443,6 +3444,9 @@ pub fn addModuleErrorMsg(...@@ -3443,6 +3444,9 @@ pub fn addModuleErrorMsg(
3443 const note_file_path = try note_src_loc.file_scope.fullPath(gpa);3444 const note_file_path = try note_src_loc.file_scope.fullPath(gpa);
3444 defer gpa.free(note_file_path);3445 defer gpa.free(note_file_path);
34453446
3447 const omit_source_line = loc.eql(err_loc) or (last_note_loc != null and loc.eql(last_note_loc.?));
3448 last_note_loc = loc;
3449
3446 const gop = try notes.getOrPutContext(gpa, .{3450 const gop = try notes.getOrPutContext(gpa, .{
3447 .msg = try eb.addString(module_note.msg),3451 .msg = try eb.addString(module_note.msg),
3448 .src_loc = try eb.addSourceLocation(.{3452 .src_loc = try eb.addSourceLocation(.{
...@@ -3452,7 +3456,7 @@ pub fn addModuleErrorMsg(...@@ -3452,7 +3456,7 @@ pub fn addModuleErrorMsg(
3452 .span_end = span.end,3456 .span_end = span.end,
3453 .line = @intCast(loc.line),3457 .line = @intCast(loc.line),
3454 .column = @intCast(loc.column),3458 .column = @intCast(loc.column),
3455 .source_line = if (err_loc.eql(loc)) 0 else try eb.addString(loc.source_line),3459 .source_line = if (omit_source_line) 0 else try eb.addString(loc.source_line),
3456 }),3460 }),
3457 }, .{ .eb = eb });3461 }, .{ .eb = eb });
3458 if (gop.found_existing) {3462 if (gop.found_existing) {
src/Sema.zig+506-635
...@@ -377,9 +377,7 @@ pub const Block = struct {...@@ -377,9 +377,7 @@ pub const Block = struct {
377 runtime_index: RuntimeIndex = .zero,377 runtime_index: RuntimeIndex = .zero,
378 inline_block: Zir.Inst.OptionalIndex = .none,378 inline_block: Zir.Inst.OptionalIndex = .none,
379379
380 comptime_reason: ?*const ComptimeReason = null,380 comptime_reason: ?BlockComptimeReason = null,
381 // TODO is_comptime and comptime_reason should probably be merged together.
382 is_comptime: bool,
383 is_typeof: bool = false,381 is_typeof: bool = false,
384382
385 /// Keep track of the active error return trace index around blocks so that we can correctly383 /// Keep track of the active error return trace index around blocks so that we can correctly
...@@ -419,6 +417,10 @@ pub const Block = struct {...@@ -419,6 +417,10 @@ pub const Block = struct {
419 };417 };
420 }418 }
421419
420 fn isComptime(block: Block) bool {
421 return block.comptime_reason != null;
422 }
423
422 fn builtinCallArgSrc(block: *Block, builtin_call_node: i32, arg_index: u32) LazySrcLoc {424 fn builtinCallArgSrc(block: *Block, builtin_call_node: i32, arg_index: u32) LazySrcLoc {
423 return block.src(.{ .node_offset_builtin_call_arg = .{425 return block.src(.{ .node_offset_builtin_call_arg = .{
424 .builtin_call_node = builtin_call_node,426 .builtin_call_node = builtin_call_node,
...@@ -434,44 +436,6 @@ pub const Block = struct {...@@ -434,44 +436,6 @@ pub const Block = struct {
434 return block.src(.{ .token_offset = tok_offset });436 return block.src(.{ .token_offset = tok_offset });
435 }437 }
436438
437 const ComptimeReason = union(enum) {
438 c_import: struct {
439 src: LazySrcLoc,
440 },
441 comptime_ret_ty: struct {
442 func: Air.Inst.Ref,
443 func_src: LazySrcLoc,
444 return_ty: Type,
445 },
446
447 fn explain(cr: ComptimeReason, sema: *Sema, msg: ?*Zcu.ErrorMsg) !void {
448 const parent = msg orelse return;
449 const pt = sema.pt;
450 const prefix = "expression is evaluated at comptime because ";
451 switch (cr) {
452 .c_import => |ci| {
453 try sema.errNote(ci.src, parent, prefix ++ "it is inside a @cImport", .{});
454 },
455 .comptime_ret_ty => |rt| {
456 const ret_ty_src: LazySrcLoc = if (try sema.funcDeclSrcInst(rt.func)) |fn_decl_inst| .{
457 .base_node_inst = fn_decl_inst,
458 .offset = .{ .node_offset_fn_type_ret_ty = 0 },
459 } else rt.func_src;
460 if (rt.return_ty.isGenericPoison()) {
461 return sema.errNote(ret_ty_src, parent, prefix ++ "the generic function was instantiated with a comptime-only return type", .{});
462 }
463 try sema.errNote(
464 ret_ty_src,
465 parent,
466 prefix ++ "the function returns a comptime-only type '{}'",
467 .{rt.return_ty.fmt(pt)},
468 );
469 try sema.explainWhyTypeIsComptime(parent, ret_ty_src, rt.return_ty);
470 },
471 }
472 }
473 };
474
475 const Param = struct {439 const Param = struct {
476 /// `none` means `anytype`.440 /// `none` means `anytype`.
477 ty: InternPool.Index,441 ty: InternPool.Index,
...@@ -539,7 +503,6 @@ pub const Block = struct {...@@ -539,7 +503,6 @@ pub const Block = struct {
539 .instructions = .{},503 .instructions = .{},
540 .label = null,504 .label = null,
541 .inlining = parent.inlining,505 .inlining = parent.inlining,
542 .is_comptime = parent.is_comptime,
543 .comptime_reason = parent.comptime_reason,506 .comptime_reason = parent.comptime_reason,
544 .is_typeof = parent.is_typeof,507 .is_typeof = parent.is_typeof,
545 .runtime_cond = parent.runtime_cond,508 .runtime_cond = parent.runtime_cond,
...@@ -860,6 +823,83 @@ pub const Block = struct {...@@ -860,6 +823,83 @@ pub const Block = struct {
860 .inst = inst,823 .inst = inst,
861 });824 });
862 }825 }
826
827 /// Returns the `*Block` that should be passed to `Sema.failWithOwnedErrorMsg`, because all inline
828 /// calls below it have already been reported with "called at comptime from here" notes.
829 fn explainWhyBlockIsComptime(start_block: *Block, err_msg: *Zcu.ErrorMsg) !*Block {
830 const sema = start_block.sema;
831 var block = start_block;
832 while (true) {
833 switch (block.comptime_reason.?) {
834 .inlining_parent => {
835 const inlining = block.inlining.?;
836 try sema.errNote(inlining.call_src, err_msg, "called at comptime from here", .{});
837 block = inlining.call_block;
838 },
839 .reason => |r| {
840 try r.r.explain(sema, r.src, err_msg);
841 return block;
842 },
843 }
844 }
845 }
846};
847
848/// Represents the reason we are resolving a value or evaluating code at comptime.
849/// Most reasons are represented by a `std.zig.SimpleComptimeReason`, which provides a plain message.
850const ComptimeReason = union(enum) {
851 /// Evaluating at comptime for a reason in the `std.zig.SimpleComptimeReason` enum.
852 simple: std.zig.SimpleComptimeReason,
853
854 /// Evaluating at comptime because of a comptime-only type. This field is separate so that
855 /// the type in question can be included in the error message. AstGen could never emit this
856 /// reason, because it knows nothing of types.
857 /// The format string looks like "foo '{}' bar", where "{}" is the comptime-only type.
858 /// We will then explain why this type is comptime-only.
859 comptime_only: struct {
860 ty: Type,
861 msg: enum {
862 union_init,
863 struct_init,
864 tuple_init,
865 param_ty_arg,
866 ret_ty_call,
867 ret_ty_generic_call,
868 },
869 },
870
871 fn explain(reason: ComptimeReason, sema: *Sema, src: LazySrcLoc, err_msg: *Zcu.ErrorMsg) !void {
872 switch (reason) {
873 .simple => |simple| {
874 try sema.errNote(src, err_msg, "{s}", .{simple.message()});
875 },
876 .comptime_only => |co| {
877 const pre, const post = switch (co.msg) {
878 .union_init => .{ "initializer of comptime-only union", "must be comptime-known" },
879 .struct_init => .{ "initializer of comptime-only struct", "must be comptime-known" },
880 .tuple_init => .{ "initializer of comptime-only tuple", "must be comptime-known" },
881 .param_ty_arg => .{ "argument to parameter with comptime-only type", "must be comptime-known" },
882 .ret_ty_call => .{ "function with comptime-only return type", "is evaluated at comptime" },
883 .ret_ty_generic_call => .{ "generic function instantiated with comptime-only return type", "is evaluated at comptime" },
884 };
885 try sema.errNote(src, err_msg, "{s} '{}' {s}", .{ pre, co.ty.fmt(sema.pt), post });
886 try sema.explainWhyTypeIsComptime(err_msg, src, co.ty);
887 },
888 }
889 }
890};
891
892/// Represents the reason a `Block` is being evaluated at comptime.
893const BlockComptimeReason = union(enum) {
894 /// This block inherits being comptime-only from the `inlining` call site.
895 inlining_parent,
896
897 /// Comptime evaluation began somewhere in the current function for a given `ComptimeReason`.
898 reason: struct {
899 /// The source location which this reason originates from. `r` is reported here.
900 src: LazySrcLoc,
901 r: ComptimeReason,
902 },
863};903};
864904
865const LabeledBlock = struct {905const LabeledBlock = struct {
...@@ -885,12 +925,6 @@ const InferredAlloc = struct {...@@ -885,12 +925,6 @@ const InferredAlloc = struct {
885 prongs: std.ArrayListUnmanaged(Air.Inst.Index) = .empty,925 prongs: std.ArrayListUnmanaged(Air.Inst.Index) = .empty,
886};926};
887927
888const NeededComptimeReason = struct {
889 needed_comptime_reason: []const u8,
890 value_comptime_reason: ?[]const u8 = null,
891 block_comptime_reason: ?*const Block.ComptimeReason = null,
892};
893
894pub fn deinit(sema: *Sema) void {928pub fn deinit(sema: *Sema) void {
895 const gpa = sema.gpa;929 const gpa = sema.gpa;
896 sema.air_instructions.deinit(gpa);930 sema.air_instructions.deinit(gpa);
...@@ -954,7 +988,7 @@ pub fn analyzeFnBody(...@@ -954,7 +988,7 @@ pub fn analyzeFnBody(
954/// we are evaluating at comptime, semantically analyze the body and return the result from it.988/// we are evaluating at comptime, semantically analyze the body and return the result from it.
955/// Returns `null` if control flow did not break from this block, but instead terminated with some989/// Returns `null` if control flow did not break from this block, but instead terminated with some
956/// other runtime noreturn instruction. Compile-time breaks to blocks further up the stack still990/// other runtime noreturn instruction. Compile-time breaks to blocks further up the stack still
957/// return `error.ComptimeBreak`. If `block.is_comptime`, this function will never return `null`.991/// return `error.ComptimeBreak`. If `block.isComptime()`, this function will never return `null`.
958fn analyzeInlineBody(992fn analyzeInlineBody(
959 sema: *Sema,993 sema: *Sema,
960 block: *Block,994 block: *Block,
...@@ -1003,7 +1037,7 @@ pub fn resolveInlineBody(...@@ -1003,7 +1037,7 @@ pub fn resolveInlineBody(
1003/// If this function returns normally, the merges of `block` were populated with all possible1037/// If this function returns normally, the merges of `block` were populated with all possible
1004/// (runtime) results of this block. Peer type resolution should be performed on the result,1038/// (runtime) results of this block. Peer type resolution should be performed on the result,
1005/// and relevant runtime instructions written to perform necessary coercions and breaks. See1039/// and relevant runtime instructions written to perform necessary coercions and breaks. See
1006/// `resolveAnalyzedBlock`. This form of return is impossible if `block.is_comptime == true`.1040/// `resolveAnalyzedBlock`. This form of return is impossible if `block.isComptime()`.
1007///1041///
1008/// Alternatively, this function may return `error.ComptimeBreak`. This indicates that comptime1042/// Alternatively, this function may return `error.ComptimeBreak`. This indicates that comptime
1009/// control flow is happening, and we are breaking at comptime from a block indicated by the1043/// control flow is happening, and we are breaking at comptime from a block indicated by the
...@@ -1340,7 +1374,7 @@ fn analyzeBodyInner(...@@ -1340,7 +1374,7 @@ fn analyzeBodyInner(
1340 continue;1374 continue;
1341 },1375 },
1342 .breakpoint => {1376 .breakpoint => {
1343 if (!block.is_comptime) {1377 if (!block.isComptime()) {
1344 _ = try block.addNoOp(.breakpoint);1378 _ = try block.addNoOp(.breakpoint);
1345 }1379 }
1346 i += 1;1380 i += 1;
...@@ -1474,6 +1508,11 @@ fn analyzeBodyInner(...@@ -1474,6 +1508,11 @@ fn analyzeBodyInner(
1474 i += 1;1508 i += 1;
1475 continue;1509 continue;
1476 },1510 },
1511 .validate_const => {
1512 try sema.zirValidateConst(block, inst);
1513 i += 1;
1514 continue;
1515 },
1477 .@"export" => {1516 .@"export" => {
1478 try sema.zirExport(block, inst);1517 try sema.zirExport(block, inst);
1479 i += 1;1518 i += 1;
...@@ -1515,7 +1554,7 @@ fn analyzeBodyInner(...@@ -1515,7 +1554,7 @@ fn analyzeBodyInner(
1515 continue;1554 continue;
1516 },1555 },
1517 .check_comptime_control_flow => {1556 .check_comptime_control_flow => {
1518 if (!block.is_comptime) {1557 if (!block.isComptime()) {
1519 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;1558 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1520 const src = block.nodeOffset(inst_data.src_node);1559 const src = block.nodeOffset(inst_data.src_node);
1521 const inline_block = inst_data.operand.toIndex().?;1560 const inline_block = inst_data.operand.toIndex().?;
...@@ -1562,7 +1601,7 @@ fn analyzeBodyInner(...@@ -1562,7 +1601,7 @@ fn analyzeBodyInner(
15621601
1563 // Special case instructions to handle comptime control flow.1602 // Special case instructions to handle comptime control flow.
1564 .@"break" => {1603 .@"break" => {
1565 if (block.is_comptime) {1604 if (block.isComptime()) {
1566 sema.comptime_break_inst = inst;1605 sema.comptime_break_inst = inst;
1567 return error.ComptimeBreak;1606 return error.ComptimeBreak;
1568 } else {1607 } else {
...@@ -1575,7 +1614,7 @@ fn analyzeBodyInner(...@@ -1575,7 +1614,7 @@ fn analyzeBodyInner(
1575 return error.ComptimeBreak;1614 return error.ComptimeBreak;
1576 },1615 },
1577 .repeat => {1616 .repeat => {
1578 if (block.is_comptime) {1617 if (block.isComptime()) {
1579 // Send comptime control flow back to the beginning of this block.1618 // Send comptime control flow back to the beginning of this block.
1580 const src = block.nodeOffset(datas[@intFromEnum(inst)].node);1619 const src = block.nodeOffset(datas[@intFromEnum(inst)].node);
1581 try sema.emitBackwardBranch(block, src);1620 try sema.emitBackwardBranch(block, src);
...@@ -1597,7 +1636,7 @@ fn analyzeBodyInner(...@@ -1597,7 +1636,7 @@ fn analyzeBodyInner(
1597 i = 0;1636 i = 0;
1598 continue;1637 continue;
1599 },1638 },
1600 .switch_continue => if (block.is_comptime) {1639 .switch_continue => if (block.isComptime()) {
1601 sema.comptime_break_inst = inst;1640 sema.comptime_break_inst = inst;
1602 return error.ComptimeBreak;1641 return error.ComptimeBreak;
1603 } else {1642 } else {
...@@ -1605,17 +1644,40 @@ fn analyzeBodyInner(...@@ -1605,17 +1644,40 @@ fn analyzeBodyInner(
1605 break;1644 break;
1606 },1645 },
16071646
1608 .loop => if (block.is_comptime) {1647 .loop => if (block.isComptime()) {
1609 continue :inst .block_inline;1648 continue :inst .block_inline;
1610 } else try sema.zirLoop(block, inst),1649 } else try sema.zirLoop(block, inst),
16111650
1612 .block => if (block.is_comptime) {1651 .block => if (block.isComptime()) {
1613 continue :inst .block_inline;1652 continue :inst .block_inline;
1614 } else try sema.zirBlock(block, inst, false),1653 } else try sema.zirBlock(block, inst),
16151654
1616 .block_comptime => if (block.is_comptime) {1655 .block_comptime => {
1617 continue :inst .block_inline;1656 const pl_node = datas[@intFromEnum(inst)].pl_node;
1618 } else try sema.zirBlock(block, inst, true),1657 const src = block.nodeOffset(pl_node.src_node);
1658 const extra = sema.code.extraData(Zir.Inst.BlockComptime, pl_node.payload_index);
1659 const block_body = sema.code.bodySlice(extra.end, extra.data.body_len);
1660
1661 if (block.isComptime()) {
1662 // No need for a sub-block; just resolve the other body directly!
1663 break :inst try sema.resolveInlineBody(block, block_body, inst);
1664 }
1665
1666 var child_block = block.makeSubBlock();
1667 defer child_block.instructions.deinit(sema.gpa);
1668 child_block.comptime_reason = .{ .reason = .{
1669 .src = src,
1670 .r = .{ .simple = extra.data.reason },
1671 } };
1672
1673 const result = try sema.resolveInlineBody(&child_block, block_body, inst);
1674
1675 if (!try sema.isComptimeKnown(result)) {
1676 return sema.failWithNeededComptime(&child_block, src, null);
1677 }
1678
1679 break :inst result;
1680 },
16191681
1620 .block_inline => blk: {1682 .block_inline => blk: {
1621 // Directly analyze the block body without introducing a new block.1683 // Directly analyze the block body without introducing a new block.
...@@ -1725,7 +1787,7 @@ fn analyzeBodyInner(...@@ -1725,7 +1787,7 @@ fn analyzeBodyInner(
1725 return error.ComptimeBreak;1787 return error.ComptimeBreak;
1726 }1788 }
1727 },1789 },
1728 .condbr => if (block.is_comptime) {1790 .condbr => if (block.isComptime()) {
1729 continue :inst .condbr_inline;1791 continue :inst .condbr_inline;
1730 } else {1792 } else {
1731 try sema.zirCondbr(block, inst);1793 try sema.zirCondbr(block, inst);
...@@ -1742,10 +1804,7 @@ fn analyzeBodyInner(...@@ -1742,10 +1804,7 @@ fn analyzeBodyInner(
1742 );1804 );
1743 const uncasted_cond = try sema.resolveInst(extra.data.condition);1805 const uncasted_cond = try sema.resolveInst(extra.data.condition);
1744 const cond = try sema.coerce(block, Type.bool, uncasted_cond, cond_src);1806 const cond = try sema.coerce(block, Type.bool, uncasted_cond, cond_src);
1745 const cond_val = try sema.resolveConstDefinedValue(block, cond_src, cond, .{1807 const cond_val = try sema.resolveConstDefinedValue(block, cond_src, cond, null);
1746 .needed_comptime_reason = "condition in comptime branch must be comptime-known",
1747 .block_comptime_reason = block.comptime_reason,
1748 });
1749 const inline_body = if (cond_val.toBool()) then_body else else_body;1808 const inline_body = if (cond_val.toBool()) then_body else else_body;
17501809
1751 try sema.maybeErrorUnwrapCondbr(block, inline_body, extra.data.condition, cond_src);1810 try sema.maybeErrorUnwrapCondbr(block, inline_body, extra.data.condition, cond_src);
...@@ -1756,7 +1815,7 @@ fn analyzeBodyInner(...@@ -1756,7 +1815,7 @@ fn analyzeBodyInner(
1756 break :inst result;1815 break :inst result;
1757 },1816 },
1758 .@"try" => blk: {1817 .@"try" => blk: {
1759 if (!block.is_comptime) break :blk try sema.zirTry(block, inst);1818 if (!block.isComptime()) break :blk try sema.zirTry(block, inst);
1760 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1819 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1761 const src = block.nodeOffset(inst_data.src_node);1820 const src = block.nodeOffset(inst_data.src_node);
1762 const operand_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });1821 const operand_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
...@@ -1771,10 +1830,7 @@ fn analyzeBodyInner(...@@ -1771,10 +1830,7 @@ fn analyzeBodyInner(
1771 }1830 }
1772 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);1831 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
1773 assert(is_non_err != .none);1832 assert(is_non_err != .none);
1774 const is_non_err_val = try sema.resolveConstDefinedValue(block, operand_src, is_non_err, .{1833 const is_non_err_val = try sema.resolveConstDefinedValue(block, operand_src, is_non_err, null);
1775 .needed_comptime_reason = "try operand inside comptime block must be comptime-known",
1776 .block_comptime_reason = block.comptime_reason,
1777 });
1778 if (is_non_err_val.toBool()) {1834 if (is_non_err_val.toBool()) {
1779 break :blk try sema.analyzeErrUnionPayload(block, src, err_union_ty, err_union, operand_src, false);1835 break :blk try sema.analyzeErrUnionPayload(block, src, err_union_ty, err_union, operand_src, false);
1780 }1836 }
...@@ -1782,7 +1838,7 @@ fn analyzeBodyInner(...@@ -1782,7 +1838,7 @@ fn analyzeBodyInner(
1782 break :blk result;1838 break :blk result;
1783 },1839 },
1784 .try_ptr => blk: {1840 .try_ptr => blk: {
1785 if (!block.is_comptime) break :blk try sema.zirTryPtr(block, inst);1841 if (!block.isComptime()) break :blk try sema.zirTryPtr(block, inst);
1786 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1842 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1787 const src = block.nodeOffset(inst_data.src_node);1843 const src = block.nodeOffset(inst_data.src_node);
1788 const operand_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });1844 const operand_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
...@@ -1792,10 +1848,7 @@ fn analyzeBodyInner(...@@ -1792,10 +1848,7 @@ fn analyzeBodyInner(
1792 const err_union = try sema.analyzeLoad(block, src, operand, operand_src);1848 const err_union = try sema.analyzeLoad(block, src, operand, operand_src);
1793 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);1849 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
1794 assert(is_non_err != .none);1850 assert(is_non_err != .none);
1795 const is_non_err_val = try sema.resolveConstDefinedValue(block, operand_src, is_non_err, .{1851 const is_non_err_val = try sema.resolveConstDefinedValue(block, operand_src, is_non_err, null);
1796 .needed_comptime_reason = "try operand inside comptime block must be comptime-known",
1797 .block_comptime_reason = block.comptime_reason,
1798 });
1799 if (is_non_err_val.toBool()) {1852 if (is_non_err_val.toBool()) {
1800 break :blk try sema.analyzeErrUnionPayloadPtr(block, src, operand, false, false);1853 break :blk try sema.analyzeErrUnionPayloadPtr(block, src, operand, false, false);
1801 }1854 }
...@@ -1873,7 +1926,7 @@ fn resolveConstBool(...@@ -1873,7 +1926,7 @@ fn resolveConstBool(
1873 block: *Block,1926 block: *Block,
1874 src: LazySrcLoc,1927 src: LazySrcLoc,
1875 zir_ref: Zir.Inst.Ref,1928 zir_ref: Zir.Inst.Ref,
1876 reason: NeededComptimeReason,1929 reason: ComptimeReason,
1877) !bool {1930) !bool {
1878 const air_inst = try sema.resolveInst(zir_ref);1931 const air_inst = try sema.resolveInst(zir_ref);
1879 const wanted_type = Type.bool;1932 const wanted_type = Type.bool;
...@@ -1887,7 +1940,7 @@ fn resolveConstString(...@@ -1887,7 +1940,7 @@ fn resolveConstString(
1887 block: *Block,1940 block: *Block,
1888 src: LazySrcLoc,1941 src: LazySrcLoc,
1889 zir_ref: Zir.Inst.Ref,1942 zir_ref: Zir.Inst.Ref,
1890 reason: NeededComptimeReason,1943 reason: ComptimeReason,
1891) ![]u8 {1944) ![]u8 {
1892 const air_inst = try sema.resolveInst(zir_ref);1945 const air_inst = try sema.resolveInst(zir_ref);
1893 return sema.toConstString(block, src, air_inst, reason);1946 return sema.toConstString(block, src, air_inst, reason);
...@@ -1898,7 +1951,7 @@ pub fn toConstString(...@@ -1898,7 +1951,7 @@ pub fn toConstString(
1898 block: *Block,1951 block: *Block,
1899 src: LazySrcLoc,1952 src: LazySrcLoc,
1900 air_inst: Air.Inst.Ref,1953 air_inst: Air.Inst.Ref,
1901 reason: NeededComptimeReason,1954 reason: ComptimeReason,
1902) ![]u8 {1955) ![]u8 {
1903 const pt = sema.pt;1956 const pt = sema.pt;
1904 const coerced_inst = try sema.coerce(block, Type.slice_const_u8, air_inst, src);1957 const coerced_inst = try sema.coerce(block, Type.slice_const_u8, air_inst, src);
...@@ -1912,7 +1965,7 @@ pub fn resolveConstStringIntern(...@@ -1912,7 +1965,7 @@ pub fn resolveConstStringIntern(
1912 block: *Block,1965 block: *Block,
1913 src: LazySrcLoc,1966 src: LazySrcLoc,
1914 zir_ref: Zir.Inst.Ref,1967 zir_ref: Zir.Inst.Ref,
1915 reason: NeededComptimeReason,1968 reason: ComptimeReason,
1916) !InternPool.NullTerminatedString {1969) !InternPool.NullTerminatedString {
1917 const air_inst = try sema.resolveInst(zir_ref);1970 const air_inst = try sema.resolveInst(zir_ref);
1918 const wanted_type = Type.slice_const_u8;1971 const wanted_type = Type.slice_const_u8;
...@@ -2063,9 +2116,7 @@ fn analyzeAsType(...@@ -2063,9 +2116,7 @@ fn analyzeAsType(
2063) !Type {2116) !Type {
2064 const wanted_type = Type.type;2117 const wanted_type = Type.type;
2065 const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);2118 const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);
2066 const val = try sema.resolveConstDefinedValue(block, src, coerced_inst, .{2119 const val = try sema.resolveConstDefinedValue(block, src, coerced_inst, .{ .simple = .type });
2067 .needed_comptime_reason = "types must be comptime-known",
2068 });
2069 return val.toType();2120 return val.toType();
2070}2121}
20712122
...@@ -2077,7 +2128,7 @@ pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize)...@@ -2077,7 +2128,7 @@ pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize)
2077 const ip = &zcu.intern_pool;2128 const ip = &zcu.intern_pool;
2078 if (!comp.config.any_error_tracing) return;2129 if (!comp.config.any_error_tracing) return;
20792130
2080 assert(!block.is_comptime);2131 assert(!block.isComptime());
2081 var err_trace_block = block.makeSubBlock();2132 var err_trace_block = block.makeSubBlock();
2082 defer err_trace_block.instructions.deinit(gpa);2133 defer err_trace_block.instructions.deinit(gpa);
20832134
...@@ -2148,7 +2199,7 @@ fn resolveConstValue(...@@ -2148,7 +2199,7 @@ fn resolveConstValue(
2148 block: *Block,2199 block: *Block,
2149 src: LazySrcLoc,2200 src: LazySrcLoc,
2150 inst: Air.Inst.Ref,2201 inst: Air.Inst.Ref,
2151 reason: NeededComptimeReason,2202 reason: ?ComptimeReason,
2152) CompileError!Value {2203) CompileError!Value {
2153 return try sema.resolveValue(inst) orelse {2204 return try sema.resolveValue(inst) orelse {
2154 return sema.failWithNeededComptime(block, src, reason);2205 return sema.failWithNeededComptime(block, src, reason);
...@@ -2177,7 +2228,7 @@ fn resolveConstDefinedValue(...@@ -2177,7 +2228,7 @@ fn resolveConstDefinedValue(
2177 block: *Block,2228 block: *Block,
2178 src: LazySrcLoc,2229 src: LazySrcLoc,
2179 air_ref: Air.Inst.Ref,2230 air_ref: Air.Inst.Ref,
2180 reason: NeededComptimeReason,2231 reason: ?ComptimeReason,
2181) CompileError!Value {2232) CompileError!Value {
2182 const val = try sema.resolveConstValue(block, src, air_ref, reason);2233 const val = try sema.resolveConstValue(block, src, air_ref, reason);
2183 if (val.isUndef(sema.pt.zcu)) return sema.failWithUseOfUndef(block, src);2234 if (val.isUndef(sema.pt.zcu)) return sema.failWithUseOfUndef(block, src);
...@@ -2217,15 +2268,16 @@ pub fn resolveFinalDeclValue(...@@ -2217,15 +2268,16 @@ pub fn resolveFinalDeclValue(
2217 const val: Value = .fromInterned(ip_index);2268 const val: Value = .fromInterned(ip_index);
2218 break :rt_ptr val.isPtrRuntimeValue(zcu);2269 break :rt_ptr val.isPtrRuntimeValue(zcu);
2219 };2270 };
2220 const value_comptime_reason: ?[]const u8 = if (is_runtime_ptr)
2221 "thread local and dll imported variables have runtime-known addresses"
2222 else
2223 null;
22242271
2225 return sema.failWithNeededComptime(block, src, .{2272 switch (sema.failWithNeededComptime(block, src, .{ .simple = .container_var_init })) {
2226 .needed_comptime_reason = "global variable initializer must be comptime-known",2273 error.AnalysisFail => |e| {
2227 .value_comptime_reason = value_comptime_reason,2274 if (sema.err != null and is_runtime_ptr) {
2228 });2275 try sema.errNote(src, sema.err.?, "threadlocal and dll imported variables have runtime-known addresses", .{});
2276 }
2277 return e;
2278 },
2279 else => |e| return e,
2280 }
2229 };2281 };
22302282
2231 if (val.canMutateComptimeVarState(zcu)) {2283 if (val.canMutateComptimeVarState(zcu)) {
...@@ -2235,21 +2287,19 @@ pub fn resolveFinalDeclValue(...@@ -2235,21 +2287,19 @@ pub fn resolveFinalDeclValue(
2235 return val;2287 return val;
2236}2288}
22372289
2238fn failWithNeededComptime(sema: *Sema, block: *Block, src: LazySrcLoc, reason: NeededComptimeReason) CompileError {2290fn failWithNeededComptime(sema: *Sema, block: *Block, src: LazySrcLoc, reason: ?ComptimeReason) CompileError {
2239 const msg = msg: {2291 const msg, const fail_block = msg: {
2240 const msg = try sema.errMsg(src, "unable to resolve comptime value", .{});2292 const msg = try sema.errMsg(src, "unable to resolve comptime value", .{});
2241 errdefer msg.destroy(sema.gpa);2293 errdefer msg.destroy(sema.gpa);
2242 try sema.errNote(src, msg, "{s}", .{reason.needed_comptime_reason});2294 const fail_block = if (reason) |r| b: {
2243 if (reason.value_comptime_reason) |value_comptime_reason| {2295 try r.explain(sema, src, msg);
2244 try sema.errNote(src, msg, "{s}", .{value_comptime_reason});2296 break :b block;
2245 }2297 } else b: {
22462298 break :b try block.explainWhyBlockIsComptime(msg);
2247 if (reason.block_comptime_reason) |block_comptime_reason| {2299 };
2248 try block_comptime_reason.explain(sema, msg);2300 break :msg .{ msg, fail_block };
2249 }
2250 break :msg msg;
2251 };2301 };
2252 return sema.failWithOwnedErrorMsg(block, msg);2302 return sema.failWithOwnedErrorMsg(fail_block, msg);
2253}2303}
22542304
2255fn failWithUseOfUndef(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError {2305fn failWithUseOfUndef(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError {
...@@ -2578,9 +2628,7 @@ pub fn analyzeAsAlign(...@@ -2578,9 +2628,7 @@ pub fn analyzeAsAlign(
2578 src: LazySrcLoc,2628 src: LazySrcLoc,
2579 air_ref: Air.Inst.Ref,2629 air_ref: Air.Inst.Ref,
2580) !Alignment {2630) !Alignment {
2581 const alignment_big = try sema.analyzeAsInt(block, src, air_ref, align_ty, .{2631 const alignment_big = try sema.analyzeAsInt(block, src, air_ref, align_ty, .{ .simple = .@"align" });
2582 .needed_comptime_reason = "alignment must be comptime-known",
2583 });
2584 return sema.validateAlign(block, src, alignment_big);2632 return sema.validateAlign(block, src, alignment_big);
2585}2633}
25862634
...@@ -2615,7 +2663,7 @@ fn resolveInt(...@@ -2615,7 +2663,7 @@ fn resolveInt(
2615 src: LazySrcLoc,2663 src: LazySrcLoc,
2616 zir_ref: Zir.Inst.Ref,2664 zir_ref: Zir.Inst.Ref,
2617 dest_ty: Type,2665 dest_ty: Type,
2618 reason: NeededComptimeReason,2666 reason: ComptimeReason,
2619) !u64 {2667) !u64 {
2620 const air_ref = try sema.resolveInst(zir_ref);2668 const air_ref = try sema.resolveInst(zir_ref);
2621 return sema.analyzeAsInt(block, src, air_ref, dest_ty, reason);2669 return sema.analyzeAsInt(block, src, air_ref, dest_ty, reason);
...@@ -2627,7 +2675,7 @@ fn analyzeAsInt(...@@ -2627,7 +2675,7 @@ fn analyzeAsInt(
2627 src: LazySrcLoc,2675 src: LazySrcLoc,
2628 air_ref: Air.Inst.Ref,2676 air_ref: Air.Inst.Ref,
2629 dest_ty: Type,2677 dest_ty: Type,
2630 reason: NeededComptimeReason,2678 reason: ComptimeReason,
2631) !u64 {2679) !u64 {
2632 const coerced = try sema.coerce(block, dest_ty, air_ref, src);2680 const coerced = try sema.coerce(block, dest_ty, air_ref, src);
2633 const val = try sema.resolveConstDefinedValue(block, src, coerced, reason);2681 const val = try sema.resolveConstDefinedValue(block, src, coerced, reason);
...@@ -2687,9 +2735,7 @@ fn zirTupleDecl(...@@ -2687,9 +2735,7 @@ fn zirTupleDecl(
2687 if (zir_field_init != .none) {2735 if (zir_field_init != .none) {
2688 const uncoerced_field_init = try sema.resolveInst(zir_field_init);2736 const uncoerced_field_init = try sema.resolveInst(zir_field_init);
2689 const coerced_field_init = try sema.coerce(block, field_type, uncoerced_field_init, init_src);2737 const coerced_field_init = try sema.coerce(block, field_type, uncoerced_field_init, init_src);
2690 const field_init_val = try sema.resolveConstDefinedValue(block, init_src, coerced_field_init, .{2738 const field_init_val = try sema.resolveConstDefinedValue(block, init_src, coerced_field_init, .{ .simple = .tuple_field_default_value });
2691 .needed_comptime_reason = "tuple field default value must be comptime-known",
2692 });
2693 if (field_init_val.canMutateComptimeVarState(zcu)) {2739 if (field_init_val.canMutateComptimeVarState(zcu)) {
2694 return sema.fail(block, init_src, "field default value contains reference to comptime-mutable memory", .{});2740 return sema.fail(block, init_src, "field default value contains reference to comptime-mutable memory", .{});
2695 }2741 }
...@@ -3414,7 +3460,7 @@ fn zirRetPtr(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {...@@ -3414,7 +3460,7 @@ fn zirRetPtr(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
34143460
3415 const pt = sema.pt;3461 const pt = sema.pt;
34163462
3417 if (block.is_comptime or try sema.fn_ret_ty.comptimeOnlySema(pt)) {3463 if (block.isComptime() or try sema.fn_ret_ty.comptimeOnlySema(pt)) {
3418 try sema.fn_ret_ty.resolveFields(pt);3464 try sema.fn_ret_ty.resolveFields(pt);
3419 return sema.analyzeComptimeAlloc(block, sema.fn_ret_ty, .none);3465 return sema.analyzeComptimeAlloc(block, sema.fn_ret_ty, .none);
3420 }3466 }
...@@ -3608,7 +3654,7 @@ fn zirAllocExtended(...@@ -3608,7 +3654,7 @@ fn zirAllocExtended(
3608 break :blk try sema.resolveAlign(block, align_src, align_ref);3654 break :blk try sema.resolveAlign(block, align_src, align_ref);
3609 } else .none;3655 } else .none;
36103656
3611 if (block.is_comptime or small.is_comptime) {3657 if (block.isComptime() or small.is_comptime) {
3612 if (small.has_type) {3658 if (small.has_type) {
3613 return sema.analyzeComptimeAlloc(block, var_ty, alignment);3659 return sema.analyzeComptimeAlloc(block, var_ty, alignment);
3614 } else {3660 } else {
...@@ -4075,7 +4121,7 @@ fn zirAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I...@@ -4075,7 +4121,7 @@ fn zirAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
4075 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });4121 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });
40764122
4077 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);4123 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
4078 if (block.is_comptime or try var_ty.comptimeOnlySema(pt)) {4124 if (block.isComptime() or try var_ty.comptimeOnlySema(pt)) {
4079 return sema.analyzeComptimeAlloc(block, var_ty, .none);4125 return sema.analyzeComptimeAlloc(block, var_ty, .none);
4080 }4126 }
4081 if (sema.func_is_naked and try var_ty.hasRuntimeBitsSema(pt)) {4127 if (sema.func_is_naked and try var_ty.hasRuntimeBitsSema(pt)) {
...@@ -4103,7 +4149,7 @@ fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai...@@ -4103,7 +4149,7 @@ fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
4103 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;4149 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
4104 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });4150 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });
4105 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);4151 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
4106 if (block.is_comptime) {4152 if (block.isComptime()) {
4107 return sema.analyzeComptimeAlloc(block, var_ty, .none);4153 return sema.analyzeComptimeAlloc(block, var_ty, .none);
4108 }4154 }
4109 if (sema.func_is_naked and try var_ty.hasRuntimeBitsSema(pt)) {4155 if (sema.func_is_naked and try var_ty.hasRuntimeBitsSema(pt)) {
...@@ -4129,7 +4175,7 @@ fn zirAllocInferred(...@@ -4129,7 +4175,7 @@ fn zirAllocInferred(
41294175
4130 const gpa = sema.gpa;4176 const gpa = sema.gpa;
41314177
4132 if (block.is_comptime) {4178 if (block.isComptime()) {
4133 try sema.air_instructions.append(gpa, .{4179 try sema.air_instructions.append(gpa, .{
4134 .tag = .inferred_alloc_comptime,4180 .tag = .inferred_alloc_comptime,
4135 .data = .{ .inferred_alloc_comptime = .{4181 .data = .{ .inferred_alloc_comptime = .{
...@@ -4579,6 +4625,17 @@ fn zirValidateRefTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr...@@ -4579,6 +4625,17 @@ fn zirValidateRefTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
4579 }4625 }
4580}4626}
45814627
4628fn zirValidateConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
4629 if (!block.isComptime()) return;
4630
4631 const un_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
4632 const src = block.nodeOffset(un_node.src_node);
4633 const init_ref = try sema.resolveInst(un_node.operand);
4634 if (!try sema.isComptimeKnown(init_ref)) {
4635 return sema.failWithNeededComptime(block, src, null);
4636 }
4637}
4638
4582fn zirValidateArrayInitRefTy(4639fn zirValidateArrayInitRefTy(
4583 sema: *Sema,4640 sema: *Sema,
4584 block: *Block,4641 block: *Block,
...@@ -4778,7 +4835,7 @@ fn validateUnionInit(...@@ -4778,7 +4835,7 @@ fn validateUnionInit(
4778 return sema.failWithOwnedErrorMsg(block, msg);4835 return sema.failWithOwnedErrorMsg(block, msg);
4779 }4836 }
47804837
4781 if (block.is_comptime and4838 if (block.isComptime() and
4782 (try sema.resolveDefinedValue(block, init_src, union_ptr)) != null)4839 (try sema.resolveDefinedValue(block, init_src, union_ptr)) != null)
4783 {4840 {
4784 // In this case, comptime machinery already did everything. No work to do here.4841 // In this case, comptime machinery already did everything. No work to do here.
...@@ -4897,9 +4954,11 @@ fn validateUnionInit(...@@ -4897,9 +4954,11 @@ fn validateUnionInit(
4897 try sema.storePtr2(block, init_src, union_ptr, init_src, union_init, init_src, .store);4954 try sema.storePtr2(block, init_src, union_ptr, init_src, union_init, init_src, .store);
4898 return;4955 return;
4899 } else if (try union_ty.comptimeOnlySema(pt)) {4956 } else if (try union_ty.comptimeOnlySema(pt)) {
4900 return sema.failWithNeededComptime(block, block.nodeOffset(field_ptr_data.src_node), .{4957 const src = block.nodeOffset(field_ptr_data.src_node);
4901 .needed_comptime_reason = "initializer of comptime only union must be comptime-known",4958 return sema.failWithNeededComptime(block, src, .{ .comptime_only = .{
4902 });4959 .ty = union_ty,
4960 .msg = .union_init,
4961 } });
4903 }4962 }
4904 if (init_ref) |v| try sema.validateRuntimeValue(block, block.nodeOffset(field_ptr_data.src_node), v);4963 if (init_ref) |v| try sema.validateRuntimeValue(block, block.nodeOffset(field_ptr_data.src_node), v);
49054964
...@@ -4953,7 +5012,7 @@ fn validateStructInit(...@@ -4953,7 +5012,7 @@ fn validateStructInit(
4953 errdefer if (root_msg) |msg| msg.destroy(sema.gpa);5012 errdefer if (root_msg) |msg| msg.destroy(sema.gpa);
49545013
4955 const struct_ptr = try sema.resolveInst(struct_ptr_zir_ref);5014 const struct_ptr = try sema.resolveInst(struct_ptr_zir_ref);
4956 if (block.is_comptime and5015 if (block.isComptime() and
4957 (try sema.resolveDefinedValue(block, init_src, struct_ptr)) != null)5016 (try sema.resolveDefinedValue(block, init_src, struct_ptr)) != null)
4958 {5017 {
4959 try struct_ty.resolveLayout(pt);5018 try struct_ty.resolveLayout(pt);
...@@ -5081,9 +5140,11 @@ fn validateStructInit(...@@ -5081,9 +5140,11 @@ fn validateStructInit(
5081 field_values[i] = val.toIntern();5140 field_values[i] = val.toIntern();
5082 } else if (require_comptime) {5141 } else if (require_comptime) {
5083 const field_ptr_data = sema.code.instructions.items(.data)[@intFromEnum(field_ptr)].pl_node;5142 const field_ptr_data = sema.code.instructions.items(.data)[@intFromEnum(field_ptr)].pl_node;
5084 return sema.failWithNeededComptime(block, block.nodeOffset(field_ptr_data.src_node), .{5143 const src = block.nodeOffset(field_ptr_data.src_node);
5085 .needed_comptime_reason = "initializer of comptime only struct must be comptime-known",5144 return sema.failWithNeededComptime(block, src, .{ .comptime_only = .{
5086 });5145 .ty = struct_ty,
5146 .msg = .struct_init,
5147 } });
5087 } else {5148 } else {
5088 struct_is_comptime = false;5149 struct_is_comptime = false;
5089 }5150 }
...@@ -5253,7 +5314,7 @@ fn zirValidatePtrArrayInit(...@@ -5253,7 +5314,7 @@ fn zirValidatePtrArrayInit(
5253 else => unreachable,5314 else => unreachable,
5254 };5315 };
52555316
5256 if (block.is_comptime and5317 if (block.isComptime() and
5257 (try sema.resolveDefinedValue(block, init_src, array_ptr)) != null)5318 (try sema.resolveDefinedValue(block, init_src, array_ptr)) != null)
5258 {5319 {
5259 // In this case the comptime machinery will have evaluated the store instructions5320 // In this case the comptime machinery will have evaluated the store instructions
...@@ -5629,9 +5690,7 @@ fn storeToInferredAllocComptime(...@@ -5629,9 +5690,7 @@ fn storeToInferredAllocComptime(
5629 // There will be only one store_to_inferred_ptr because we are running at comptime.5690 // There will be only one store_to_inferred_ptr because we are running at comptime.
5630 // The alloc will turn into a Decl or a ComptimeAlloc.5691 // The alloc will turn into a Decl or a ComptimeAlloc.
5631 const operand_val = try sema.resolveValue(operand) orelse {5692 const operand_val = try sema.resolveValue(operand) orelse {
5632 return sema.failWithNeededComptime(block, src, .{5693 return sema.failWithNeededComptime(block, src, .{ .simple = .stored_to_comptime_var });
5633 .needed_comptime_reason = "value being stored to a comptime variable must be comptime-known",
5634 });
5635 };5694 };
5636 const alloc_ty = try pt.ptrTypeSema(.{5695 const alloc_ty = try pt.ptrTypeSema(.{
5637 .child = operand_ty.toIntern(),5696 .child = operand_ty.toIntern(),
...@@ -5663,9 +5722,7 @@ fn storeToInferredAllocComptime(...@@ -5663,9 +5722,7 @@ fn storeToInferredAllocComptime(
5663fn zirSetEvalBranchQuota(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {5722fn zirSetEvalBranchQuota(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
5664 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;5723 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
5665 const src = block.nodeOffset(inst_data.src_node);5724 const src = block.nodeOffset(inst_data.src_node);
5666 const quota: u32 = @intCast(try sema.resolveInt(block, src, inst_data.operand, Type.u32, .{5725 const quota: u32 = @intCast(try sema.resolveInt(block, src, inst_data.operand, .u32, .{ .simple = .operand_setEvalBranchQuota }));
5667 .needed_comptime_reason = "eval branch quota must be comptime-known",
5668 }));
5669 sema.branch_quota = @max(sema.branch_quota, quota);5726 sema.branch_quota = @max(sema.branch_quota, quota);
5670 sema.allow_memoize = false;5727 sema.allow_memoize = false;
5671}5728}
...@@ -5794,9 +5851,7 @@ fn zirCompileError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro...@@ -5794,9 +5851,7 @@ fn zirCompileError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
5794 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;5851 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
5795 const src = block.nodeOffset(inst_data.src_node);5852 const src = block.nodeOffset(inst_data.src_node);
5796 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);5853 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
5797 const msg = try sema.resolveConstString(block, operand_src, inst_data.operand, .{5854 const msg = try sema.resolveConstString(block, operand_src, inst_data.operand, .{ .simple = .compile_error_string });
5798 .needed_comptime_reason = "compile error string must be comptime-known",
5799 });
5800 return sema.fail(block, src, "{s}", .{msg});5855 return sema.fail(block, src, "{s}", .{msg});
5801}5856}
58025857
...@@ -5848,7 +5903,7 @@ fn zirPanic(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void...@@ -5848,7 +5903,7 @@ fn zirPanic(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
5848 // source location if we do it here.5903 // source location if we do it here.
5849 const coerced_msg = try sema.coerce(block, Type.slice_const_u8, msg_inst, block.builtinCallArgSrc(inst_data.src_node, 0));5904 const coerced_msg = try sema.coerce(block, Type.slice_const_u8, msg_inst, block.builtinCallArgSrc(inst_data.src_node, 0));
58505905
5851 if (block.is_comptime) {5906 if (block.isComptime()) {
5852 return sema.fail(block, src, "encountered @panic at comptime", .{});5907 return sema.fail(block, src, "encountered @panic at comptime", .{});
5853 }5908 }
58545909
...@@ -5864,7 +5919,7 @@ fn zirPanic(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void...@@ -5864,7 +5919,7 @@ fn zirPanic(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
5864fn zirTrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {5919fn zirTrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
5865 const src_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].node;5920 const src_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].node;
5866 const src = block.nodeOffset(src_node);5921 const src = block.nodeOffset(src_node);
5867 if (block.is_comptime)5922 if (block.isComptime())
5868 return sema.fail(block, src, "encountered @trap at comptime", .{});5923 return sema.fail(block, src, "encountered @trap at comptime", .{});
5869 _ = try block.addNoOp(.trap);5924 _ = try block.addNoOp(.trap);
5870}5925}
...@@ -5974,15 +6029,16 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr...@@ -5974,15 +6029,16 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
5974 var c_import_buf = std.ArrayList(u8).init(gpa);6029 var c_import_buf = std.ArrayList(u8).init(gpa);
5975 defer c_import_buf.deinit();6030 defer c_import_buf.deinit();
59766031
5977 const comptime_reason: Block.ComptimeReason = .{ .c_import = .{ .src = src } };
5978 var child_block: Block = .{6032 var child_block: Block = .{
5979 .parent = parent_block,6033 .parent = parent_block,
5980 .sema = sema,6034 .sema = sema,
5981 .namespace = parent_block.namespace,6035 .namespace = parent_block.namespace,
5982 .instructions = .{},6036 .instructions = .{},
5983 .inlining = parent_block.inlining,6037 .inlining = parent_block.inlining,
5984 .is_comptime = true,6038 .comptime_reason = .{ .reason = .{
5985 .comptime_reason = &comptime_reason,6039 .src = src,
6040 .r = .{ .simple = .operand_cImport },
6041 } },
5986 .c_import_buf = &c_import_buf,6042 .c_import_buf = &c_import_buf,
5987 .runtime_cond = parent_block.runtime_cond,6043 .runtime_cond = parent_block.runtime_cond,
5988 .runtime_loop = parent_block.runtime_loop,6044 .runtime_loop = parent_block.runtime_loop,
...@@ -6073,7 +6129,7 @@ fn zirSuspendBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) Comp...@@ -6073,7 +6129,7 @@ fn zirSuspendBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) Comp
6073 return sema.failWithUseOfAsync(parent_block, src);6129 return sema.failWithUseOfAsync(parent_block, src);
6074}6130}
60756131
6076fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index, force_comptime: bool) CompileError!Air.Inst.Ref {6132fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6077 const tracy = trace(@src());6133 const tracy = trace(@src());
6078 defer tracy.end();6134 defer tracy.end();
60796135
...@@ -6109,7 +6165,6 @@ fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index, force_compt...@@ -6109,7 +6165,6 @@ fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index, force_compt
6109 .instructions = .{},6165 .instructions = .{},
6110 .label = &label,6166 .label = &label,
6111 .inlining = parent_block.inlining,6167 .inlining = parent_block.inlining,
6112 .is_comptime = parent_block.is_comptime or force_comptime,
6113 .comptime_reason = parent_block.comptime_reason,6168 .comptime_reason = parent_block.comptime_reason,
6114 .is_typeof = parent_block.is_typeof,6169 .is_typeof = parent_block.is_typeof,
6115 .want_safety = parent_block.want_safety,6170 .want_safety = parent_block.want_safety,
...@@ -6143,7 +6198,7 @@ fn resolveBlockBody(...@@ -6143,7 +6198,7 @@ fn resolveBlockBody(
6143 body_inst: Zir.Inst.Index,6198 body_inst: Zir.Inst.Index,
6144 merges: *Block.Merges,6199 merges: *Block.Merges,
6145) CompileError!Air.Inst.Ref {6200) CompileError!Air.Inst.Ref {
6146 if (child_block.is_comptime) {6201 if (child_block.isComptime()) {
6147 return sema.resolveInlineBody(child_block, body, body_inst);6202 return sema.resolveInlineBody(child_block, body, body_inst);
6148 } else {6203 } else {
6149 assert(sema.air_instructions.items(.tag)[@intFromEnum(merges.block_inst)] == .block);6204 assert(sema.air_instructions.items(.tag)[@intFromEnum(merges.block_inst)] == .block);
...@@ -6303,7 +6358,7 @@ fn resolveAnalyzedBlock(...@@ -6303,7 +6358,7 @@ fn resolveAnalyzedBlock(
6303 }6358 }
6304 }6359 }
6305 // It is impossible to have the number of results be > 1 in a comptime scope.6360 // It is impossible to have the number of results be > 1 in a comptime scope.
6306 assert(!child_block.is_comptime); // Should already got a compile error in the condbr condition.6361 assert(!child_block.isComptime()); // Should already got a compile error in the condbr condition.
63076362
6308 // Note that we'll always create an AIR block here, so `need_debug_scope` is irrelevant.6363 // Note that we'll always create an AIR block here, so `need_debug_scope` is irrelevant.
63096364
...@@ -6425,9 +6480,7 @@ fn zirExport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void...@@ -6425,9 +6480,7 @@ fn zirExport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
6425 const options_src = block.builtinCallArgSrc(inst_data.src_node, 1);6480 const options_src = block.builtinCallArgSrc(inst_data.src_node, 1);
64266481
6427 const ptr = try sema.resolveInst(extra.exported);6482 const ptr = try sema.resolveInst(extra.exported);
6428 const ptr_val = try sema.resolveConstDefinedValue(block, ptr_src, ptr, .{6483 const ptr_val = try sema.resolveConstDefinedValue(block, ptr_src, ptr, .{ .simple = .export_target });
6429 .needed_comptime_reason = "export target must be comptime-known",
6430 });
6431 const ptr_ty = ptr_val.typeOf(zcu);6484 const ptr_ty = ptr_val.typeOf(zcu);
64326485
6433 const options = try sema.resolveExportOptions(block, options_src, extra.options);6486 const options = try sema.resolveExportOptions(block, options_src, extra.options);
...@@ -6553,17 +6606,13 @@ fn zirDisableInstrumentation(sema: *Sema) CompileError!void {...@@ -6553,17 +6606,13 @@ fn zirDisableInstrumentation(sema: *Sema) CompileError!void {
6553fn zirSetFloatMode(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {6606fn zirSetFloatMode(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
6554 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;6607 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
6555 const src = block.builtinCallArgSrc(extra.node, 0);6608 const src = block.builtinCallArgSrc(extra.node, 0);
6556 block.float_mode = try sema.resolveBuiltinEnum(block, src, extra.operand, "FloatMode", .{6609 block.float_mode = try sema.resolveBuiltinEnum(block, src, extra.operand, "FloatMode", .{ .simple = .operand_setFloatMode });
6557 .needed_comptime_reason = "operand to @setFloatMode must be comptime-known",
6558 });
6559}6610}
65606611
6561fn zirSetRuntimeSafety(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {6612fn zirSetRuntimeSafety(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
6562 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;6613 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
6563 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);6614 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
6564 block.want_safety = try sema.resolveConstBool(block, operand_src, inst_data.operand, .{6615 block.want_safety = try sema.resolveConstBool(block, operand_src, inst_data.operand, .{ .simple = .operand_setRuntimeSafety });
6565 .needed_comptime_reason = "operand to @setRuntimeSafety must be comptime-known",
6566 });
6567}6616}
65686617
6569fn zirBreak(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index) CompileError!void {6618fn zirBreak(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index) CompileError!void {
...@@ -6650,7 +6699,7 @@ fn zirSwitchContinue(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index) Com...@@ -6650,7 +6699,7 @@ fn zirSwitchContinue(sema: *Sema, start_block: *Block, inst: Zir.Inst.Index) Com
6650}6699}
66516700
6652fn zirDbgStmt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {6701fn zirDbgStmt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
6653 if (block.is_comptime or block.ownerModule().strip) return;6702 if (block.isComptime() or block.ownerModule().strip) return;
66546703
6655 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;6704 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;
66566705
...@@ -6676,7 +6725,7 @@ fn zirDbgStmt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!voi...@@ -6676,7 +6725,7 @@ fn zirDbgStmt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!voi
6676}6725}
66776726
6678fn zirDbgEmptyStmt(_: *Sema, block: *Block, _: Zir.Inst.Index) CompileError!void {6727fn zirDbgEmptyStmt(_: *Sema, block: *Block, _: Zir.Inst.Index) CompileError!void {
6679 if (block.is_comptime or block.ownerModule().strip) return;6728 if (block.isComptime() or block.ownerModule().strip) return;
6680 _ = try block.addNoOp(.dbg_empty_stmt);6729 _ = try block.addNoOp(.dbg_empty_stmt);
6681}6730}
66826731
...@@ -6699,7 +6748,7 @@ fn addDbgVar(...@@ -6699,7 +6748,7 @@ fn addDbgVar(
6699 air_tag: Air.Inst.Tag,6748 air_tag: Air.Inst.Tag,
6700 name: []const u8,6749 name: []const u8,
6701) CompileError!void {6750) CompileError!void {
6702 if (block.is_comptime or block.ownerModule().strip) return;6751 if (block.isComptime() or block.ownerModule().strip) return;
67036752
6704 const pt = sema.pt;6753 const pt = sema.pt;
6705 const zcu = pt.zcu;6754 const zcu = pt.zcu;
...@@ -6931,7 +6980,7 @@ pub fn analyzeSaveErrRetIndex(sema: *Sema, block: *Block) SemaError!Air.Inst.Ref...@@ -6931,7 +6980,7 @@ pub fn analyzeSaveErrRetIndex(sema: *Sema, block: *Block) SemaError!Air.Inst.Ref
6931 const zcu = pt.zcu;6980 const zcu = pt.zcu;
6932 const gpa = sema.gpa;6981 const gpa = sema.gpa;
69336982
6934 if (block.is_comptime or block.is_typeof) {6983 if (block.isComptime() or block.is_typeof) {
6935 const index_val = try pt.intValue_u64(Type.usize, sema.comptime_err_ret_trace.items.len);6984 const index_val = try pt.intValue_u64(Type.usize, sema.comptime_err_ret_trace.items.len);
6936 return Air.internedToRef(index_val.toIntern());6985 return Air.internedToRef(index_val.toIntern());
6937 }6986 }
...@@ -7134,7 +7183,7 @@ fn zirCall(...@@ -7134,7 +7183,7 @@ fn zirCall(
7134 }7183 }
71357184
7136 if (block.ownerModule().error_tracing and7185 if (block.ownerModule().error_tracing and
7137 !block.is_comptime and !block.is_typeof and (input_is_error or pop_error_return_trace))7186 !block.isComptime() and !block.is_typeof and (input_is_error or pop_error_return_trace))
7138 {7187 {
7139 const return_ty = sema.typeOf(call_inst);7188 const return_ty = sema.typeOf(call_inst);
7140 if (modifier != .always_tail and return_ty.isNoReturn(zcu))7189 if (modifier != .always_tail and return_ty.isNoReturn(zcu))
...@@ -7404,12 +7453,14 @@ const CallArgsInfo = union(enum) {...@@ -7404,12 +7453,14 @@ const CallArgsInfo = union(enum) {
7404 };7453 };
74057454
7406 // Generate args to comptime params in comptime block7455 // Generate args to comptime params in comptime block
7407 const parent_comptime = block.is_comptime;7456 const parent_comptime = block.comptime_reason;
7408 defer block.is_comptime = parent_comptime;7457 defer block.comptime_reason = parent_comptime;
7409 // Note that we are indexing into parameters, not arguments, so use `arg_index` instead of `real_arg_idx`7458 // Note that we are indexing into parameters, not arguments, so use `arg_index` instead of `real_arg_idx`
7410 if (arg_index < @min(param_count, 32) and func_ty_info.paramIsComptime(@intCast(arg_index))) {7459 if (arg_index < @min(param_count, 32) and func_ty_info.paramIsComptime(@intCast(arg_index))) {
7411 block.is_comptime = true;7460 block.comptime_reason = .{ .reason = .{
7412 // TODO set comptime_reason7461 .src = cai.argSrc(block, arg_index),
7462 .r = .{ .simple = .comptime_param_arg },
7463 } };
7413 }7464 }
7414 // Give the arg its result type7465 // Give the arg its result type
7415 const provide_param_ty = if (maybe_param_ty) |t| t else Type.generic_poison;7466 const provide_param_ty = if (maybe_param_ty) |t| t else Type.generic_poison;
...@@ -7611,23 +7662,37 @@ fn analyzeCall(...@@ -7611,23 +7662,37 @@ fn analyzeCall(
76117662
7612 const gpa = sema.gpa;7663 const gpa = sema.gpa;
76137664
7665 const func_ret_ty_src: LazySrcLoc = if (try sema.funcDeclSrcInst(func)) |fn_decl_inst| .{
7666 .base_node_inst = fn_decl_inst,
7667 .offset = .{ .node_offset_fn_type_ret_ty = 0 },
7668 } else func_src;
7669
7670 // If this is not `null`, the call is comptime.
7671 var comptime_call_reason: ?BlockComptimeReason = cr: {
7672 if (block.comptime_reason) |r| break :cr r;
7673 if (modifier == .compile_time) break :cr .{ .reason = .{
7674 .src = call_src,
7675 .r = .{ .simple = .comptime_call_modifier },
7676 } };
7677 break :cr null;
7678 };
7679
7614 const is_generic_call = func_ty_info.is_generic;7680 const is_generic_call = func_ty_info.is_generic;
7615 var is_comptime_call = block.is_comptime or modifier == .compile_time;7681 var is_inline_call = comptime_call_reason != null or modifier == .always_inline or func_ty_info.cc == .@"inline";
7616 var is_inline_call = is_comptime_call or modifier == .always_inline or func_ty_info.cc == .@"inline";7682 if (!is_inline_call) {
7617 var comptime_reason: ?*const Block.ComptimeReason = null;
7618 if (!is_inline_call and !is_comptime_call) {
7619 if (try Type.fromInterned(func_ty_info.return_type).comptimeOnlySema(pt)) {7683 if (try Type.fromInterned(func_ty_info.return_type).comptimeOnlySema(pt)) {
7620 is_comptime_call = true;
7621 is_inline_call = true;7684 is_inline_call = true;
7622 comptime_reason = &.{ .comptime_ret_ty = .{7685 comptime_call_reason = .{ .reason = .{
7623 .func = func,7686 .src = func_ret_ty_src,
7624 .func_src = func_src,7687 .r = .{ .comptime_only = .{
7625 .return_ty = Type.fromInterned(func_ty_info.return_type),7688 .ty = .fromInterned(func_ty_info.return_type),
7689 .msg = .ret_ty_call,
7690 } },
7626 } };7691 } };
7627 }7692 }
7628 }7693 }
76297694
7630 if (sema.func_is_naked and !is_inline_call and !is_comptime_call) {7695 if (sema.func_is_naked and !is_inline_call) {
7631 const msg = msg: {7696 const msg = msg: {
7632 const msg = try sema.errMsg(call_src, "runtime {s} not allowed in naked function", .{@tagName(operation)});7697 const msg = try sema.errMsg(call_src, "runtime {s} not allowed in naked function", .{@tagName(operation)});
7633 errdefer msg.destroy(sema.gpa);7698 errdefer msg.destroy(sema.gpa);
...@@ -7642,6 +7707,7 @@ fn analyzeCall(...@@ -7642,6 +7707,7 @@ fn analyzeCall(
7642 }7707 }
76437708
7644 if (!is_inline_call and is_generic_call) {7709 if (!is_inline_call and is_generic_call) {
7710 var comptime_ret_ty: Type = undefined;
7645 if (sema.instantiateGenericCall(7711 if (sema.instantiateGenericCall(
7646 block,7712 block,
7647 func,7713 func,
...@@ -7651,6 +7717,7 @@ fn analyzeCall(...@@ -7651,6 +7717,7 @@ fn analyzeCall(
7651 args_info,7717 args_info,
7652 call_tag,7718 call_tag,
7653 call_dbg_node,7719 call_dbg_node,
7720 &comptime_ret_ty,
7654 )) |some| {7721 )) |some| {
7655 return some;7722 return some;
7656 } else |err| switch (err) {7723 } else |err| switch (err) {
...@@ -7659,26 +7726,34 @@ fn analyzeCall(...@@ -7659,26 +7726,34 @@ fn analyzeCall(
7659 },7726 },
7660 error.ComptimeReturn => {7727 error.ComptimeReturn => {
7661 is_inline_call = true;7728 is_inline_call = true;
7662 is_comptime_call = true;7729 comptime_call_reason = .{ .reason = .{
7663 comptime_reason = &.{ .comptime_ret_ty = .{7730 .src = func_ret_ty_src,
7664 .func = func,7731 .r = .{
7665 .func_src = func_src,7732 .comptime_only = .{
7666 .return_ty = Type.fromInterned(func_ty_info.return_type),7733 .ty = comptime_ret_ty,
7734 .msg = .ret_ty_generic_call,
7735 },
7736 },
7667 } };7737 } };
7668 },7738 },
7669 else => |e| return e,7739 else => |e| return e,
7670 }7740 }
7671 }7741 }
76727742
7743 const is_comptime_call = comptime_call_reason != null;
7744 // `comptime_call_reason` shouldn't be mutated again
7745 defer assert(is_comptime_call == (comptime_call_reason != null));
7746
7673 if (is_comptime_call and modifier == .never_inline) {7747 if (is_comptime_call and modifier == .never_inline) {
7674 return sema.fail(block, call_src, "unable to perform 'never_inline' call at compile-time", .{});7748 return sema.fail(block, call_src, "unable to perform 'never_inline' call at compile-time", .{});
7675 }7749 }
76767750
7677 const result: Air.Inst.Ref = if (is_inline_call) res: {7751 const result: Air.Inst.Ref = if (is_inline_call) res: {
7678 const func_val = try sema.resolveConstDefinedValue(block, func_src, func, .{7752 const old_comptime_reason = block.comptime_reason;
7679 .needed_comptime_reason = "function being called at comptime must be comptime-known",7753 block.comptime_reason = comptime_call_reason;
7680 .block_comptime_reason = comptime_reason,7754 defer block.comptime_reason = old_comptime_reason;
7681 });7755
7756 const func_val = try sema.resolveConstDefinedValue(block, func_src, func, .{ .simple = .comptime_call_target });
7682 const module_fn_index = switch (zcu.intern_pool.indexToKey(func_val.toIntern())) {7757 const module_fn_index = switch (zcu.intern_pool.indexToKey(func_val.toIntern())) {
7683 .@"extern" => return sema.fail(block, call_src, "{s} call of extern function", .{7758 .@"extern" => return sema.fail(block, call_src, "{s} call of extern function", .{
7684 @as([]const u8, if (is_comptime_call) "comptime" else "inline"),7759 @as([]const u8, if (is_comptime_call) "comptime" else "inline"),
...@@ -7767,8 +7842,7 @@ fn analyzeCall(...@@ -7767,8 +7842,7 @@ fn analyzeCall(
7767 .label = null,7842 .label = null,
7768 .inlining = &inlining,7843 .inlining = &inlining,
7769 .is_typeof = block.is_typeof,7844 .is_typeof = block.is_typeof,
7770 .is_comptime = is_comptime_call,7845 .comptime_reason = if (is_comptime_call) .inlining_parent else null,
7771 .comptime_reason = comptime_reason,
7772 .error_return_trace_index = block.error_return_trace_index,7846 .error_return_trace_index = block.error_return_trace_index,
7773 .runtime_cond = block.runtime_cond,7847 .runtime_cond = block.runtime_cond,
7774 .runtime_loop = block.runtime_loop,7848 .runtime_loop = block.runtime_loop,
...@@ -7857,11 +7931,16 @@ fn analyzeCall(...@@ -7857,11 +7931,16 @@ fn analyzeCall(
7857 // on parameters, we must now do the same for the return type as we just did with7931 // on parameters, we must now do the same for the return type as we just did with
7858 // each of the parameters, resolving the return type and providing it to the child7932 // each of the parameters, resolving the return type and providing it to the child
7859 // `Sema` so that it can be used for the `ret_ptr` instruction.7933 // `Sema` so that it can be used for the `ret_ptr` instruction.
7860 const ret_ty_inst = if (fn_info.ret_ty_body.len != 0)
7861 try sema.resolveInlineBody(&child_block, fn_info.ret_ty_body, module_fn.zir_body_inst.resolve(ip) orelse return error.AnalysisFail)
7862 else
7863 try sema.resolveInst(fn_info.ret_ty_ref);
7864 const ret_ty_src: LazySrcLoc = .{ .base_node_inst = module_fn.zir_body_inst, .offset = .{ .node_offset_fn_type_ret_ty = 0 } };7934 const ret_ty_src: LazySrcLoc = .{ .base_node_inst = module_fn.zir_body_inst, .offset = .{ .node_offset_fn_type_ret_ty = 0 } };
7935 const ret_ty_inst = if (fn_info.ret_ty_body.len != 0) r: {
7936 const old_child_comptime_reason = child_block.comptime_reason;
7937 defer child_block.comptime_reason = old_child_comptime_reason;
7938 child_block.comptime_reason = .{ .reason = .{
7939 .src = ret_ty_src,
7940 .r = .{ .simple = .function_ret_ty },
7941 } };
7942 break :r try sema.resolveInlineBody(&child_block, fn_info.ret_ty_body, module_fn.zir_body_inst.resolve(ip) orelse return error.AnalysisFail);
7943 } else try sema.resolveInst(fn_info.ret_ty_ref);
7865 sema.fn_ret_ty = try sema.analyzeAsType(&child_block, ret_ty_src, ret_ty_inst);7944 sema.fn_ret_ty = try sema.analyzeAsType(&child_block, ret_ty_src, ret_ty_inst);
7866 if (module_fn.analysisUnordered(ip).inferred_error_set) {7945 if (module_fn.analysisUnordered(ip).inferred_error_set) {
7867 // Create a fresh inferred error set type for inline/comptime calls.7946 // Create a fresh inferred error set type for inline/comptime calls.
...@@ -8136,23 +8215,18 @@ fn analyzeInlineCallArg(...@@ -8136,23 +8215,18 @@ fn analyzeInlineCallArg(
8136 return casted_arg;8215 return casted_arg;
8137 }8216 }
8138 const arg_src = args_info.argSrc(arg_block, arg_i.*);8217 const arg_src = args_info.argSrc(arg_block, arg_i.*);
8139 if (try Type.fromInterned(param_ty).comptimeOnlySema(ics.callee().pt)) {8218 if (zir_tags[@intFromEnum(inst)] == .param_comptime) {
8140 _ = try ics.caller().resolveConstValue(arg_block, arg_src, casted_arg, .{8219 _ = try ics.caller().resolveConstValue(arg_block, arg_src, casted_arg, .{ .simple = .comptime_param_arg });
8141 .needed_comptime_reason = "argument to parameter with comptime-only type must be comptime-known",8220 } else if (!is_comptime_call and try Type.fromInterned(param_ty).comptimeOnlySema(ics.callee().pt)) {
8142 .block_comptime_reason = param_block.comptime_reason,8221 _ = try ics.caller().resolveConstValue(arg_block, arg_src, casted_arg, .{ .comptime_only = .{
8143 });8222 .ty = .fromInterned(param_ty),
8144 } else if (!is_comptime_call and zir_tags[@intFromEnum(inst)] == .param_comptime) {8223 .msg = .param_ty_arg,
8145 _ = try ics.caller().resolveConstValue(arg_block, arg_src, casted_arg, .{8224 } });
8146 .needed_comptime_reason = "parameter is comptime",
8147 });
8148 }8225 }
81498226
8150 if (is_comptime_call) {8227 if (is_comptime_call) {
8151 ics.callee().inst_map.putAssumeCapacityNoClobber(inst, casted_arg);8228 ics.callee().inst_map.putAssumeCapacityNoClobber(inst, casted_arg);
8152 const arg_val = try ics.caller().resolveConstValue(arg_block, arg_src, casted_arg, .{8229 const arg_val = try ics.caller().resolveConstValue(arg_block, arg_src, casted_arg, null);
8153 .needed_comptime_reason = "argument to function being called at comptime must be comptime-known",
8154 .block_comptime_reason = param_block.comptime_reason,
8155 });
8156 switch (arg_val.toIntern()) {8230 switch (arg_val.toIntern()) {
8157 .generic_poison, .generic_poison_type => {8231 .generic_poison, .generic_poison_type => {
8158 // This function is currently evaluated as part of an as-of-yet unresolvable8232 // This function is currently evaluated as part of an as-of-yet unresolvable
...@@ -8188,10 +8262,7 @@ fn analyzeInlineCallArg(...@@ -8188,10 +8262,7 @@ fn analyzeInlineCallArg(
81888262
8189 if (is_comptime_call) {8263 if (is_comptime_call) {
8190 ics.callee().inst_map.putAssumeCapacityNoClobber(inst, uncasted_arg);8264 ics.callee().inst_map.putAssumeCapacityNoClobber(inst, uncasted_arg);
8191 const arg_val = try ics.caller().resolveConstValue(arg_block, arg_src, uncasted_arg, .{8265 const arg_val = try ics.caller().resolveConstValue(arg_block, arg_src, uncasted_arg, null);
8192 .needed_comptime_reason = "argument to function being called at comptime must be comptime-known",
8193 .block_comptime_reason = param_block.comptime_reason,
8194 });
8195 switch (arg_val.toIntern()) {8266 switch (arg_val.toIntern()) {
8196 .generic_poison, .generic_poison_type => {8267 .generic_poison, .generic_poison_type => {
8197 // This function is currently evaluated as part of an as-of-yet unresolvable8268 // This function is currently evaluated as part of an as-of-yet unresolvable
...@@ -8208,9 +8279,7 @@ fn analyzeInlineCallArg(...@@ -8208,9 +8279,7 @@ fn analyzeInlineCallArg(
8208 memoized_arg_values[arg_i.*] = resolved_arg_val.toIntern();8279 memoized_arg_values[arg_i.*] = resolved_arg_val.toIntern();
8209 } else {8280 } else {
8210 if (zir_tags[@intFromEnum(inst)] == .param_anytype_comptime) {8281 if (zir_tags[@intFromEnum(inst)] == .param_anytype_comptime) {
8211 _ = try ics.caller().resolveConstValue(arg_block, arg_src, uncasted_arg, .{8282 _ = try ics.caller().resolveConstValue(arg_block, arg_src, uncasted_arg, .{ .simple = .comptime_param_arg });
8212 .needed_comptime_reason = "parameter is comptime",
8213 });
8214 }8283 }
8215 ics.callee().inst_map.putAssumeCapacityNoClobber(inst, uncasted_arg);8284 ics.callee().inst_map.putAssumeCapacityNoClobber(inst, uncasted_arg);
8216 }8285 }
...@@ -8237,15 +8306,18 @@ fn instantiateGenericCall(...@@ -8237,15 +8306,18 @@ fn instantiateGenericCall(
8237 args_info: CallArgsInfo,8306 args_info: CallArgsInfo,
8238 call_tag: Air.Inst.Tag,8307 call_tag: Air.Inst.Tag,
8239 call_dbg_node: ?Zir.Inst.Index,8308 call_dbg_node: ?Zir.Inst.Index,
8309 /// Populated when `error.ComptimeReturn` is returned.
8310 comptime_ret_ty: *Type,
8240) CompileError!Air.Inst.Ref {8311) CompileError!Air.Inst.Ref {
8241 const pt = sema.pt;8312 const pt = sema.pt;
8242 const zcu = pt.zcu;8313 const zcu = pt.zcu;
8243 const gpa = sema.gpa;8314 const gpa = sema.gpa;
8244 const ip = &zcu.intern_pool;8315 const ip = &zcu.intern_pool;
82458316
8246 const func_val = try sema.resolveConstDefinedValue(block, func_src, func, .{8317 // Generic function pointers are comptime-only types, so `func` is definitely comptime-known.
8247 .needed_comptime_reason = "generic function being called must be comptime-known",8318 const func_val = (sema.resolveValue(func) catch unreachable).?;
8248 });8319 if (func_val.isUndef(zcu)) return sema.failWithUseOfUndef(block, func_src);
8320
8249 const generic_owner = switch (zcu.intern_pool.indexToKey(func_val.toIntern())) {8321 const generic_owner = switch (zcu.intern_pool.indexToKey(func_val.toIntern())) {
8250 .func => func_val.toIntern(),8322 .func => func_val.toIntern(),
8251 .ptr => |ptr| ip.getNav(ptr.base_addr.nav).status.fully_resolved.val,8323 .ptr => |ptr| ip.getNav(ptr.base_addr.nav).status.fully_resolved.val,
...@@ -8310,7 +8382,7 @@ fn instantiateGenericCall(...@@ -8310,7 +8382,7 @@ fn instantiateGenericCall(
8310 .namespace = fn_nav.analysis.?.namespace,8382 .namespace = fn_nav.analysis.?.namespace,
8311 .instructions = .{},8383 .instructions = .{},
8312 .inlining = null,8384 .inlining = null,
8313 .is_comptime = true,8385 .comptime_reason = undefined, // set as needed
8314 .src_base_inst = fn_nav.analysis.?.zir_index,8386 .src_base_inst = fn_nav.analysis.?.zir_index,
8315 .type_name_ctx = fn_nav.fqn,8387 .type_name_ctx = fn_nav.fqn,
8316 };8388 };
...@@ -8354,12 +8426,13 @@ fn instantiateGenericCall(...@@ -8354,12 +8426,13 @@ fn instantiateGenericCall(
8354 child_sema.generic_call_src = prev_generic_call_src;8426 child_sema.generic_call_src = prev_generic_call_src;
8355 }8427 }
83568428
8429 const param_ty_src = child_block.tokenOffset(param_data.src_tok);
8430 child_block.comptime_reason = .{ .reason = .{
8431 .src = param_ty_src,
8432 .r = .{ .simple = .type },
8433 } };
8357 const param_ty_inst = try child_sema.resolveInlineBody(&child_block, param_ty_body, param_inst);8434 const param_ty_inst = try child_sema.resolveInlineBody(&child_block, param_ty_body, param_inst);
8358 break :param_ty try child_sema.analyzeAsType(8435 break :param_ty try child_sema.analyzeAsType(&child_block, param_ty_src, param_ty_inst);
8359 &child_block,
8360 child_block.tokenOffset(param_data.src_tok),
8361 param_ty_inst,
8362 );
8363 },8436 },
8364 else => unreachable,8437 else => unreachable,
8365 }8438 }
...@@ -8452,6 +8525,10 @@ fn instantiateGenericCall(...@@ -8452,6 +8525,10 @@ fn instantiateGenericCall(
84528525
8453 // We've already handled parameters, so don't resolve the whole body. Instead, just8526 // We've already handled parameters, so don't resolve the whole body. Instead, just
8454 // do the instructions after the params (i.e. the func itself).8527 // do the instructions after the params (i.e. the func itself).
8528 child_block.comptime_reason = .{ .reason = .{
8529 .src = call_src,
8530 .r = .{ .simple = .type },
8531 } };
8455 const new_func_inst = try child_sema.resolveInlineBody(&child_block, fn_info.param_body[args_info.count()..], fn_info.param_body_inst);8532 const new_func_inst = try child_sema.resolveInlineBody(&child_block, fn_info.param_body[args_info.count()..], fn_info.param_body_inst);
8456 const callee_index = (child_sema.resolveConstDefinedValue(&child_block, LazySrcLoc.unneeded, new_func_inst, undefined) catch unreachable).toIntern();8533 const callee_index = (child_sema.resolveConstDefinedValue(&child_block, LazySrcLoc.unneeded, new_func_inst, undefined) catch unreachable).toIntern();
84578534
...@@ -8465,6 +8542,7 @@ fn instantiateGenericCall(...@@ -8465,6 +8542,7 @@ fn instantiateGenericCall(
8465 // If the call evaluated to a return type that requires comptime, never mind8542 // If the call evaluated to a return type that requires comptime, never mind
8466 // our generic instantiation. Instead we need to perform a comptime call.8543 // our generic instantiation. Instead we need to perform a comptime call.
8467 if (try Type.fromInterned(func_ty_info.return_type).comptimeOnlySema(pt)) {8544 if (try Type.fromInterned(func_ty_info.return_type).comptimeOnlySema(pt)) {
8545 comptime_ret_ty.* = .fromInterned(func_ty_info.return_type);
8468 return error.ComptimeReturn;8546 return error.ComptimeReturn;
8469 }8547 }
8470 // Similarly, if the call evaluated to a generic type we need to instead8548 // Similarly, if the call evaluated to a generic type we need to instead
...@@ -8622,9 +8700,7 @@ fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!...@@ -8622,9 +8700,7 @@ fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
8622 const len_src = block.builtinCallArgSrc(inst_data.src_node, 0);8700 const len_src = block.builtinCallArgSrc(inst_data.src_node, 0);
8623 const elem_type_src = block.builtinCallArgSrc(inst_data.src_node, 1);8701 const elem_type_src = block.builtinCallArgSrc(inst_data.src_node, 1);
8624 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;8702 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
8625 const len: u32 = @intCast(try sema.resolveInt(block, len_src, extra.lhs, Type.u32, .{8703 const len: u32 = @intCast(try sema.resolveInt(block, len_src, extra.lhs, Type.u32, .{ .simple = .vector_length }));
8626 .needed_comptime_reason = "vector length must be comptime-known",
8627 }));
8628 const elem_type = try sema.resolveType(block, elem_type_src, extra.rhs);8704 const elem_type = try sema.resolveType(block, elem_type_src, extra.rhs);
8629 try sema.checkVectorElemType(block, elem_type_src, elem_type);8705 try sema.checkVectorElemType(block, elem_type_src, elem_type);
8630 const vector_type = try sema.pt.vectorType(.{8706 const vector_type = try sema.pt.vectorType(.{
...@@ -8642,9 +8718,7 @@ fn zirArrayType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -8642,9 +8718,7 @@ fn zirArrayType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
8642 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;8718 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
8643 const len_src = block.src(.{ .node_offset_array_type_len = inst_data.src_node });8719 const len_src = block.src(.{ .node_offset_array_type_len = inst_data.src_node });
8644 const elem_src = block.src(.{ .node_offset_array_type_elem = inst_data.src_node });8720 const elem_src = block.src(.{ .node_offset_array_type_elem = inst_data.src_node });
8645 const len = try sema.resolveInt(block, len_src, extra.lhs, Type.usize, .{8721 const len = try sema.resolveInt(block, len_src, extra.lhs, Type.usize, .{ .simple = .array_length });
8646 .needed_comptime_reason = "array length must be comptime-known",
8647 });
8648 const elem_type = try sema.resolveType(block, elem_src, extra.rhs);8722 const elem_type = try sema.resolveType(block, elem_src, extra.rhs);
8649 try sema.validateArrayElemType(block, elem_type, elem_src);8723 try sema.validateArrayElemType(block, elem_type, elem_src);
8650 const array_ty = try sema.pt.arrayType(.{8724 const array_ty = try sema.pt.arrayType(.{
...@@ -8664,16 +8738,12 @@ fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil...@@ -8664,16 +8738,12 @@ fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
8664 const len_src = block.src(.{ .node_offset_array_type_len = inst_data.src_node });8738 const len_src = block.src(.{ .node_offset_array_type_len = inst_data.src_node });
8665 const sentinel_src = block.src(.{ .node_offset_array_type_sentinel = inst_data.src_node });8739 const sentinel_src = block.src(.{ .node_offset_array_type_sentinel = inst_data.src_node });
8666 const elem_src = block.src(.{ .node_offset_array_type_elem = inst_data.src_node });8740 const elem_src = block.src(.{ .node_offset_array_type_elem = inst_data.src_node });
8667 const len = try sema.resolveInt(block, len_src, extra.len, Type.usize, .{8741 const len = try sema.resolveInt(block, len_src, extra.len, Type.usize, .{ .simple = .array_length });
8668 .needed_comptime_reason = "array length must be comptime-known",
8669 });
8670 const elem_type = try sema.resolveType(block, elem_src, extra.elem_type);8742 const elem_type = try sema.resolveType(block, elem_src, extra.elem_type);
8671 try sema.validateArrayElemType(block, elem_type, elem_src);8743 try sema.validateArrayElemType(block, elem_type, elem_src);
8672 const uncasted_sentinel = try sema.resolveInst(extra.sentinel);8744 const uncasted_sentinel = try sema.resolveInst(extra.sentinel);
8673 const sentinel = try sema.coerce(block, elem_type, uncasted_sentinel, sentinel_src);8745 const sentinel = try sema.coerce(block, elem_type, uncasted_sentinel, sentinel_src);
8674 const sentinel_val = try sema.resolveConstDefinedValue(block, sentinel_src, sentinel, .{8746 const sentinel_val = try sema.resolveConstDefinedValue(block, sentinel_src, sentinel, .{ .simple = .array_sentinel });
8675 .needed_comptime_reason = "array sentinel value must be comptime-known",
8676 });
8677 const array_ty = try sema.pt.arrayType(.{8747 const array_ty = try sema.pt.arrayType(.{
8678 .len = len,8748 .len = len,
8679 .sentinel = sentinel_val.toIntern(),8749 .sentinel = sentinel_val.toIntern(),
...@@ -9071,9 +9141,7 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError...@@ -9071,9 +9141,7 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
9071 }9141 }
90729142
9073 if (dest_ty.intTagType(zcu).zigTypeTag(zcu) == .comptime_int) {9143 if (dest_ty.intTagType(zcu).zigTypeTag(zcu) == .comptime_int) {
9074 return sema.failWithNeededComptime(block, operand_src, .{9144 return sema.failWithNeededComptime(block, operand_src, .{ .simple = .casted_to_comptime_enum });
9075 .needed_comptime_reason = "value being casted to enum with 'comptime_int' tag type must be comptime-known",
9076 });
9077 }9145 }
90789146
9079 if (try sema.typeHasOnePossibleValue(dest_ty)) |opv| {9147 if (try sema.typeHasOnePossibleValue(dest_ty)) |opv| {
...@@ -9487,9 +9555,7 @@ fn zirFunc(...@@ -9487,9 +9555,7 @@ fn zirFunc(
9487 const ret_ty_body = sema.code.bodySlice(extra_index, extra.data.ret_body_len);9555 const ret_ty_body = sema.code.bodySlice(extra_index, extra.data.ret_body_len);
9488 extra_index += ret_ty_body.len;9556 extra_index += ret_ty_body.len;
94899557
9490 const ret_ty_val = try sema.resolveGenericBody(block, ret_ty_src, ret_ty_body, inst, Type.type, .{9558 const ret_ty_val = try sema.resolveGenericBody(block, ret_ty_src, ret_ty_body, inst, Type.type, .{ .simple = .function_ret_ty });
9491 .needed_comptime_reason = "return type must be comptime-known",
9492 });
9493 break :blk ret_ty_val.toType();9559 break :blk ret_ty_val.toType();
9494 },9560 },
9495 };9561 };
...@@ -9556,7 +9622,7 @@ fn resolveGenericBody(...@@ -9556,7 +9622,7 @@ fn resolveGenericBody(
9556 body: []const Zir.Inst.Index,9622 body: []const Zir.Inst.Index,
9557 func_inst: Zir.Inst.Index,9623 func_inst: Zir.Inst.Index,
9558 dest_ty: Type,9624 dest_ty: Type,
9559 reason: NeededComptimeReason,9625 reason: ComptimeReason,
9560) !Value {9626) !Value {
9561 assert(body.len != 0);9627 assert(body.len != 0);
95629628
...@@ -9894,7 +9960,7 @@ fn funcCommon(...@@ -9894,7 +9960,7 @@ fn funcCommon(
9894 };9960 };
9895 return sema.failWithOwnedErrorMsg(block, msg);9961 return sema.failWithOwnedErrorMsg(block, msg);
9896 }9962 }
9897 if (is_source_decl and requires_comptime and !param_is_comptime and has_body and !block.is_comptime) {9963 if (is_source_decl and requires_comptime and !param_is_comptime and has_body and !block.isComptime()) {
9898 const msg = msg: {9964 const msg = msg: {
9899 const msg = try sema.errMsg(param_src, "parameter of type '{}' must be declared comptime", .{9965 const msg = try sema.errMsg(param_src, "parameter of type '{}' must be declared comptime", .{
9900 param_ty.fmt(pt),9966 param_ty.fmt(pt),
...@@ -10132,7 +10198,7 @@ fn finishFunc(...@@ -10132,7 +10198,7 @@ fn finishFunc(
1013210198
10133 // If the return type is comptime-only but not dependent on parameters then10199 // If the return type is comptime-only but not dependent on parameters then
10134 // all parameter types also need to be comptime.10200 // all parameter types also need to be comptime.
10135 if (is_source_decl and opt_func_index != .none and ret_ty_requires_comptime and !block.is_comptime) comptime_check: {10201 if (is_source_decl and opt_func_index != .none and ret_ty_requires_comptime and !block.isComptime()) comptime_check: {
10136 for (block.params.items(.is_comptime)) |is_comptime| {10202 for (block.params.items(.is_comptime)) |is_comptime| {
10137 if (!is_comptime) break;10203 if (!is_comptime) break;
10138 } else break :comptime_check;10204 } else break :comptime_check;
...@@ -10547,9 +10613,7 @@ fn zirFieldValNamed(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr...@@ -10547,9 +10613,7 @@ fn zirFieldValNamed(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
10547 const field_name_src = block.builtinCallArgSrc(inst_data.src_node, 1);10613 const field_name_src = block.builtinCallArgSrc(inst_data.src_node, 1);
10548 const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;10614 const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;
10549 const object = try sema.resolveInst(extra.lhs);10615 const object = try sema.resolveInst(extra.lhs);
10550 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{10616 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{ .simple = .field_name });
10551 .needed_comptime_reason = "field name must be comptime-known",
10552 });
10553 return sema.fieldVal(block, src, object, field_name, field_name_src);10617 return sema.fieldVal(block, src, object, field_name, field_name_src);
10554}10618}
1055510619
...@@ -10562,9 +10626,7 @@ fn zirFieldPtrNamed(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr...@@ -10562,9 +10626,7 @@ fn zirFieldPtrNamed(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
10562 const field_name_src = block.builtinCallArgSrc(inst_data.src_node, 1);10626 const field_name_src = block.builtinCallArgSrc(inst_data.src_node, 1);
10563 const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;10627 const extra = sema.code.extraData(Zir.Inst.FieldNamed, inst_data.payload_index).data;
10564 const object_ptr = try sema.resolveInst(extra.lhs);10628 const object_ptr = try sema.resolveInst(extra.lhs);
10565 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{10629 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{ .simple = .field_name });
10566 .needed_comptime_reason = "field name must be comptime-known",
10567 });
10568 return sema.fieldPtr(block, src, object_ptr, field_name, field_name_src, false);10630 return sema.fieldPtr(block, src, object_ptr, field_name, field_name_src, false);
10569}10631}
1057010632
...@@ -11923,7 +11985,6 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp...@@ -11923,7 +11985,6 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
11923 .instructions = .{},11985 .instructions = .{},
11924 .label = &label,11986 .label = &label,
11925 .inlining = block.inlining,11987 .inlining = block.inlining,
11926 .is_comptime = block.is_comptime,
11927 .comptime_reason = block.comptime_reason,11988 .comptime_reason = block.comptime_reason,
11928 .is_typeof = block.is_typeof,11989 .is_typeof = block.is_typeof,
11929 .c_import_buf = block.c_import_buf,11990 .c_import_buf = block.c_import_buf,
...@@ -12027,11 +12088,8 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp...@@ -12027,11 +12088,8 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
12027 };12088 };
12028 }12089 }
1202912090
12030 if (child_block.is_comptime) {12091 if (child_block.isComptime()) {
12031 _ = try sema.resolveConstDefinedValue(&child_block, main_operand_src, raw_operand_val, .{12092 _ = try sema.resolveConstDefinedValue(&child_block, main_operand_src, raw_operand_val, null);
12032 .needed_comptime_reason = "condition in comptime switch must be comptime-known",
12033 .block_comptime_reason = child_block.comptime_reason,
12034 });
12035 unreachable;12093 unreachable;
12036 }12094 }
1203712095
...@@ -12148,7 +12206,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r...@@ -12148,7 +12206,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1214812206
12149 const operand_ty = sema.typeOf(val);12207 const operand_ty = sema.typeOf(val);
1215012208
12151 if (extra.data.bits.has_continue and !block.is_comptime) {12209 if (extra.data.bits.has_continue and !block.isComptime()) {
12152 // Even if the operand is comptime-known, this `switch` is runtime.12210 // Even if the operand is comptime-known, this `switch` is runtime.
12153 if (try operand_ty.comptimeOnlySema(pt)) {12211 if (try operand_ty.comptimeOnlySema(pt)) {
12154 return sema.failWithOwnedErrorMsg(block, msg: {12212 return sema.failWithOwnedErrorMsg(block, msg: {
...@@ -12707,7 +12765,6 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r...@@ -12707,7 +12765,6 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
12707 .instructions = .{},12765 .instructions = .{},
12708 .label = &label,12766 .label = &label,
12709 .inlining = block.inlining,12767 .inlining = block.inlining,
12710 .is_comptime = block.is_comptime,
12711 .comptime_reason = block.comptime_reason,12768 .comptime_reason = block.comptime_reason,
12712 .is_typeof = block.is_typeof,12769 .is_typeof = block.is_typeof,
12713 .c_import_buf = block.c_import_buf,12770 .c_import_buf = block.c_import_buf,
...@@ -12790,11 +12847,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r...@@ -12790,11 +12847,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
12790 },12847 },
12791 }12848 }
1279212849
12793 if (child_block.is_comptime) {12850 if (child_block.isComptime()) {
12794 _ = try sema.resolveConstDefinedValue(&child_block, operand_src, operand.simple.cond, .{12851 _ = try sema.resolveConstDefinedValue(&child_block, operand_src, operand.simple.cond, null);
12795 .needed_comptime_reason = "condition in comptime switch must be comptime-known",
12796 .block_comptime_reason = child_block.comptime_reason,
12797 });
12798 unreachable;12852 unreachable;
12799 }12853 }
1280012854
...@@ -13582,10 +13636,7 @@ fn resolveSwitchComptimeLoop(...@@ -13582,10 +13636,7 @@ fn resolveSwitchComptimeLoop(
1358213636
13583 const cond_ref = try sema.switchCond(child_block, src, val);13637 const cond_ref = try sema.switchCond(child_block, src, val);
1358413638
13585 cond_val = try sema.resolveConstDefinedValue(child_block, src, cond_ref, .{13639 cond_val = try sema.resolveConstDefinedValue(child_block, src, cond_ref, null);
13586 .needed_comptime_reason = "condition in comptime switch must be comptime-known",
13587 .block_comptime_reason = child_block.comptime_reason,
13588 });
13589 spa.operand = .{ .simple = .{13640 spa.operand = .{ .simple = .{
13590 .by_val = val,13641 .by_val = val,
13591 .by_ref = ref,13642 .by_ref = ref,
...@@ -13825,9 +13876,7 @@ fn resolveSwitchItemVal(...@@ -13825,9 +13876,7 @@ fn resolveSwitchItemVal(
1382513876
13826 const item = try sema.coerce(block, coerce_ty, uncoerced_item, item_src);13877 const item = try sema.coerce(block, coerce_ty, uncoerced_item, item_src);
1382713878
13828 const maybe_lazy = try sema.resolveConstDefinedValue(block, item_src, item, .{13879 const maybe_lazy = try sema.resolveConstDefinedValue(block, item_src, item, .{ .simple = .switch_item });
13829 .needed_comptime_reason = "switch prong values must be comptime-known",
13830 });
1383113880
13832 const val = try sema.resolveLazyValue(maybe_lazy);13881 const val = try sema.resolveLazyValue(maybe_lazy);
13833 const new_item = if (val.toIntern() != maybe_lazy.toIntern()) blk: {13882 const new_item = if (val.toIntern() != maybe_lazy.toIntern()) blk: {
...@@ -14295,9 +14344,7 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai...@@ -14295,9 +14344,7 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
14295 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);14344 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
14296 const name_src = block.builtinCallArgSrc(inst_data.src_node, 1);14345 const name_src = block.builtinCallArgSrc(inst_data.src_node, 1);
14297 const ty = try sema.resolveType(block, ty_src, extra.lhs);14346 const ty = try sema.resolveType(block, ty_src, extra.lhs);
14298 const field_name = try sema.resolveConstStringIntern(block, name_src, extra.rhs, .{14347 const field_name = try sema.resolveConstStringIntern(block, name_src, extra.rhs, .{ .simple = .field_name });
14299 .needed_comptime_reason = "field name must be comptime-known",
14300 });
14301 try ty.resolveFields(pt);14348 try ty.resolveFields(pt);
14302 const ip = &zcu.intern_pool;14349 const ip = &zcu.intern_pool;
1430314350
...@@ -14344,9 +14391,7 @@ fn zirHasDecl(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air...@@ -14344,9 +14391,7 @@ fn zirHasDecl(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
14344 const lhs_src = block.builtinCallArgSrc(inst_data.src_node, 0);14391 const lhs_src = block.builtinCallArgSrc(inst_data.src_node, 0);
14345 const rhs_src = block.builtinCallArgSrc(inst_data.src_node, 1);14392 const rhs_src = block.builtinCallArgSrc(inst_data.src_node, 1);
14346 const container_type = try sema.resolveType(block, lhs_src, extra.lhs);14393 const container_type = try sema.resolveType(block, lhs_src, extra.lhs);
14347 const decl_name = try sema.resolveConstStringIntern(block, rhs_src, extra.rhs, .{14394 const decl_name = try sema.resolveConstStringIntern(block, rhs_src, extra.rhs, .{ .simple = .decl_name });
14348 .needed_comptime_reason = "decl name must be comptime-known",
14349 });
1435014395
14351 try sema.checkNamespaceType(block, lhs_src, container_type);14396 try sema.checkNamespaceType(block, lhs_src, container_type);
1435214397
...@@ -14399,9 +14444,7 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -14399,9 +14444,7 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
14399 const pt = sema.pt;14444 const pt = sema.pt;
14400 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;14445 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
14401 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);14446 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
14402 const name = try sema.resolveConstString(block, operand_src, inst_data.operand, .{14447 const name = try sema.resolveConstString(block, operand_src, inst_data.operand, .{ .simple = .operand_embedFile });
14403 .needed_comptime_reason = "file path name must be comptime-known",
14404 });
1440514448
14406 if (name.len == 0) {14449 if (name.len == 0) {
14407 return sema.fail(block, operand_src, "file path name cannot be empty", .{});14450 return sema.fail(block, operand_src, "file path name cannot be empty", .{});
...@@ -14589,7 +14632,7 @@ fn zirShl(...@@ -14589,7 +14632,7 @@ fn zirShl(
14589 }),14632 }),
14590 } },14633 } },
14591 });14634 });
14592 const ov_bit = try sema.tupleFieldValByIndex(block, src, op_ov, 1, op_ov_tuple_ty);14635 const ov_bit = try sema.tupleFieldValByIndex(block, op_ov, 1, op_ov_tuple_ty);
14593 const any_ov_bit = if (lhs_ty.zigTypeTag(zcu) == .vector)14636 const any_ov_bit = if (lhs_ty.zigTypeTag(zcu) == .vector)
14594 try block.addInst(.{14637 try block.addInst(.{
14595 .tag = if (block.float_mode == .optimized) .reduce_optimized else .reduce,14638 .tag = if (block.float_mode == .optimized) .reduce_optimized else .reduce,
...@@ -14604,7 +14647,7 @@ fn zirShl(...@@ -14604,7 +14647,7 @@ fn zirShl(
14604 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);14647 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);
1460514648
14606 try sema.addSafetyCheck(block, src, no_ov, .shl_overflow);14649 try sema.addSafetyCheck(block, src, no_ov, .shl_overflow);
14607 return sema.tupleFieldValByIndex(block, src, op_ov, 0, op_ov_tuple_ty);14650 return sema.tupleFieldValByIndex(block, op_ov, 0, op_ov_tuple_ty);
14608 }14651 }
14609 }14652 }
14610 return block.addBinOp(air_tag, lhs, new_rhs);14653 return block.addBinOp(air_tag, lhs, new_rhs);
...@@ -14932,20 +14975,12 @@ fn analyzeTupleCat(...@@ -14932,20 +14975,12 @@ fn analyzeTupleCat(
14932 const element_refs = try sema.arena.alloc(Air.Inst.Ref, final_len);14975 const element_refs = try sema.arena.alloc(Air.Inst.Ref, final_len);
14933 var i: u32 = 0;14976 var i: u32 = 0;
14934 while (i < lhs_len) : (i += 1) {14977 while (i < lhs_len) : (i += 1) {
14935 const operand_src = block.src(.{ .array_cat_lhs = .{14978 element_refs[i] = try sema.tupleFieldValByIndex(block, lhs, i, lhs_ty);
14936 .array_cat_offset = src_node,
14937 .elem_index = i,
14938 } });
14939 element_refs[i] = try sema.tupleFieldValByIndex(block, operand_src, lhs, i, lhs_ty);
14940 }14979 }
14941 i = 0;14980 i = 0;
14942 while (i < rhs_len) : (i += 1) {14981 while (i < rhs_len) : (i += 1) {
14943 const operand_src = block.src(.{ .array_cat_rhs = .{
14944 .array_cat_offset = src_node,
14945 .elem_index = i,
14946 } });
14947 element_refs[i + lhs_len] =14982 element_refs[i + lhs_len] =
14948 try sema.tupleFieldValByIndex(block, operand_src, rhs, i, rhs_ty);14983 try sema.tupleFieldValByIndex(block, rhs, i, rhs_ty);
14949 }14984 }
1495014985
14951 return block.addAggregateInit(Type.fromInterned(tuple_ty), element_refs);14986 return block.addAggregateInit(Type.fromInterned(tuple_ty), element_refs);
...@@ -14985,7 +15020,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai...@@ -14985,7 +15020,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1498515020
14986 const resolved_elem_ty = t: {15021 const resolved_elem_ty = t: {
14987 var trash_block = block.makeSubBlock();15022 var trash_block = block.makeSubBlock();
14988 trash_block.is_comptime = false;15023 trash_block.comptime_reason = null;
14989 defer trash_block.instructions.deinit(sema.gpa);15024 defer trash_block.instructions.deinit(sema.gpa);
1499015025
14991 const instructions = [_]Air.Inst.Ref{15026 const instructions = [_]Air.Inst.Ref{
...@@ -15268,9 +15303,7 @@ fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Ins...@@ -15268,9 +15303,7 @@ fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Ins
15268 const ptr_info = operand_ty.ptrInfo(zcu);15303 const ptr_info = operand_ty.ptrInfo(zcu);
15269 switch (ptr_info.flags.size) {15304 switch (ptr_info.flags.size) {
15270 .Slice => {15305 .Slice => {
15271 const val = try sema.resolveConstDefinedValue(block, src, operand, .{15306 const val = try sema.resolveConstDefinedValue(block, src, operand, .{ .simple = .slice_cat_operand });
15272 .needed_comptime_reason = "slice value being concatenated must be comptime-known",
15273 });
15274 return Type.ArrayInfo{15307 return Type.ArrayInfo{
15275 .elem_type = Type.fromInterned(ptr_info.child),15308 .elem_type = Type.fromInterned(ptr_info.child),
15276 .sentinel = switch (ptr_info.sentinel) {15309 .sentinel = switch (ptr_info.sentinel) {
...@@ -15365,11 +15398,7 @@ fn analyzeTupleMul(...@@ -15365,11 +15398,7 @@ fn analyzeTupleMul(
15365 const element_refs = try sema.arena.alloc(Air.Inst.Ref, final_len);15398 const element_refs = try sema.arena.alloc(Air.Inst.Ref, final_len);
15366 var i: u32 = 0;15399 var i: u32 = 0;
15367 while (i < tuple_len) : (i += 1) {15400 while (i < tuple_len) : (i += 1) {
15368 const operand_src = block.src(.{ .array_cat_lhs = .{15401 element_refs[i] = try sema.tupleFieldValByIndex(block, operand, @intCast(i), operand_ty);
15369 .array_cat_offset = src_node,
15370 .elem_index = i,
15371 } });
15372 element_refs[i] = try sema.tupleFieldValByIndex(block, operand_src, operand, @intCast(i), operand_ty);
15373 }15402 }
15374 i = 1;15403 i = 1;
15375 while (i < factor) : (i += 1) {15404 while (i < factor) : (i += 1) {
...@@ -15431,9 +15460,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai...@@ -15431,9 +15460,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1543115460
15432 if (lhs_ty.isTuple(zcu)) {15461 if (lhs_ty.isTuple(zcu)) {
15433 // In `**` rhs must be comptime-known, but lhs can be runtime-known15462 // In `**` rhs must be comptime-known, but lhs can be runtime-known
15434 const factor = try sema.resolveInt(block, rhs_src, extra.rhs, Type.usize, .{15463 const factor = try sema.resolveInt(block, rhs_src, extra.rhs, Type.usize, .{ .simple = .array_mul_factor });
15435 .needed_comptime_reason = "array multiplication factor must be comptime-known",
15436 });
15437 const factor_casted = try sema.usizeCast(block, rhs_src, factor);15464 const factor_casted = try sema.usizeCast(block, rhs_src, factor);
15438 return sema.analyzeTupleMul(block, inst_data.src_node, lhs, factor_casted);15465 return sema.analyzeTupleMul(block, inst_data.src_node, lhs, factor_casted);
15439 }15466 }
...@@ -15455,9 +15482,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai...@@ -15455,9 +15482,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
15455 };15482 };
1545615483
15457 // In `**` rhs must be comptime-known, but lhs can be runtime-known15484 // In `**` rhs must be comptime-known, but lhs can be runtime-known
15458 const factor = try sema.resolveInt(block, rhs_src, extra.rhs, Type.usize, .{15485 const factor = try sema.resolveInt(block, rhs_src, extra.rhs, Type.usize, .{ .simple = .array_mul_factor });
15459 .needed_comptime_reason = "array multiplication factor must be comptime-known",
15460 });
1546115486
15462 const result_len_u64 = std.math.mul(u64, lhs_info.len, factor) catch15487 const result_len_u64 = std.math.mul(u64, lhs_info.len, factor) catch
15463 return sema.fail(block, rhs_src, "operation results in overflow", .{});15488 return sema.fail(block, rhs_src, "operation results in overflow", .{});
...@@ -17471,7 +17496,7 @@ fn analyzeArithmetic(...@@ -17471,7 +17496,7 @@ fn analyzeArithmetic(
17471 }),17496 }),
17472 } },17497 } },
17473 });17498 });
17474 const ov_bit = try sema.tupleFieldValByIndex(block, src, op_ov, 1, op_ov_tuple_ty);17499 const ov_bit = try sema.tupleFieldValByIndex(block, op_ov, 1, op_ov_tuple_ty);
17475 const any_ov_bit = if (resolved_type.zigTypeTag(zcu) == .vector)17500 const any_ov_bit = if (resolved_type.zigTypeTag(zcu) == .vector)
17476 try block.addInst(.{17501 try block.addInst(.{
17477 .tag = if (block.float_mode == .optimized) .reduce_optimized else .reduce,17502 .tag = if (block.float_mode == .optimized) .reduce_optimized else .reduce,
...@@ -17486,7 +17511,7 @@ fn analyzeArithmetic(...@@ -17486,7 +17511,7 @@ fn analyzeArithmetic(
17486 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);17511 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);
1748717512
17488 try sema.addSafetyCheck(block, src, no_ov, .integer_overflow);17513 try sema.addSafetyCheck(block, src, no_ov, .integer_overflow);
17489 return sema.tupleFieldValByIndex(block, src, op_ov, 0, op_ov_tuple_ty);17514 return sema.tupleFieldValByIndex(block, op_ov, 0, op_ov_tuple_ty);
17490 }17515 }
17491 }17516 }
17492 }17517 }
...@@ -17635,12 +17660,9 @@ fn zirAsm(...@@ -17635,12 +17660,9 @@ fn zirAsm(
17635 const is_global_assembly = sema.func_index == .none;17660 const is_global_assembly = sema.func_index == .none;
17636 const zir_tags = sema.code.instructions.items(.tag);17661 const zir_tags = sema.code.instructions.items(.tag);
1763717662
17638 const asm_source: []const u8 = if (tmpl_is_expr) blk: {17663 const asm_source: []const u8 = if (tmpl_is_expr) s: {
17639 const tmpl: Zir.Inst.Ref = @enumFromInt(@intFromEnum(extra.data.asm_source));17664 const tmpl: Zir.Inst.Ref = @enumFromInt(@intFromEnum(extra.data.asm_source));
17640 const s: []const u8 = try sema.resolveConstString(block, src, tmpl, .{17665 break :s try sema.resolveConstString(block, src, tmpl, .{ .simple = .inline_assembly_code });
17641 .needed_comptime_reason = "assembly code must be comptime-known",
17642 });
17643 break :blk s;
17644 } else sema.code.nullTerminatedString(extra.data.asm_source);17666 } else sema.code.nullTerminatedString(extra.data.asm_source);
1764517667
17646 if (is_global_assembly) {17668 if (is_global_assembly) {
...@@ -18203,7 +18225,7 @@ fn zirClosureGet(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat...@@ -18203,7 +18225,7 @@ fn zirClosureGet(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
18203 return sema.failWithOwnedErrorMsg(block, msg);18225 return sema.failWithOwnedErrorMsg(block, msg);
18204 }18226 }
1820518227
18206 if (!block.is_typeof and !block.is_comptime and sema.func_index != .none) {18228 if (!block.is_typeof and !block.isComptime() and sema.func_index != .none) {
18207 const msg = msg: {18229 const msg = msg: {
18208 const name = name: {18230 const name = name: {
18209 const file, const src_base_node = Zcu.LazySrcLoc.resolveBaseNode(block.src_base_inst, zcu).?;18231 const file, const src_base_node = Zcu.LazySrcLoc.resolveBaseNode(block.src_base_inst, zcu).?;
...@@ -18244,7 +18266,7 @@ fn zirRetAddr(...@@ -18244,7 +18266,7 @@ fn zirRetAddr(
18244 extended: Zir.Inst.Extended.InstData,18266 extended: Zir.Inst.Extended.InstData,
18245) CompileError!Air.Inst.Ref {18267) CompileError!Air.Inst.Ref {
18246 _ = extended;18268 _ = extended;
18247 if (block.is_comptime) {18269 if (block.isComptime()) {
18248 // TODO: we could give a meaningful lazy value here. #1493818270 // TODO: we could give a meaningful lazy value here. #14938
18249 return sema.pt.intRef(Type.usize, 0);18271 return sema.pt.intRef(Type.usize, 0);
18250 } else {18272 } else {
...@@ -19342,7 +19364,7 @@ fn zirTypeofBuiltin(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr...@@ -19342,7 +19364,7 @@ fn zirTypeofBuiltin(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
19342 .namespace = block.namespace,19364 .namespace = block.namespace,
19343 .instructions = .{},19365 .instructions = .{},
19344 .inlining = block.inlining,19366 .inlining = block.inlining,
19345 .is_comptime = false,19367 .comptime_reason = null,
19346 .is_typeof = true,19368 .is_typeof = true,
19347 .want_safety = false,19369 .want_safety = false,
19348 .error_return_trace_index = block.error_return_trace_index,19370 .error_return_trace_index = block.error_return_trace_index,
...@@ -19422,7 +19444,7 @@ fn zirTypeofPeer(...@@ -19422,7 +19444,7 @@ fn zirTypeofPeer(
19422 .namespace = block.namespace,19444 .namespace = block.namespace,
19423 .instructions = .{},19445 .instructions = .{},
19424 .inlining = block.inlining,19446 .inlining = block.inlining,
19425 .is_comptime = false,19447 .comptime_reason = null,
19426 .is_typeof = true,19448 .is_typeof = true,
19427 .runtime_cond = block.runtime_cond,19449 .runtime_cond = block.runtime_cond,
19428 .runtime_loop = block.runtime_loop,19450 .runtime_loop = block.runtime_loop,
...@@ -19980,7 +20002,7 @@ fn ensurePostHoc(sema: *Sema, block: *Block, dest_block: Zir.Inst.Index) !*Label...@@ -19980,7 +20002,7 @@ fn ensurePostHoc(sema: *Sema, block: *Block, dest_block: Zir.Inst.Index) !*Label
19980 .instructions = .{},20002 .instructions = .{},
19981 .label = &labeled_block.label,20003 .label = &labeled_block.label,
19982 .inlining = block.inlining,20004 .inlining = block.inlining,
19983 .is_comptime = block.is_comptime,20005 .comptime_reason = block.comptime_reason,
19984 .src_base_inst = block.src_base_inst,20006 .src_base_inst = block.src_base_inst,
19985 .type_name_ctx = block.type_name_ctx,20007 .type_name_ctx = block.type_name_ctx,
19986 },20008 },
...@@ -20013,7 +20035,7 @@ fn zirUnreachable(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError...@@ -20013,7 +20035,7 @@ fn zirUnreachable(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
20013 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].@"unreachable";20035 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].@"unreachable";
20014 const src = block.nodeOffset(inst_data.src_node);20036 const src = block.nodeOffset(inst_data.src_node);
2001520037
20016 if (block.is_comptime) {20038 if (block.isComptime()) {
20017 return sema.fail(block, src, "reached unreachable code", .{});20039 return sema.fail(block, src, "reached unreachable code", .{});
20018 }20040 }
20019 // TODO Add compile error for @optimizeFor occurring too late in a scope.20041 // TODO Add compile error for @optimizeFor occurring too late in a scope.
...@@ -20066,7 +20088,7 @@ fn zirRetImplicit(...@@ -20066,7 +20088,7 @@ fn zirRetImplicit(
20066 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;20088 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;
20067 const r_brace_src = block.tokenOffset(inst_data.src_tok);20089 const r_brace_src = block.tokenOffset(inst_data.src_tok);
20068 if (block.inlining == null and sema.func_is_naked) {20090 if (block.inlining == null and sema.func_is_naked) {
20069 assert(!block.is_comptime);20091 assert(!block.isComptime());
20070 if (block.wantSafety()) {20092 if (block.wantSafety()) {
20071 // Calling a safety function from a naked function would not be legal.20093 // Calling a safety function from a naked function would not be legal.
20072 _ = try block.addNoOp(.trap);20094 _ = try block.addNoOp(.trap);
...@@ -20123,7 +20145,7 @@ fn zirRetLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!voi...@@ -20123,7 +20145,7 @@ fn zirRetLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!voi
20123 const src = block.nodeOffset(inst_data.src_node);20145 const src = block.nodeOffset(inst_data.src_node);
20124 const ret_ptr = try sema.resolveInst(inst_data.operand);20146 const ret_ptr = try sema.resolveInst(inst_data.operand);
2012520147
20126 if (block.is_comptime or block.inlining != null or sema.func_is_naked) {20148 if (block.isComptime() or block.inlining != null or sema.func_is_naked) {
20127 const operand = try sema.analyzeLoad(block, src, ret_ptr, src);20149 const operand = try sema.analyzeLoad(block, src, ret_ptr, src);
20128 return sema.analyzeRet(block, operand, src, block.src(.{ .node_offset_return_operand = inst_data.src_node }));20150 return sema.analyzeRet(block, operand, src, block.src(.{ .node_offset_return_operand = inst_data.src_node }));
20129 }20151 }
...@@ -20215,7 +20237,7 @@ fn zirSaveErrRetIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE...@@ -20215,7 +20237,7 @@ fn zirSaveErrRetIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
20215 if (!block.ownerModule().error_tracing) return;20237 if (!block.ownerModule().error_tracing) return;
2021620238
20217 // This is only relevant at runtime.20239 // This is only relevant at runtime.
20218 if (block.is_comptime or block.is_typeof) return;20240 if (block.isComptime() or block.is_typeof) return;
2021920241
20220 const save_index = inst_data.operand == .none or b: {20242 const save_index = inst_data.operand == .none or b: {
20221 const operand = try sema.resolveInst(inst_data.operand);20243 const operand = try sema.resolveInst(inst_data.operand);
...@@ -20268,7 +20290,7 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_...@@ -20268,7 +20290,7 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_
2026820290
20269 const operand = try sema.resolveInstAllowNone(operand_zir);20291 const operand = try sema.resolveInstAllowNone(operand_zir);
2027020292
20271 if (start_block.is_comptime or start_block.is_typeof) {20293 if (start_block.isComptime() or start_block.is_typeof) {
20272 const is_non_error = if (operand != .none) blk: {20294 const is_non_error = if (operand != .none) blk: {
20273 const is_non_error_inst = try sema.analyzeIsNonErr(start_block, src, operand);20295 const is_non_error_inst = try sema.analyzeIsNonErr(start_block, src, operand);
20274 const cond_val = try sema.resolveDefinedValue(start_block, src, is_non_error_inst);20296 const cond_val = try sema.resolveDefinedValue(start_block, src, is_non_error_inst);
...@@ -20345,10 +20367,8 @@ fn analyzeRet(...@@ -20345,10 +20367,8 @@ fn analyzeRet(
20345 };20367 };
2034620368
20347 if (block.inlining) |inlining| {20369 if (block.inlining) |inlining| {
20348 if (block.is_comptime) {20370 if (block.isComptime()) {
20349 const ret_val = try sema.resolveConstValue(block, operand_src, operand, .{20371 const ret_val = try sema.resolveConstValue(block, operand_src, operand, null);
20350 .needed_comptime_reason = "value being returned at comptime must be comptime-known",
20351 });
20352 inlining.comptime_result = operand;20372 inlining.comptime_result = operand;
2035320373
20354 if (sema.fn_ret_ty.isError(zcu) and ret_val.getErrorName(zcu) != .none) {20374 if (sema.fn_ret_ty.isError(zcu) and ret_val.getErrorName(zcu) != .none) {
...@@ -20362,7 +20382,7 @@ fn analyzeRet(...@@ -20362,7 +20382,7 @@ fn analyzeRet(
20362 try inlining.merges.br_list.append(sema.gpa, br_inst.toIndex().?);20382 try inlining.merges.br_list.append(sema.gpa, br_inst.toIndex().?);
20363 try inlining.merges.src_locs.append(sema.gpa, operand_src);20383 try inlining.merges.src_locs.append(sema.gpa, operand_src);
20364 return;20384 return;
20365 } else if (block.is_comptime) {20385 } else if (block.isComptime()) {
20366 return sema.fail(block, src, "function called at runtime cannot return value at comptime", .{});20386 return sema.fail(block, src, "function called at runtime cannot return value at comptime", .{});
20367 } else if (sema.func_is_naked) {20387 } else if (sema.func_is_naked) {
20368 const msg = msg: {20388 const msg = msg: {
...@@ -20436,9 +20456,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air...@@ -20436,9 +20456,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
20436 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);20456 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);
20437 extra_i += 1;20457 extra_i += 1;
20438 const coerced = try sema.coerce(block, elem_ty, try sema.resolveInst(ref), sentinel_src);20458 const coerced = try sema.coerce(block, elem_ty, try sema.resolveInst(ref), sentinel_src);
20439 const val = try sema.resolveConstDefinedValue(block, sentinel_src, coerced, .{20459 const val = try sema.resolveConstDefinedValue(block, sentinel_src, coerced, .{ .simple = .pointer_sentinel });
20440 .needed_comptime_reason = "pointer sentinel value must be comptime-known",
20441 });
20442 try checkSentinelType(sema, block, sentinel_src, elem_ty);20460 try checkSentinelType(sema, block, sentinel_src, elem_ty);
20443 break :blk val.toIntern();20461 break :blk val.toIntern();
20444 } else .none;20462 } else .none;
...@@ -20447,9 +20465,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air...@@ -20447,9 +20465,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
20447 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);20465 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);
20448 extra_i += 1;20466 extra_i += 1;
20449 const coerced = try sema.coerce(block, Type.u32, try sema.resolveInst(ref), align_src);20467 const coerced = try sema.coerce(block, Type.u32, try sema.resolveInst(ref), align_src);
20450 const val = try sema.resolveConstDefinedValue(block, align_src, coerced, .{20468 const val = try sema.resolveConstDefinedValue(block, align_src, coerced, .{ .simple = .@"align" });
20451 .needed_comptime_reason = "pointer alignment must be comptime-known",
20452 });
20453 // Check if this happens to be the lazy alignment of our element type, in20469 // Check if this happens to be the lazy alignment of our element type, in
20454 // which case we can make this 0 without resolving it.20470 // which case we can make this 0 without resolving it.
20455 switch (zcu.intern_pool.indexToKey(val.toIntern())) {20471 switch (zcu.intern_pool.indexToKey(val.toIntern())) {
...@@ -20472,18 +20488,14 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air...@@ -20472,18 +20488,14 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
20472 const bit_offset: u16 = if (inst_data.flags.has_bit_range) blk: {20488 const bit_offset: u16 = if (inst_data.flags.has_bit_range) blk: {
20473 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);20489 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);
20474 extra_i += 1;20490 extra_i += 1;
20475 const bit_offset = try sema.resolveInt(block, bitoffset_src, ref, Type.u16, .{20491 const bit_offset = try sema.resolveInt(block, bitoffset_src, ref, Type.u16, .{ .simple = .type });
20476 .needed_comptime_reason = "pointer bit-offset must be comptime-known",
20477 });
20478 break :blk @intCast(bit_offset);20492 break :blk @intCast(bit_offset);
20479 } else 0;20493 } else 0;
2048020494
20481 const host_size: u16 = if (inst_data.flags.has_bit_range) blk: {20495 const host_size: u16 = if (inst_data.flags.has_bit_range) blk: {
20482 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);20496 const ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_i]);
20483 extra_i += 1;20497 extra_i += 1;
20484 const host_size = try sema.resolveInt(block, hostsize_src, ref, Type.u16, .{20498 const host_size = try sema.resolveInt(block, hostsize_src, ref, Type.u16, .{ .simple = .type });
20485 .needed_comptime_reason = "pointer host size must be comptime-known",
20486 });
20487 break :blk @intCast(host_size);20499 break :blk @intCast(host_size);
20488 } else 0;20500 } else 0;
2048920501
...@@ -20671,9 +20683,7 @@ fn zirUnionInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -20671,9 +20683,7 @@ fn zirUnionInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
20671 if (union_ty.zigTypeTag(pt.zcu) != .@"union") {20683 if (union_ty.zigTypeTag(pt.zcu) != .@"union") {
20672 return sema.fail(block, ty_src, "expected union type, found '{}'", .{union_ty.fmt(pt)});20684 return sema.fail(block, ty_src, "expected union type, found '{}'", .{union_ty.fmt(pt)});
20673 }20685 }
20674 const field_name = try sema.resolveConstStringIntern(block, field_src, extra.field_name, .{20686 const field_name = try sema.resolveConstStringIntern(block, field_src, extra.field_name, .{ .simple = .union_field_name });
20675 .needed_comptime_reason = "name of field being initialized must be comptime-known",
20676 });
20677 const init = try sema.resolveInst(extra.init);20687 const init = try sema.resolveInst(extra.init);
20678 return sema.unionInit(block, init, init_src, union_ty, ty_src, field_name, field_src);20688 return sema.unionInit(block, init, init_src, union_ty, ty_src, field_name, field_src);
20679}20689}
...@@ -20800,9 +20810,7 @@ fn zirStructInit(...@@ -20800,9 +20810,7 @@ fn zirStructInit(
20800 try resolved_ty.resolveStructFieldInits(pt);20810 try resolved_ty.resolveStructFieldInits(pt);
20801 if (try resolved_ty.structFieldValueComptime(pt, field_index)) |default_value| {20811 if (try resolved_ty.structFieldValueComptime(pt, field_index)) |default_value| {
20802 const init_val = (try sema.resolveValue(field_inits[field_index])) orelse {20812 const init_val = (try sema.resolveValue(field_inits[field_index])) orelse {
20803 return sema.failWithNeededComptime(block, field_src, .{20813 return sema.failWithNeededComptime(block, field_src, .{ .simple = .stored_to_comptime_field });
20804 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
20805 });
20806 };20814 };
2080720815
20808 if (!init_val.eql(default_value, resolved_ty.fieldType(field_index, zcu), zcu)) {20816 if (!init_val.eql(default_value, resolved_ty.fieldType(field_index, zcu), zcu)) {
...@@ -20862,9 +20870,10 @@ fn zirStructInit(...@@ -20862,9 +20870,10 @@ fn zirStructInit(
20862 }20870 }
2086320871
20864 if (try resolved_ty.comptimeOnlySema(pt)) {20872 if (try resolved_ty.comptimeOnlySema(pt)) {
20865 return sema.failWithNeededComptime(block, field_src, .{20873 return sema.failWithNeededComptime(block, field_src, .{ .comptime_only = .{
20866 .needed_comptime_reason = "initializer of comptime only union must be comptime-known",20874 .ty = resolved_ty,
20867 });20875 .msg = .union_init,
20876 } });
20868 }20877 }
2086920878
20870 try sema.validateRuntimeValue(block, field_src, init_inst);20879 try sema.validateRuntimeValue(block, field_src, init_inst);
...@@ -21003,9 +21012,10 @@ fn finishStructInit(...@@ -21003,9 +21012,10 @@ fn finishStructInit(
21003 return sema.failWithNeededComptime(block, block.src(.{ .init_elem = .{21012 return sema.failWithNeededComptime(block, block.src(.{ .init_elem = .{
21004 .init_node_offset = init_src.offset.node_offset.x,21013 .init_node_offset = init_src.offset.node_offset.x,
21005 .elem_index = @intCast(runtime_index),21014 .elem_index = @intCast(runtime_index),
21006 } }), .{21015 } }), .{ .comptime_only = .{
21007 .needed_comptime_reason = "initializer of comptime only struct must be comptime-known",21016 .ty = struct_ty,
21008 });21017 .msg = .struct_init,
21018 } });
21009 }21019 }
2101021020
21011 for (field_inits) |field_init| {21021 for (field_inits) |field_init| {
...@@ -21315,11 +21325,7 @@ fn zirArrayInit(...@@ -21315,11 +21325,7 @@ fn zirArrayInit(
21315 if (array_ty.structFieldIsComptime(i, zcu))21325 if (array_ty.structFieldIsComptime(i, zcu))
21316 try array_ty.resolveStructFieldInits(pt);21326 try array_ty.resolveStructFieldInits(pt);
21317 if (try array_ty.structFieldValueComptime(pt, i)) |field_val| {21327 if (try array_ty.structFieldValueComptime(pt, i)) |field_val| {
21318 const init_val = try sema.resolveValue(dest.*) orelse {21328 const init_val = try sema.resolveConstValue(block, elem_src, dest.*, .{ .simple = .stored_to_comptime_field });
21319 return sema.failWithNeededComptime(block, elem_src, .{
21320 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
21321 });
21322 };
21323 if (!field_val.eql(init_val, elem_ty, zcu)) {21329 if (!field_val.eql(init_val, elem_ty, zcu)) {
21324 return sema.failWithInvalidComptimeFieldStore(block, elem_src, array_ty, i);21330 return sema.failWithInvalidComptimeFieldStore(block, elem_src, array_ty, i);
21325 }21331 }
...@@ -21508,9 +21514,7 @@ fn zirFieldTypeRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro...@@ -21508,9 +21514,7 @@ fn zirFieldTypeRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
21508 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);21514 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
21509 const field_src = block.builtinCallArgSrc(inst_data.src_node, 1);21515 const field_src = block.builtinCallArgSrc(inst_data.src_node, 1);
21510 const aggregate_ty = try sema.resolveType(block, ty_src, extra.container_type);21516 const aggregate_ty = try sema.resolveType(block, ty_src, extra.container_type);
21511 const field_name = try sema.resolveConstStringIntern(block, field_src, extra.field_name, .{21517 const field_name = try sema.resolveConstStringIntern(block, field_src, extra.field_name, .{ .simple = .field_name });
21512 .needed_comptime_reason = "field name must be comptime-known",
21513 });
21514 return sema.fieldType(block, aggregate_ty, field_name, field_src, ty_src);21518 return sema.fieldType(block, aggregate_ty, field_name, field_src, ty_src);
21515}21519}
2151621520
...@@ -21890,9 +21894,7 @@ fn zirReify(...@@ -21890,9 +21894,7 @@ fn zirReify(
21890 const type_info_ty = try sema.getBuiltinType("Type");21894 const type_info_ty = try sema.getBuiltinType("Type");
21891 const uncasted_operand = try sema.resolveInst(extra.operand);21895 const uncasted_operand = try sema.resolveInst(extra.operand);
21892 const type_info = try sema.coerce(block, type_info_ty, uncasted_operand, operand_src);21896 const type_info = try sema.coerce(block, type_info_ty, uncasted_operand, operand_src);
21893 const val = try sema.resolveConstDefinedValue(block, operand_src, type_info, .{21897 const val = try sema.resolveConstDefinedValue(block, operand_src, type_info, .{ .simple = .operand_Type });
21894 .needed_comptime_reason = "operand to @Type must be comptime-known",
21895 });
21896 const union_val = ip.indexToKey(val.toIntern()).un;21898 const union_val = ip.indexToKey(val.toIntern()).un;
21897 if (try sema.anyUndef(block, operand_src, Value.fromInterned(union_val.val))) {21899 if (try sema.anyUndef(block, operand_src, Value.fromInterned(union_val.val))) {
21898 return sema.failWithUseOfUndef(block, operand_src);21900 return sema.failWithUseOfUndef(block, operand_src);
...@@ -22136,9 +22138,7 @@ fn zirReify(...@@ -22136,9 +22138,7 @@ fn zirReify(
22136 const payload_val = Value.fromInterned(union_val.val).optionalValue(zcu) orelse22138 const payload_val = Value.fromInterned(union_val.val).optionalValue(zcu) orelse
22137 return Air.internedToRef(Type.anyerror.toIntern());22139 return Air.internedToRef(Type.anyerror.toIntern());
2213822140
22139 const names_val = try sema.derefSliceAsArray(block, src, payload_val, .{22141 const names_val = try sema.derefSliceAsArray(block, src, payload_val, .{ .simple = .error_set_contents });
22140 .needed_comptime_reason = "error set contents must be comptime-known",
22141 });
2214222142
22143 const len = try sema.usizeCast(block, src, names_val.typeOf(zcu).arrayLen(zcu));22143 const len = try sema.usizeCast(block, src, names_val.typeOf(zcu).arrayLen(zcu));
22144 var names: InferredErrorSet.NameMap = .{};22144 var names: InferredErrorSet.NameMap = .{};
...@@ -22151,9 +22151,7 @@ fn zirReify(...@@ -22151,9 +22151,7 @@ fn zirReify(
22151 try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls),22151 try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls),
22152 ).?);22152 ).?);
2215322153
22154 const name = try sema.sliceToIpString(block, src, name_val, .{22154 const name = try sema.sliceToIpString(block, src, name_val, .{ .simple = .error_set_contents });
22155 .needed_comptime_reason = "error set contents must be comptime-known",
22156 });
22157 _ = try pt.getErrorValue(name);22155 _ = try pt.getErrorValue(name);
22158 const gop = names.getOrPutAssumeCapacity(name);22156 const gop = names.getOrPutAssumeCapacity(name);
22159 if (gop.found_existing) {22157 if (gop.found_existing) {
...@@ -22200,9 +22198,7 @@ fn zirReify(...@@ -22200,9 +22198,7 @@ fn zirReify(
22200 return sema.fail(block, src, "non-packed struct does not support backing integer type", .{});22198 return sema.fail(block, src, "non-packed struct does not support backing integer type", .{});
22201 }22199 }
2220222200
22203 const fields_arr = try sema.derefSliceAsArray(block, operand_src, fields_val, .{22201 const fields_arr = try sema.derefSliceAsArray(block, operand_src, fields_val, .{ .simple = .struct_fields });
22204 .needed_comptime_reason = "struct fields must be comptime-known",
22205 });
2220622202
22207 if (is_tuple_val.toBool()) {22203 if (is_tuple_val.toBool()) {
22208 switch (layout) {22204 switch (layout) {
...@@ -22238,9 +22234,7 @@ fn zirReify(...@@ -22238,9 +22234,7 @@ fn zirReify(
22238 return sema.fail(block, src, "reified enums must have no decls", .{});22234 return sema.fail(block, src, "reified enums must have no decls", .{});
22239 }22235 }
2224022236
22241 const fields_arr = try sema.derefSliceAsArray(block, operand_src, fields_val, .{22237 const fields_arr = try sema.derefSliceAsArray(block, operand_src, fields_val, .{ .simple = .enum_fields });
22242 .needed_comptime_reason = "enum fields must be comptime-known",
22243 });
2224422238
22245 return sema.reifyEnum(block, inst, src, tag_type_val.toType(), is_exhaustive_val.toBool(), fields_arr, name_strategy);22239 return sema.reifyEnum(block, inst, src, tag_type_val.toType(), is_exhaustive_val.toBool(), fields_arr, name_strategy);
22246 },22240 },
...@@ -22311,9 +22305,7 @@ fn zirReify(...@@ -22311,9 +22305,7 @@ fn zirReify(
22311 }22305 }
22312 const layout = zcu.toEnum(std.builtin.Type.ContainerLayout, layout_val);22306 const layout = zcu.toEnum(std.builtin.Type.ContainerLayout, layout_val);
2231322307
22314 const fields_arr = try sema.derefSliceAsArray(block, operand_src, fields_val, .{22308 const fields_arr = try sema.derefSliceAsArray(block, operand_src, fields_val, .{ .simple = .union_fields });
22315 .needed_comptime_reason = "union fields must be comptime-known",
22316 });
2231722309
22318 return sema.reifyUnion(block, inst, src, layout, tag_type_val, fields_arr, name_strategy);22310 return sema.reifyUnion(block, inst, src, layout, tag_type_val, fields_arr, name_strategy);
22319 },22311 },
...@@ -22354,9 +22346,7 @@ fn zirReify(...@@ -22354,9 +22346,7 @@ fn zirReify(
22354 const return_type = return_type_val.optionalValue(zcu) orelse22346 const return_type = return_type_val.optionalValue(zcu) orelse
22355 return sema.fail(block, src, "Type.Fn.return_type must be non-null for @Type", .{});22347 return sema.fail(block, src, "Type.Fn.return_type must be non-null for @Type", .{});
2235622348
22357 const params_val = try sema.derefSliceAsArray(block, operand_src, params_slice_val, .{22349 const params_val = try sema.derefSliceAsArray(block, operand_src, params_slice_val, .{ .simple = .function_parameters });
22358 .needed_comptime_reason = "function parameters must be comptime-known",
22359 });
2236022350
22361 const args_len = try sema.usizeCast(block, src, params_val.typeOf(zcu).arrayLen(zcu));22351 const args_len = try sema.usizeCast(block, src, params_val.typeOf(zcu).arrayLen(zcu));
22362 const param_types = try sema.arena.alloc(InternPool.Index, args_len);22352 const param_types = try sema.arena.alloc(InternPool.Index, args_len);
...@@ -22444,9 +22434,7 @@ fn reifyEnum(...@@ -22444,9 +22434,7 @@ fn reifyEnum(
22444 const field_name_val = try field_info.fieldValue(pt, 0);22434 const field_name_val = try field_info.fieldValue(pt, 0);
22445 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 1));22435 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 1));
2244622436
22447 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{22437 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{ .simple = .enum_field_name });
22448 .needed_comptime_reason = "enum field name must be comptime-known",
22449 });
2245022438
22451 std.hash.autoHash(&hasher, .{22439 std.hash.autoHash(&hasher, .{
22452 field_name,22440 field_name,
...@@ -22591,9 +22579,7 @@ fn reifyUnion(...@@ -22591,9 +22579,7 @@ fn reifyUnion(
22591 const field_type_val = try field_info.fieldValue(pt, 1);22579 const field_type_val = try field_info.fieldValue(pt, 1);
22592 const field_align_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 2));22580 const field_align_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 2));
2259322581
22594 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{22582 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{ .simple = .union_field_name });
22595 .needed_comptime_reason = "union field name must be comptime-known",
22596 });
2259722583
22598 std.hash.autoHash(&hasher, .{22584 std.hash.autoHash(&hasher, .{
22599 field_name,22585 field_name,
...@@ -22835,9 +22821,7 @@ fn reifyTuple(...@@ -22835,9 +22821,7 @@ fn reifyTuple(
22835 const field_is_comptime_val = try field_info.fieldValue(pt, 3);22821 const field_is_comptime_val = try field_info.fieldValue(pt, 3);
22836 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 4));22822 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 4));
2283722823
22838 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{22824 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{ .simple = .tuple_field_name });
22839 .needed_comptime_reason = "tuple field name must be comptime-known",
22840 });
22841 const field_type = field_type_val.toType();22825 const field_type = field_type_val.toType();
22842 const field_default_value: InternPool.Index = if (field_default_value_val.optionalValue(zcu)) |ptr_val| d: {22826 const field_default_value: InternPool.Index = if (field_default_value_val.optionalValue(zcu)) |ptr_val| d: {
22843 const ptr_ty = try pt.singleConstPtrType(field_type_val.toType());22827 const ptr_ty = try pt.singleConstPtrType(field_type_val.toType());
...@@ -22845,7 +22829,7 @@ fn reifyTuple(...@@ -22845,7 +22829,7 @@ fn reifyTuple(
22845 const val = try sema.pointerDeref(block, src, ptr_val, ptr_ty) orelse return sema.failWithNeededComptime(22829 const val = try sema.pointerDeref(block, src, ptr_val, ptr_ty) orelse return sema.failWithNeededComptime(
22846 block,22830 block,
22847 src,22831 src,
22848 .{ .needed_comptime_reason = "tuple field default value must be comptime-known" },22832 .{ .simple = .tuple_field_default_value },
22849 );22833 );
22850 // Resolve the value so that lazy values do not create distinct types.22834 // Resolve the value so that lazy values do not create distinct types.
22851 break :d (try sema.resolveLazyValue(val)).toIntern();22835 break :d (try sema.resolveLazyValue(val)).toIntern();
...@@ -22951,9 +22935,7 @@ fn reifyStruct(...@@ -22951,9 +22935,7 @@ fn reifyStruct(
22951 const field_is_comptime_val = try field_info.fieldValue(pt, 3);22935 const field_is_comptime_val = try field_info.fieldValue(pt, 3);
22952 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 4));22936 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 4));
2295322937
22954 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{22938 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{ .simple = .struct_field_name });
22955 .needed_comptime_reason = "struct field name must be comptime-known",
22956 });
22957 const field_is_comptime = field_is_comptime_val.toBool();22939 const field_is_comptime = field_is_comptime_val.toBool();
22958 const field_default_value: InternPool.Index = if (field_default_value_val.optionalValue(zcu)) |ptr_val| d: {22940 const field_default_value: InternPool.Index = if (field_default_value_val.optionalValue(zcu)) |ptr_val| d: {
22959 const ptr_ty = try pt.singleConstPtrType(field_type_val.toType());22941 const ptr_ty = try pt.singleConstPtrType(field_type_val.toType());
...@@ -22961,7 +22943,7 @@ fn reifyStruct(...@@ -22961,7 +22943,7 @@ fn reifyStruct(
22961 const val = try sema.pointerDeref(block, src, ptr_val, ptr_ty) orelse return sema.failWithNeededComptime(22943 const val = try sema.pointerDeref(block, src, ptr_val, ptr_ty) orelse return sema.failWithNeededComptime(
22962 block,22944 block,
22963 src,22945 src,
22964 .{ .needed_comptime_reason = "struct field default value must be comptime-known" },22946 .{ .simple = .struct_field_default_value },
22965 );22947 );
22966 // Resolve the value so that lazy values do not create distinct types.22948 // Resolve the value so that lazy values do not create distinct types.
22967 break :d (try sema.resolveLazyValue(val)).toIntern();22949 break :d (try sema.resolveLazyValue(val)).toIntern();
...@@ -23285,9 +23267,7 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro...@@ -23285,9 +23267,7 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
23285 const result_val = try sema.intFromFloat(block, operand_src, operand_val, operand_ty, dest_ty, .truncate);23267 const result_val = try sema.intFromFloat(block, operand_src, operand_val, operand_ty, dest_ty, .truncate);
23286 return Air.internedToRef(result_val.toIntern());23268 return Air.internedToRef(result_val.toIntern());
23287 } else if (dest_scalar_ty.zigTypeTag(zcu) == .comptime_int) {23269 } else if (dest_scalar_ty.zigTypeTag(zcu) == .comptime_int) {
23288 return sema.failWithNeededComptime(block, operand_src, .{23270 return sema.failWithNeededComptime(block, operand_src, .{ .simple = .casted_to_comptime_int });
23289 .needed_comptime_reason = "value being casted to 'comptime_int' must be comptime-known",
23290 });
23291 }23271 }
2329223272
23293 try sema.requireRuntimeBlock(block, src, operand_src);23273 try sema.requireRuntimeBlock(block, src, operand_src);
...@@ -23368,9 +23348,7 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro...@@ -23368,9 +23348,7 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
23368 const result_val = try operand_val.floatFromIntAdvanced(sema.arena, operand_ty, dest_ty, pt, .sema);23348 const result_val = try operand_val.floatFromIntAdvanced(sema.arena, operand_ty, dest_ty, pt, .sema);
23369 return Air.internedToRef(result_val.toIntern());23349 return Air.internedToRef(result_val.toIntern());
23370 } else if (dest_scalar_ty.zigTypeTag(zcu) == .comptime_float) {23350 } else if (dest_scalar_ty.zigTypeTag(zcu) == .comptime_float) {
23371 return sema.failWithNeededComptime(block, operand_src, .{23351 return sema.failWithNeededComptime(block, operand_src, .{ .simple = .casted_to_comptime_float });
23372 .needed_comptime_reason = "value being casted to 'comptime_float' must be comptime-known",
23373 });
23374 }23352 }
2337523353
23376 try sema.requireRuntimeBlock(block, src, operand_src);23354 try sema.requireRuntimeBlock(block, src, operand_src);
...@@ -24394,9 +24372,7 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6...@@ -24394,9 +24372,7 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
24394 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;24372 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
2439524373
24396 const ty = try sema.resolveType(block, lhs_src, extra.lhs);24374 const ty = try sema.resolveType(block, lhs_src, extra.lhs);
24397 const field_name = try sema.resolveConstStringIntern(block, rhs_src, extra.rhs, .{24375 const field_name = try sema.resolveConstStringIntern(block, rhs_src, extra.rhs, .{ .simple = .field_name });
24398 .needed_comptime_reason = "name of field must be comptime-known",
24399 });
2440024376
24401 const pt = sema.pt;24377 const pt = sema.pt;
24402 const zcu = pt.zcu;24378 const zcu = pt.zcu;
...@@ -24850,31 +24826,21 @@ fn resolveExportOptions(...@@ -24850,31 +24826,21 @@ fn resolveExportOptions(
24850 const visibility_src = block.src(.{ .init_field_visibility = src.offset.node_offset_builtin_call_arg.builtin_call_node });24826 const visibility_src = block.src(.{ .init_field_visibility = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2485124827
24852 const name_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls), name_src);24828 const name_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls), name_src);
24853 const name = try sema.toConstString(block, name_src, name_operand, .{24829 const name = try sema.toConstString(block, name_src, name_operand, .{ .simple = .export_options });
24854 .needed_comptime_reason = "name of exported value must be comptime-known",
24855 });
2485624830
24857 const linkage_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "linkage", .no_embedded_nulls), linkage_src);24831 const linkage_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "linkage", .no_embedded_nulls), linkage_src);
24858 const linkage_val = try sema.resolveConstDefinedValue(block, linkage_src, linkage_operand, .{24832 const linkage_val = try sema.resolveConstDefinedValue(block, linkage_src, linkage_operand, .{ .simple = .export_options });
24859 .needed_comptime_reason = "linkage of exported value must be comptime-known",
24860 });
24861 const linkage = zcu.toEnum(std.builtin.GlobalLinkage, linkage_val);24833 const linkage = zcu.toEnum(std.builtin.GlobalLinkage, linkage_val);
2486224834
24863 const section_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "section", .no_embedded_nulls), section_src);24835 const section_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "section", .no_embedded_nulls), section_src);
24864 const section_opt_val = try sema.resolveConstDefinedValue(block, section_src, section_operand, .{24836 const section_opt_val = try sema.resolveConstDefinedValue(block, section_src, section_operand, .{ .simple = .export_options });
24865 .needed_comptime_reason = "linksection of exported value must be comptime-known",
24866 });
24867 const section = if (section_opt_val.optionalValue(zcu)) |section_val|24837 const section = if (section_opt_val.optionalValue(zcu)) |section_val|
24868 try sema.toConstString(block, section_src, Air.internedToRef(section_val.toIntern()), .{24838 try sema.toConstString(block, section_src, Air.internedToRef(section_val.toIntern()), .{ .simple = .export_options })
24869 .needed_comptime_reason = "linksection of exported value must be comptime-known",
24870 })
24871 else24839 else
24872 null;24840 null;
2487324841
24874 const visibility_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "visibility", .no_embedded_nulls), visibility_src);24842 const visibility_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "visibility", .no_embedded_nulls), visibility_src);
24875 const visibility_val = try sema.resolveConstDefinedValue(block, visibility_src, visibility_operand, .{24843 const visibility_val = try sema.resolveConstDefinedValue(block, visibility_src, visibility_operand, .{ .simple = .export_options });
24876 .needed_comptime_reason = "visibility of exported value must be comptime-known",
24877 });
24878 const visibility = zcu.toEnum(std.builtin.SymbolVisibility, visibility_val);24844 const visibility = zcu.toEnum(std.builtin.SymbolVisibility, visibility_val);
2487924845
24880 if (name.len < 1) {24846 if (name.len < 1) {
...@@ -24901,7 +24867,7 @@ fn resolveBuiltinEnum(...@@ -24901,7 +24867,7 @@ fn resolveBuiltinEnum(
24901 src: LazySrcLoc,24867 src: LazySrcLoc,
24902 zir_ref: Zir.Inst.Ref,24868 zir_ref: Zir.Inst.Ref,
24903 comptime name: []const u8,24869 comptime name: []const u8,
24904 reason: NeededComptimeReason,24870 reason: ComptimeReason,
24905) CompileError!@field(std.builtin, name) {24871) CompileError!@field(std.builtin, name) {
24906 const pt = sema.pt;24872 const pt = sema.pt;
24907 const ty = try sema.getBuiltinType(name);24873 const ty = try sema.getBuiltinType(name);
...@@ -24916,7 +24882,7 @@ fn resolveAtomicOrder(...@@ -24916,7 +24882,7 @@ fn resolveAtomicOrder(
24916 block: *Block,24882 block: *Block,
24917 src: LazySrcLoc,24883 src: LazySrcLoc,
24918 zir_ref: Zir.Inst.Ref,24884 zir_ref: Zir.Inst.Ref,
24919 reason: NeededComptimeReason,24885 reason: ComptimeReason,
24920) CompileError!std.builtin.AtomicOrder {24886) CompileError!std.builtin.AtomicOrder {
24921 return sema.resolveBuiltinEnum(block, src, zir_ref, "AtomicOrder", reason);24887 return sema.resolveBuiltinEnum(block, src, zir_ref, "AtomicOrder", reason);
24922}24888}
...@@ -24927,9 +24893,7 @@ fn resolveAtomicRmwOp(...@@ -24927,9 +24893,7 @@ fn resolveAtomicRmwOp(
24927 src: LazySrcLoc,24893 src: LazySrcLoc,
24928 zir_ref: Zir.Inst.Ref,24894 zir_ref: Zir.Inst.Ref,
24929) CompileError!std.builtin.AtomicRmwOp {24895) CompileError!std.builtin.AtomicRmwOp {
24930 return sema.resolveBuiltinEnum(block, src, zir_ref, "AtomicRmwOp", .{24896 return sema.resolveBuiltinEnum(block, src, zir_ref, "AtomicRmwOp", .{ .simple = .operand_atomicRmw_operation });
24931 .needed_comptime_reason = "@atomicRmW operation must be comptime-known",
24932 });
24933}24897}
2493424898
24935fn zirCmpxchg(24899fn zirCmpxchg(
...@@ -24967,12 +24931,8 @@ fn zirCmpxchg(...@@ -24967,12 +24931,8 @@ fn zirCmpxchg(
24967 const uncasted_ptr = try sema.resolveInst(extra.ptr);24931 const uncasted_ptr = try sema.resolveInst(extra.ptr);
24968 const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, false);24932 const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, false);
24969 const new_value = try sema.coerce(block, elem_ty, try sema.resolveInst(extra.new_value), new_value_src);24933 const new_value = try sema.coerce(block, elem_ty, try sema.resolveInst(extra.new_value), new_value_src);
24970 const success_order = try sema.resolveAtomicOrder(block, success_order_src, extra.success_order, .{24934 const success_order = try sema.resolveAtomicOrder(block, success_order_src, extra.success_order, .{ .simple = .atomic_order });
24971 .needed_comptime_reason = "atomic order of cmpxchg success must be comptime-known",24935 const failure_order = try sema.resolveAtomicOrder(block, failure_order_src, extra.failure_order, .{ .simple = .atomic_order });
24972 });
24973 const failure_order = try sema.resolveAtomicOrder(block, failure_order_src, extra.failure_order, .{
24974 .needed_comptime_reason = "atomic order of cmpxchg failure must be comptime-known",
24975 });
2497624936
24977 if (@intFromEnum(success_order) < @intFromEnum(std.builtin.AtomicOrder.monotonic)) {24937 if (@intFromEnum(success_order) < @intFromEnum(std.builtin.AtomicOrder.monotonic)) {
24978 return sema.fail(block, success_order_src, "success atomic ordering must be monotonic or stricter", .{});24938 return sema.fail(block, success_order_src, "success atomic ordering must be monotonic or stricter", .{});
...@@ -25113,9 +25073,7 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air....@@ -25113,9 +25073,7 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
25113 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;25073 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
25114 const op_src = block.builtinCallArgSrc(inst_data.src_node, 0);25074 const op_src = block.builtinCallArgSrc(inst_data.src_node, 0);
25115 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 1);25075 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 1);
25116 const operation = try sema.resolveBuiltinEnum(block, op_src, extra.lhs, "ReduceOp", .{25076 const operation = try sema.resolveBuiltinEnum(block, op_src, extra.lhs, "ReduceOp", .{ .simple = .operand_reduce_operation });
25117 .needed_comptime_reason = "@reduce operation must be comptime-known",
25118 });
25119 const operand = try sema.resolveInst(extra.rhs);25077 const operand = try sema.resolveInst(extra.rhs);
25120 const operand_ty = sema.typeOf(operand);25078 const operand_ty = sema.typeOf(operand);
25121 const pt = sema.pt;25079 const pt = sema.pt;
...@@ -25204,9 +25162,7 @@ fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air...@@ -25204,9 +25162,7 @@ fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
25204 .child = .i32_type,25162 .child = .i32_type,
25205 });25163 });
25206 mask = try sema.coerce(block, mask_ty, mask, mask_src);25164 mask = try sema.coerce(block, mask_ty, mask, mask_src);
25207 const mask_val = try sema.resolveConstValue(block, mask_src, mask, .{25165 const mask_val = try sema.resolveConstValue(block, mask_src, mask, .{ .simple = .operand_shuffle_mask });
25208 .needed_comptime_reason = "shuffle mask must be comptime-known",
25209 });
25210 return sema.analyzeShuffle(block, inst_data.src_node, elem_ty, a, b, mask_val, @intCast(mask_len));25166 return sema.analyzeShuffle(block, inst_data.src_node, elem_ty, a, b, mask_val, @intCast(mask_len));
25211}25167}
2521225168
...@@ -25474,9 +25430,7 @@ fn zirAtomicLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!...@@ -25474,9 +25430,7 @@ fn zirAtomicLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
25474 const elem_ty = try sema.resolveType(block, elem_ty_src, extra.elem_type);25430 const elem_ty = try sema.resolveType(block, elem_ty_src, extra.elem_type);
25475 const uncasted_ptr = try sema.resolveInst(extra.ptr);25431 const uncasted_ptr = try sema.resolveInst(extra.ptr);
25476 const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, true);25432 const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, true);
25477 const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, .{25433 const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, .{ .simple = .atomic_order });
25478 .needed_comptime_reason = "atomic order of @atomicLoad must be comptime-known",
25479 });
2548025434
25481 switch (order) {25435 switch (order) {
25482 .release, .acq_rel => {25436 .release, .acq_rel => {
...@@ -25542,9 +25496,7 @@ fn zirAtomicRmw(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -25542,9 +25496,7 @@ fn zirAtomicRmw(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
25542 },25496 },
25543 else => {},25497 else => {},
25544 }25498 }
25545 const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, .{25499 const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, .{ .simple = .atomic_order });
25546 .needed_comptime_reason = "atomic order of @atomicRmW must be comptime-known",
25547 });
2554825500
25549 if (order == .unordered) {25501 if (order == .unordered) {
25550 return sema.fail(block, order_src, "@atomicRmw atomic ordering must not be unordered", .{});25502 return sema.fail(block, order_src, "@atomicRmw atomic ordering must not be unordered", .{});
...@@ -25611,9 +25563,7 @@ fn zirAtomicStore(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError...@@ -25611,9 +25563,7 @@ fn zirAtomicStore(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
25611 const elem_ty = sema.typeOf(operand);25563 const elem_ty = sema.typeOf(operand);
25612 const uncasted_ptr = try sema.resolveInst(extra.ptr);25564 const uncasted_ptr = try sema.resolveInst(extra.ptr);
25613 const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, false);25565 const ptr = try sema.checkAtomicPtrOperand(block, elem_ty, elem_ty_src, uncasted_ptr, ptr_src, false);
25614 const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, .{25566 const order = try sema.resolveAtomicOrder(block, order_src, extra.ordering, .{ .simple = .atomic_order });
25615 .needed_comptime_reason = "atomic order of @atomicStore must be comptime-known",
25616 });
2561725567
25618 const air_tag: Air.Inst.Tag = switch (order) {25568 const air_tag: Air.Inst.Tag = switch (order) {
25619 .acquire, .acq_rel => {25569 .acquire, .acq_rel => {
...@@ -25716,14 +25666,12 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError...@@ -25716,14 +25666,12 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
25716 const modifier_ty = try sema.getBuiltinType("CallModifier");25666 const modifier_ty = try sema.getBuiltinType("CallModifier");
25717 const air_ref = try sema.resolveInst(extra.modifier);25667 const air_ref = try sema.resolveInst(extra.modifier);
25718 const modifier_ref = try sema.coerce(block, modifier_ty, air_ref, modifier_src);25668 const modifier_ref = try sema.coerce(block, modifier_ty, air_ref, modifier_src);
25719 const modifier_val = try sema.resolveConstDefinedValue(block, modifier_src, modifier_ref, .{25669 const modifier_val = try sema.resolveConstDefinedValue(block, modifier_src, modifier_ref, .{ .simple = .call_modifier });
25720 .needed_comptime_reason = "call modifier must be comptime-known",
25721 });
25722 var modifier = zcu.toEnum(std.builtin.CallModifier, modifier_val);25670 var modifier = zcu.toEnum(std.builtin.CallModifier, modifier_val);
25723 switch (modifier) {25671 switch (modifier) {
25724 // These can be upgraded to comptime or nosuspend calls.25672 // These can be upgraded to comptime or nosuspend calls.
25725 .auto, .never_tail, .no_async => {25673 .auto, .never_tail, .no_async => {
25726 if (block.is_comptime) {25674 if (block.isComptime()) {
25727 if (modifier == .never_tail) {25675 if (modifier == .never_tail) {
25728 return sema.fail(block, modifier_src, "unable to perform 'never_tail' call at compile-time", .{});25676 return sema.fail(block, modifier_src, "unable to perform 'never_tail' call at compile-time", .{});
25729 }25677 }
...@@ -25738,12 +25686,12 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError...@@ -25738,12 +25686,12 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
25738 return sema.fail(block, func_src, "modifier '{s}' requires a comptime-known function", .{@tagName(modifier)});25686 return sema.fail(block, func_src, "modifier '{s}' requires a comptime-known function", .{@tagName(modifier)});
25739 };25687 };
2574025688
25741 if (block.is_comptime) {25689 if (block.isComptime()) {
25742 modifier = .compile_time;25690 modifier = .compile_time;
25743 }25691 }
25744 },25692 },
25745 .always_tail => {25693 .always_tail => {
25746 if (block.is_comptime) {25694 if (block.isComptime()) {
25747 modifier = .compile_time;25695 modifier = .compile_time;
25748 }25696 }
25749 },25697 },
...@@ -25751,12 +25699,12 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError...@@ -25751,12 +25699,12 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
25751 if (extra.flags.is_nosuspend) {25699 if (extra.flags.is_nosuspend) {
25752 return sema.fail(block, modifier_src, "modifier 'async_kw' cannot be used inside nosuspend block", .{});25700 return sema.fail(block, modifier_src, "modifier 'async_kw' cannot be used inside nosuspend block", .{});
25753 }25701 }
25754 if (block.is_comptime) {25702 if (block.isComptime()) {
25755 return sema.fail(block, modifier_src, "modifier 'async_kw' cannot be used in combination with comptime function call", .{});25703 return sema.fail(block, modifier_src, "modifier 'async_kw' cannot be used in combination with comptime function call", .{});
25756 }25704 }
25757 },25705 },
25758 .never_inline => {25706 .never_inline => {
25759 if (block.is_comptime) {25707 if (block.isComptime()) {
25760 return sema.fail(block, modifier_src, "unable to perform 'never_inline' call at compile-time", .{});25708 return sema.fail(block, modifier_src, "unable to perform 'never_inline' call at compile-time", .{});
25761 }25709 }
25762 },25710 },
...@@ -25771,7 +25719,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError...@@ -25771,7 +25719,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2577125719
25772 const resolved_args: []Air.Inst.Ref = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount(zcu));25720 const resolved_args: []Air.Inst.Ref = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount(zcu));
25773 for (resolved_args, 0..) |*resolved, i| {25721 for (resolved_args, 0..) |*resolved, i| {
25774 resolved.* = try sema.tupleFieldValByIndex(block, args_src, args, @intCast(i), args_ty);25722 resolved.* = try sema.tupleFieldValByIndex(block, args, @intCast(i), args_ty);
25775 }25723 }
2577625724
25777 const callee_ty = sema.typeOf(func);25725 const callee_ty = sema.typeOf(func);
...@@ -25820,9 +25768,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins...@@ -25820,9 +25768,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
25820 }25768 }
25821 try parent_ty.resolveLayout(pt);25769 try parent_ty.resolveLayout(pt);
2582225770
25823 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{25771 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{ .simple = .field_name });
25824 .needed_comptime_reason = "field name must be comptime-known",
25825 });
25826 const field_index = switch (parent_ty.zigTypeTag(zcu)) {25772 const field_index = switch (parent_ty.zigTypeTag(zcu)) {
25827 .@"struct" => blk: {25773 .@"struct" => blk: {
25828 if (parent_ty.isTuple(zcu)) {25774 if (parent_ty.isTuple(zcu)) {
...@@ -26680,9 +26626,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -26680,9 +26626,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
26680 extra_index += body.len;26626 extra_index += body.len;
2668126627
26682 const cc_ty = try sema.getBuiltinType("CallingConvention");26628 const cc_ty = try sema.getBuiltinType("CallingConvention");
26683 const val = try sema.resolveGenericBody(block, cc_src, body, inst, cc_ty, .{26629 const val = try sema.resolveGenericBody(block, cc_src, body, inst, cc_ty, .{ .simple = .@"callconv" });
26684 .needed_comptime_reason = "calling convention must be comptime-known",
26685 });
26686 break :blk try sema.analyzeValueAsCallconv(block, cc_src, val);26630 break :blk try sema.analyzeValueAsCallconv(block, cc_src, val);
26687 } else if (extra.data.bits.has_cc_ref) blk: {26631 } else if (extra.data.bits.has_cc_ref) blk: {
26688 const cc_ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_index]);26632 const cc_ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_index]);
...@@ -26690,9 +26634,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -26690,9 +26634,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
26690 const cc_ty = try sema.getBuiltinType("CallingConvention");26634 const cc_ty = try sema.getBuiltinType("CallingConvention");
26691 const uncoerced_cc = try sema.resolveInst(cc_ref);26635 const uncoerced_cc = try sema.resolveInst(cc_ref);
26692 const coerced_cc = try sema.coerce(block, cc_ty, uncoerced_cc, cc_src);26636 const coerced_cc = try sema.coerce(block, cc_ty, uncoerced_cc, cc_src);
26693 const cc_val = try sema.resolveConstDefinedValue(block, cc_src, coerced_cc, .{26637 const cc_val = try sema.resolveConstDefinedValue(block, cc_src, coerced_cc, .{ .simple = .@"callconv" });
26694 .needed_comptime_reason = "calling convention must be comptime-known",
26695 });
26696 break :blk try sema.analyzeValueAsCallconv(block, cc_src, cc_val);26638 break :blk try sema.analyzeValueAsCallconv(block, cc_src, cc_val);
26697 } else cc: {26639 } else cc: {
26698 if (has_body) {26640 if (has_body) {
...@@ -26730,9 +26672,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -26730,9 +26672,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
26730 const body = sema.code.bodySlice(extra_index, body_len);26672 const body = sema.code.bodySlice(extra_index, body_len);
26731 extra_index += body.len;26673 extra_index += body.len;
2673226674
26733 const val = try sema.resolveGenericBody(block, ret_src, body, inst, Type.type, .{26675 const val = try sema.resolveGenericBody(block, ret_src, body, inst, Type.type, .{ .simple = .function_ret_ty });
26734 .needed_comptime_reason = "return type must be comptime-known",
26735 });
26736 const ty = val.toType();26676 const ty = val.toType();
26737 break :blk ty;26677 break :blk ty;
26738 } else if (extra.data.bits.has_ret_ty_ref) blk: {26678 } else if (extra.data.bits.has_ret_ty_ref) blk: {
...@@ -26742,9 +26682,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -26742,9 +26682,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
26742 error.GenericPoison => break :blk Type.generic_poison,26682 error.GenericPoison => break :blk Type.generic_poison,
26743 else => |e| return e,26683 else => |e| return e,
26744 };26684 };
26745 const ret_ty_val = sema.resolveConstDefinedValue(block, ret_src, ret_ty_air_ref, .{26685 const ret_ty_val = sema.resolveConstDefinedValue(block, ret_src, ret_ty_air_ref, .{ .simple = .function_ret_ty }) catch |err| switch (err) {
26746 .needed_comptime_reason = "return type must be comptime-known",
26747 }) catch |err| switch (err) {
26748 error.GenericPoison => break :blk Type.generic_poison,26686 error.GenericPoison => break :blk Type.generic_poison,
26749 else => |e| return e,26687 else => |e| return e,
26750 };26688 };
...@@ -26790,9 +26728,7 @@ fn zirCUndef(...@@ -26790,9 +26728,7 @@ fn zirCUndef(
26790 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;26728 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
26791 const src = block.builtinCallArgSrc(extra.node, 0);26729 const src = block.builtinCallArgSrc(extra.node, 0);
2679226730
26793 const name = try sema.resolveConstString(block, src, extra.operand, .{26731 const name = try sema.resolveConstString(block, src, extra.operand, .{ .simple = .operand_cUndef_macro_name });
26794 .needed_comptime_reason = "name of macro being undefined must be comptime-known",
26795 });
26796 try block.c_import_buf.?.writer().print("#undef {s}\n", .{name});26732 try block.c_import_buf.?.writer().print("#undef {s}\n", .{name});
26797 return .void_value;26733 return .void_value;
26798}26734}
...@@ -26805,9 +26741,7 @@ fn zirCInclude(...@@ -26805,9 +26741,7 @@ fn zirCInclude(
26805 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;26741 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
26806 const src = block.builtinCallArgSrc(extra.node, 0);26742 const src = block.builtinCallArgSrc(extra.node, 0);
2680726743
26808 const name = try sema.resolveConstString(block, src, extra.operand, .{26744 const name = try sema.resolveConstString(block, src, extra.operand, .{ .simple = .operand_cInclude_file_name });
26809 .needed_comptime_reason = "path being included must be comptime-known",
26810 });
26811 try block.c_import_buf.?.writer().print("#include <{s}>\n", .{name});26745 try block.c_import_buf.?.writer().print("#include <{s}>\n", .{name});
26812 return .void_value;26746 return .void_value;
26813}26747}
...@@ -26823,14 +26757,10 @@ fn zirCDefine(...@@ -26823,14 +26757,10 @@ fn zirCDefine(
26823 const name_src = block.builtinCallArgSrc(extra.node, 0);26757 const name_src = block.builtinCallArgSrc(extra.node, 0);
26824 const val_src = block.builtinCallArgSrc(extra.node, 1);26758 const val_src = block.builtinCallArgSrc(extra.node, 1);
2682526759
26826 const name = try sema.resolveConstString(block, name_src, extra.lhs, .{26760 const name = try sema.resolveConstString(block, name_src, extra.lhs, .{ .simple = .operand_cDefine_macro_name });
26827 .needed_comptime_reason = "name of macro being undefined must be comptime-known",
26828 });
26829 const rhs = try sema.resolveInst(extra.rhs);26761 const rhs = try sema.resolveInst(extra.rhs);
26830 if (sema.typeOf(rhs).zigTypeTag(zcu) != .void) {26762 if (sema.typeOf(rhs).zigTypeTag(zcu) != .void) {
26831 const value = try sema.resolveConstString(block, val_src, extra.rhs, .{26763 const value = try sema.resolveConstString(block, val_src, extra.rhs, .{ .simple = .operand_cDefine_macro_value });
26832 .needed_comptime_reason = "value of macro being undefined must be comptime-known",
26833 });
26834 try block.c_import_buf.?.writer().print("#define {s} {s}\n", .{ name, value });26764 try block.c_import_buf.?.writer().print("#define {s} {s}\n", .{ name, value });
26835 } else {26765 } else {
26836 try block.c_import_buf.?.writer().print("#define {s}\n", .{name});26766 try block.c_import_buf.?.writer().print("#define {s}\n", .{name});
...@@ -26851,9 +26781,7 @@ fn zirWasmMemorySize(...@@ -26851,9 +26781,7 @@ fn zirWasmMemorySize(
26851 return sema.fail(block, builtin_src, "builtin @wasmMemorySize is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});26781 return sema.fail(block, builtin_src, "builtin @wasmMemorySize is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
26852 }26782 }
2685326783
26854 const index: u32 = @intCast(try sema.resolveInt(block, index_src, extra.operand, Type.u32, .{26784 const index: u32 = @intCast(try sema.resolveInt(block, index_src, extra.operand, Type.u32, .{ .simple = .wasm_memory_index }));
26855 .needed_comptime_reason = "wasm memory size index must be comptime-known",
26856 }));
26857 try sema.requireRuntimeBlock(block, builtin_src, null);26785 try sema.requireRuntimeBlock(block, builtin_src, null);
26858 return block.addInst(.{26786 return block.addInst(.{
26859 .tag = .wasm_memory_size,26787 .tag = .wasm_memory_size,
...@@ -26878,9 +26806,7 @@ fn zirWasmMemoryGrow(...@@ -26878,9 +26806,7 @@ fn zirWasmMemoryGrow(
26878 return sema.fail(block, builtin_src, "builtin @wasmMemoryGrow is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});26806 return sema.fail(block, builtin_src, "builtin @wasmMemoryGrow is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
26879 }26807 }
2688026808
26881 const index: u32 = @intCast(try sema.resolveInt(block, index_src, extra.lhs, Type.u32, .{26809 const index: u32 = @intCast(try sema.resolveInt(block, index_src, extra.lhs, Type.u32, .{ .simple = .wasm_memory_index }));
26882 .needed_comptime_reason = "wasm memory size index must be comptime-known",
26883 }));
26884 const delta = try sema.coerce(block, Type.usize, try sema.resolveInst(extra.rhs), delta_src);26810 const delta = try sema.coerce(block, Type.usize, try sema.resolveInst(extra.rhs), delta_src);
2688526811
26886 try sema.requireRuntimeBlock(block, builtin_src, null);26812 try sema.requireRuntimeBlock(block, builtin_src, null);
...@@ -26911,19 +26837,13 @@ fn resolvePrefetchOptions(...@@ -26911,19 +26837,13 @@ fn resolvePrefetchOptions(
26911 const cache_src = block.src(.{ .init_field_cache = src.offset.node_offset_builtin_call_arg.builtin_call_node });26837 const cache_src = block.src(.{ .init_field_cache = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2691226838
26913 const rw = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "rw", .no_embedded_nulls), rw_src);26839 const rw = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "rw", .no_embedded_nulls), rw_src);
26914 const rw_val = try sema.resolveConstDefinedValue(block, rw_src, rw, .{26840 const rw_val = try sema.resolveConstDefinedValue(block, rw_src, rw, .{ .simple = .prefetch_options });
26915 .needed_comptime_reason = "prefetch read/write must be comptime-known",
26916 });
2691726841
26918 const locality = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "locality", .no_embedded_nulls), locality_src);26842 const locality = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "locality", .no_embedded_nulls), locality_src);
26919 const locality_val = try sema.resolveConstDefinedValue(block, locality_src, locality, .{26843 const locality_val = try sema.resolveConstDefinedValue(block, locality_src, locality, .{ .simple = .prefetch_options });
26920 .needed_comptime_reason = "prefetch locality must be comptime-known",
26921 });
2692226844
26923 const cache = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "cache", .no_embedded_nulls), cache_src);26845 const cache = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "cache", .no_embedded_nulls), cache_src);
26924 const cache_val = try sema.resolveConstDefinedValue(block, cache_src, cache, .{26846 const cache_val = try sema.resolveConstDefinedValue(block, cache_src, cache, .{ .simple = .prefetch_options });
26925 .needed_comptime_reason = "prefetch cache must be comptime-known",
26926 });
2692726847
26928 return std.builtin.PrefetchOptions{26848 return std.builtin.PrefetchOptions{
26929 .rw = zcu.toEnum(std.builtin.PrefetchOptions.Rw, rw_val),26849 .rw = zcu.toEnum(std.builtin.PrefetchOptions.Rw, rw_val),
...@@ -26945,7 +26865,7 @@ fn zirPrefetch(...@@ -26945,7 +26865,7 @@ fn zirPrefetch(
2694526865
26946 const options = try sema.resolvePrefetchOptions(block, opts_src, extra.rhs);26866 const options = try sema.resolvePrefetchOptions(block, opts_src, extra.rhs);
2694726867
26948 if (!block.is_comptime) {26868 if (!block.isComptime()) {
26949 _ = try block.addInst(.{26869 _ = try block.addInst(.{
26950 .tag = .prefetch,26870 .tag = .prefetch,
26951 .data = .{ .prefetch = .{26871 .data = .{ .prefetch = .{
...@@ -26987,30 +26907,20 @@ fn resolveExternOptions(...@@ -26987,30 +26907,20 @@ fn resolveExternOptions(
26987 const dll_import_src = block.src(.{ .init_field_dll_import = src.offset.node_offset_builtin_call_arg.builtin_call_node });26907 const dll_import_src = block.src(.{ .init_field_dll_import = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2698826908
26989 const name_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls), name_src);26909 const name_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls), name_src);
26990 const name = try sema.toConstString(block, name_src, name_ref, .{26910 const name = try sema.toConstString(block, name_src, name_ref, .{ .simple = .extern_options });
26991 .needed_comptime_reason = "name of the extern symbol must be comptime-known",
26992 });
2699326911
26994 const library_name_inst = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "library_name", .no_embedded_nulls), library_src);26912 const library_name_inst = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "library_name", .no_embedded_nulls), library_src);
26995 const library_name_val = try sema.resolveConstDefinedValue(block, library_src, library_name_inst, .{26913 const library_name_val = try sema.resolveConstDefinedValue(block, library_src, library_name_inst, .{ .simple = .extern_options });
26996 .needed_comptime_reason = "library in which extern symbol is must be comptime-known",
26997 });
2699826914
26999 const linkage_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "linkage", .no_embedded_nulls), linkage_src);26915 const linkage_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "linkage", .no_embedded_nulls), linkage_src);
27000 const linkage_val = try sema.resolveConstDefinedValue(block, linkage_src, linkage_ref, .{26916 const linkage_val = try sema.resolveConstDefinedValue(block, linkage_src, linkage_ref, .{ .simple = .extern_options });
27001 .needed_comptime_reason = "linkage of the extern symbol must be comptime-known",
27002 });
27003 const linkage = zcu.toEnum(std.builtin.GlobalLinkage, linkage_val);26917 const linkage = zcu.toEnum(std.builtin.GlobalLinkage, linkage_val);
2700426918
27005 const is_thread_local = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "is_thread_local", .no_embedded_nulls), thread_local_src);26919 const is_thread_local = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "is_thread_local", .no_embedded_nulls), thread_local_src);
27006 const is_thread_local_val = try sema.resolveConstDefinedValue(block, thread_local_src, is_thread_local, .{26920 const is_thread_local_val = try sema.resolveConstDefinedValue(block, thread_local_src, is_thread_local, .{ .simple = .extern_options });
27007 .needed_comptime_reason = "threadlocality of the extern symbol must be comptime-known",
27008 });
2700926921
27010 const library_name = if (library_name_val.optionalValue(zcu)) |library_name_payload| library_name: {26922 const library_name = if (library_name_val.optionalValue(zcu)) |library_name_payload| library_name: {
27011 const library_name = try sema.toConstString(block, library_src, Air.internedToRef(library_name_payload.toIntern()), .{26923 const library_name = try sema.toConstString(block, library_src, Air.internedToRef(library_name_payload.toIntern()), .{ .simple = .extern_options });
27012 .needed_comptime_reason = "library in which extern symbol is must be comptime-known",
27013 });
27014 if (library_name.len == 0) {26924 if (library_name.len == 0) {
27015 return sema.fail(block, library_src, "library name cannot be empty", .{});26925 return sema.fail(block, library_src, "library name cannot be empty", .{});
27016 }26926 }
...@@ -27019,9 +26929,7 @@ fn resolveExternOptions(...@@ -27019,9 +26929,7 @@ fn resolveExternOptions(
27019 } else null;26929 } else null;
2702026930
27021 const is_dll_import_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "is_dll_import", .no_embedded_nulls), dll_import_src);26931 const is_dll_import_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "is_dll_import", .no_embedded_nulls), dll_import_src);
27022 const is_dll_import_val = try sema.resolveConstDefinedValue(block, dll_import_src, is_dll_import_ref, .{26932 const is_dll_import_val = try sema.resolveConstDefinedValue(block, dll_import_src, is_dll_import_ref, .{ .simple = .extern_options });
27023 .needed_comptime_reason = "it must be comptime-known if the symbol is imported from a dll",
27024 });
2702526933
27026 if (name.len == 0) {26934 if (name.len == 0) {
27027 return sema.fail(block, name_src, "extern symbol name cannot be empty", .{});26935 return sema.fail(block, name_src, "extern symbol name cannot be empty", .{});
...@@ -27134,9 +27042,7 @@ fn zirWorkItem(...@@ -27134,9 +27042,7 @@ fn zirWorkItem(
27134 },27042 },
27135 }27043 }
2713627044
27137 const dimension: u32 = @intCast(try sema.resolveInt(block, dimension_src, extra.operand, Type.u32, .{27045 const dimension: u32 = @intCast(try sema.resolveInt(block, dimension_src, extra.operand, Type.u32, .{ .simple = .work_group_dim_index }));
27138 .needed_comptime_reason = "dimension must be comptime-known",
27139 }));
27140 try sema.requireRuntimeBlock(block, builtin_src, null);27046 try sema.requireRuntimeBlock(block, builtin_src, null);
2714127047
27142 return block.addInst(.{27048 return block.addInst(.{
...@@ -27158,7 +27064,7 @@ fn zirInComptime(...@@ -27158,7 +27064,7 @@ fn zirInComptime(
27158 block: *Block,27064 block: *Block,
27159) CompileError!Air.Inst.Ref {27065) CompileError!Air.Inst.Ref {
27160 _ = sema;27066 _ = sema;
27161 return if (block.is_comptime) .bool_true else .bool_false;27067 return if (block.isComptime()) .bool_true else .bool_false;
27162}27068}
2716327069
27164fn zirBuiltinValue(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {27070fn zirBuiltinValue(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
...@@ -27249,9 +27155,7 @@ fn zirBranchHint(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat...@@ -27249,9 +27155,7 @@ fn zirBranchHint(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
2724927155
27250 const hint_ty = try sema.getBuiltinType("BranchHint");27156 const hint_ty = try sema.getBuiltinType("BranchHint");
27251 const coerced_hint = try sema.coerce(block, hint_ty, uncoerced_hint, operand_src);27157 const coerced_hint = try sema.coerce(block, hint_ty, uncoerced_hint, operand_src);
27252 const hint_val = try sema.resolveConstDefinedValue(block, operand_src, coerced_hint, .{27158 const hint_val = try sema.resolveConstDefinedValue(block, operand_src, coerced_hint, .{ .simple = .operand_branchHint });
27253 .needed_comptime_reason = "operand to '@branchHint' must be comptime-known",
27254 });
2725527159
27256 // We only apply the first hint in a branch.27160 // We only apply the first hint in a branch.
27257 // This allows user-provided hints to override implicit cold hints.27161 // This allows user-provided hints to override implicit cold hints.
...@@ -27261,20 +27165,20 @@ fn zirBranchHint(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat...@@ -27261,20 +27165,20 @@ fn zirBranchHint(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
27261}27165}
2726227166
27263fn requireRuntimeBlock(sema: *Sema, block: *Block, src: LazySrcLoc, runtime_src: ?LazySrcLoc) !void {27167fn requireRuntimeBlock(sema: *Sema, block: *Block, src: LazySrcLoc, runtime_src: ?LazySrcLoc) !void {
27264 if (block.is_comptime) {27168 if (block.isComptime()) {
27265 const msg = msg: {27169 const msg, const fail_block = msg: {
27266 const msg = try sema.errMsg(src, "unable to evaluate comptime expression", .{});27170 const msg = try sema.errMsg(src, "unable to evaluate comptime expression", .{});
27267 errdefer msg.destroy(sema.gpa);27171 errdefer msg.destroy(sema.gpa);
2726827172
27269 if (runtime_src) |some| {27173 if (runtime_src) |some| {
27270 try sema.errNote(some, msg, "operation is runtime due to this operand", .{});27174 try sema.errNote(some, msg, "operation is runtime due to this operand", .{});
27271 }27175 }
27272 if (block.comptime_reason) |some| {27176
27273 try some.explain(sema, msg);27177 const fail_block = try block.explainWhyBlockIsComptime(msg);
27274 }27178
27275 break :msg msg;27179 break :msg .{ msg, fail_block };
27276 };27180 };
27277 return sema.failWithOwnedErrorMsg(block, msg);27181 return sema.failWithOwnedErrorMsg(fail_block, msg);
27278 }27182 }
27279}27183}
2728027184
...@@ -27759,7 +27663,7 @@ fn addSafetyCheck(...@@ -27759,7 +27663,7 @@ fn addSafetyCheck(
27759 panic_id: Zcu.PanicId,27663 panic_id: Zcu.PanicId,
27760) !void {27664) !void {
27761 const gpa = sema.gpa;27665 const gpa = sema.gpa;
27762 assert(!parent_block.is_comptime);27666 assert(!parent_block.isComptime());
2776327667
27764 var fail_block: Block = .{27668 var fail_block: Block = .{
27765 .parent = parent_block,27669 .parent = parent_block,
...@@ -27767,7 +27671,7 @@ fn addSafetyCheck(...@@ -27767,7 +27671,7 @@ fn addSafetyCheck(
27767 .namespace = parent_block.namespace,27671 .namespace = parent_block.namespace,
27768 .instructions = .{},27672 .instructions = .{},
27769 .inlining = parent_block.inlining,27673 .inlining = parent_block.inlining,
27770 .is_comptime = false,27674 .comptime_reason = null,
27771 .src_base_inst = parent_block.src_base_inst,27675 .src_base_inst = parent_block.src_base_inst,
27772 .type_name_ctx = parent_block.type_name_ctx,27676 .type_name_ctx = parent_block.type_name_ctx,
27773 };27677 };
...@@ -27874,7 +27778,7 @@ fn addSafetyCheckUnwrapError(...@@ -27874,7 +27778,7 @@ fn addSafetyCheckUnwrapError(
27874 unwrap_err_tag: Air.Inst.Tag,27778 unwrap_err_tag: Air.Inst.Tag,
27875 is_non_err_tag: Air.Inst.Tag,27779 is_non_err_tag: Air.Inst.Tag,
27876) !void {27780) !void {
27877 assert(!parent_block.is_comptime);27781 assert(!parent_block.isComptime());
27878 const ok = try parent_block.addUnOp(is_non_err_tag, operand);27782 const ok = try parent_block.addUnOp(is_non_err_tag, operand);
27879 const gpa = sema.gpa;27783 const gpa = sema.gpa;
2788027784
...@@ -27884,7 +27788,7 @@ fn addSafetyCheckUnwrapError(...@@ -27884,7 +27788,7 @@ fn addSafetyCheckUnwrapError(
27884 .namespace = parent_block.namespace,27788 .namespace = parent_block.namespace,
27885 .instructions = .{},27789 .instructions = .{},
27886 .inlining = parent_block.inlining,27790 .inlining = parent_block.inlining,
27887 .is_comptime = false,27791 .comptime_reason = null,
27888 .src_base_inst = parent_block.src_base_inst,27792 .src_base_inst = parent_block.src_base_inst,
27889 .type_name_ctx = parent_block.type_name_ctx,27793 .type_name_ctx = parent_block.type_name_ctx,
27890 };27794 };
...@@ -27918,7 +27822,7 @@ fn addSafetyCheckIndexOob(...@@ -27918,7 +27822,7 @@ fn addSafetyCheckIndexOob(
27918 len: Air.Inst.Ref,27822 len: Air.Inst.Ref,
27919 cmp_op: Air.Inst.Tag,27823 cmp_op: Air.Inst.Tag,
27920) !void {27824) !void {
27921 assert(!parent_block.is_comptime);27825 assert(!parent_block.isComptime());
27922 const ok = try parent_block.addBinOp(cmp_op, index, len);27826 const ok = try parent_block.addBinOp(cmp_op, index, len);
27923 return addSafetyCheckCall(sema, parent_block, src, ok, "outOfBounds", &.{ index, len });27827 return addSafetyCheckCall(sema, parent_block, src, ok, "outOfBounds", &.{ index, len });
27924}27828}
...@@ -27930,7 +27834,7 @@ fn addSafetyCheckInactiveUnionField(...@@ -27930,7 +27834,7 @@ fn addSafetyCheckInactiveUnionField(
27930 active_tag: Air.Inst.Ref,27834 active_tag: Air.Inst.Ref,
27931 wanted_tag: Air.Inst.Ref,27835 wanted_tag: Air.Inst.Ref,
27932) !void {27836) !void {
27933 assert(!parent_block.is_comptime);27837 assert(!parent_block.isComptime());
27934 const ok = try parent_block.addBinOp(.cmp_eq, active_tag, wanted_tag);27838 const ok = try parent_block.addBinOp(.cmp_eq, active_tag, wanted_tag);
27935 return addSafetyCheckCall(sema, parent_block, src, ok, "inactiveUnionField", &.{ active_tag, wanted_tag });27839 return addSafetyCheckCall(sema, parent_block, src, ok, "inactiveUnionField", &.{ active_tag, wanted_tag });
27936}27840}
...@@ -27944,7 +27848,7 @@ fn addSafetyCheckSentinelMismatch(...@@ -27944,7 +27848,7 @@ fn addSafetyCheckSentinelMismatch(
27944 ptr: Air.Inst.Ref,27848 ptr: Air.Inst.Ref,
27945 sentinel_index: Air.Inst.Ref,27849 sentinel_index: Air.Inst.Ref,
27946) !void {27850) !void {
27947 assert(!parent_block.is_comptime);27851 assert(!parent_block.isComptime());
27948 const pt = sema.pt;27852 const pt = sema.pt;
27949 const zcu = pt.zcu;27853 const zcu = pt.zcu;
27950 const expected_sentinel_val = maybe_sentinel orelse return;27854 const expected_sentinel_val = maybe_sentinel orelse return;
...@@ -27986,7 +27890,7 @@ fn addSafetyCheckCall(...@@ -27986,7 +27890,7 @@ fn addSafetyCheckCall(
27986 func_name: []const u8,27890 func_name: []const u8,
27987 args: []const Air.Inst.Ref,27891 args: []const Air.Inst.Ref,
27988) !void {27892) !void {
27989 assert(!parent_block.is_comptime);27893 assert(!parent_block.isComptime());
27990 const gpa = sema.gpa;27894 const gpa = sema.gpa;
27991 const pt = sema.pt;27895 const pt = sema.pt;
27992 const zcu = pt.zcu;27896 const zcu = pt.zcu;
...@@ -27997,7 +27901,7 @@ fn addSafetyCheckCall(...@@ -27997,7 +27901,7 @@ fn addSafetyCheckCall(
27997 .namespace = parent_block.namespace,27901 .namespace = parent_block.namespace,
27998 .instructions = .{},27902 .instructions = .{},
27999 .inlining = parent_block.inlining,27903 .inlining = parent_block.inlining,
28000 .is_comptime = false,27904 .comptime_reason = null,
28001 .src_base_inst = parent_block.src_base_inst,27905 .src_base_inst = parent_block.src_base_inst,
28002 .type_name_ctx = parent_block.type_name_ctx,27906 .type_name_ctx = parent_block.type_name_ctx,
28003 };27907 };
...@@ -28203,7 +28107,7 @@ fn fieldVal(...@@ -28203,7 +28107,7 @@ fn fieldVal(
28203 const field_ptr = try sema.structFieldPtr(block, src, object, field_name, field_name_src, inner_ty, false);28107 const field_ptr = try sema.structFieldPtr(block, src, object, field_name, field_name_src, inner_ty, false);
28204 return sema.analyzeLoad(block, src, field_ptr, object_src);28108 return sema.analyzeLoad(block, src, field_ptr, object_src);
28205 } else {28109 } else {
28206 return sema.structFieldVal(block, src, object, field_name, field_name_src, inner_ty);28110 return sema.structFieldVal(block, object, field_name, field_name_src, inner_ty);
28207 },28111 },
28208 .@"union" => if (is_pointer_to) {28112 .@"union" => if (is_pointer_to) {
28209 // Avoid loading the entire union by fetching a pointer and loading that28113 // Avoid loading the entire union by fetching a pointer and loading that
...@@ -28823,14 +28727,12 @@ fn structFieldPtrByIndex(...@@ -28823,14 +28727,12 @@ fn structFieldPtrByIndex(
28823 return Air.internedToRef(val);28727 return Air.internedToRef(val);
28824 }28728 }
2882528729
28826 try sema.requireRuntimeBlock(block, src, null);
28827 return block.addStructFieldPtr(struct_ptr, field_index, ptr_field_ty);28730 return block.addStructFieldPtr(struct_ptr, field_index, ptr_field_ty);
28828}28731}
2882928732
28830fn structFieldVal(28733fn structFieldVal(
28831 sema: *Sema,28734 sema: *Sema,
28832 block: *Block,28735 block: *Block,
28833 src: LazySrcLoc,
28834 struct_byval: Air.Inst.Ref,28736 struct_byval: Air.Inst.Ref,
28835 field_name: InternPool.NullTerminatedString,28737 field_name: InternPool.NullTerminatedString,
28836 field_name_src: LazySrcLoc,28738 field_name_src: LazySrcLoc,
...@@ -28866,12 +28768,11 @@ fn structFieldVal(...@@ -28866,12 +28768,11 @@ fn structFieldVal(
28866 return Air.internedToRef((try struct_val.fieldValue(pt, field_index)).toIntern());28768 return Air.internedToRef((try struct_val.fieldValue(pt, field_index)).toIntern());
28867 }28769 }
2886828770
28869 try sema.requireRuntimeBlock(block, src, null);
28870 try field_ty.resolveLayout(pt);28771 try field_ty.resolveLayout(pt);
28871 return block.addStructFieldVal(struct_byval, field_index, field_ty);28772 return block.addStructFieldVal(struct_byval, field_index, field_ty);
28872 },28773 },
28873 .tuple_type => {28774 .tuple_type => {
28874 return sema.tupleFieldVal(block, src, struct_byval, field_name, field_name_src, struct_ty);28775 return sema.tupleFieldVal(block, struct_byval, field_name, field_name_src, struct_ty);
28875 },28776 },
28876 else => unreachable,28777 else => unreachable,
28877 }28778 }
...@@ -28880,7 +28781,6 @@ fn structFieldVal(...@@ -28880,7 +28781,6 @@ fn structFieldVal(
28880fn tupleFieldVal(28781fn tupleFieldVal(
28881 sema: *Sema,28782 sema: *Sema,
28882 block: *Block,28783 block: *Block,
28883 src: LazySrcLoc,
28884 tuple_byval: Air.Inst.Ref,28784 tuple_byval: Air.Inst.Ref,
28885 field_name: InternPool.NullTerminatedString,28785 field_name: InternPool.NullTerminatedString,
28886 field_name_src: LazySrcLoc,28786 field_name_src: LazySrcLoc,
...@@ -28892,7 +28792,7 @@ fn tupleFieldVal(...@@ -28892,7 +28792,7 @@ fn tupleFieldVal(
28892 return pt.intRef(Type.usize, tuple_ty.structFieldCount(zcu));28792 return pt.intRef(Type.usize, tuple_ty.structFieldCount(zcu));
28893 }28793 }
28894 const field_index = try sema.tupleFieldIndex(block, tuple_ty, field_name, field_name_src);28794 const field_index = try sema.tupleFieldIndex(block, tuple_ty, field_name, field_name_src);
28895 return sema.tupleFieldValByIndex(block, src, tuple_byval, field_index, tuple_ty);28795 return sema.tupleFieldValByIndex(block, tuple_byval, field_index, tuple_ty);
28896}28796}
2889728797
28898/// Asserts that `field_name` is not "len".28798/// Asserts that `field_name` is not "len".
...@@ -28921,7 +28821,6 @@ fn tupleFieldIndex(...@@ -28921,7 +28821,6 @@ fn tupleFieldIndex(
28921fn tupleFieldValByIndex(28821fn tupleFieldValByIndex(
28922 sema: *Sema,28822 sema: *Sema,
28923 block: *Block,28823 block: *Block,
28924 src: LazySrcLoc,
28925 tuple_byval: Air.Inst.Ref,28824 tuple_byval: Air.Inst.Ref,
28926 field_index: u32,28825 field_index: u32,
28927 tuple_ty: Type,28826 tuple_ty: Type,
...@@ -28951,7 +28850,6 @@ fn tupleFieldValByIndex(...@@ -28951,7 +28850,6 @@ fn tupleFieldValByIndex(
28951 };28850 };
28952 }28851 }
2895328852
28954 try sema.requireRuntimeBlock(block, src, null);
28955 try field_ty.resolveLayout(pt);28853 try field_ty.resolveLayout(pt);
28956 return block.addStructFieldVal(tuple_byval, field_index, field_ty);28854 return block.addStructFieldVal(tuple_byval, field_index, field_ty);
28957}28855}
...@@ -29049,7 +28947,6 @@ fn unionFieldPtr(...@@ -29049,7 +28947,6 @@ fn unionFieldPtr(
29049 return Air.internedToRef(field_ptr_val.toIntern());28947 return Air.internedToRef(field_ptr_val.toIntern());
29050 }28948 }
2905128949
29052 try sema.requireRuntimeBlock(block, src, null);
29053 if (!initializing and union_obj.flagsUnordered(ip).layout == .auto and block.wantSafety() and28950 if (!initializing and union_obj.flagsUnordered(ip).layout == .auto and block.wantSafety() and
29054 union_ty.unionTagTypeSafety(zcu) != null and union_obj.field_types.len > 1)28951 union_ty.unionTagTypeSafety(zcu) != null and union_obj.field_types.len > 1)
29055 {28952 {
...@@ -29126,7 +29023,6 @@ fn unionFieldVal(...@@ -29126,7 +29023,6 @@ fn unionFieldVal(
29126 }29023 }
29127 }29024 }
2912829025
29129 try sema.requireRuntimeBlock(block, src, null);
29130 if (union_obj.flagsUnordered(ip).layout == .auto and block.wantSafety() and29026 if (union_obj.flagsUnordered(ip).layout == .auto and block.wantSafety() and
29131 union_ty.unionTagTypeSafety(zcu) != null and union_obj.field_types.len > 1)29027 union_ty.unionTagTypeSafety(zcu) != null and union_obj.field_types.len > 1)
29132 {29028 {
...@@ -29168,9 +29064,7 @@ fn elemPtr(...@@ -29168,9 +29064,7 @@ fn elemPtr(
29168 .array, .vector => try sema.elemPtrArray(block, src, indexable_ptr_src, indexable_ptr, elem_index_src, elem_index, init, oob_safety),29064 .array, .vector => try sema.elemPtrArray(block, src, indexable_ptr_src, indexable_ptr, elem_index_src, elem_index, init, oob_safety),
29169 .@"struct" => blk: {29065 .@"struct" => blk: {
29170 // Tuple field access.29066 // Tuple field access.
29171 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{29067 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{ .simple = .tuple_field_index });
29172 .needed_comptime_reason = "tuple field access index must be comptime-known",
29173 });
29174 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));29068 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
29175 break :blk try sema.tupleFieldPtr(block, src, indexable_ptr, elem_index_src, index, init);29069 break :blk try sema.tupleFieldPtr(block, src, indexable_ptr, elem_index_src, index, init);
29176 },29070 },
...@@ -29207,16 +29101,15 @@ fn elemPtrOneLayerOnly(...@@ -29207,16 +29101,15 @@ fn elemPtrOneLayerOnly(
29207 .Many, .C => {29101 .Many, .C => {
29208 const maybe_ptr_val = try sema.resolveDefinedValue(block, indexable_src, indexable);29102 const maybe_ptr_val = try sema.resolveDefinedValue(block, indexable_src, indexable);
29209 const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);29103 const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);
29210 const runtime_src = rs: {29104 ct: {
29211 const ptr_val = maybe_ptr_val orelse break :rs indexable_src;29105 const ptr_val = maybe_ptr_val orelse break :ct;
29212 const index_val = maybe_index_val orelse break :rs elem_index_src;29106 const index_val = maybe_index_val orelse break :ct;
29213 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));29107 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
29214 const elem_ptr = try ptr_val.ptrElem(index, pt);29108 const elem_ptr = try ptr_val.ptrElem(index, pt);
29215 return Air.internedToRef(elem_ptr.toIntern());29109 return Air.internedToRef(elem_ptr.toIntern());
29216 };29110 }
29217 const result_ty = try indexable_ty.elemPtrType(null, pt);29111 const result_ty = try indexable_ty.elemPtrType(null, pt);
2921829112
29219 try sema.requireRuntimeBlock(block, src, runtime_src);
29220 return block.addPtrElemPtr(indexable, elem_index, result_ty);29113 return block.addPtrElemPtr(indexable, elem_index, result_ty);
29221 },29114 },
29222 .One => {29115 .One => {
...@@ -29225,9 +29118,7 @@ fn elemPtrOneLayerOnly(...@@ -29225,9 +29118,7 @@ fn elemPtrOneLayerOnly(
29225 .array, .vector => try sema.elemPtrArray(block, src, indexable_src, indexable, elem_index_src, elem_index, init, oob_safety),29118 .array, .vector => try sema.elemPtrArray(block, src, indexable_src, indexable, elem_index_src, elem_index, init, oob_safety),
29226 .@"struct" => blk: {29119 .@"struct" => blk: {
29227 assert(child_ty.isTuple(zcu));29120 assert(child_ty.isTuple(zcu));
29228 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{29121 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{ .simple = .tuple_field_index });
29229 .needed_comptime_reason = "tuple field access index must be comptime-known",
29230 });
29231 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));29122 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
29232 break :blk try sema.tupleFieldPtr(block, indexable_src, indexable, elem_index_src, index, false);29123 break :blk try sema.tupleFieldPtr(block, indexable_src, indexable, elem_index_src, index, false);
29233 },29124 },
...@@ -29266,22 +29157,19 @@ fn elemVal(...@@ -29266,22 +29157,19 @@ fn elemVal(
29266 const maybe_indexable_val = try sema.resolveDefinedValue(block, indexable_src, indexable);29157 const maybe_indexable_val = try sema.resolveDefinedValue(block, indexable_src, indexable);
29267 const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);29158 const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);
2926829159
29269 const runtime_src = rs: {29160 ct: {
29270 const indexable_val = maybe_indexable_val orelse break :rs indexable_src;29161 const indexable_val = maybe_indexable_val orelse break :ct;
29271 const index_val = maybe_index_val orelse break :rs elem_index_src;29162 const index_val = maybe_index_val orelse break :ct;
29272 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));29163 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
29273 const elem_ty = indexable_ty.elemType2(zcu);29164 const elem_ty = indexable_ty.elemType2(zcu);
29274 const many_ptr_ty = try pt.manyConstPtrType(elem_ty);29165 const many_ptr_ty = try pt.manyConstPtrType(elem_ty);
29275 const many_ptr_val = try pt.getCoerced(indexable_val, many_ptr_ty);29166 const many_ptr_val = try pt.getCoerced(indexable_val, many_ptr_ty);
29276 const elem_ptr_ty = try pt.singleConstPtrType(elem_ty);29167 const elem_ptr_ty = try pt.singleConstPtrType(elem_ty);
29277 const elem_ptr_val = try many_ptr_val.ptrElem(index, pt);29168 const elem_ptr_val = try many_ptr_val.ptrElem(index, pt);
29278 if (try sema.pointerDeref(block, indexable_src, elem_ptr_val, elem_ptr_ty)) |elem_val| {29169 const elem_val = try sema.pointerDeref(block, indexable_src, elem_ptr_val, elem_ptr_ty) orelse break :ct;
29279 return Air.internedToRef((try pt.getCoerced(elem_val, elem_ty)).toIntern());29170 return Air.internedToRef((try pt.getCoerced(elem_val, elem_ty)).toIntern());
29280 }29171 }
29281 break :rs indexable_src;
29282 };
2928329172
29284 try sema.requireRuntimeBlock(block, src, runtime_src);
29285 return block.addBinOp(.ptr_elem_val, indexable, elem_index);29173 return block.addBinOp(.ptr_elem_val, indexable, elem_index);
29286 },29174 },
29287 .One => {29175 .One => {
...@@ -29305,9 +29193,7 @@ fn elemVal(...@@ -29305,9 +29193,7 @@ fn elemVal(
29305 },29193 },
29306 .@"struct" => {29194 .@"struct" => {
29307 // Tuple field access.29195 // Tuple field access.
29308 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{29196 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{ .simple = .tuple_field_index });
29309 .needed_comptime_reason = "tuple field access index must be comptime-known",
29310 });
29311 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));29197 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
29312 return sema.tupleField(block, indexable_src, indexable, elem_index_src, index);29198 return sema.tupleField(block, indexable_src, indexable, elem_index_src, index);
29313 },29199 },
...@@ -29396,7 +29282,6 @@ fn tupleFieldPtr(...@@ -29396,7 +29282,6 @@ fn tupleFieldPtr(
29396 try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_ptr_src);29282 try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_ptr_src);
29397 }29283 }
2939829284
29399 try sema.requireRuntimeBlock(block, tuple_ptr_src, null);
29400 return block.addStructFieldPtr(tuple_ptr, field_index, ptr_field_ty);29285 return block.addStructFieldPtr(tuple_ptr, field_index, ptr_field_ty);
29401}29286}
2940229287
...@@ -29439,7 +29324,6 @@ fn tupleField(...@@ -29439,7 +29324,6 @@ fn tupleField(
2943929324
29440 try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_src);29325 try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_src);
2944129326
29442 try sema.requireRuntimeBlock(block, tuple_src, null);
29443 try field_ty.resolveLayout(pt);29327 try field_ty.resolveLayout(pt);
29444 return block.addStructFieldVal(tuple, field_index, field_ty);29328 return block.addStructFieldVal(tuple, field_index, field_ty);
29445}29329}
...@@ -29495,7 +29379,6 @@ fn elemValArray(...@@ -29495,7 +29379,6 @@ fn elemValArray(
2949529379
29496 try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ty, array_ty, array_src);29380 try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ty, array_ty, array_src);
2949729381
29498 const runtime_src = if (maybe_undef_array_val != null) elem_index_src else array_src;
29499 if (oob_safety and block.wantSafety()) {29382 if (oob_safety and block.wantSafety()) {
29500 // Runtime check is only needed if unable to comptime check.29383 // Runtime check is only needed if unable to comptime check.
29501 if (maybe_index_val == null) {29384 if (maybe_index_val == null) {
...@@ -29508,7 +29391,6 @@ fn elemValArray(...@@ -29508,7 +29391,6 @@ fn elemValArray(
29508 if (try sema.typeHasOnePossibleValue(elem_ty)) |elem_val|29391 if (try sema.typeHasOnePossibleValue(elem_ty)) |elem_val|
29509 return Air.internedToRef(elem_val.toIntern());29392 return Air.internedToRef(elem_val.toIntern());
2951029393
29511 try sema.requireRuntimeBlock(block, src, runtime_src);
29512 return block.addBinOp(.array_elem_val, array, elem_index);29394 return block.addBinOp(.array_elem_val, array, elem_index);
29513}29395}
2951429396
...@@ -29562,9 +29444,6 @@ fn elemPtrArray(...@@ -29562,9 +29444,6 @@ fn elemPtrArray(
29562 try sema.validateRuntimeElemAccess(block, elem_index_src, array_ty.elemType2(zcu), array_ty, array_ptr_src);29444 try sema.validateRuntimeElemAccess(block, elem_index_src, array_ty.elemType2(zcu), array_ty, array_ptr_src);
29563 }29445 }
2956429446
29565 const runtime_src = if (maybe_undef_array_ptr_val != null) elem_index_src else array_ptr_src;
29566 try sema.requireRuntimeBlock(block, src, runtime_src);
29567
29568 // Runtime check is only needed if unable to comptime check.29447 // Runtime check is only needed if unable to comptime check.
29569 if (oob_safety and block.wantSafety() and offset == null) {29448 if (oob_safety and block.wantSafety() and offset == null) {
29570 const len_inst = try pt.intRef(Type.usize, array_len);29449 const len_inst = try pt.intRef(Type.usize, array_len);
...@@ -29621,7 +29500,6 @@ fn elemValSlice(...@@ -29621,7 +29500,6 @@ fn elemValSlice(
2962129500
29622 try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ty, slice_ty, slice_src);29501 try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ty, slice_ty, slice_src);
2962329502
29624 try sema.requireRuntimeBlock(block, src, runtime_src);
29625 if (oob_safety and block.wantSafety()) {29503 if (oob_safety and block.wantSafety()) {
29626 const len_inst = if (maybe_slice_val) |slice_val|29504 const len_inst = if (maybe_slice_val) |slice_val|
29627 try pt.intRef(Type.usize, try slice_val.sliceLen(pt))29505 try pt.intRef(Type.usize, try slice_val.sliceLen(pt))
...@@ -29678,8 +29556,6 @@ fn elemPtrSlice(...@@ -29678,8 +29556,6 @@ fn elemPtrSlice(
2967829556
29679 try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ptr_ty, slice_ty, slice_src);29557 try sema.validateRuntimeElemAccess(block, elem_index_src, elem_ptr_ty, slice_ty, slice_src);
2968029558
29681 const runtime_src = if (maybe_undef_slice_val != null) elem_index_src else slice_src;
29682 try sema.requireRuntimeBlock(block, src, runtime_src);
29683 if (oob_safety and block.wantSafety()) {29559 if (oob_safety and block.wantSafety()) {
29684 const len_inst = len: {29560 const len_inst = len: {
29685 if (maybe_undef_slice_val) |slice_val|29561 if (maybe_undef_slice_val) |slice_val|
...@@ -30093,9 +29969,7 @@ fn coerceExtra(...@@ -30093,9 +29969,7 @@ fn coerceExtra(
30093 const val = maybe_inst_val orelse {29969 const val = maybe_inst_val orelse {
30094 if (dest_ty.zigTypeTag(zcu) == .comptime_int) {29970 if (dest_ty.zigTypeTag(zcu) == .comptime_int) {
30095 if (!opts.report_err) return error.NotCoercible;29971 if (!opts.report_err) return error.NotCoercible;
30096 return sema.failWithNeededComptime(block, inst_src, .{29972 return sema.failWithNeededComptime(block, inst_src, .{ .simple = .casted_to_comptime_int });
30097 .needed_comptime_reason = "value being casted to 'comptime_int' must be comptime-known",
30098 });
30099 }29973 }
30100 break :float;29974 break :float;
30101 };29975 };
...@@ -30120,9 +29994,7 @@ fn coerceExtra(...@@ -30120,9 +29994,7 @@ fn coerceExtra(
30120 if (dest_ty.zigTypeTag(zcu) == .comptime_int) {29994 if (dest_ty.zigTypeTag(zcu) == .comptime_int) {
30121 if (!opts.report_err) return error.NotCoercible;29995 if (!opts.report_err) return error.NotCoercible;
30122 if (opts.no_cast_to_comptime_int) return inst;29996 if (opts.no_cast_to_comptime_int) return inst;
30123 return sema.failWithNeededComptime(block, inst_src, .{29997 return sema.failWithNeededComptime(block, inst_src, .{ .simple = .casted_to_comptime_int });
30124 .needed_comptime_reason = "value being casted to 'comptime_int' must be comptime-known",
30125 });
30126 }29998 }
3012729999
30128 // integer widening30000 // integer widening
...@@ -30158,9 +30030,7 @@ fn coerceExtra(...@@ -30158,9 +30030,7 @@ fn coerceExtra(
30158 return Air.internedToRef(result_val.toIntern());30030 return Air.internedToRef(result_val.toIntern());
30159 } else if (dest_ty.zigTypeTag(zcu) == .comptime_float) {30031 } else if (dest_ty.zigTypeTag(zcu) == .comptime_float) {
30160 if (!opts.report_err) return error.NotCoercible;30032 if (!opts.report_err) return error.NotCoercible;
30161 return sema.failWithNeededComptime(block, inst_src, .{30033 return sema.failWithNeededComptime(block, inst_src, .{ .simple = .casted_to_comptime_float });
30162 .needed_comptime_reason = "value being casted to 'comptime_float' must be comptime-known",
30163 });
30164 }30034 }
3016530035
30166 // float widening30036 // float widening
...@@ -30175,9 +30045,7 @@ fn coerceExtra(...@@ -30175,9 +30045,7 @@ fn coerceExtra(
30175 const val = maybe_inst_val orelse {30045 const val = maybe_inst_val orelse {
30176 if (dest_ty.zigTypeTag(zcu) == .comptime_float) {30046 if (dest_ty.zigTypeTag(zcu) == .comptime_float) {
30177 if (!opts.report_err) return error.NotCoercible;30047 if (!opts.report_err) return error.NotCoercible;
30178 return sema.failWithNeededComptime(block, inst_src, .{30048 return sema.failWithNeededComptime(block, inst_src, .{ .simple = .casted_to_comptime_float });
30179 .needed_comptime_reason = "value being casted to 'comptime_float' must be comptime-known",
30180 });
30181 }30049 }
30182 break :int;30050 break :int;
30183 };30051 };
...@@ -32435,9 +32303,7 @@ fn coerceTupleToStruct(...@@ -32435,9 +32303,7 @@ fn coerceTupleToStruct(
32435 field_refs[struct_field_index] = coerced;32303 field_refs[struct_field_index] = coerced;
32436 if (struct_type.fieldIsComptime(ip, struct_field_index)) {32304 if (struct_type.fieldIsComptime(ip, struct_field_index)) {
32437 const init_val = try sema.resolveValue(coerced) orelse {32305 const init_val = try sema.resolveValue(coerced) orelse {
32438 return sema.failWithNeededComptime(block, field_src, .{32306 return sema.failWithNeededComptime(block, field_src, .{ .simple = .stored_to_comptime_field });
32439 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
32440 });
32441 };32307 };
3244232308
32443 const field_init = Value.fromInterned(struct_type.field_inits.get(ip)[struct_field_index]);32309 const field_init = Value.fromInterned(struct_type.field_inits.get(ip)[struct_field_index]);
...@@ -32550,9 +32416,7 @@ fn coerceTupleToTuple(...@@ -32550,9 +32416,7 @@ fn coerceTupleToTuple(
32550 field_refs[field_index] = coerced;32416 field_refs[field_index] = coerced;
32551 if (default_val != .none) {32417 if (default_val != .none) {
32552 const init_val = (try sema.resolveValue(coerced)) orelse {32418 const init_val = (try sema.resolveValue(coerced)) orelse {
32553 return sema.failWithNeededComptime(block, field_src, .{32419 return sema.failWithNeededComptime(block, field_src, .{ .simple = .stored_to_comptime_field });
32554 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
32555 });
32556 };32420 };
3255732421
32558 if (!init_val.eql(Value.fromInterned(default_val), Type.fromInterned(field_ty), pt.zcu)) {32422 if (!init_val.eql(Value.fromInterned(default_val), Type.fromInterned(field_ty), pt.zcu)) {
...@@ -32816,12 +32680,12 @@ fn analyzeRef(...@@ -32816,12 +32680,12 @@ fn analyzeRef(
32816 // In a comptime context, the store would fail, since the operand is runtime-known. But that's32680 // In a comptime context, the store would fail, since the operand is runtime-known. But that's
32817 // okay; we don't actually need this store to succeed, since we're creating a runtime value in a32681 // okay; we don't actually need this store to succeed, since we're creating a runtime value in a
32818 // comptime scope, so the value can never be used aside from to get its type.32682 // comptime scope, so the value can never be used aside from to get its type.
32819 if (!block.is_comptime) {32683 if (!block.isComptime()) {
32820 try sema.storePtr(block, src, alloc, operand);32684 try sema.storePtr(block, src, alloc, operand);
32821 }32685 }
3282232686
32823 // Cast to the constant pointer type. We do this directly rather than going via `coerce` to32687 // Cast to the constant pointer type. We do this directly rather than going via `coerce` to
32824 // avoid errors in the `block.is_comptime` case.32688 // avoid errors in the `block.isComptime()` case.
32825 return block.addBitCast(ptr_type, alloc);32689 return block.addBitCast(ptr_type, alloc);
32826}32690}
3282732691
...@@ -33184,24 +33048,24 @@ fn analyzeSlice(...@@ -33184,24 +33048,24 @@ fn analyzeSlice(
33184 array_ty = double_child_ty;33048 array_ty = double_child_ty;
33185 elem_ty = double_child_ty.childType(zcu);33049 elem_ty = double_child_ty.childType(zcu);
33186 } else {33050 } else {
33187 const bounds_error_message = "slice of single-item pointer must have comptime-known bounds [0..0], [0..1], or [1..1]";
33188 if (uncasted_end_opt == .none) {33051 if (uncasted_end_opt == .none) {
33189 return sema.fail(block, src, bounds_error_message, .{});33052 return sema.fail(block, src, "slice of single-item pointer must be bounded", .{});
33190 }33053 }
33191 const start_value = try sema.resolveConstDefinedValue(33054 const start_value = try sema.resolveConstDefinedValue(
33192 block,33055 block,
33193 start_src,33056 start_src,
33194 uncasted_start,33057 uncasted_start,
33195 .{ .needed_comptime_reason = bounds_error_message },33058 .{ .simple = .slice_single_item_ptr_bounds },
33196 );33059 );
3319733060
33198 const end_value = try sema.resolveConstDefinedValue(33061 const end_value = try sema.resolveConstDefinedValue(
33199 block,33062 block,
33200 end_src,33063 end_src,
33201 uncasted_end_opt,33064 uncasted_end_opt,
33202 .{ .needed_comptime_reason = bounds_error_message },33065 .{ .simple = .slice_single_item_ptr_bounds },
33203 );33066 );
3320433067
33068 const bounds_error_message = "slice of single-item pointer must have bounds [0..0], [0..1], or [1..1]";
33205 if (try sema.compareScalar(start_value, .neq, end_value, Type.comptime_int)) {33069 if (try sema.compareScalar(start_value, .neq, end_value, Type.comptime_int)) {
33206 if (try sema.compareScalar(start_value, .neq, Value.zero_comptime_int, Type.comptime_int)) {33070 if (try sema.compareScalar(start_value, .neq, Value.zero_comptime_int, Type.comptime_int)) {
33207 const msg = msg: {33071 const msg = msg: {
...@@ -33416,9 +33280,7 @@ fn analyzeSlice(...@@ -33416,9 +33280,7 @@ fn analyzeSlice(
33416 if (sentinel_opt != .none) {33280 if (sentinel_opt != .none) {
33417 const casted = try sema.coerce(block, elem_ty, sentinel_opt, sentinel_src);33281 const casted = try sema.coerce(block, elem_ty, sentinel_opt, sentinel_src);
33418 try checkSentinelType(sema, block, sentinel_src, elem_ty);33282 try checkSentinelType(sema, block, sentinel_src, elem_ty);
33419 break :s try sema.resolveConstDefinedValue(block, sentinel_src, casted, .{33283 break :s try sema.resolveConstDefinedValue(block, sentinel_src, casted, .{ .simple = .slice_sentinel });
33420 .needed_comptime_reason = "slice sentinel must be comptime-known",
33421 });
33422 }33284 }
33423 // If we are slicing to the end of something that is sentinel-terminated33285 // If we are slicing to the end of something that is sentinel-terminated
33424 // then the resulting slice type is also sentinel-terminated.33286 // then the resulting slice type is also sentinel-terminated.
...@@ -33499,9 +33361,9 @@ fn analyzeSlice(...@@ -33499,9 +33361,9 @@ fn analyzeSlice(
33499 runtime_src = end_src;33361 runtime_src = end_src;
33500 }33362 }
3350133363
33502 if (!checked_start_lte_end and block.wantSafety() and !block.is_comptime) {33364 if (!checked_start_lte_end and block.wantSafety() and !block.isComptime()) {
33503 // requirement: start <= end33365 // requirement: start <= end
33504 assert(!block.is_comptime);33366 assert(!block.isComptime());
33505 try sema.requireRuntimeBlock(block, src, runtime_src.?);33367 try sema.requireRuntimeBlock(block, src, runtime_src.?);
33506 const ok = try block.addBinOp(.cmp_lte, start, end);33368 const ok = try block.addBinOp(.cmp_lte, start, end);
33507 try sema.addSafetyCheckCall(block, src, ok, "startGreaterThanEnd", &.{ start, end });33369 try sema.addSafetyCheckCall(block, src, ok, "startGreaterThanEnd", &.{ start, end });
...@@ -35859,7 +35721,7 @@ fn backingIntType(...@@ -35859,7 +35721,7 @@ fn backingIntType(
35859 .namespace = struct_type.namespace,35721 .namespace = struct_type.namespace,
35860 .instructions = .{},35722 .instructions = .{},
35861 .inlining = null,35723 .inlining = null,
35862 .is_comptime = true,35724 .comptime_reason = null, // set below if needed
35863 .src_base_inst = struct_type.zir_index,35725 .src_base_inst = struct_type.zir_index,
35864 .type_name_ctx = struct_type.name,35726 .type_name_ctx = struct_type.name,
35865 };35727 };
...@@ -35899,6 +35761,10 @@ fn backingIntType(...@@ -35899,6 +35761,10 @@ fn backingIntType(
35899 .base_node_inst = struct_type.zir_index,35761 .base_node_inst = struct_type.zir_index,
35900 .offset = .{ .node_offset_container_tag = 0 },35762 .offset = .{ .node_offset_container_tag = 0 },
35901 };35763 };
35764 block.comptime_reason = .{ .reason = .{
35765 .src = backing_int_src,
35766 .r = .{ .simple = .type },
35767 } };
35902 const backing_int_ty = blk: {35768 const backing_int_ty = blk: {
35903 if (backing_int_body_len == 0) {35769 if (backing_int_body_len == 0) {
35904 const backing_int_ref: Zir.Inst.Ref = @enumFromInt(zir.extra[extra_index]);35770 const backing_int_ref: Zir.Inst.Ref = @enumFromInt(zir.extra[extra_index]);
...@@ -36512,7 +36378,13 @@ fn structFields(...@@ -36512,7 +36378,13 @@ fn structFields(
36512 .namespace = namespace_index,36378 .namespace = namespace_index,
36513 .instructions = .{},36379 .instructions = .{},
36514 .inlining = null,36380 .inlining = null,
36515 .is_comptime = true,36381 .comptime_reason = .{ .reason = .{
36382 .src = .{
36383 .base_node_inst = struct_type.zir_index,
36384 .offset = .nodeOffset(0),
36385 },
36386 .r = .{ .simple = .struct_fields },
36387 } },
36516 .src_base_inst = struct_type.zir_index,36388 .src_base_inst = struct_type.zir_index,
36517 .type_name_ctx = struct_type.name,36389 .type_name_ctx = struct_type.name,
36518 };36390 };
...@@ -36698,7 +36570,7 @@ fn structFieldInits(...@@ -36698,7 +36570,7 @@ fn structFieldInits(
36698 .namespace = namespace_index,36570 .namespace = namespace_index,
36699 .instructions = .{},36571 .instructions = .{},
36700 .inlining = null,36572 .inlining = null,
36701 .is_comptime = true,36573 .comptime_reason = undefined, // set when `block_scope` is used
36702 .src_base_inst = struct_type.zir_index,36574 .src_base_inst = struct_type.zir_index,
36703 .type_name_ctx = struct_type.name,36575 .type_name_ctx = struct_type.name,
36704 };36576 };
...@@ -36776,13 +36648,13 @@ fn structFieldInits(...@@ -36776,13 +36648,13 @@ fn structFieldInits(
36776 .offset = .{ .container_field_value = @intCast(field_i) },36648 .offset = .{ .container_field_value = @intCast(field_i) },
36777 };36649 };
3677836650
36651 block_scope.comptime_reason = .{ .reason = .{
36652 .src = init_src,
36653 .r = .{ .simple = .struct_field_default_value },
36654 } };
36779 const init = try sema.resolveInlineBody(&block_scope, body, zir_index);36655 const init = try sema.resolveInlineBody(&block_scope, body, zir_index);
36780 const coerced = try sema.coerce(&block_scope, field_ty, init, init_src);36656 const coerced = try sema.coerce(&block_scope, field_ty, init, init_src);
36781 const default_val = try sema.resolveValue(coerced) orelse {36657 const default_val = try sema.resolveConstValue(&block_scope, init_src, coerced, null);
36782 return sema.failWithNeededComptime(&block_scope, init_src, .{
36783 .needed_comptime_reason = "struct field default value must be comptime-known",
36784 });
36785 };
3678636658
36787 if (default_val.canMutateComptimeVarState(zcu)) {36659 if (default_val.canMutateComptimeVarState(zcu)) {
36788 return sema.fail(&block_scope, init_src, "field default value contains reference to comptime-mutable memory", .{});36660 return sema.fail(&block_scope, init_src, "field default value contains reference to comptime-mutable memory", .{});
...@@ -36850,20 +36722,26 @@ fn unionFields(...@@ -36850,20 +36722,26 @@ fn unionFields(
36850 const body = zir.bodySlice(extra_index, body_len);36722 const body = zir.bodySlice(extra_index, body_len);
36851 extra_index += body.len;36723 extra_index += body.len;
3685236724
36725 const src: LazySrcLoc = .{
36726 .base_node_inst = union_type.zir_index,
36727 .offset = .nodeOffset(0),
36728 };
36729
36853 var block_scope: Block = .{36730 var block_scope: Block = .{
36854 .parent = null,36731 .parent = null,
36855 .sema = sema,36732 .sema = sema,
36856 .namespace = union_type.namespace,36733 .namespace = union_type.namespace,
36857 .instructions = .{},36734 .instructions = .{},
36858 .inlining = null,36735 .inlining = null,
36859 .is_comptime = true,36736 .comptime_reason = .{ .reason = .{
36737 .src = src,
36738 .r = .{ .simple = .union_fields },
36739 } },
36860 .src_base_inst = union_type.zir_index,36740 .src_base_inst = union_type.zir_index,
36861 .type_name_ctx = union_type.name,36741 .type_name_ctx = union_type.name,
36862 };36742 };
36863 defer assert(block_scope.instructions.items.len == 0);36743 defer assert(block_scope.instructions.items.len == 0);
3686436744
36865 const src = block_scope.nodeOffset(0);
36866
36867 if (body.len != 0) {36745 if (body.len != 0) {
36868 _ = try sema.analyzeInlineBody(&block_scope, body, zir_index);36746 _ = try sema.analyzeInlineBody(&block_scope, body, zir_index);
36869 }36747 }
...@@ -36993,9 +36871,7 @@ fn unionFields(...@@ -36993,9 +36871,7 @@ fn unionFields(
36993 if (enum_field_vals.capacity() > 0) {36871 if (enum_field_vals.capacity() > 0) {
36994 const enum_tag_val = if (tag_ref != .none) blk: {36872 const enum_tag_val = if (tag_ref != .none) blk: {
36995 const coerced = try sema.coerce(&block_scope, int_tag_ty, tag_ref, value_src);36873 const coerced = try sema.coerce(&block_scope, int_tag_ty, tag_ref, value_src);
36996 const val = try sema.resolveConstDefinedValue(&block_scope, value_src, coerced, .{36874 const val = try sema.resolveConstDefinedValue(&block_scope, value_src, coerced, .{ .simple = .enum_field_tag_value });
36997 .needed_comptime_reason = "enum tag value must be comptime-known",
36998 });
36999 last_tag_val = val;36875 last_tag_val = val;
3700036876
37001 break :blk val;36877 break :blk val;
...@@ -37669,9 +37545,7 @@ pub fn analyzeAsAddressSpace(...@@ -37669,9 +37545,7 @@ pub fn analyzeAsAddressSpace(
37669 const zcu = pt.zcu;37545 const zcu = pt.zcu;
37670 const addrspace_ty = try sema.getBuiltinType("AddressSpace");37546 const addrspace_ty = try sema.getBuiltinType("AddressSpace");
37671 const coerced = try sema.coerce(block, addrspace_ty, air_ref, src);37547 const coerced = try sema.coerce(block, addrspace_ty, air_ref, src);
37672 const addrspace_val = try sema.resolveConstDefinedValue(block, src, coerced, .{37548 const addrspace_val = try sema.resolveConstDefinedValue(block, src, coerced, .{ .simple = .@"addrspace" });
37673 .needed_comptime_reason = "address space must be comptime-known",
37674 });
37675 const address_space = zcu.toEnum(std.builtin.AddressSpace, addrspace_val);37549 const address_space = zcu.toEnum(std.builtin.AddressSpace, addrspace_val);
37676 const target = pt.zcu.getTarget();37550 const target = pt.zcu.getTarget();
37677 const arch = target.cpu.arch;37551 const arch = target.cpu.arch;
...@@ -38560,7 +38434,7 @@ fn sliceToIpString(...@@ -38560,7 +38434,7 @@ fn sliceToIpString(
38560 block: *Block,38434 block: *Block,
38561 src: LazySrcLoc,38435 src: LazySrcLoc,
38562 slice_val: Value,38436 slice_val: Value,
38563 reason: NeededComptimeReason,38437 reason: ComptimeReason,
38564) CompileError!InternPool.NullTerminatedString {38438) CompileError!InternPool.NullTerminatedString {
38565 const pt = sema.pt;38439 const pt = sema.pt;
38566 const zcu = pt.zcu;38440 const zcu = pt.zcu;
...@@ -38580,7 +38454,7 @@ fn derefSliceAsArray(...@@ -38580,7 +38454,7 @@ fn derefSliceAsArray(
38580 block: *Block,38454 block: *Block,
38581 src: LazySrcLoc,38455 src: LazySrcLoc,
38582 slice_val: Value,38456 slice_val: Value,
38583 reason: NeededComptimeReason,38457 reason: ComptimeReason,
38584) CompileError!Value {38458) CompileError!Value {
38585 return try sema.maybeDerefSliceAsArray(block, src, slice_val) orelse {38459 return try sema.maybeDerefSliceAsArray(block, src, slice_val) orelse {
38586 return sema.failWithNeededComptime(block, src, reason);38460 return sema.failWithNeededComptime(block, src, reason);
...@@ -38734,7 +38608,10 @@ pub fn resolveDeclaredEnum(...@@ -38734,7 +38608,10 @@ pub fn resolveDeclaredEnum(
38734 .namespace = namespace,38608 .namespace = namespace,
38735 .instructions = .{},38609 .instructions = .{},
38736 .inlining = null,38610 .inlining = null,
38737 .is_comptime = true,38611 .comptime_reason = .{ .reason = .{
38612 .src = src,
38613 .r = .{ .simple = .enum_fields },
38614 } },
38738 .src_base_inst = tracked_inst,38615 .src_base_inst = tracked_inst,
38739 .type_name_ctx = type_name,38616 .type_name_ctx = type_name,
38740 };38617 };
...@@ -38798,9 +38675,7 @@ pub fn resolveDeclaredEnum(...@@ -38798,9 +38675,7 @@ pub fn resolveDeclaredEnum(
38798 last_tag_val = try sema.resolveConstDefinedValue(&block, .{38675 last_tag_val = try sema.resolveConstDefinedValue(&block, .{
38799 .base_node_inst = tracked_inst,38676 .base_node_inst = tracked_inst,
38800 .offset = .{ .container_field_name = field_i },38677 .offset = .{ .container_field_name = field_i },
38801 }, tag_inst, .{38678 }, tag_inst, .{ .simple = .enum_field_tag_value });
38802 .needed_comptime_reason = "enum tag value must be comptime-known",
38803 });
38804 if (!(try sema.intFitsInType(last_tag_val.?, int_tag_ty, null))) break :overflow true;38679 if (!(try sema.intFitsInType(last_tag_val.?, int_tag_ty, null))) break :overflow true;
38805 last_tag_val = try pt.getCoerced(last_tag_val.?, int_tag_ty);38680 last_tag_val = try pt.getCoerced(last_tag_val.?, int_tag_ty);
38806 if (wip_ty.nextField(ip, field_name, last_tag_val.?.toIntern())) |conflict| {38681 if (wip_ty.nextField(ip, field_name, last_tag_val.?.toIntern())) |conflict| {
...@@ -38879,9 +38754,7 @@ fn getPanicInnerFn(...@@ -38879,9 +38754,7 @@ fn getPanicInnerFn(
38879 const inner_name_ip = try ip.getOrPutString(gpa, pt.tid, inner_name, .no_embedded_nulls);38754 const inner_name_ip = try ip.getOrPutString(gpa, pt.tid, inner_name, .no_embedded_nulls);
38880 const opt_fn_ref = try namespaceLookupVal(sema, block, src, outer_ty.getNamespaceIndex(zcu), inner_name_ip);38755 const opt_fn_ref = try namespaceLookupVal(sema, block, src, outer_ty.getNamespaceIndex(zcu), inner_name_ip);
38881 const fn_ref = opt_fn_ref orelse return sema.fail(block, src, "std.builtin.Panic missing {s}", .{inner_name});38756 const fn_ref = opt_fn_ref orelse return sema.fail(block, src, "std.builtin.Panic missing {s}", .{inner_name});
38882 const fn_val = try sema.resolveConstValue(block, src, fn_ref, .{38757 const fn_val = try sema.resolveConstValue(block, src, fn_ref, .{ .simple = .panic_handler });
38883 .needed_comptime_reason = "panic handler must be comptime-known",
38884 });
38885 if (fn_val.typeOf(zcu).zigTypeTag(zcu) != .@"fn") {38758 if (fn_val.typeOf(zcu).zigTypeTag(zcu) != .@"fn") {
38886 return sema.fail(block, src, "std.builtin.Panic.{s} is not a function", .{inner_name});38759 return sema.fail(block, src, "std.builtin.Panic.{s} is not a function", .{inner_name});
38887 }38760 }
...@@ -38963,9 +38836,7 @@ pub fn resolveNavPtrModifiers(...@@ -38963,9 +38836,7 @@ pub fn resolveNavPtrModifiers(
38963 const @"linksection": InternPool.OptionalNullTerminatedString = ls: {38836 const @"linksection": InternPool.OptionalNullTerminatedString = ls: {
38964 const linksection_body = zir_decl.linksection_body orelse break :ls .none;38837 const linksection_body = zir_decl.linksection_body orelse break :ls .none;
38965 const linksection_ref = try sema.resolveInlineBody(block, linksection_body, decl_inst);38838 const linksection_ref = try sema.resolveInlineBody(block, linksection_body, decl_inst);
38966 const bytes = try sema.toConstString(block, section_src, linksection_ref, .{38839 const bytes = try sema.toConstString(block, section_src, linksection_ref, .{ .simple = .@"linksection" });
38967 .needed_comptime_reason = "linksection must be comptime-known",
38968 });
38969 if (std.mem.indexOfScalar(u8, bytes, 0) != null) {38840 if (std.mem.indexOfScalar(u8, bytes, 0) != null) {
38970 return sema.fail(block, section_src, "linksection cannot contain null bytes", .{});38841 return sema.fail(block, section_src, "linksection cannot contain null bytes", .{});
38971 } else if (bytes.len == 0) {38842 } else if (bytes.len == 0) {
src/Zcu/PerThread.zig+22-6
...@@ -682,7 +682,13 @@ fn analyzeComptimeUnit(pt: Zcu.PerThread, cu_id: InternPool.ComptimeUnit.Id) Zcu...@@ -682,7 +682,13 @@ fn analyzeComptimeUnit(pt: Zcu.PerThread, cu_id: InternPool.ComptimeUnit.Id) Zcu
682 .namespace = comptime_unit.namespace,682 .namespace = comptime_unit.namespace,
683 .instructions = .{},683 .instructions = .{},
684 .inlining = null,684 .inlining = null,
685 .is_comptime = true,685 .comptime_reason = .{ .reason = .{
686 .src = .{
687 .base_node_inst = comptime_unit.zir_index,
688 .offset = .{ .token_offset = 0 },
689 },
690 .r = .{ .simple = .comptime_keyword },
691 } },
686 .src_base_inst = comptime_unit.zir_index,692 .src_base_inst = comptime_unit.zir_index,
687 .type_name_ctx = try ip.getOrPutStringFmt(gpa, pt.tid, "{}.comptime", .{693 .type_name_ctx = try ip.getOrPutStringFmt(gpa, pt.tid, "{}.comptime", .{
688 Type.fromInterned(zcu.namespacePtr(comptime_unit.namespace).owner_type).containerTypeName(ip).fmt(ip),694 Type.fromInterned(zcu.namespacePtr(comptime_unit.namespace).owner_type).containerTypeName(ip).fmt(ip),
...@@ -878,7 +884,7 @@ fn analyzeNavVal(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileErr...@@ -878,7 +884,7 @@ fn analyzeNavVal(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileErr
878 .namespace = old_nav.analysis.?.namespace,884 .namespace = old_nav.analysis.?.namespace,
879 .instructions = .{},885 .instructions = .{},
880 .inlining = null,886 .inlining = null,
881 .is_comptime = true,887 .comptime_reason = undefined, // set below
882 .src_base_inst = old_nav.analysis.?.zir_index,888 .src_base_inst = old_nav.analysis.?.zir_index,
883 .type_name_ctx = old_nav.fqn,889 .type_name_ctx = old_nav.fqn,
884 };890 };
...@@ -893,6 +899,11 @@ fn analyzeNavVal(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileErr...@@ -893,6 +899,11 @@ fn analyzeNavVal(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileErr
893 const section_src = block.src(.{ .node_offset_var_decl_section = 0 });899 const section_src = block.src(.{ .node_offset_var_decl_section = 0 });
894 const addrspace_src = block.src(.{ .node_offset_var_decl_addrspace = 0 });900 const addrspace_src = block.src(.{ .node_offset_var_decl_addrspace = 0 });
895901
902 block.comptime_reason = .{ .reason = .{
903 .src = init_src,
904 .r = .{ .simple = .container_var_init },
905 } };
906
896 const maybe_ty: ?Type = if (zir_decl.type_body != null) ty: {907 const maybe_ty: ?Type = if (zir_decl.type_body != null) ty: {
897 // Since we have a type body, the type is resolved separately!908 // Since we have a type body, the type is resolved separately!
898 // Of course, we need to make sure we depend on it properly.909 // Of course, we need to make sure we depend on it properly.
...@@ -1253,7 +1264,7 @@ fn analyzeNavType(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileEr...@@ -1253,7 +1264,7 @@ fn analyzeNavType(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileEr
1253 .namespace = old_nav.analysis.?.namespace,1264 .namespace = old_nav.analysis.?.namespace,
1254 .instructions = .{},1265 .instructions = .{},
1255 .inlining = null,1266 .inlining = null,
1256 .is_comptime = true,1267 .comptime_reason = undefined, // set below
1257 .src_base_inst = old_nav.analysis.?.zir_index,1268 .src_base_inst = old_nav.analysis.?.zir_index,
1258 .type_name_ctx = old_nav.fqn,1269 .type_name_ctx = old_nav.fqn,
1259 };1270 };
...@@ -1262,6 +1273,13 @@ fn analyzeNavType(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileEr...@@ -1262,6 +1273,13 @@ fn analyzeNavType(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileEr
1262 const zir_decl = zir.getDeclaration(inst_resolved.inst);1273 const zir_decl = zir.getDeclaration(inst_resolved.inst);
1263 assert(old_nav.is_usingnamespace == (zir_decl.kind == .@"usingnamespace"));1274 assert(old_nav.is_usingnamespace == (zir_decl.kind == .@"usingnamespace"));
12641275
1276 const ty_src = block.src(.{ .node_offset_var_decl_ty = 0 });
1277
1278 block.comptime_reason = .{ .reason = .{
1279 .src = ty_src,
1280 .r = .{ .simple = .type },
1281 } };
1282
1265 const type_body = zir_decl.type_body orelse {1283 const type_body = zir_decl.type_body orelse {
1266 // The type of this `Nav` is inferred from the value.1284 // The type of this `Nav` is inferred from the value.
1267 // In other words, this `nav_ty` depends on the corresponding `nav_val`.1285 // In other words, this `nav_ty` depends on the corresponding `nav_val`.
...@@ -1279,8 +1297,6 @@ fn analyzeNavType(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileEr...@@ -1279,8 +1297,6 @@ fn analyzeNavType(pt: Zcu.PerThread, nav_id: InternPool.Nav.Index) Zcu.CompileEr
1279 return .{ .type_changed = true };1297 return .{ .type_changed = true };
1280 };1298 };
12811299
1282 const ty_src = block.src(.{ .node_offset_var_decl_ty = 0 });
1283
1284 const resolved_ty: Type = ty: {1300 const resolved_ty: Type = ty: {
1285 const uncoerced_type_ref = try sema.resolveInlineBody(&block, type_body, inst_resolved.inst);1301 const uncoerced_type_ref = try sema.resolveInlineBody(&block, type_body, inst_resolved.inst);
1286 const type_ref = try sema.coerce(&block, .type, uncoerced_type_ref, ty_src);1302 const type_ref = try sema.coerce(&block, .type, uncoerced_type_ref, ty_src);
...@@ -2442,7 +2458,7 @@ fn analyzeFnBodyInner(pt: Zcu.PerThread, func_index: InternPool.Index) Zcu.SemaE...@@ -2442,7 +2458,7 @@ fn analyzeFnBodyInner(pt: Zcu.PerThread, func_index: InternPool.Index) Zcu.SemaE
2442 .namespace = decl_nav.analysis.?.namespace,2458 .namespace = decl_nav.analysis.?.namespace,
2443 .instructions = .{},2459 .instructions = .{},
2444 .inlining = null,2460 .inlining = null,
2445 .is_comptime = false,2461 .comptime_reason = null,
2446 .src_base_inst = decl_nav.analysis.?.zir_index,2462 .src_base_inst = decl_nav.analysis.?.zir_index,
2447 .type_name_ctx = func_nav.fqn,2463 .type_name_ctx = func_nav.fqn,
2448 };2464 };
src/print_zir.zig+11-4
...@@ -273,6 +273,7 @@ const Writer = struct {...@@ -273,6 +273,7 @@ const Writer = struct {
273 .@"await",273 .@"await",
274 .make_ptr_const,274 .make_ptr_const,
275 .validate_deref,275 .validate_deref,
276 .validate_const,
276 .check_comptime_control_flow,277 .check_comptime_control_flow,
277 .opt_eu_base_ptr_init,278 .opt_eu_base_ptr_init,
278 .restore_err_ret_index_unconditional,279 .restore_err_ret_index_unconditional,
...@@ -437,7 +438,6 @@ const Writer = struct {...@@ -437,7 +438,6 @@ const Writer = struct {
437 .field_call => try self.writeCall(stream, inst, .field),438 .field_call => try self.writeCall(stream, inst, .field),
438439
439 .block,440 .block,
440 .block_comptime,
441 .block_inline,441 .block_inline,
442 .suspend_block,442 .suspend_block,
443 .loop,443 .loop,
...@@ -445,6 +445,8 @@ const Writer = struct {...@@ -445,6 +445,8 @@ const Writer = struct {
445 .typeof_builtin,445 .typeof_builtin,
446 => try self.writeBlock(stream, inst),446 => try self.writeBlock(stream, inst),
447447
448 .block_comptime => try self.writeBlockComptime(stream, inst),
449
448 .condbr,450 .condbr,
449 .condbr_inline,451 .condbr_inline,
450 => try self.writeCondBr(stream, inst),452 => try self.writeCondBr(stream, inst),
...@@ -1343,16 +1345,21 @@ const Writer = struct {...@@ -1343,16 +1345,21 @@ const Writer = struct {
13431345
1344 fn writeBlock(self: *Writer, stream: anytype, inst: Zir.Inst.Index) !void {1346 fn writeBlock(self: *Writer, stream: anytype, inst: Zir.Inst.Index) !void {
1345 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1347 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1346 try self.writePlNodeBlockWithoutSrc(stream, inst);1348 const extra = self.code.extraData(Zir.Inst.Block, inst_data.payload_index);
1349 const body = self.code.bodySlice(extra.end, extra.data.body_len);
1350 try self.writeBracedBody(stream, body);
1351 try stream.writeAll(") ");
1347 try self.writeSrcNode(stream, inst_data.src_node);1352 try self.writeSrcNode(stream, inst_data.src_node);
1348 }1353 }
13491354
1350 fn writePlNodeBlockWithoutSrc(self: *Writer, stream: anytype, inst: Zir.Inst.Index) !void {1355 fn writeBlockComptime(self: *Writer, stream: anytype, inst: Zir.Inst.Index) !void {
1351 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;1356 const inst_data = self.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1352 const extra = self.code.extraData(Zir.Inst.Block, inst_data.payload_index);1357 const extra = self.code.extraData(Zir.Inst.BlockComptime, inst_data.payload_index);
1353 const body = self.code.bodySlice(extra.end, extra.data.body_len);1358 const body = self.code.bodySlice(extra.end, extra.data.body_len);
1359 try stream.print("reason={s}, ", .{@tagName(extra.data.reason)});
1354 try self.writeBracedBody(stream, body);1360 try self.writeBracedBody(stream, body);
1355 try stream.writeAll(") ");1361 try stream.writeAll(") ");
1362 try self.writeSrcNode(stream, inst_data.src_node);
1356 }1363 }
13571364
1358 fn writeCondBr(self: *Writer, stream: anytype, inst: Zir.Inst.Index) !void {1365 fn writeCondBr(self: *Writer, stream: anytype, inst: Zir.Inst.Index) !void {
test/cases/compile_errors/address_of_threadlocal_not_comptime_known.zig+2-2
...@@ -10,5 +10,5 @@ pub export fn entry() void {...@@ -10,5 +10,5 @@ pub export fn entry() void {
10// target=native10// target=native
11//11//
12// :2:36: error: unable to resolve comptime value12// :2:36: error: unable to resolve comptime value
13// :2:36: note: global variable initializer must be comptime-known13// :2:36: note: initializer of container-level variable must be comptime-known
14// :2:36: note: thread local and dll imported variables have runtime-known addresses14// :2:36: note: threadlocal and dll imported variables have runtime-known addresses
test/cases/compile_errors/anytype_param_requires_comptime.zig+3-3
...@@ -13,8 +13,8 @@ pub export fn entry() void {...@@ -13,8 +13,8 @@ pub export fn entry() void {
13}13}
1414
15// error15// error
16// backend=stage2
17// target=native
18//16//
19// :7:25: error: unable to resolve comptime value17// :7:25: error: unable to resolve comptime value
20// :7:25: note: initializer of comptime only struct must be comptime-known18// :7:25: note: initializer of comptime-only struct 'tmp.S.foo__anon_166.C' must be comptime-known
19// :4:16: note: struct requires comptime because of this field
20// :4:16: note: types are not available at runtime
test/cases/compile_errors/array_mult_with_number_type.zig+4-5
...@@ -1,10 +1,9 @@...@@ -1,10 +1,9 @@
1export fn entry(base: f32, exponent: f32) f32 {1const exponent: f32 = 1.0;
2export fn entry(base: f32) f32 {
2 return base ** exponent;3 return base ** exponent;
3}4}
45
5// error6// error
6// backend=stage2
7// target=native
8//7//
9// :2:12: error: expected indexable; found 'f32'8// :3:12: error: expected indexable; found 'f32'
10// :2:17: note: this operator multiplies arrays; use std.math.pow for exponentiation9// :3:17: note: this operator multiplies arrays; use std.math.pow for exponentiation
test/cases/compile_errors/asm_at_compile_time.zig+2-1
...@@ -15,4 +15,5 @@ fn doSomeAsm() void {...@@ -15,4 +15,5 @@ fn doSomeAsm() void {
15// target=native15// target=native
16//16//
17// :6:5: error: unable to evaluate comptime expression17// :6:5: error: unable to evaluate comptime expression
18// :2:14: note: called from here18// :2:14: note: called at comptime from here
19// :1:1: note: 'comptime' keyword forces comptime evaluation
test/cases/compile_errors/attempted_double_pipe_on_boolean_values.zig+3-5
...@@ -1,13 +1,11 @@...@@ -1,13 +1,11 @@
1export fn entry(a: bool, b: bool) i32 {1export fn entry() i32 {
2 if (a || b) {2 if (true || false) {
3 return 1234;3 return 1234;
4 }4 }
5 return 5678;5 return 5678;
6}6}
77
8// error8// error
9// backend=stage2
10// target=native
11//9//
12// :2:9: error: expected error set type, found 'bool'10// :2:9: error: expected error set type, found 'bool'
13// :2:11: note: '||' merges error sets; 'or' performs boolean OR11// :2:14: note: '||' merges error sets; 'or' performs boolean OR
test/cases/compile_errors/branch_in_comptime_only_scope_uses_condbr_inline.zig+2
...@@ -20,4 +20,6 @@ pub export fn entry2() void {...@@ -20,4 +20,6 @@ pub export fn entry2() void {
20//20//
21// :5:15: error: unable to evaluate comptime expression21// :5:15: error: unable to evaluate comptime expression
22// :5:13: note: operation is runtime due to this operand22// :5:13: note: operation is runtime due to this operand
23// :4:72: note: '@shuffle' mask must be comptime-known
23// :13:11: error: unable to evaluate comptime expression24// :13:11: error: unable to evaluate comptime expression
25// :12:72: note: '@shuffle' mask must be comptime-known
test/cases/compile_errors/builtin_extern_in_comptime_scope.zig+4-4
...@@ -11,8 +11,8 @@ pub export fn entry2() void {...@@ -11,8 +11,8 @@ pub export fn entry2() void {
11// target=native11// target=native
12//12//
13// :1:16: error: unable to resolve comptime value13// :1:16: error: unable to resolve comptime value
14// :1:16: note: global variable initializer must be comptime-known14// :1:16: note: initializer of container-level variable must be comptime-known
15// :1:16: note: thread local and dll imported variables have runtime-known addresses15// :1:16: note: threadlocal and dll imported variables have runtime-known addresses
16// :2:17: error: unable to resolve comptime value16// :2:17: error: unable to resolve comptime value
17// :2:17: note: global variable initializer must be comptime-known17// :2:17: note: initializer of container-level variable must be comptime-known
18// :2:17: note: thread local and dll imported variables have runtime-known addresses18// :2:17: note: threadlocal and dll imported variables have runtime-known addresses
test/cases/compile_errors/compile_time_struct_field.zig+8-9
...@@ -4,16 +4,15 @@ const S = struct {...@@ -4,16 +4,15 @@ const S = struct {
4};4};
55
6export fn a() void {6export fn a() void {
7 var value: u32 = 3;7 var value: u32 = 3;
8 const comptimeStruct = S {8 const comptimeStruct = S{
9 .normal_ptr = &value,9 .normal_ptr = &value,
10 };10 };
11 _ = comptimeStruct;11 _ = comptimeStruct;
12}12}
1313
14// error14// error
15// backend=stage2
16// target=native
17//15//
18// 9:6: error: unable to resolve comptime value16// :9:10: error: unable to resolve comptime value
19// 9:6: note: initializer of comptime only struct must be comptime-known17// :9:10: note: initializer of comptime-only struct 'tmp.S' must be comptime-known
18// :2:21: note: struct requires comptime because of this field
test/cases/compile_errors/condition_comptime_reason_explained.zig+4-8
...@@ -33,18 +33,14 @@ pub export fn entry2() void {...@@ -33,18 +33,14 @@ pub export fn entry2() void {
33}33}
3434
35// error35// error
36// backend=stage2
37// target=native
38//36//
39// :8:9: error: unable to resolve comptime value37// :8:9: error: unable to resolve comptime value
40// :8:9: note: condition in comptime branch must be comptime-known38// :19:15: note: called at comptime from here
41// :7:13: note: expression is evaluated at comptime because the function returns a comptime-only type 'tmp.S'39// :7:13: note: function with comptime-only return type 'tmp.S' is evaluated at comptime
42// :2:12: note: struct requires comptime because of this field40// :2:12: note: struct requires comptime because of this field
43// :2:12: note: use '*const fn () void' for a function pointer type41// :2:12: note: use '*const fn () void' for a function pointer type
44// :19:15: note: called from here
45// :22:13: error: unable to resolve comptime value42// :22:13: error: unable to resolve comptime value
46// :22:13: note: condition in comptime switch must be comptime-known43// :32:19: note: called at comptime from here
47// :21:17: note: expression is evaluated at comptime because the function returns a comptime-only type 'tmp.S'44// :21:17: note: function with comptime-only return type 'tmp.S' is evaluated at comptime
48// :2:12: note: struct requires comptime because of this field45// :2:12: note: struct requires comptime because of this field
49// :2:12: note: use '*const fn () void' for a function pointer type46// :2:12: note: use '*const fn () void' for a function pointer type
50// :32:19: note: called from here
test/cases/compile_errors/enum_backed_by_comptime_int_must_be_casted_from_comptime_value.zig+1-1
...@@ -11,4 +11,4 @@ export fn entry() void {...@@ -11,4 +11,4 @@ export fn entry() void {
11// target=native11// target=native
12//12//
13// :6:31: error: unable to resolve comptime value13// :6:31: error: unable to resolve comptime value
14// :6:31: note: value being casted to enum with 'comptime_int' tag type must be comptime-known14// :6:31: note: value casted to enum with 'comptime_int' tag type must be comptime-known
test/cases/compile_errors/error_in_typeof_param.zig+1-1
...@@ -11,4 +11,4 @@ pub export fn entry() void {...@@ -11,4 +11,4 @@ pub export fn entry() void {
11// target=native11// target=native
12//12//
13// :6:31: error: unable to resolve comptime value13// :6:31: error: unable to resolve comptime value
14// :6:31: note: value being casted to 'comptime_int' must be comptime-known14// :6:31: note: value casted to 'comptime_int' must be comptime-known
test/cases/compile_errors/explain_why_fn_is_called_at_comptime.zig+2-5
...@@ -4,7 +4,7 @@ const S = struct {...@@ -4,7 +4,7 @@ const S = struct {
4};4};
5fn bar() void {}5fn bar() void {}
66
7fn foo(comptime a: *u8) S {7fn foo(a: *u8) S {
8 return .{ .fnPtr = bar, .a = a.* };8 return .{ .fnPtr = bar, .a = a.* };
9}9}
10pub export fn entry() void {10pub export fn entry() void {
...@@ -13,11 +13,8 @@ pub export fn entry() void {...@@ -13,11 +13,8 @@ pub export fn entry() void {
13}13}
1414
15// error15// error
16// backend=stage2
17// target=native
18//16//
19// :12:13: error: unable to resolve comptime value17// :12:13: error: unable to resolve comptime value
20// :12:13: note: argument to function being called at comptime must be comptime-known18// :7:16: note: function with comptime-only return type 'tmp.S' is evaluated at comptime
21// :7:25: note: expression is evaluated at comptime because the function returns a comptime-only type 'tmp.S'
22// :2:12: note: struct requires comptime because of this field19// :2:12: note: struct requires comptime because of this field
23// :2:12: note: use '*const fn () void' for a function pointer type20// :2:12: note: use '*const fn () void' for a function pointer type
test/cases/compile_errors/explain_why_generic_fn_is_called_at_comptime.zig+3-4
...@@ -15,9 +15,8 @@ pub export fn entry() void {...@@ -15,9 +15,8 @@ pub export fn entry() void {
15 _ = foo(a, fn () void);15 _ = foo(a, fn () void);
16}16}
17// error17// error
18// backend=stage2
19// target=native
20//18//
21// :15:13: error: unable to resolve comptime value19// :15:13: error: unable to resolve comptime value
22// :15:13: note: argument to function being called at comptime must be comptime-known20// :9:38: note: generic function instantiated with comptime-only return type 'tmp.S(fn () void)' is evaluated at comptime
23// :9:38: note: expression is evaluated at comptime because the generic function was instantiated with a comptime-only return type21// :3:16: note: struct requires comptime because of this field
22// :3:16: note: use '*const fn () void' for a function pointer type
test/cases/compile_errors/global_var_struct_init_in_comptim_block.zig deleted-14
...@@ -1,14 +0,0 @@
1const Foo = struct {
2 x: i32,
3};
4var x: Foo = .{ .x = 2 };
5comptime {
6 x = .{ .x = 3 };
7}
8
9// error
10// backend=stage2
11// target=native
12//
13// :6:17: error: unable to evaluate comptime expression
14// :6:17: note: operation is runtime due to this operand
test/cases/compile_errors/global_var_struct_init_in_comptime_block.zig created+15
...@@ -0,0 +1,15 @@
1const Foo = struct {
2 x: i32,
3};
4var x: Foo = .{ .x = 2 };
5comptime {
6 x = .{ .x = 3 };
7}
8
9// error
10// backend=stage2
11// target=native
12//
13// :6:17: error: unable to evaluate comptime expression
14// :6:17: note: operation is runtime due to this operand
15// :5:1: note: 'comptime' keyword forces comptime evaluation
test/cases/compile_errors/global_variable_stored_in_global_const.zig+1-3
...@@ -5,8 +5,6 @@ pub export fn entry() void {...@@ -5,8 +5,6 @@ pub export fn entry() void {
5}5}
66
7// error7// error
8// backend=stage2
9// target=native
10//8//
11// :2:11: error: unable to resolve comptime value9// :2:11: error: unable to resolve comptime value
12// :2:11: note: global variable initializer must be comptime-known10// :2:11: note: initializer of container-level variable must be comptime-known
test/cases/compile_errors/incorrect_pointer_dereference_syntax.zig+1-4
...@@ -1,12 +1,9 @@...@@ -1,12 +1,9 @@
1pub export fn entry() void {1pub export fn entry() void {
2 var a: *u32 = undefined;2 const a: *u32 = undefined;
3 _ = *a;3 _ = *a;
4 _ = &a;
5}4}
65
7// error6// error
8// backend=stage2
9// target=native
10//7//
11// :3:10: error: expected type 'type', found '*u32'8// :3:10: error: expected type 'type', found '*u32'
12// :3:10: note: use '.*' to dereference pointer9// :3:10: note: use '.*' to dereference pointer
test/cases/compile_errors/inline_call_runtime_value_to_comptime_param.zig+1-1
...@@ -14,4 +14,4 @@ pub export fn entry() void {...@@ -14,4 +14,4 @@ pub export fn entry() void {
14// target=native14// target=native
15//15//
16// :5:18: error: unable to resolve comptime value16// :5:18: error: unable to resolve comptime value
17// :5:18: note: parameter is comptime17// :5:18: note: argument to comptime parameter must be comptime-known
test/cases/compile_errors/int-float_conversion_to_comptime_int-float.zig+2-4
...@@ -10,10 +10,8 @@ export fn bar() void {...@@ -10,10 +10,8 @@ export fn bar() void {
10}10}
1111
12// error12// error
13// backend=stage2
14// target=native
15//13//
16// :4:41: error: unable to resolve comptime value14// :4:41: error: unable to resolve comptime value
17// :4:41: note: value being casted to 'comptime_int' must be comptime-known15// :4:41: note: value casted to 'comptime_int' must be comptime-known
18// :9:43: error: unable to resolve comptime value16// :9:43: error: unable to resolve comptime value
19// :9:43: note: value being casted to 'comptime_float' must be comptime-known17// :9:43: note: value casted to 'comptime_float' must be comptime-known
test/cases/compile_errors/non-const_expression_function_call_with_struct_return_value_outside_function.zig+2-3
...@@ -13,9 +13,8 @@ export fn entry() usize {...@@ -13,9 +13,8 @@ export fn entry() usize {
13}13}
1414
15// error15// error
16// backend=stage2
17// target=native
18//16//
19// :6:24: error: unable to evaluate comptime expression17// :6:24: error: unable to evaluate comptime expression
20// :6:5: note: operation is runtime due to this operand18// :6:5: note: operation is runtime due to this operand
21// :4:17: note: called from here19// :4:17: note: called at comptime from here
20// :4:17: note: initializer of container-level variable must be comptime-known
test/cases/compile_errors/non-pure_function_returns_type.zig+2-1
...@@ -23,4 +23,5 @@ export fn function_with_return_type_type() void {...@@ -23,4 +23,5 @@ export fn function_with_return_type_type() void {
23//23//
24// :3:7: error: unable to evaluate comptime expression24// :3:7: error: unable to evaluate comptime expression
25// :3:5: note: operation is runtime due to this operand25// :3:5: note: operation is runtime due to this operand
26// :16:19: note: called from here26// :16:19: note: called at comptime from here
27// :16:19: note: types must be comptime-known
test/cases/compile_errors/non_comptime_param_in_comptime_function.zig+1-4
...@@ -9,10 +9,7 @@ export fn entry() void {...@@ -9,10 +9,7 @@ export fn entry() void {
9}9}
1010
11// error11// error
12// backend=stage2
13// target=native
14//12//
15// :8:11: error: unable to resolve comptime value13// :8:11: error: unable to resolve comptime value
16// :8:11: note: argument to function being called at comptime must be comptime-known14// :1:20: note: function with comptime-only return type 'type' is evaluated at comptime
17// :1:20: note: expression is evaluated at comptime because the function returns a comptime-only type 'type'
18// :1:20: note: types are not available at runtime15// :1:20: note: types are not available at runtime
test/cases/compile_errors/non_constant_expression_in_array_size.zig+2-2
...@@ -15,5 +15,5 @@ export fn entry() usize {...@@ -15,5 +15,5 @@ export fn entry() usize {
15// target=native15// target=native
16//16//
17// :6:12: error: unable to resolve comptime value17// :6:12: error: unable to resolve comptime value
18// :6:12: note: value being returned at comptime must be comptime-known18// :2:12: note: called at comptime from here
19// :2:12: note: called from here19// :1:13: note: struct fields must be comptime-known
test/cases/compile_errors/runtime_assignment_to_comptime_struct_type.zig+3-3
...@@ -10,8 +10,8 @@ export fn f() void {...@@ -10,8 +10,8 @@ export fn f() void {
10}10}
1111
12// error12// error
13// backend=stage2
14// target=native
15//13//
16// :7:23: error: unable to resolve comptime value14// :7:23: error: unable to resolve comptime value
17// :7:23: note: initializer of comptime only struct must be comptime-known15// :7:23: note: initializer of comptime-only struct 'tmp.Foo' must be comptime-known
16// :3:10: note: struct requires comptime because of this field
17// :3:10: note: types are not available at runtime
test/cases/compile_errors/runtime_assignment_to_comptime_union_type.zig+3-3
...@@ -10,8 +10,8 @@ export fn f() void {...@@ -10,8 +10,8 @@ export fn f() void {
10}10}
1111
12// error12// error
13// backend=stage2
14// target=native
15//13//
16// :8:23: error: unable to resolve comptime value14// :8:23: error: unable to resolve comptime value
17// :8:23: note: initializer of comptime only union must be comptime-known15// :8:23: note: initializer of comptime-only union 'tmp.Foo' must be comptime-known
16// :3:10: note: union requires comptime because of this field
17// :3:10: note: types are not available at runtime
test/cases/compile_errors/runtime_operation_in_comptime_scope.zig created+36
...@@ -0,0 +1,36 @@
1export fn entry1() void {
2 foo();
3}
4
5comptime {
6 qux();
7}
8
9inline fn foo() void {
10 _ = bar();
11}
12
13fn bar() type {
14 qux();
15 return u8;
16}
17
18fn qux() void {
19 rt = 123;
20}
21
22var rt: u32 = undefined;
23
24// error
25//
26// :19:8: error: unable to evaluate comptime expression
27// :19:5: note: operation is runtime due to this operand
28// :14:8: note: called at comptime from here
29// :10:12: note: called at comptime from here
30// :13:10: note: function with comptime-only return type 'type' is evaluated at comptime
31// :13:10: note: types are not available at runtime
32// :2:8: note: called from here
33// :19:8: error: unable to evaluate comptime expression
34// :19:5: note: operation is runtime due to this operand
35// :6:8: note: called at comptime from here
36// :5:1: note: 'comptime' keyword forces comptime evaluation
test/cases/compile_errors/runtime_to_comptime_num.zig+4-4
...@@ -26,10 +26,10 @@ pub export fn entry4() void {...@@ -26,10 +26,10 @@ pub export fn entry4() void {
26// target=native26// target=native
27//27//
28// :4:27: error: unable to resolve comptime value28// :4:27: error: unable to resolve comptime value
29// :4:27: note: value being casted to 'comptime_int' must be comptime-known29// :4:27: note: value casted to 'comptime_int' must be comptime-known
30// :9:29: error: unable to resolve comptime value30// :9:29: error: unable to resolve comptime value
31// :9:29: note: value being casted to 'comptime_float' must be comptime-known31// :9:29: note: value casted to 'comptime_float' must be comptime-known
32// :15:10: error: unable to resolve comptime value32// :15:10: error: unable to resolve comptime value
33// :15:10: note: value being casted to 'comptime_float' must be comptime-known33// :15:10: note: value casted to 'comptime_float' must be comptime-known
34// :21:10: error: unable to resolve comptime value34// :21:10: error: unable to resolve comptime value
35// :21:10: note: value being casted to 'comptime_int' must be comptime-known35// :21:10: note: value casted to 'comptime_int' must be comptime-known
test/cases/compile_errors/runtime_value_in_comptime_scope.zig created+61
...@@ -0,0 +1,61 @@
1var rt_val: [5]u32 = .{ 1, 2, 3, 4, 5 };
2
3comptime {
4 _ = rt_val; // fine
5}
6
7comptime {
8 const a = rt_val; // error
9 _ = a;
10}
11
12comptime {
13 const l = rt_val.len; // fine
14 @compileLog(l);
15}
16
17export fn foo() void {
18 _ = comptime rt_val; // error
19}
20
21export fn bar() void {
22 const l = comptime rt_val.len; // fine
23 @compileLog(l);
24}
25
26export fn baz() void {
27 const S = struct {
28 fn inner() void {
29 _ = comptime rt_val;
30 }
31 };
32 comptime S.inner(); // fine; inner comptime is a nop
33 S.inner(); // error
34}
35
36export fn qux() void {
37 const S = struct {
38 fn inner() void {
39 const a = rt_val;
40 _ = a;
41 }
42 };
43 S.inner(); // fine; everything is runtime
44 comptime S.inner(); // error
45}
46
47// error
48//
49// :8:15: error: unable to resolve comptime value
50// :7:1: note: 'comptime' keyword forces comptime evaluation
51// :18:9: error: unable to resolve comptime value
52// :18:9: note: 'comptime' keyword forces comptime evaluation
53// :29:17: error: unable to resolve comptime value
54// :29:17: note: 'comptime' keyword forces comptime evaluation
55// :39:23: error: unable to resolve comptime value
56// :44:21: note: called at comptime from here
57// :44:5: note: 'comptime' keyword forces comptime evaluation
58//
59// Compile Log Output:
60// @as(usize, 5)
61// @as(usize, 5)
test/cases/compile_errors/slice_of_single-item_pointer_bounds.zig+5-5
...@@ -31,13 +31,13 @@ export fn entry2() void {...@@ -31,13 +31,13 @@ export fn entry2() void {
3131
32// error32// error
33//33//
34// :5:12: error: slice of single-item pointer must have comptime-known bounds [0..0], [0..1], or [1..1]34// :5:12: error: slice of single-item pointer must be bounded
35// :9:13: error: slice of single-item pointer must have comptime-known bounds [0..0], [0..1], or [1..1]35// :9:13: error: slice of single-item pointer must have bounds [0..0], [0..1], or [1..1]
36// :9:13: note: expected '0', found '1'36// :9:13: note: expected '0', found '1'
37// :13:16: error: slice of single-item pointer must have comptime-known bounds [0..0], [0..1], or [1..1]37// :13:16: error: slice of single-item pointer must have bounds [0..0], [0..1], or [1..1]
38// :13:16: note: expected '1', found '2'38// :13:16: note: expected '1', found '2'
39// :17:16: error: end index 2 out of bounds for slice of single-item pointer39// :17:16: error: end index 2 out of bounds for slice of single-item pointer
40// :23:13: error: unable to resolve comptime value40// :23:13: error: unable to resolve comptime value
41// :23:13: note: slice of single-item pointer must have comptime-known bounds [0..0], [0..1], or [1..1]41// :23:13: note: slice of single-item pointer must have comptime-known bounds
42// :29:16: error: unable to resolve comptime value42// :29:16: error: unable to resolve comptime value
43// :29:16: note: slice of single-item pointer must have comptime-known bounds [0..0], [0..1], or [1..1]43// :29:16: note: slice of single-item pointer must have comptime-known bounds
test/cases/compile_errors/unable_to_evaluate_comptime_expr.zig+3-2
...@@ -33,12 +33,13 @@ pub export fn entry3() void {...@@ -33,12 +33,13 @@ pub export fn entry3() void {
33}33}
3434
35// error35// error
36// backend=stage2
37// target=native
38//36//
39// :7:13: error: unable to evaluate comptime expression37// :7:13: error: unable to evaluate comptime expression
40// :7:16: note: operation is runtime due to this operand38// :7:16: note: operation is runtime due to this operand
39// :7:13: note: initializer of container-level variable must be comptime-known
41// :13:13: error: unable to evaluate comptime expression40// :13:13: error: unable to evaluate comptime expression
42// :13:16: note: operation is runtime due to this operand41// :13:16: note: operation is runtime due to this operand
42// :13:13: note: initializer of container-level variable must be comptime-known
43// :22:9: error: unable to evaluate comptime expression43// :22:9: error: unable to evaluate comptime expression
44// :22:21: note: operation is runtime due to this operand44// :22:21: note: operation is runtime due to this operand
45// :21:13: note: enum fields must be comptime-known
test/cases/compile_errors/unable_to_evaluate_expr_inside_cimport.zig+1-1
...@@ -12,4 +12,4 @@ export fn entry() void {...@@ -12,4 +12,4 @@ export fn entry() void {
12//12//
13// :2:11: error: unable to evaluate comptime expression13// :2:11: error: unable to evaluate comptime expression
14// :2:13: note: operation is runtime due to this operand14// :2:13: note: operation is runtime due to this operand
15// :1:11: note: expression is evaluated at comptime because it is inside a @cImport15// :1:11: note: operand to '@cImport' is evaluated at comptime
test/compile_errors.zig+5-3
...@@ -57,8 +57,8 @@ pub fn addCases(ctx: *Cases, b: *std.Build) !void {...@@ -57,8 +57,8 @@ pub fn addCases(ctx: *Cases, b: *std.Build) !void {
57 \\}57 \\}
58 , &[_][]const u8{58 , &[_][]const u8{
59 ":3:12: error: unable to resolve comptime value",59 ":3:12: error: unable to resolve comptime value",
60 ":3:12: note: argument to function being called at comptime must be comptime-known",60 ":2:55: note: generic function instantiated with comptime-only return type '?fn () void' is evaluated at comptime",
61 ":2:55: note: expression is evaluated at comptime because the generic function was instantiated with a comptime-only return type",61 ":2:55: note: use '*const fn () void' for a function pointer type",
62 });62 });
63 case.addSourceFile("b.zig",63 case.addSourceFile("b.zig",
64 \\pub const ElfDynLib = struct {64 \\pub const ElfDynLib = struct {
...@@ -198,7 +198,9 @@ pub fn addCases(ctx: *Cases, b: *std.Build) !void {...@@ -198,7 +198,9 @@ pub fn addCases(ctx: *Cases, b: *std.Build) !void {
198 ":8:36: error: runtime-known argument passed to comptime parameter",198 ":8:36: error: runtime-known argument passed to comptime parameter",
199 ":2:41: note: declared comptime here",199 ":2:41: note: declared comptime here",
200 ":13:32: error: unable to resolve comptime value",200 ":13:32: error: unable to resolve comptime value",
201 ":13:32: note: initializer of comptime only struct must be comptime-known",201 ":13:32: note: initializer of comptime-only struct 'tmp.callAnytypeFunctionWithRuntimeComptimeOnlyType.S' must be comptime-known",
202 ":12:35: note: struct requires comptime because of this field",
203 ":12:35: note: types are not available at runtime",
202 });204 });
203205
204 case.addSourceFile("import.zig",206 case.addSourceFile("import.zig",