authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-04-15 17:35:01-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-04-15 17:43:53-07:00
log67a5b6e5e8280ef736d458c4596137c58c2c253a
tree6a0adf9a5ff6140ef7dc4a8072bb9b8a62f2d151
parent0dd99c37cca1894ad7219e5944e7eef25902e44e

delete `@cImport` from the language

closes #20630

47 files changed, 67 insertions(+), 844 deletions(-)

.forgejo/ISSUE_TEMPLATE/config.yml+1-1
...@@ -6,7 +6,7 @@ contact_links:...@@ -6,7 +6,7 @@ contact_links:
6 about: "Please use one of the community spaces instead for questions or general discussions."6 about: "Please use one of the community spaces instead for questions or general discussions."
7 url: https://ziglang.org/community7 url: https://ziglang.org/community
8 - name: C Translation8 - name: C Translation
9 about: "Issues related to `zig translate-c` and `@cImport` are tracked separately."9 about: "Issues related to `zig translate-c` are tracked separately."
10 url: https://codeberg.org/ziglang/translate-c10 url: https://codeberg.org/ziglang/translate-c
11 - name: Copilot and Other LLMs11 - name: Copilot and Other LLMs
12 about: "Please do not use GitHub Copilot or any other LLM to write an issue."12 about: "Please do not use GitHub Copilot or any other LLM to write an issue."
CMakeLists.txt-7
...@@ -735,11 +735,6 @@ if(MSVC OR MINGW)...@@ -735,11 +735,6 @@ if(MSVC OR MINGW)
735endif()735endif()
736736
737737
738# "-Dno-langref" is hardcoded because stage2 builds lack the `@cImport`
739# feature, which some of the doctests rely on.
740
741# To obtain this document, run `zig build` against stage3 rather than stage2.
742# Note that the `langref` step can be used to isolate this task.
743set(ZIG_BUILD_ARGS738set(ZIG_BUILD_ARGS
744 --zig-lib-dir "${PROJECT_SOURCE_DIR}/lib"739 --zig-lib-dir "${PROJECT_SOURCE_DIR}/lib"
745740
...@@ -749,8 +744,6 @@ set(ZIG_BUILD_ARGS...@@ -749,8 +744,6 @@ set(ZIG_BUILD_ARGS
749744
750 -Denable-llvm745 -Denable-llvm
751 "-Dconfig_h=${ZIG_CONFIG_H_OUT}"746 "-Dconfig_h=${ZIG_CONFIG_H_OUT}"
752
753 -Dno-langref
754)747)
755748
756set(ZIG_EXTRA_BUILD_ARGS "" CACHE STRING "Extra zig build args")749set(ZIG_EXTRA_BUILD_ARGS "" CACHE STRING "Extra zig build args")
README.md+13-20
...@@ -658,38 +658,31 @@ WebAssembly-related....@@ -658,38 +658,31 @@ WebAssembly-related.
658658
659### Improving Translate-C659### Improving Translate-C
660660
661`translate-c` is a feature provided by Zig that converts C source code into661`translate-c` is a feature provided by Zig that converts C source code into Zig
662Zig source code. It powers the `zig translate-c` command as well as662source code. It powers the `zig translate-c` command, allowing Zig code to not
663[@cImport](https://ziglang.org/documentation/master/#cImport), allowing Zig663only take advantage of function prototypes defined in C header files, but also
664code to not only take advantage of function prototypes defined in .h files,664`static inline` functions written in C, and even some macros.
665but also `static inline` functions written in C, and even some macros.
666665
667This feature used to work by using libclang API to parse and semantically666This feature used to work by using libclang API to parse and semantically
668analyze C/C++ files, and then based on the provided AST and type information,667analyze C/C++ files, and then based on the provided AST and type information,
669generating Zig AST, and finally using the mechanisms of `zig fmt` to render the668generating Zig AST, and finally using the mechanisms of `zig fmt` to render the
670Zig AST to a file.669Zig AST to a file.
671670
672However, C translation is in a transitional period right now. It used to be671However, it is now based on [arocc](https://github.com/Vexu/arocc/), a
673based on Clang, but is now based on Aro:672third-party C compiler written in Zig. Test coverage, bug reports, and official
673implementation live in this repository: [ziglang/translate-c](https://codeberg.org/ziglang/translate-c/)
674674
675[Pull Request: update aro and translate-c to latest; delete clang translate-c](https://github.com/ziglang/zig/pull/24497)675This package is currently vendored into the Zig source tree. The TranslateC
676676build step takes advantage of this to provide the ability to setup C
677Test coverage as well as bug reports have been moved to this repository:677translation in one's build.zig script.
678
679[ziglang/translate-c](https://codeberg.org/ziglang/translate-c/)
680
681In the future, [@cImport will move to the build system](https://github.com/ziglang/zig/issues/20630),
682but for now, the translate-c logic is copy-pasted from that project into
683[ziglang/zig](https://codeberg.org/ziglang/zig/), powering both `zig translate-c`
684and `@cImport`.
685678
686Please see the readme of the translate-c project for how to contribute. Once an679Please see the readme of the translate-c project for how to contribute. Once an
687issue is resolved (and test coverage added) there, the changes can be680issue is resolved (and test coverage added) there, the changes can be
688immediately backported to the zig compiler.681immediately backported to the zig compiler.
689682
690Once we fix the problems people are facing from this transition from Clang to683However, in the future, this build step will be removed in favor of explicit
691Aro, we can move on to enhancing the translate-c package such that `@cImport`684dependency on the translate-c package via build system / package manager. At
692becomes redundant and can therefore be eliminated from the language.685that point, Zig will stop vendoring arocc.
693686
694### Autodoc687### Autodoc
695688
doc/langref.html.in+2-163
...@@ -1032,9 +1032,8 @@...@@ -1032,9 +1032,8 @@
1032 {#header_close#}1032 {#header_close#}
10331033
1034 {#header_open|Local Variables#}1034 {#header_open|Local Variables#}
1035 <p>1035 <p>Local variables occur inside {#link|Functions#}, {#link|comptime#}
1036 Local variables occur inside {#link|Functions#}, {#link|comptime#} blocks, and {#link|@cImport#} blocks.1036 blocks, and labeled {#link|Blocks#}.</p>
1037 </p>
1038 <p>1037 <p>
1039 When a local variable is {#syntax#}const{#endsyntax#}, it means that after initialization, the variable's1038 When a local variable is {#syntax#}const{#endsyntax#}, it means that after initialization, the variable's
1040 value will not change. If the initialization value of a {#syntax#}const{#endsyntax#} variable is1039 value will not change. If the initialization value of a {#syntax#}const{#endsyntax#} variable is
...@@ -4573,62 +4572,6 @@ comptime {...@@ -4573,62 +4572,6 @@ comptime {
45734572
4574 {#header_close#}4573 {#header_close#}
45754574
4576 {#header_open|@cDefine#}
4577 <pre>{#syntax#}@cDefine(comptime name: []const u8, value) void{#endsyntax#}</pre>
4578 <p>
4579 This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
4580 </p>
4581 <p>
4582 This appends <code>#define $name $value</code> to the {#syntax#}@cImport{#endsyntax#}
4583 temporary buffer.
4584 </p>
4585 <p>
4586 To define without a value, like this:
4587 </p>
4588 <pre><code class="c">#define _GNU_SOURCE</code></pre>
4589 <p>
4590 Use the void value, like this:
4591 </p>
4592 <pre>{#syntax#}@cDefine("_GNU_SOURCE", {}){#endsyntax#}</pre>
4593 {#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#}
4594 {#header_close#}
4595 {#header_open|@cImport#}
4596 <pre>{#syntax#}@cImport(expression) type{#endsyntax#}</pre>
4597 <p>
4598 This function parses C code and imports the functions, types, variables,
4599 and compatible macro definitions into a new empty struct type, and then
4600 returns that type.
4601 </p>
4602 <p>
4603 {#syntax#}expression{#endsyntax#} is interpreted at compile time. The builtin functions
4604 {#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#} work
4605 within this expression, appending to a temporary buffer which is then parsed as C code.
4606 </p>
4607 <p>
4608 Usually you should only have one {#syntax#}@cImport{#endsyntax#} in your entire application, because it saves the compiler
4609 from invoking clang multiple times, and prevents inline functions from being duplicated.
4610 </p>
4611 <p>
4612 Reasons for having multiple {#syntax#}@cImport{#endsyntax#} expressions would be:
4613 </p>
4614 <ul>
4615 <li>To avoid a symbol collision, for example if foo.h and bar.h both <code>#define CONNECTION_COUNT</code></li>
4616 <li>To analyze the C code with different preprocessor defines</li>
4617 </ul>
4618 {#see_also|Import from C Header File|@cInclude|@cDefine|@cUndef#}
4619 {#header_close#}
4620 {#header_open|@cInclude#}
4621 <pre>{#syntax#}@cInclude(comptime path: []const u8) void{#endsyntax#}</pre>
4622 <p>
4623 This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
4624 </p>
4625 <p>
4626 This appends <code>#include &lt;$path&gt;\n</code> to the {#syntax#}c_import{#endsyntax#}
4627 temporary buffer.
4628 </p>
4629 {#see_also|Import from C Header File|@cImport|@cDefine|@cUndef#}
4630 {#header_close#}
4631
4632 {#header_open|@clz#}4575 {#header_open|@clz#}
4633 <pre>{#syntax#}@clz(operand: anytype) anytype{#endsyntax#}</pre>4576 <pre>{#syntax#}@clz(operand: anytype) anytype{#endsyntax#}</pre>
4634 <p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.</p>4577 <p>{#syntax#}@TypeOf(operand){#endsyntax#} must be an integer type or an integer vector type.</p>
...@@ -4758,18 +4701,6 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val...@@ -4758,18 +4701,6 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val
4758 {#see_also|@clz|@popCount#}4701 {#see_also|@clz|@popCount#}
4759 {#header_close#}4702 {#header_close#}
47604703
4761 {#header_open|@cUndef#}
4762 <pre>{#syntax#}@cUndef(comptime name: []const u8) void{#endsyntax#}</pre>
4763 <p>
4764 This function can only occur inside {#syntax#}@cImport{#endsyntax#}.
4765 </p>
4766 <p>
4767 This appends <code>#undef $name</code> to the {#syntax#}@cImport{#endsyntax#}
4768 temporary buffer.
4769 </p>
4770 {#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#}
4771 {#header_close#}
4772
4773 {#header_open|@cVaArg#}4704 {#header_open|@cVaArg#}
4774 <pre>{#syntax#}@cVaArg(operand: *std.builtin.VaList, comptime T: type) T{#endsyntax#}</pre>4705 <pre>{#syntax#}@cVaArg(operand: *std.builtin.VaList, comptime T: type) T{#endsyntax#}</pre>
4775 <p>4706 <p>
...@@ -6784,35 +6715,6 @@ const builtin = @import("builtin");...@@ -6784,35 +6715,6 @@ const builtin = @import("builtin");
6784 </p>6715 </p>
6785 {#see_also|Primitive Types#}6716 {#see_also|Primitive Types#}
6786 {#header_close#}6717 {#header_close#}
6787 {#header_open|Import from C Header File#}
6788 <p>
6789 The {#syntax#}@cImport{#endsyntax#} builtin function can be used
6790 to directly import symbols from <code class="file">.h</code> files:
6791 </p>
6792 {#code|cImport_builtin.zig#}
6793
6794 <p>
6795 The {#syntax#}@cImport{#endsyntax#} function takes an expression as a parameter.
6796 This expression is evaluated at compile-time and is used to control
6797 preprocessor directives and include multiple <code class="file">.h</code> files:
6798 </p>
6799 {#syntax_block|zig|@cImport Expression#}
6800const builtin = @import("builtin");
6801
6802const c = @cImport({
6803 @cDefine("NDEBUG", builtin.mode == .ReleaseFast);
6804 if (something) {
6805 @cDefine("_GNU_SOURCE", {});
6806 }
6807 @cInclude("stdlib.h");
6808 if (something) {
6809 @cUndef("_GNU_SOURCE");
6810 }
6811 @cInclude("soundio.h");
6812});
6813 {#end_syntax_block#}
6814 {#see_also|@cImport|@cInclude|@cDefine|@cUndef|@import#}
6815 {#header_close#}
68166718
6817 {#header_open|C Translation CLI#}6719 {#header_open|C Translation CLI#}
6818 <p>6720 <p>
...@@ -6872,42 +6774,8 @@ $ zig translate-c -cflags -fshort-enums -- varycflags.h|grep -B1 do_something...@@ -6872,42 +6774,8 @@ $ zig translate-c -cflags -fshort-enums -- varycflags.h|grep -B1 do_something
6872pub const enum_FOO = u8;6774pub const enum_FOO = u8;
6873pub extern fn do_something(foo: enum_FOO) c_int;{#end_shell_samp#}6775pub extern fn do_something(foo: enum_FOO) c_int;{#end_shell_samp#}
6874 {#header_close#}6776 {#header_close#}
6875 {#header_open|@cImport vs translate-c#}
6876 <p>{#syntax#}@cImport{#endsyntax#} and <kbd>zig translate-c</kbd> use the same underlying
6877 C translation functionality, so on a technical level they are equivalent. In practice,
6878 {#syntax#}@cImport{#endsyntax#} is useful as a way to quickly and easily access numeric constants, typedefs,
6879 and record types without needing any extra setup. If you need to pass {#link|cflags|Using -target and -cflags#}
6880 to clang, or if you would like to edit the translated code, it is recommended to use
6881 <kbd>zig translate-c</kbd> and save the results to a file. Common reasons for editing
6882 the generated code include: changing {#syntax#}anytype{#endsyntax#} parameters in function-like macros to more
6883 specific types; changing {#syntax#}[*c]T{#endsyntax#} pointers to {#syntax#}[*]T{#endsyntax#} or
6884 {#syntax#}*T{#endsyntax#} pointers for improved type safety; and
6885 {#link|enabling or disabling runtime safety|@setRuntimeSafety#} within specific functions.
6886 </p>
6887 {#header_close#}
6888 {#see_also|Targets|C Type Primitives|Pointers|C Pointers|Import from C Header File|@cInclude|@cImport|@setRuntimeSafety#}
6889 {#header_close#}6777 {#header_close#}
6890 {#header_open|C Translation Caching#}
6891 <p>
6892 The C translation feature (whether used via <kbd>zig translate-c</kbd> or
6893 {#syntax#}@cImport{#endsyntax#}) integrates with the Zig caching system. Subsequent runs with
6894 the same source file, target, and cflags will use the cache instead of repeatedly translating
6895 the same code.
6896 </p>
6897 <p>
6898 To see where the cached files are stored when compiling code that uses {#syntax#}@cImport{#endsyntax#},
6899 use the <kbd>--verbose-cimport</kbd> flag:
6900 </p>
6901 {#code|verbose_cimport_flag.zig#}
69026778
6903 <p>
6904 <code class="file">cimport.h</code> contains the file to translate (constructed from calls to
6905 {#syntax#}@cInclude{#endsyntax#}, {#syntax#}@cDefine{#endsyntax#}, and {#syntax#}@cUndef{#endsyntax#}),
6906 <code class="file">cimport.h.d</code> is the list of file dependencies, and
6907 <code class="file">cimport.zig</code> contains the translated output.
6908 </p>
6909 {#see_also|Import from C Header File|C Translation CLI|@cInclude|@cImport#}
6910 {#header_close#}
6911 {#header_open|Translation failures#}6779 {#header_open|Translation failures#}
6912 <p>6780 <p>
6913 Some C constructs cannot be translated to Zig - for example, <em>goto</em>,6781 Some C constructs cannot be translated to Zig - for example, <em>goto</em>,
...@@ -6933,35 +6801,6 @@ pub extern fn do_something(foo: enum_FOO) c_int;{#end_shell_samp#}...@@ -6933,35 +6801,6 @@ pub extern fn do_something(foo: enum_FOO) c_int;{#end_shell_samp#}
6933 </p>6801 </p>
6934 {#see_also|opaque|extern|@compileError#}6802 {#see_also|opaque|extern|@compileError#}
6935 {#header_close#}6803 {#header_close#}
6936 {#header_open|C Macros#}
6937 <p>
6938 C Translation makes a best-effort attempt to translate function-like macros into equivalent
6939 Zig functions. Since C macros operate at the level of lexical tokens, not all C macros
6940 can be translated to Zig. Macros that cannot be translated will be demoted to
6941 {#syntax#}@compileError{#endsyntax#}. Note that C code which <em>uses</em> macros will be
6942 translated without any additional issues (since Zig operates on the pre-processed source
6943 with macros expanded). It is merely the macros themselves which may not be translatable to
6944 Zig.
6945 </p>
6946 <p>Consider the following example:</p>
6947 {#syntax_block|c|macro.c#}
6948#define MAKELOCAL(NAME, INIT) int NAME = INIT
6949int foo(void) {
6950 MAKELOCAL(a, 1);
6951 MAKELOCAL(b, 2);
6952 return a + b;
6953}
6954 {#end_syntax_block#}
6955 {#shell_samp#}$ zig translate-c macro.c > macro.zig{#end_shell_samp#}
6956 {#code|macro.zig#}
6957
6958 <p>Note that {#syntax#}foo{#endsyntax#} was translated correctly despite using a non-translatable
6959 macro. {#syntax#}MAKELOCAL{#endsyntax#} was demoted to {#syntax#}@compileError{#endsyntax#} since
6960 it cannot be expressed as a Zig function; this simply means that you cannot directly use
6961 {#syntax#}MAKELOCAL{#endsyntax#} from Zig.
6962 </p>
6963 {#see_also|@compileError#}
6964 {#header_close#}
69656804
6966 {#header_open|C Pointers#}6805 {#header_open|C Pointers#}
6967 <p>6806 <p>
doc/langref/cImport_builtin.zig deleted-12
...@@ -1,12 +0,0 @@
1const c = @cImport({
2 // See https://github.com/ziglang/zig/issues/515
3 @cDefine("_NO_CRT_STDIO_INLINE", "1");
4 @cInclude("stdio.h");
5});
6pub fn main() void {
7 if (@import("builtin").os.tag == .netbsd) return; // https://github.com/Vexu/arocc/issues/960
8 _ = c.printf("hello\n");
9}
10
11// exe=succeed
12// link_libc
doc/langref/macro.zig deleted-10
...@@ -1,10 +0,0 @@
1pub export fn foo() c_int {
2 var a: c_int = 1;
3 _ = &a;
4 var b: c_int = 2;
5 _ = &b;
6 return a + b;
7}
8pub const MAKELOCAL = @compileError("unable to translate C expr: unexpected token .Equal"); // macro.c:1:9
9
10// syntax
doc/langref/test_variadic_function.zig-1
...@@ -10,4 +10,3 @@ test "variadic function" {...@@ -10,4 +10,3 @@ test "variadic function" {
1010
11// test11// test
12// link_libc12// link_libc
13// verbose_cimport
doc/langref/verbose_cimport_flag.zig deleted-12
...@@ -1,12 +0,0 @@
1const c = @cImport({
2 @cDefine("_NO_CRT_STDIO_INLINE", "1");
3 @cInclude("stdio.h");
4});
5pub fn main() void {
6 if (@import("builtin").os.tag == .netbsd) return; // https://github.com/Vexu/arocc/issues/960
7 _ = c;
8}
9
10// exe=succeed
11// link_libc
12// verbose_cimport
lib/compiler/build_runner.zig-2
...@@ -333,8 +333,6 @@ pub fn main(init: process.Init.Minimal) !void {...@@ -333,8 +333,6 @@ pub fn main(init: process.Init.Minimal) !void {
333 builder.verbose_llvm_ir = arg["--verbose-llvm-ir=".len..];333 builder.verbose_llvm_ir = arg["--verbose-llvm-ir=".len..];
334 } else if (mem.startsWith(u8, arg, "--verbose-llvm-bc=")) {334 } else if (mem.startsWith(u8, arg, "--verbose-llvm-bc=")) {
335 builder.verbose_llvm_bc = arg["--verbose-llvm-bc=".len..];335 builder.verbose_llvm_bc = arg["--verbose-llvm-bc=".len..];
336 } else if (mem.eql(u8, arg, "--verbose-cimport")) {
337 builder.verbose_cimport = true;
338 } else if (mem.eql(u8, arg, "--verbose-cc")) {336 } else if (mem.eql(u8, arg, "--verbose-cc")) {
339 builder.verbose_cc = true;337 builder.verbose_cc = true;
340 } else if (mem.eql(u8, arg, "--verbose-llvm-cpu-features")) {338 } else if (mem.eql(u8, arg, "--verbose-llvm-cpu-features")) {
lib/std/Build.zig-3
...@@ -38,7 +38,6 @@ verbose_cc: bool,...@@ -38,7 +38,6 @@ verbose_cc: bool,
38verbose_air: bool,38verbose_air: bool,
39verbose_llvm_ir: ?[]const u8,39verbose_llvm_ir: ?[]const u8,
40verbose_llvm_bc: ?[]const u8,40verbose_llvm_bc: ?[]const u8,
41verbose_cimport: bool,
42verbose_llvm_cpu_features: bool,41verbose_llvm_cpu_features: bool,
43reference_trace: ?u32 = null,42reference_trace: ?u32 = null,
44invalid_user_input: bool,43invalid_user_input: bool,
...@@ -278,7 +277,6 @@ pub fn create(...@@ -278,7 +277,6 @@ pub fn create(
278 .verbose_air = false,277 .verbose_air = false,
279 .verbose_llvm_ir = null,278 .verbose_llvm_ir = null,
280 .verbose_llvm_bc = null,279 .verbose_llvm_bc = null,
281 .verbose_cimport = false,
282 .verbose_llvm_cpu_features = false,280 .verbose_llvm_cpu_features = false,
283 .invalid_user_input = false,281 .invalid_user_input = false,
284 .allocator = arena,282 .allocator = arena,
...@@ -377,7 +375,6 @@ fn createChildOnly(...@@ -377,7 +375,6 @@ fn createChildOnly(
377 .verbose_air = parent.verbose_air,375 .verbose_air = parent.verbose_air,
378 .verbose_llvm_ir = parent.verbose_llvm_ir,376 .verbose_llvm_ir = parent.verbose_llvm_ir,
379 .verbose_llvm_bc = parent.verbose_llvm_bc,377 .verbose_llvm_bc = parent.verbose_llvm_bc,
380 .verbose_cimport = parent.verbose_cimport,
381 .verbose_llvm_cpu_features = parent.verbose_llvm_cpu_features,378 .verbose_llvm_cpu_features = parent.verbose_llvm_cpu_features,
382 .reference_trace = parent.reference_trace,379 .reference_trace = parent.reference_trace,
383 .invalid_user_input = false,380 .invalid_user_input = false,
lib/std/Build/Step/Compile.zig-1
...@@ -1393,7 +1393,6 @@ fn getZigArgs(compile: *Compile, fuzz: bool) ![][]const u8 {...@@ -1393,7 +1393,6 @@ fn getZigArgs(compile: *Compile, fuzz: bool) ![][]const u8 {
1393 try zig_args.append("--debug-incremental");1393 try zig_args.append("--debug-incremental");
1394 }1394 }
13951395
1396 if (b.verbose_cimport) try zig_args.append("--verbose-cimport");
1397 if (b.verbose_air) try zig_args.append("--verbose-air");1396 if (b.verbose_air) try zig_args.append("--verbose-air");
1398 if (b.verbose_llvm_ir) |path| try zig_args.append(b.fmt("--verbose-llvm-ir={s}", .{path}));1397 if (b.verbose_llvm_ir) |path| try zig_args.append(b.fmt("--verbose-llvm-ir={s}", .{path}));
1399 if (b.verbose_llvm_bc) |path| try zig_args.append(b.fmt("--verbose-llvm-bc={s}", .{path}));1398 if (b.verbose_llvm_bc) |path| try zig_args.append(b.fmt("--verbose-llvm-bc={s}", .{path}));
lib/std/zig.zig-10
...@@ -796,11 +796,6 @@ pub const SimpleComptimeReason = enum(u32) {...@@ -796,11 +796,6 @@ pub const SimpleComptimeReason = enum(u32) {
796 operand_branchHint,796 operand_branchHint,
797 operand_setRuntimeSafety,797 operand_setRuntimeSafety,
798 operand_embedFile,798 operand_embedFile,
799 operand_cImport,
800 operand_cDefine_macro_name,
801 operand_cDefine_macro_value,
802 operand_cInclude_file_name,
803 operand_cUndef_macro_name,
804 operand_shuffle_mask,799 operand_shuffle_mask,
805 operand_atomicRmw_operation,800 operand_atomicRmw_operation,
806 operand_reduce_operation,801 operand_reduce_operation,
...@@ -891,11 +886,6 @@ pub const SimpleComptimeReason = enum(u32) {...@@ -891,11 +886,6 @@ pub const SimpleComptimeReason = enum(u32) {
891 .operand_branchHint => "operand to '@branchHint' must be comptime-known",886 .operand_branchHint => "operand to '@branchHint' must be comptime-known",
892 .operand_setRuntimeSafety => "operand to '@setRuntimeSafety' must be comptime-known",887 .operand_setRuntimeSafety => "operand to '@setRuntimeSafety' must be comptime-known",
893 .operand_embedFile => "operand to '@embedFile' must be comptime-known",888 .operand_embedFile => "operand to '@embedFile' must be comptime-known",
894 .operand_cImport => "operand to '@cImport' is evaluated at comptime",
895 .operand_cDefine_macro_name => "'@cDefine' macro name must be comptime-known",
896 .operand_cDefine_macro_value => "'@cDefine' macro value must be comptime-known",
897 .operand_cInclude_file_name => "'@cInclude' file name must be comptime-known",
898 .operand_cUndef_macro_name => "'@cUndef' macro name must be comptime-known",
899 .operand_shuffle_mask => "'@shuffle' mask must be comptime-known",889 .operand_shuffle_mask => "'@shuffle' mask must be comptime-known",
900 .operand_atomicRmw_operation => "'@atomicRmw' operation must be comptime-known",890 .operand_atomicRmw_operation => "'@atomicRmw' operation must be comptime-known",
901 .operand_reduce_operation => "'@reduce' operation must be comptime-known",891 .operand_reduce_operation => "'@reduce' operation must be comptime-known",
lib/std/zig/AstGen.zig+1-74
...@@ -2870,7 +2870,6 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As...@@ -2870,7 +2870,6 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As
2870 .mul_add,2870 .mul_add,
2871 .max,2871 .max,
2872 .min,2872 .min,
2873 .c_import,
2874 .@"resume",2873 .@"resume",
2875 .ret_err_value_code,2874 .ret_err_value_code,
2876 .ret_ptr,2875 .ret_ptr,
...@@ -8955,7 +8954,6 @@ fn typeOf(...@@ -8955,7 +8954,6 @@ fn typeOf(
8955 var typeof_scope = gz.makeSubBlock(scope);8954 var typeof_scope = gz.makeSubBlock(scope);
8956 typeof_scope.is_comptime = false;8955 typeof_scope.is_comptime = false;
8957 typeof_scope.is_typeof = true;8956 typeof_scope.is_typeof = true;
8958 typeof_scope.c_import = false;
8959 defer typeof_scope.unstack();8957 defer typeof_scope.unstack();
89608958
8961 const ty_expr = try reachableExpr(&typeof_scope, &typeof_scope.base, .{ .rl = .none }, args[0], node);8959 const ty_expr = try reachableExpr(&typeof_scope, &typeof_scope.base, .{ .rl = .none }, args[0], node);
...@@ -9055,8 +9053,7 @@ fn builtinCall(...@@ -9055,8 +9053,7 @@ fn builtinCall(
9055 const builtin_name = tree.tokenSlice(builtin_token);9053 const builtin_name = tree.tokenSlice(builtin_token);
90569054
9057 // We handle the different builtins manually because they have different semantics depending9055 // We handle the different builtins manually because they have different semantics depending
9058 // on the function. For example, `@as` and others participate in result location semantics,9056 // on the function. For example, `@as` and others participate in result location semantics.
9059 // and `@cImport` creates a special scope that collects a .c source code text buffer.
9060 // Also, some builtins have a variable number of parameters.9057 // Also, some builtins have a variable number of parameters.
90619058
9062 const info = BuiltinFn.list.get(builtin_name) orelse {9059 const info = BuiltinFn.list.get(builtin_name) orelse {
...@@ -9175,7 +9172,6 @@ fn builtinCall(...@@ -9175,7 +9172,6 @@ fn builtinCall(
9175 .bit_cast => return bitCast( gz, scope, ri, node, params[0]),9172 .bit_cast => return bitCast( gz, scope, ri, node, params[0]),
9176 .TypeOf => return typeOf( gz, scope, ri, node, params),9173 .TypeOf => return typeOf( gz, scope, ri, node, params),
9177 .union_init => return unionInit(gz, scope, ri, node, params),9174 .union_init => return unionInit(gz, scope, ri, node, params),
9178 .c_import => return cImport( gz, scope, node, params[0]),
9179 .min => return minMax( gz, scope, ri, node, params, .min),9175 .min => return minMax( gz, scope, ri, node, params, .min),
9180 .max => return minMax( gz, scope, ri, node, params, .max),9176 .max => return minMax( gz, scope, ri, node, params, .max),
9181 // zig fmt: on9177 // zig fmt: on
...@@ -9484,9 +9480,6 @@ fn builtinCall(...@@ -9484,9 +9480,6 @@ fn builtinCall(
9484 .bit_offset_of => return offsetOf(gz, scope, ri, node, params[0], params[1], .bit_offset_of),9480 .bit_offset_of => return offsetOf(gz, scope, ri, node, params[0], params[1], .bit_offset_of),
9485 .offset_of => return offsetOf(gz, scope, ri, node, params[0], params[1], .offset_of),9481 .offset_of => return offsetOf(gz, scope, ri, node, params[0], params[1], .offset_of),
94869482
9487 .c_undef => return simpleCBuiltin(gz, scope, ri, node, params[0], .c_undef),
9488 .c_include => return simpleCBuiltin(gz, scope, ri, node, params[0], .c_include),
9489
9490 .cmpxchg_strong => return cmpxchg(gz, scope, ri, node, params, 1),9483 .cmpxchg_strong => return cmpxchg(gz, scope, ri, node, params, 1),
9491 .cmpxchg_weak => return cmpxchg(gz, scope, ri, node, params, 0),9484 .cmpxchg_weak => return cmpxchg(gz, scope, ri, node, params, 0),
9492 // zig fmt: on9485 // zig fmt: on
...@@ -9509,17 +9502,6 @@ fn builtinCall(...@@ -9509,17 +9502,6 @@ fn builtinCall(
9509 });9502 });
9510 return rvalue(gz, ri, result, node);9503 return rvalue(gz, ri, result, node);
9511 },9504 },
9512 .c_define => {
9513 if (!gz.c_import) return gz.astgen.failNode(node, "C define valid only inside C import block", .{});
9514 const name = try comptimeExpr(gz, scope, .{ .rl = .{ .coerced_ty = .slice_const_u8_type } }, params[0], .operand_cDefine_macro_name);
9515 const value = try comptimeExpr(gz, scope, .{ .rl = .none }, params[1], .operand_cDefine_macro_value);
9516 const result = try gz.addExtendedPayload(.c_define, Zir.Inst.BinNode{
9517 .node = gz.nodeIndexToRelative(node),
9518 .lhs = name,
9519 .rhs = value,
9520 });
9521 return rvalue(gz, ri, result, node);
9522 },
9523 .splat => {9505 .splat => {
9524 const result_type = try ri.rl.resultTypeForCast(gz, node, builtin_name);9506 const result_type = try ri.rl.resultTypeForCast(gz, node, builtin_name);
9525 const elem_type = try gz.addUnNode(.splat_op_result_ty, result_type, node);9507 const elem_type = try gz.addUnNode(.splat_op_result_ty, result_type, node);
...@@ -9951,30 +9933,6 @@ fn divBuiltin(...@@ -9951,30 +9933,6 @@ fn divBuiltin(
9951 return rvalue(gz, ri, result, node);9933 return rvalue(gz, ri, result, node);
9952}9934}
99539935
9954fn simpleCBuiltin(
9955 gz: *GenZir,
9956 scope: *Scope,
9957 ri: ResultInfo,
9958 node: Ast.Node.Index,
9959 operand_node: Ast.Node.Index,
9960 tag: Zir.Inst.Extended,
9961) InnerError!Zir.Inst.Ref {
9962 const name: []const u8 = if (tag == .c_undef) "C undef" else "C include";
9963 if (!gz.c_import) return gz.astgen.failNode(node, "{s} valid only inside C import block", .{name});
9964 const operand = try comptimeExpr(
9965 gz,
9966 scope,
9967 .{ .rl = .{ .coerced_ty = .slice_const_u8_type } },
9968 operand_node,
9969 if (tag == .c_undef) .operand_cUndef_macro_name else .operand_cInclude_file_name,
9970 );
9971 _ = try gz.addExtendedPayload(tag, Zir.Inst.UnNode{
9972 .node = gz.nodeIndexToRelative(node),
9973 .operand = operand,
9974 });
9975 return rvalue(gz, ri, .void_value, node);
9976}
9977
9978fn offsetOf(9936fn offsetOf(
9979 gz: *GenZir,9937 gz: *GenZir,
9980 scope: *Scope,9938 scope: *Scope,
...@@ -10024,35 +9982,6 @@ fn shiftOp(...@@ -10024,35 +9982,6 @@ fn shiftOp(
10024 return rvalue(gz, ri, result, node);9982 return rvalue(gz, ri, result, node);
10025}9983}
100269984
10027fn cImport(
10028 gz: *GenZir,
10029 scope: *Scope,
10030 node: Ast.Node.Index,
10031 body_node: Ast.Node.Index,
10032) InnerError!Zir.Inst.Ref {
10033 const astgen = gz.astgen;
10034 const gpa = astgen.gpa;
10035
10036 if (gz.c_import) return gz.astgen.failNode(node, "cannot nest @cImport", .{});
10037
10038 var block_scope = gz.makeSubBlock(scope);
10039 block_scope.is_comptime = true;
10040 block_scope.c_import = true;
10041 defer block_scope.unstack();
10042
10043 const block_inst = try gz.makeBlockInst(.c_import, node);
10044 const block_result = try fullBodyExpr(&block_scope, &block_scope.base, .{ .rl = .none }, body_node, .normal);
10045 _ = try gz.addUnNode(.ensure_result_used, block_result, node);
10046 if (!gz.refIsNoReturn(block_result)) {
10047 _ = try block_scope.addBreak(.break_inline, block_inst, .void_value);
10048 }
10049 try block_scope.setBlockBody(block_inst);
10050 // block_scope unstacked now, can add new instructions to gz
10051 try gz.instructions.append(gpa, block_inst);
10052
10053 return block_inst.toRef();
10054}
10055
10056fn overflowArithmetic(9985fn overflowArithmetic(
10057 gz: *GenZir,9986 gz: *GenZir,
10058 scope: *Scope,9987 scope: *Scope,
...@@ -11339,7 +11268,6 @@ const GenZir = struct {...@@ -11339,7 +11268,6 @@ const GenZir = struct {
11339 /// This is set to true for a `GenZir` of a `block_inline`, indicating that11268 /// This is set to true for a `GenZir` of a `block_inline`, indicating that
11340 /// exits from this block should use `break_inline` rather than `break`.11269 /// exits from this block should use `break_inline` rather than `break`.
11341 is_inline: bool = false,11270 is_inline: bool = false,
11342 c_import: bool = false,
11343 /// The containing decl AST node.11271 /// The containing decl AST node.
11344 decl_node_index: Ast.Node.Index,11272 decl_node_index: Ast.Node.Index,
11345 /// The containing decl line index, absolute.11273 /// The containing decl line index, absolute.
...@@ -11427,7 +11355,6 @@ const GenZir = struct {...@@ -11427,7 +11355,6 @@ const GenZir = struct {
11427 return .{11355 return .{
11428 .is_comptime = gz.is_comptime,11356 .is_comptime = gz.is_comptime,
11429 .is_typeof = gz.is_typeof,11357 .is_typeof = gz.is_typeof,
11430 .c_import = gz.c_import,
11431 .decl_node_index = gz.decl_node_index,11358 .decl_node_index = gz.decl_node_index,
11432 .decl_line = gz.decl_line,11359 .decl_line = gz.decl_line,
11433 .parent = scope,11360 .parent = scope,
lib/std/zig/AstRlAnnotate.zig-11
...@@ -842,10 +842,6 @@ fn builtinCall(astrl: *AstRlAnnotate, block: ?*Block, ri: ResultInfo, node: Ast....@@ -842,10 +842,6 @@ fn builtinCall(astrl: *AstRlAnnotate, block: ?*Block, ri: ResultInfo, node: Ast.
842 _ = try astrl.expr(args[2], block, ResultInfo.type_only);842 _ = try astrl.expr(args[2], block, ResultInfo.type_only);
843 return false;843 return false;
844 },844 },
845 .c_import => {
846 _ = try astrl.expr(args[0], block, ResultInfo.none);
847 return false;
848 },
849 .min, .max => {845 .min, .max => {
850 for (args) |arg_node| {846 for (args) |arg_node| {
851 _ = try astrl.expr(arg_node, block, ResultInfo.none);847 _ = try astrl.expr(arg_node, block, ResultInfo.none);
...@@ -907,8 +903,6 @@ fn builtinCall(astrl: *AstRlAnnotate, block: ?*Block, ri: ResultInfo, node: Ast....@@ -907,8 +903,6 @@ fn builtinCall(astrl: *AstRlAnnotate, block: ?*Block, ri: ResultInfo, node: Ast.
907 .error_name,903 .error_name,
908 .set_runtime_safety,904 .set_runtime_safety,
909 .Tuple,905 .Tuple,
910 .c_undef,
911 .c_include,
912 .wasm_memory_size,906 .wasm_memory_size,
913 .splat,907 .splat,
914 .set_float_mode,908 .set_float_mode,
...@@ -986,11 +980,6 @@ fn builtinCall(astrl: *AstRlAnnotate, block: ?*Block, ri: ResultInfo, node: Ast....@@ -986,11 +980,6 @@ fn builtinCall(astrl: *AstRlAnnotate, block: ?*Block, ri: ResultInfo, node: Ast.
986 _ = try astrl.expr(args[1], block, ResultInfo.type_only);980 _ = try astrl.expr(args[1], block, ResultInfo.type_only);
987 return false;981 return false;
988 },982 },
989 .c_define => {
990 _ = try astrl.expr(args[0], block, ResultInfo.type_only);
991 _ = try astrl.expr(args[1], block, ResultInfo.none);
992 return false;
993 },
994 .reduce => {983 .reduce => {
995 _ = try astrl.expr(args[0], block, ResultInfo.type_only);984 _ = try astrl.expr(args[0], block, ResultInfo.type_only);
996 _ = try astrl.expr(args[1], block, ResultInfo.none);985 _ = try astrl.expr(args[1], block, ResultInfo.none);
lib/std/zig/BuiltinFn.zig-32
...@@ -20,9 +20,6 @@ pub const Tag = enum {...@@ -20,9 +20,6 @@ pub const Tag = enum {
20 bit_reverse,20 bit_reverse,
21 offset_of,21 offset_of,
22 call,22 call,
23 c_define,
24 c_import,
25 c_include,
26 clz,23 clz,
27 cmpxchg_strong,24 cmpxchg_strong,
28 cmpxchg_weak,25 cmpxchg_weak,
...@@ -30,7 +27,6 @@ pub const Tag = enum {...@@ -30,7 +27,6 @@ pub const Tag = enum {
30 compile_log,27 compile_log,
31 const_cast,28 const_cast,
32 ctz,29 ctz,
33 c_undef,
34 c_va_arg,30 c_va_arg,
35 c_va_copy,31 c_va_copy,
36 c_va_end,32 c_va_end,
...@@ -306,27 +302,6 @@ pub const list = list: {...@@ -306,27 +302,6 @@ pub const list = list: {
306 .param_count = 3,302 .param_count = 3,
307 },303 },
308 },304 },
309 .{
310 "@cDefine",
311 .{
312 .tag = .c_define,
313 .param_count = 2,
314 },
315 },
316 .{
317 "@cImport",
318 .{
319 .tag = .c_import,
320 .param_count = 1,
321 },
322 },
323 .{
324 "@cInclude",
325 .{
326 .tag = .c_include,
327 .param_count = 1,
328 },
329 },
330 .{305 .{
331 "@clz",306 "@clz",
332 .{307 .{
...@@ -376,13 +351,6 @@ pub const list = list: {...@@ -376,13 +351,6 @@ pub const list = list: {
376 .param_count = 1,351 .param_count = 1,
377 },352 },
378 },353 },
379 .{
380 "@cUndef",
381 .{
382 .tag = .c_undef,
383 .param_count = 1,
384 },
385 },
386 .{354 .{
387 "@cVaArg",355 "@cVaArg",
388 .{356 .{
lib/std/zig/Zir.zig-16
...@@ -1016,9 +1016,6 @@ pub const Inst = struct {...@@ -1016,9 +1016,6 @@ pub const Inst = struct {
1016 /// Implements the `@max` builtin for 2 args.1016 /// Implements the `@max` builtin for 2 args.
1017 /// Uses the `pl_node` union field with payload `Bin`1017 /// Uses the `pl_node` union field with payload `Bin`
1018 max,1018 max,
1019 /// Implements the `@cImport` builtin.
1020 /// Uses the `pl_node` union field with payload `Block`.
1021 c_import,
10221019
1023 /// Allocates stack local memory.1020 /// Allocates stack local memory.
1024 /// Uses the `un_node` union field. The operand is the type of the allocated object.1021 /// Uses the `un_node` union field. The operand is the type of the allocated object.
...@@ -1297,7 +1294,6 @@ pub const Inst = struct {...@@ -1297,7 +1294,6 @@ pub const Inst = struct {
1297 .memset,1294 .memset,
1298 .memmove,1295 .memmove,
1299 .min,1296 .min,
1300 .c_import,
1301 .@"resume",1297 .@"resume",
1302 .ret_err_value_code,1298 .ret_err_value_code,
1303 .extended,1299 .extended,
...@@ -1577,7 +1573,6 @@ pub const Inst = struct {...@@ -1577,7 +1573,6 @@ pub const Inst = struct {
1577 .builtin_call,1573 .builtin_call,
1578 .max,1574 .max,
1579 .min,1575 .min,
1580 .c_import,
1581 .@"resume",1576 .@"resume",
1582 .ret_err_value_code,1577 .ret_err_value_code,
1583 .@"break",1578 .@"break",
...@@ -1857,7 +1852,6 @@ pub const Inst = struct {...@@ -1857,7 +1852,6 @@ pub const Inst = struct {
1857 .memset = .pl_node,1852 .memset = .pl_node,
1858 .memmove = .pl_node,1853 .memmove = .pl_node,
1859 .min = .pl_node,1854 .min = .pl_node,
1860 .c_import = .pl_node,
18611855
1862 .alloc = .un_node,1856 .alloc = .un_node,
1863 .alloc_mut = .un_node,1857 .alloc_mut = .un_node,
...@@ -2018,12 +2012,6 @@ pub const Inst = struct {...@@ -2018,12 +2012,6 @@ pub const Inst = struct {
2018 /// `small` is unused.2012 /// `small` is unused.
2019 round_op_ty,2013 round_op_ty,
2020 /// `operand` is payload index to `UnNode`.2014 /// `operand` is payload index to `UnNode`.
2021 c_undef,
2022 /// `operand` is payload index to `UnNode`.
2023 c_include,
2024 /// `operand` is payload index to `BinNode`.
2025 c_define,
2026 /// `operand` is payload index to `UnNode`.
2027 wasm_memory_size,2015 wasm_memory_size,
2028 /// `operand` is payload index to `BinNode`.2016 /// `operand` is payload index to `BinNode`.
2029 wasm_memory_grow,2017 wasm_memory_grow,
...@@ -4360,9 +4348,6 @@ fn findTrackableInner(...@@ -4360,9 +4348,6 @@ fn findTrackableInner(
4360 .mul_with_overflow,4348 .mul_with_overflow,
4361 .shl_with_overflow,4349 .shl_with_overflow,
4362 .round_op,4350 .round_op,
4363 .c_undef,
4364 .c_include,
4365 .c_define,
4366 .wasm_memory_size,4351 .wasm_memory_size,
4367 .wasm_memory_grow,4352 .wasm_memory_grow,
4368 .prefetch,4353 .prefetch,
...@@ -4532,7 +4517,6 @@ fn findTrackableInner(...@@ -4532,7 +4517,6 @@ fn findTrackableInner(
45324517
4533 .block,4518 .block,
4534 .block_inline,4519 .block_inline,
4535 .c_import,
4536 .typeof_builtin,4520 .typeof_builtin,
4537 .loop,4521 .loop,
4538 => {4522 => {
src/Compilation.zig+6-103
...@@ -172,7 +172,6 @@ verbose_intern_pool: bool,...@@ -172,7 +172,6 @@ verbose_intern_pool: bool,
172verbose_generic_instances: bool,172verbose_generic_instances: bool,
173verbose_llvm_ir: ?[]const u8,173verbose_llvm_ir: ?[]const u8,
174verbose_llvm_bc: ?[]const u8,174verbose_llvm_bc: ?[]const u8,
175verbose_cimport: bool,
176verbose_llvm_cpu_features: bool,175verbose_llvm_cpu_features: bool,
177verbose_link: bool,176verbose_link: bool,
178link_depfile: ?[]const u8,177link_depfile: ?[]const u8,
...@@ -1681,7 +1680,6 @@ pub const CreateOptions = struct {...@@ -1681,7 +1680,6 @@ pub const CreateOptions = struct {
1681 verbose_llvm_ir: ?[]const u8 = null,1680 verbose_llvm_ir: ?[]const u8 = null,
1682 verbose_llvm_bc: ?[]const u8 = null,1681 verbose_llvm_bc: ?[]const u8 = null,
1683 link_depfile: ?[]const u8 = null,1682 link_depfile: ?[]const u8 = null,
1684 verbose_cimport: bool = false,
1685 verbose_llvm_cpu_features: bool = false,1683 verbose_llvm_cpu_features: bool = false,
1686 debug_compiler_runtime_libs: ?std.builtin.OptimizeMode = null,1684 debug_compiler_runtime_libs: ?std.builtin.OptimizeMode = null,
1687 debug_compile_errors: bool = false,1685 debug_compile_errors: bool = false,
...@@ -2254,7 +2252,6 @@ pub fn create(gpa: Allocator, arena: Allocator, io: Io, diag: *CreateDiagnostic,...@@ -2254,7 +2252,6 @@ pub fn create(gpa: Allocator, arena: Allocator, io: Io, diag: *CreateDiagnostic,
2254 .verbose_llvm_ir = options.verbose_llvm_ir,2252 .verbose_llvm_ir = options.verbose_llvm_ir,
2255 .verbose_llvm_bc = options.verbose_llvm_bc,2253 .verbose_llvm_bc = options.verbose_llvm_bc,
2256 .link_depfile = options.link_depfile,2254 .link_depfile = options.link_depfile,
2257 .verbose_cimport = options.verbose_cimport,
2258 .verbose_llvm_cpu_features = options.verbose_llvm_cpu_features,2255 .verbose_llvm_cpu_features = options.verbose_llvm_cpu_features,
2259 .verbose_link = options.verbose_link,2256 .verbose_link = options.verbose_link,
2260 .disable_c_depfile = options.disable_c_depfile,2257 .disable_c_depfile = options.disable_c_depfile,
...@@ -4095,27 +4092,6 @@ pub fn getAllErrorsAlloc(comp: *Compilation) error{OutOfMemory}!ErrorBundle {...@@ -4095,27 +4092,6 @@ pub fn getAllErrorsAlloc(comp: *Compilation) error{OutOfMemory}!ErrorBundle {
40954092
4096 try addModuleErrorMsg(zcu, &bundle, error_msg.*, added_any_analysis_error);4093 try addModuleErrorMsg(zcu, &bundle, error_msg.*, added_any_analysis_error);
4097 added_any_analysis_error = true;4094 added_any_analysis_error = true;
4098
4099 if (zcu.cimport_errors.get(anal_unit)) |errors| {
4100 for (errors.getMessages()) |err_msg_index| {
4101 const err_msg = errors.getErrorMessage(err_msg_index);
4102 try bundle.addRootErrorMessage(.{
4103 .msg = try bundle.addString(errors.nullTerminatedString(err_msg.msg)),
4104 .src_loc = if (err_msg.src_loc != .none) blk: {
4105 const src_loc = errors.getSourceLocation(err_msg.src_loc);
4106 break :blk try bundle.addSourceLocation(.{
4107 .src_path = try bundle.addString(errors.nullTerminatedString(src_loc.src_path)),
4108 .span_start = src_loc.span_start,
4109 .span_main = src_loc.span_main,
4110 .span_end = src_loc.span_end,
4111 .line = src_loc.line,
4112 .column = src_loc.column,
4113 .source_line = if (src_loc.source_line != 0) try bundle.addString(errors.nullTerminatedString(src_loc.source_line)) else 0,
4114 });
4115 } else .none,
4116 });
4117 }
4118 }
4119 }4095 }
4120 try zcu.addDependencyLoopErrors(&bundle);4096 try zcu.addDependencyLoopErrors(&bundle);
4121 for (zcu.failed_codegen.values()) |error_msg| {4097 for (zcu.failed_codegen.values()) |error_msg| {
...@@ -5048,7 +5024,6 @@ fn workerDocsWasmFallible(comp: *Compilation, prog_node: std.Progress.Node) SubU...@@ -5048,7 +5024,6 @@ fn workerDocsWasmFallible(comp: *Compilation, prog_node: std.Progress.Node) SubU
5048 .verbose_generic_instances = comp.verbose_intern_pool,5024 .verbose_generic_instances = comp.verbose_intern_pool,
5049 .verbose_llvm_ir = comp.verbose_llvm_ir,5025 .verbose_llvm_ir = comp.verbose_llvm_ir,
5050 .verbose_llvm_bc = comp.verbose_llvm_bc,5026 .verbose_llvm_bc = comp.verbose_llvm_bc,
5051 .verbose_cimport = comp.verbose_cimport,
5052 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,5027 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
5053 .environ_map = comp.environ_map,5028 .environ_map = comp.environ_map,
5054 }) catch |err| switch (err) {5029 }) catch |err| switch (err) {
...@@ -5100,8 +5075,8 @@ pub fn obtainCObjectCacheManifest(...@@ -5100,8 +5075,8 @@ pub fn obtainCObjectCacheManifest(
5100) Cache.Manifest {5075) Cache.Manifest {
5101 var man = comp.cache_parent.obtain();5076 var man = comp.cache_parent.obtain();
51025077
5103 // Only things that need to be added on top of the base hash, and only things5078 // Only things that need to be added on top of the base hash, and only
5104 // that apply both to @cImport and compiling C objects. No linking stuff here!5079 // things that apply to compiling C objects. No linking stuff here!
5105 // Also nothing that applies only to compiling .zig code.5080 // Also nothing that applies only to compiling .zig code.
5106 cache_helpers.addModule(&man.hash, owner_mod);5081 cache_helpers.addModule(&man.hash, owner_mod);
5107 man.hash.addListOfBytes(comp.global_cc_argv);5082 man.hash.addListOfBytes(comp.global_cc_argv);
...@@ -5126,13 +5101,13 @@ pub fn obtainWin32ResourceCacheManifest(comp: *const Compilation) Cache.Manifest...@@ -5126,13 +5101,13 @@ pub fn obtainWin32ResourceCacheManifest(comp: *const Compilation) Cache.Manifest
5126 return man;5101 return man;
5127}5102}
51285103
5129pub const CImportResult = struct {5104pub const TranslateCResult = struct {
5130 // Only valid if `errors` is not empty5105 // Only valid if `errors` is not empty
5131 digest: [Cache.bin_digest_len]u8,5106 digest: [Cache.bin_digest_len]u8,
5132 cache_hit: bool,5107 cache_hit: bool,
5133 errors: std.zig.ErrorBundle,5108 errors: std.zig.ErrorBundle,
51345109
5135 pub fn deinit(result: *CImportResult, gpa: mem.Allocator) void {5110 pub fn deinit(result: *TranslateCResult, gpa: mem.Allocator) void {
5136 result.errors.deinit(gpa);5111 result.errors.deinit(gpa);
5137 }5112 }
5138};5113};
...@@ -5142,15 +5117,12 @@ pub fn translateC(...@@ -5142,15 +5117,12 @@ pub fn translateC(
5142 arena: Allocator,5117 arena: Allocator,
5143 man: *Cache.Manifest,5118 man: *Cache.Manifest,
5144 ext: FileExt,5119 ext: FileExt,
5145 source: union(enum) {5120 source_path: []const u8,
5146 path: []const u8,
5147 c_src: []const u8,
5148 },
5149 translated_basename: []const u8,5121 translated_basename: []const u8,
5150 owner_mod: *Package.Module,5122 owner_mod: *Package.Module,
5151 prog_node: std.Progress.Node,5123 prog_node: std.Progress.Node,
5152 environ_map: *const std.process.Environ.Map,5124 environ_map: *const std.process.Environ.Map,
5153) !CImportResult {5125) !TranslateCResult {
5154 dev.check(.translate_c_command);5126 dev.check(.translate_c_command);
51555127
5156 const gpa = comp.gpa;5128 const gpa = comp.gpa;
...@@ -5166,17 +5138,6 @@ pub fn translateC(...@@ -5166,17 +5138,6 @@ pub fn translateC(
5166 defer cache_tmp_dir.close(io);5138 defer cache_tmp_dir.close(io);
51675139
5168 const translated_path = try comp.dirs.local_cache.join(arena, &.{ tmp_sub_path, translated_basename });5140 const translated_path = try comp.dirs.local_cache.join(arena, &.{ tmp_sub_path, translated_basename });
5169 const source_path = switch (source) {
5170 .c_src => |c_src| path: {
5171 const cimport_basename = "cimport.h";
5172 const out_h_sub_path = tmp_sub_path ++ fs.path.sep_str ++ cimport_basename;
5173 const out_h_path = try comp.dirs.local_cache.join(arena, &.{out_h_sub_path});
5174 if (comp.verbose_cimport) log.info("writing C import source to {s}", .{out_h_path});
5175 try cache_dir.writeFile(io, .{ .sub_path = out_h_sub_path, .data = c_src });
5176 break :path out_h_path;
5177 },
5178 .path => |p| p,
5179 };
51805141
5181 const out_dep_path: ?[]const u8 = blk: {5142 const out_dep_path: ?[]const u8 = blk: {
5182 if (comp.disable_c_depfile) break :blk null;5143 if (comp.disable_c_depfile) break :blk null;
...@@ -5219,15 +5180,12 @@ pub fn translateC(...@@ -5219,15 +5180,12 @@ pub fn translateC(
5219 try argv.appendSlice(comp.global_cc_argv);5180 try argv.appendSlice(comp.global_cc_argv);
5220 try argv.appendSlice(owner_mod.cc_argv);5181 try argv.appendSlice(owner_mod.cc_argv);
5221 try argv.appendSlice(&.{ source_path, "-o", translated_path });5182 try argv.appendSlice(&.{ source_path, "-o", translated_path });
5222 if (comp.verbose_cimport) try dumpArgv(io, argv.items);
5223 }5183 }
52245184
5225 var stdout: []u8 = undefined;5185 var stdout: []u8 = undefined;
5226 try @import("main.zig").translateC(gpa, arena, io, argv.items, environ_map, prog_node, comp.thread_limit, &stdout);5186 try @import("main.zig").translateC(gpa, arena, io, argv.items, environ_map, prog_node, comp.thread_limit, &stdout);
52275187
5228 if (out_dep_path) |dep_file_path| add_deps: {5188 if (out_dep_path) |dep_file_path| add_deps: {
5229 if (comp.verbose_cimport) log.info("processing dep file at {s}", .{dep_file_path});
5230
5231 const dep_basename = fs.path.basename(dep_file_path);5189 const dep_basename = fs.path.basename(dep_file_path);
5232 // Add the files depended on to the cache system, if a dep file was emitted5190 // Add the files depended on to the cache system, if a dep file was emitted
5233 man.addDepFilePost(cache_tmp_dir, dep_basename) catch |err| switch (err) {5191 man.addDepFilePost(cache_tmp_dir, dep_basename) catch |err| switch (err) {
...@@ -5274,7 +5232,6 @@ pub fn translateC(...@@ -5274,7 +5232,6 @@ pub fn translateC(
5274 const hex_digest = Cache.binToHex(bin_digest);5232 const hex_digest = Cache.binToHex(bin_digest);
5275 const o_sub_path = "o" ++ fs.path.sep_str ++ hex_digest;5233 const o_sub_path = "o" ++ fs.path.sep_str ++ hex_digest;
52765234
5277 if (comp.verbose_cimport) log.info("renaming {s} to {s}", .{ tmp_sub_path, o_sub_path });
5278 try renameTmpIntoCache(io, comp.dirs.local_cache, tmp_sub_path, o_sub_path);5235 try renameTmpIntoCache(io, comp.dirs.local_cache, tmp_sub_path, o_sub_path);
52795236
5280 return .{5237 return .{
...@@ -5284,58 +5241,6 @@ pub fn translateC(...@@ -5284,58 +5241,6 @@ pub fn translateC(
5284 };5241 };
5285}5242}
52865243
5287/// Caller owns returned memory.
5288pub fn cImport(
5289 comp: *Compilation,
5290 c_src: []const u8,
5291 owner_mod: *Package.Module,
5292 prog_node: std.Progress.Node,
5293) !CImportResult {
5294 dev.check(.translate_c_command);
5295
5296 const translated_basename = "cimport.zig";
5297
5298 var man = comp.obtainCObjectCacheManifest(owner_mod);
5299 defer man.deinit();
5300
5301 man.hash.add(@as(u16, 0x7dd9)); // Random number to distinguish c-import from compiling C objects
5302 man.hash.addBytes(c_src);
5303
5304 const result: CImportResult = if (try man.hit()) .{
5305 .digest = man.finalBin(),
5306 .cache_hit = true,
5307 .errors = ErrorBundle.empty,
5308 } else result: {
5309 var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
5310 defer arena_allocator.deinit();
5311 const arena = arena_allocator.allocator();
5312
5313 break :result try translateC(
5314 comp,
5315 arena,
5316 &man,
5317 .c,
5318 .{ .c_src = c_src },
5319 translated_basename,
5320 owner_mod,
5321 prog_node,
5322 comp.environ_map,
5323 );
5324 };
5325
5326 if (result.errors.errorMessageCount() == 0 and man.have_exclusive_lock) {
5327 // Write the updated manifest. This is a no-op if the manifest is not dirty. Note that it is
5328 // possible we had a hit and the manifest is dirty, for example if the file mtime changed but
5329 // the contents were the same, we hit the cache but the manifest is dirty and we need to update
5330 // it to prevent doing a full file content comparison the next time around.
5331 man.writeManifest() catch |err| {
5332 log.warn("failed to write cache manifest for C import: {s}", .{@errorName(err)});
5333 };
5334 }
5335
5336 return result;
5337}
5338
5339fn workerUpdateCObject(5244fn workerUpdateCObject(
5340 comp: *Compilation,5245 comp: *Compilation,
5341 c_object: *CObject,5246 c_object: *CObject,
...@@ -7492,7 +7397,6 @@ fn buildOutputFromZig(...@@ -7492,7 +7397,6 @@ fn buildOutputFromZig(
7492 .verbose_generic_instances = comp.verbose_intern_pool,7397 .verbose_generic_instances = comp.verbose_intern_pool,
7493 .verbose_llvm_ir = comp.verbose_llvm_ir,7398 .verbose_llvm_ir = comp.verbose_llvm_ir,
7494 .verbose_llvm_bc = comp.verbose_llvm_bc,7399 .verbose_llvm_bc = comp.verbose_llvm_bc,
7495 .verbose_cimport = comp.verbose_cimport,
7496 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,7400 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
7497 .clang_passthrough_mode = comp.clang_passthrough_mode,7401 .clang_passthrough_mode = comp.clang_passthrough_mode,
7498 .skip_linker_dependencies = true,7402 .skip_linker_dependencies = true,
...@@ -7630,7 +7534,6 @@ pub fn build_crt_file(...@@ -7630,7 +7534,6 @@ pub fn build_crt_file(
7630 .verbose_generic_instances = comp.verbose_generic_instances,7534 .verbose_generic_instances = comp.verbose_generic_instances,
7631 .verbose_llvm_ir = comp.verbose_llvm_ir,7535 .verbose_llvm_ir = comp.verbose_llvm_ir,
7632 .verbose_llvm_bc = comp.verbose_llvm_bc,7536 .verbose_llvm_bc = comp.verbose_llvm_bc,
7633 .verbose_cimport = comp.verbose_cimport,
7634 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,7537 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
7635 .clang_passthrough_mode = comp.clang_passthrough_mode,7538 .clang_passthrough_mode = comp.clang_passthrough_mode,
7636 .skip_linker_dependencies = true,7539 .skip_linker_dependencies = true,
src/Sema.zig-186
...@@ -385,8 +385,6 @@ pub const Block = struct {...@@ -385,8 +385,6 @@ pub const Block = struct {
385 /// What mode to generate float operations in, set by @setFloatMode385 /// What mode to generate float operations in, set by @setFloatMode
386 float_mode: std.builtin.FloatMode = .strict,386 float_mode: std.builtin.FloatMode = .strict,
387387
388 c_import_buf: ?*std.array_list.Managed(u8) = null,
389
390 /// If not `null`, this boolean is set when a `dbg_var_ptr`, `dbg_var_val`, or `dbg_arg_inline`.388 /// If not `null`, this boolean is set when a `dbg_var_ptr`, `dbg_var_val`, or `dbg_arg_inline`.
391 /// instruction is emitted. It signals that the innermost lexically389 /// instruction is emitted. It signals that the innermost lexically
392 /// enclosing `block`/`block_inline` should be translated into a real AIR390 /// enclosing `block`/`block_inline` should be translated into a real AIR
...@@ -526,7 +524,6 @@ pub const Block = struct {...@@ -526,7 +524,6 @@ pub const Block = struct {
526 .runtime_index = parent.runtime_index,524 .runtime_index = parent.runtime_index,
527 .want_safety = parent.want_safety,525 .want_safety = parent.want_safety,
528 .float_mode = parent.float_mode,526 .float_mode = parent.float_mode,
529 .c_import_buf = parent.c_import_buf,
530 .error_return_trace_index = parent.error_return_trace_index,527 .error_return_trace_index = parent.error_return_trace_index,
531 .need_debug_scope = parent.need_debug_scope,528 .need_debug_scope = parent.need_debug_scope,
532 .src_base_inst = parent.src_base_inst,529 .src_base_inst = parent.src_base_inst,
...@@ -1189,7 +1186,6 @@ fn analyzeBodyInner(...@@ -1189,7 +1186,6 @@ fn analyzeBodyInner(
1189 .bool_not => try sema.zirBoolNot(block, inst),1186 .bool_not => try sema.zirBoolNot(block, inst),
1190 .bool_br_and => try sema.zirBoolBr(block, inst, false),1187 .bool_br_and => try sema.zirBoolBr(block, inst, false),
1191 .bool_br_or => try sema.zirBoolBr(block, inst, true),1188 .bool_br_or => try sema.zirBoolBr(block, inst, true),
1192 .c_import => try sema.zirCImport(block, inst),
1193 .call => try sema.zirCall(block, inst, .direct),1189 .call => try sema.zirCall(block, inst, .direct),
1194 .field_call => try sema.zirCall(block, inst, .field),1190 .field_call => try sema.zirCall(block, inst, .field),
1195 .cmp_lt => try sema.zirCmp(block, inst, .lt),1191 .cmp_lt => try sema.zirCmp(block, inst, .lt),
...@@ -1414,9 +1410,6 @@ fn analyzeBodyInner(...@@ -1414,9 +1410,6 @@ fn analyzeBodyInner(
1414 .sub_with_overflow => try sema.zirOverflowArithmetic(block, extended, extended.opcode),1410 .sub_with_overflow => try sema.zirOverflowArithmetic(block, extended, extended.opcode),
1415 .mul_with_overflow => try sema.zirOverflowArithmetic(block, extended, extended.opcode),1411 .mul_with_overflow => try sema.zirOverflowArithmetic(block, extended, extended.opcode),
1416 .shl_with_overflow => try sema.zirOverflowArithmetic(block, extended, extended.opcode),1412 .shl_with_overflow => try sema.zirOverflowArithmetic(block, extended, extended.opcode),
1417 .c_undef => try sema.zirCUndef( block, extended),
1418 .c_include => try sema.zirCInclude( block, extended),
1419 .c_define => try sema.zirCDefine( block, extended),
1420 .wasm_memory_size => try sema.zirWasmMemorySize( block, extended),1413 .wasm_memory_size => try sema.zirWasmMemorySize( block, extended),
1421 .wasm_memory_grow => try sema.zirWasmMemoryGrow( block, extended),1414 .wasm_memory_grow => try sema.zirWasmMemoryGrow( block, extended),
1422 .prefetch => try sema.zirPrefetch( block, extended),1415 .prefetch => try sema.zirPrefetch( block, extended),
...@@ -5212,136 +5205,6 @@ fn zirLoop(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError...@@ -5212,136 +5205,6 @@ fn zirLoop(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError
5212 return sema.resolveAnalyzedBlock(parent_block, src, &child_block, merges, false);5205 return sema.resolveAnalyzedBlock(parent_block, src, &child_block, merges, false);
5213}5206}
52145207
5215fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
5216 const tracy = trace(@src());
5217 defer tracy.end();
5218
5219 const pt = sema.pt;
5220 const zcu = pt.zcu;
5221 const comp = zcu.comp;
5222 const gpa = comp.gpa;
5223 const io = comp.io;
5224
5225 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
5226 const src = parent_block.nodeOffset(pl_node.src_node);
5227 const extra = sema.code.extraData(Zir.Inst.Block, pl_node.payload_index);
5228 const body = sema.code.bodySlice(extra.end, extra.data.body_len);
5229
5230 var c_import_buf = std.array_list.Managed(u8).init(gpa);
5231 defer c_import_buf.deinit();
5232
5233 var child_block: Block = .{
5234 .parent = parent_block,
5235 .sema = sema,
5236 .namespace = parent_block.namespace,
5237 .instructions = .empty,
5238 .inlining = parent_block.inlining,
5239 .comptime_reason = .{ .reason = .{
5240 .src = src,
5241 .r = .{ .simple = .operand_cImport },
5242 } },
5243 .c_import_buf = &c_import_buf,
5244 .runtime_cond = parent_block.runtime_cond,
5245 .runtime_loop = parent_block.runtime_loop,
5246 .runtime_index = parent_block.runtime_index,
5247 .src_base_inst = parent_block.src_base_inst,
5248 .type_name_ctx = parent_block.type_name_ctx,
5249 };
5250 defer child_block.instructions.deinit(gpa);
5251
5252 _ = try sema.analyzeInlineBody(&child_block, body, inst);
5253
5254 const prog_node = zcu.cur_sema_prog_node.start("@cImport", 0);
5255 defer prog_node.end();
5256
5257 var c_import_res = comp.cImport(c_import_buf.items, parent_block.ownerModule(), prog_node) catch |err|
5258 return sema.fail(&child_block, src, "C import failed: {t}", .{err});
5259 defer c_import_res.deinit(gpa);
5260
5261 if (c_import_res.errors.errorMessageCount() != 0) {
5262 const msg = msg: {
5263 const msg = try sema.errMsg(src, "C import failed", .{});
5264 errdefer msg.destroy(gpa);
5265
5266 if (!comp.config.link_libc)
5267 try sema.errNote(src, msg, "libc headers not available; compilation does not link against libc", .{});
5268
5269 const gop = try zcu.cimport_errors.getOrPut(gpa, sema.owner);
5270 if (!gop.found_existing) {
5271 gop.value_ptr.* = c_import_res.errors;
5272 c_import_res.errors = std.zig.ErrorBundle.empty;
5273 }
5274 break :msg msg;
5275 };
5276 return sema.failWithOwnedErrorMsg(&child_block, msg);
5277 }
5278 const parent_mod = parent_block.ownerModule();
5279 const digest = Cache.binToHex(c_import_res.digest);
5280
5281 const new_file_index = file: {
5282 const c_import_zig_path = try comp.arena.dupe(u8, "o" ++ std.fs.path.sep_str ++ digest);
5283 const c_import_mod = Package.Module.create(comp.arena, .{
5284 .paths = .{
5285 .root = try .fromRoot(comp.arena, comp.dirs, .local_cache, c_import_zig_path),
5286 .root_src_path = "cimport.zig",
5287 },
5288 .fully_qualified_name = c_import_zig_path,
5289 .cc_argv = parent_mod.cc_argv,
5290 .inherited = .{},
5291 .global = comp.config,
5292 .parent = parent_mod,
5293 }) catch |err| switch (err) {
5294 error.OutOfMemory => |e| return e,
5295 // None of these are possible because we are creating a package with
5296 // the exact same configuration as the parent package, which already
5297 // passed these checks.
5298 error.ValgrindUnsupportedOnTarget => unreachable,
5299 error.TargetRequiresSingleThreaded => unreachable,
5300 error.BackendRequiresSingleThreaded => unreachable,
5301 error.TargetRequiresPic => unreachable,
5302 error.PieRequiresPic => unreachable,
5303 error.DynamicLinkingRequiresPic => unreachable,
5304 error.TargetHasNoRedZone => unreachable,
5305 error.StackCheckUnsupportedByTarget => unreachable,
5306 error.StackProtectorUnsupportedByTarget => unreachable,
5307 error.StackProtectorUnavailableWithoutLibC => unreachable,
5308 };
5309 const c_import_file_path: Compilation.Path = try c_import_mod.root.join(gpa, comp.dirs, "cimport.zig");
5310 errdefer c_import_file_path.deinit(gpa);
5311 const c_import_file = try gpa.create(Zcu.File);
5312 errdefer gpa.destroy(c_import_file);
5313 const c_import_file_index = try zcu.intern_pool.createFile(gpa, io, pt.tid, .{
5314 .bin_digest = c_import_file_path.digest(),
5315 .file = c_import_file,
5316 .root_type = .none,
5317 });
5318 c_import_file.* = .{
5319 .status = .never_loaded,
5320 .stat = undefined,
5321 .is_builtin = false,
5322 .path = c_import_file_path,
5323 .source = null,
5324 .tree = null,
5325 .zir = null,
5326 .zoir = null,
5327 .mod = c_import_mod,
5328 .sub_file_path = "cimport.zig",
5329 .module_changed = false,
5330 .prev_zir = null,
5331 .zoir_invalidated = false,
5332 };
5333 try zcu.alive_files.putNoClobber(zcu.gpa, c_import_file_index, undefined);
5334 break :file c_import_file_index;
5335 };
5336 pt.updateFile(new_file_index, zcu.fileByIndex(new_file_index)) catch |err|
5337 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
5338
5339 try pt.ensureFilePopulated(new_file_index);
5340 const ty: Type = .fromInterned(zcu.fileRootType(new_file_index));
5341 try sema.addTypeReferenceEntry(src, ty);
5342 return .fromType(ty);
5343}
5344
5345fn zirSuspendBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {5208fn zirSuspendBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
5346 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;5209 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
5347 const src = parent_block.nodeOffset(inst_data.src_node);5210 const src = parent_block.nodeOffset(inst_data.src_node);
...@@ -5388,7 +5251,6 @@ fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileErro...@@ -5388,7 +5251,6 @@ fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileErro
5388 .is_typeof = parent_block.is_typeof,5251 .is_typeof = parent_block.is_typeof,
5389 .want_safety = parent_block.want_safety,5252 .want_safety = parent_block.want_safety,
5390 .float_mode = parent_block.float_mode,5253 .float_mode = parent_block.float_mode,
5391 .c_import_buf = parent_block.c_import_buf,
5392 .runtime_cond = parent_block.runtime_cond,5254 .runtime_cond = parent_block.runtime_cond,
5393 .runtime_loop = parent_block.runtime_loop,5255 .runtime_loop = parent_block.runtime_loop,
5394 .runtime_index = parent_block.runtime_index,5256 .runtime_index = parent_block.runtime_index,
...@@ -24690,54 +24552,6 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A...@@ -24690,54 +24552,6 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
24690 );24552 );
24691}24553}
2469224554
24693fn zirCUndef(
24694 sema: *Sema,
24695 block: *Block,
24696 extended: Zir.Inst.Extended.InstData,
24697) CompileError!Air.Inst.Ref {
24698 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
24699 const src = block.builtinCallArgSrc(extra.node, 0);
24700
24701 const name = try sema.resolveConstString(block, src, extra.operand, .{ .simple = .operand_cUndef_macro_name });
24702 try block.c_import_buf.?.print("#undef {s}\n", .{name});
24703 return .void_value;
24704}
24705
24706fn zirCInclude(
24707 sema: *Sema,
24708 block: *Block,
24709 extended: Zir.Inst.Extended.InstData,
24710) CompileError!Air.Inst.Ref {
24711 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
24712 const src = block.builtinCallArgSrc(extra.node, 0);
24713
24714 const name = try sema.resolveConstString(block, src, extra.operand, .{ .simple = .operand_cInclude_file_name });
24715 try block.c_import_buf.?.print("#include <{s}>\n", .{name});
24716 return .void_value;
24717}
24718
24719fn zirCDefine(
24720 sema: *Sema,
24721 block: *Block,
24722 extended: Zir.Inst.Extended.InstData,
24723) CompileError!Air.Inst.Ref {
24724 const pt = sema.pt;
24725 const zcu = pt.zcu;
24726 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
24727 const name_src = block.builtinCallArgSrc(extra.node, 0);
24728 const val_src = block.builtinCallArgSrc(extra.node, 1);
24729
24730 const name = try sema.resolveConstString(block, name_src, extra.lhs, .{ .simple = .operand_cDefine_macro_name });
24731 const rhs = sema.resolveInst(extra.rhs);
24732 if (sema.typeOf(rhs).zigTypeTag(zcu) != .void) {
24733 const value = try sema.resolveConstString(block, val_src, extra.rhs, .{ .simple = .operand_cDefine_macro_value });
24734 try block.c_import_buf.?.print("#define {s} {s}\n", .{ name, value });
24735 } else {
24736 try block.c_import_buf.?.print("#define {s}\n", .{name});
24737 }
24738 return .void_value;
24739}
24740
24741fn zirWasmMemorySize(24555fn zirWasmMemorySize(
24742 sema: *Sema,24556 sema: *Sema,
24743 block: *Block,24557 block: *Block,
src/codegen/llvm/bindings.zig-3
...@@ -1,6 +1,3 @@...@@ -1,6 +1,3 @@
1//! We do this instead of @cImport because the self-hosted compiler is easier
2//! to bootstrap if it does not depend on translate-c.
3
4/// Do not compare directly to .True, use toBool() instead.1/// Do not compare directly to .True, use toBool() instead.
5pub const Bool = enum(c_int) {2pub const Bool = enum(c_int) {
6 False,3 False,
src/libs/freebsd.zig-1
...@@ -1112,7 +1112,6 @@ fn buildSharedLib(...@@ -1112,7 +1112,6 @@ fn buildSharedLib(
1112 .verbose_air = comp.verbose_air,1112 .verbose_air = comp.verbose_air,
1113 .verbose_llvm_ir = comp.verbose_llvm_ir,1113 .verbose_llvm_ir = comp.verbose_llvm_ir,
1114 .verbose_llvm_bc = comp.verbose_llvm_bc,1114 .verbose_llvm_bc = comp.verbose_llvm_bc,
1115 .verbose_cimport = comp.verbose_cimport,
1116 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,1115 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
1117 .clang_passthrough_mode = comp.clang_passthrough_mode,1116 .clang_passthrough_mode = comp.clang_passthrough_mode,
1118 .version = version,1117 .version = version,
src/libs/glibc.zig-1
...@@ -1257,7 +1257,6 @@ fn buildSharedLib(...@@ -1257,7 +1257,6 @@ fn buildSharedLib(
1257 .verbose_air = comp.verbose_air,1257 .verbose_air = comp.verbose_air,
1258 .verbose_llvm_ir = comp.verbose_llvm_ir,1258 .verbose_llvm_ir = comp.verbose_llvm_ir,
1259 .verbose_llvm_bc = comp.verbose_llvm_bc,1259 .verbose_llvm_bc = comp.verbose_llvm_bc,
1260 .verbose_cimport = comp.verbose_cimport,
1261 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,1260 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
1262 .clang_passthrough_mode = comp.clang_passthrough_mode,1261 .clang_passthrough_mode = comp.clang_passthrough_mode,
1263 .version = version,1262 .version = version,
src/libs/libcxx.zig-2
...@@ -271,7 +271,6 @@ pub fn buildLibCxx(comp: *Compilation, prog_node: std.Progress.Node) BuildError!...@@ -271,7 +271,6 @@ pub fn buildLibCxx(comp: *Compilation, prog_node: std.Progress.Node) BuildError!
271 .verbose_air = comp.verbose_air,271 .verbose_air = comp.verbose_air,
272 .verbose_llvm_ir = comp.verbose_llvm_ir,272 .verbose_llvm_ir = comp.verbose_llvm_ir,
273 .verbose_llvm_bc = comp.verbose_llvm_bc,273 .verbose_llvm_bc = comp.verbose_llvm_bc,
274 .verbose_cimport = comp.verbose_cimport,
275 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,274 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
276 .clang_passthrough_mode = comp.clang_passthrough_mode,275 .clang_passthrough_mode = comp.clang_passthrough_mode,
277 .skip_linker_dependencies = true,276 .skip_linker_dependencies = true,
...@@ -465,7 +464,6 @@ pub fn buildLibCxxAbi(comp: *Compilation, prog_node: std.Progress.Node) BuildErr...@@ -465,7 +464,6 @@ pub fn buildLibCxxAbi(comp: *Compilation, prog_node: std.Progress.Node) BuildErr
465 .verbose_air = comp.verbose_air,464 .verbose_air = comp.verbose_air,
466 .verbose_llvm_ir = comp.verbose_llvm_ir,465 .verbose_llvm_ir = comp.verbose_llvm_ir,
467 .verbose_llvm_bc = comp.verbose_llvm_bc,466 .verbose_llvm_bc = comp.verbose_llvm_bc,
468 .verbose_cimport = comp.verbose_cimport,
469 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,467 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
470 .clang_passthrough_mode = comp.clang_passthrough_mode,468 .clang_passthrough_mode = comp.clang_passthrough_mode,
471 .skip_linker_dependencies = true,469 .skip_linker_dependencies = true,
src/libs/libtsan.zig-1
...@@ -296,7 +296,6 @@ pub fn buildTsan(comp: *Compilation, prog_node: std.Progress.Node) BuildError!vo...@@ -296,7 +296,6 @@ pub fn buildTsan(comp: *Compilation, prog_node: std.Progress.Node) BuildError!vo
296 .verbose_air = comp.verbose_air,296 .verbose_air = comp.verbose_air,
297 .verbose_llvm_ir = comp.verbose_llvm_ir,297 .verbose_llvm_ir = comp.verbose_llvm_ir,
298 .verbose_llvm_bc = comp.verbose_llvm_bc,298 .verbose_llvm_bc = comp.verbose_llvm_bc,
299 .verbose_cimport = comp.verbose_cimport,
300 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,299 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
301 .clang_passthrough_mode = comp.clang_passthrough_mode,300 .clang_passthrough_mode = comp.clang_passthrough_mode,
302 .skip_linker_dependencies = skip_linker_dependencies,301 .skip_linker_dependencies = skip_linker_dependencies,
src/libs/libunwind.zig-1
...@@ -157,7 +157,6 @@ pub fn buildStaticLib(comp: *Compilation, prog_node: std.Progress.Node) BuildErr...@@ -157,7 +157,6 @@ pub fn buildStaticLib(comp: *Compilation, prog_node: std.Progress.Node) BuildErr
157 .verbose_air = comp.verbose_air,157 .verbose_air = comp.verbose_air,
158 .verbose_llvm_ir = comp.verbose_llvm_ir,158 .verbose_llvm_ir = comp.verbose_llvm_ir,
159 .verbose_llvm_bc = comp.verbose_llvm_bc,159 .verbose_llvm_bc = comp.verbose_llvm_bc,
160 .verbose_cimport = comp.verbose_cimport,
161 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,160 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
162 .clang_passthrough_mode = comp.clang_passthrough_mode,161 .clang_passthrough_mode = comp.clang_passthrough_mode,
163 .skip_linker_dependencies = true,162 .skip_linker_dependencies = true,
src/libs/musl.zig-1
...@@ -253,7 +253,6 @@ pub fn buildCrtFile(comp: *Compilation, in_crt_file: CrtFile, prog_node: std.Pro...@@ -253,7 +253,6 @@ pub fn buildCrtFile(comp: *Compilation, in_crt_file: CrtFile, prog_node: std.Pro
253 .verbose_link = comp.verbose_link,253 .verbose_link = comp.verbose_link,
254 .verbose_air = comp.verbose_air,254 .verbose_air = comp.verbose_air,
255 .verbose_llvm_ir = comp.verbose_llvm_ir,255 .verbose_llvm_ir = comp.verbose_llvm_ir,
256 .verbose_cimport = comp.verbose_cimport,
257 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,256 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
258 .clang_passthrough_mode = comp.clang_passthrough_mode,257 .clang_passthrough_mode = comp.clang_passthrough_mode,
259 .c_source_files = &.{258 .c_source_files = &.{
src/libs/netbsd.zig-1
...@@ -755,7 +755,6 @@ fn buildSharedLib(...@@ -755,7 +755,6 @@ fn buildSharedLib(
755 .verbose_air = comp.verbose_air,755 .verbose_air = comp.verbose_air,
756 .verbose_llvm_ir = comp.verbose_llvm_ir,756 .verbose_llvm_ir = comp.verbose_llvm_ir,
757 .verbose_llvm_bc = comp.verbose_llvm_bc,757 .verbose_llvm_bc = comp.verbose_llvm_bc,
758 .verbose_cimport = comp.verbose_cimport,
759 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,758 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
760 .clang_passthrough_mode = comp.clang_passthrough_mode,759 .clang_passthrough_mode = comp.clang_passthrough_mode,
761 .version = version,760 .version = version,
src/libs/openbsd.zig-1
...@@ -683,7 +683,6 @@ fn buildSharedLib(...@@ -683,7 +683,6 @@ fn buildSharedLib(
683 .verbose_air = comp.verbose_air,683 .verbose_air = comp.verbose_air,
684 .verbose_llvm_ir = comp.verbose_llvm_ir,684 .verbose_llvm_ir = comp.verbose_llvm_ir,
685 .verbose_llvm_bc = comp.verbose_llvm_bc,685 .verbose_llvm_bc = comp.verbose_llvm_bc,
686 .verbose_cimport = comp.verbose_cimport,
687 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,686 .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features,
688 .clang_passthrough_mode = comp.clang_passthrough_mode,687 .clang_passthrough_mode = comp.clang_passthrough_mode,
689 .soname = soname,688 .soname = soname,
src/main.zig+5-13
...@@ -860,7 +860,6 @@ fn buildOutputType(...@@ -860,7 +860,6 @@ fn buildOutputType(
860 var verbose_llvm_ir: ?[]const u8 = null;860 var verbose_llvm_ir: ?[]const u8 = null;
861 var verbose_llvm_bc: ?[]const u8 = null;861 var verbose_llvm_bc: ?[]const u8 = null;
862 var link_depfile: ?[]const u8 = null;862 var link_depfile: ?[]const u8 = null;
863 var verbose_cimport = false;
864 var verbose_llvm_cpu_features = false;863 var verbose_llvm_cpu_features = false;
865 var time_report = false;864 var time_report = false;
866 var stack_report = false;865 var stack_report = false;
...@@ -1742,8 +1741,6 @@ fn buildOutputType(...@@ -1742,8 +1741,6 @@ fn buildOutputType(
1742 verbose_llvm_ir = rest;1741 verbose_llvm_ir = rest;
1743 } else if (mem.cutPrefix(u8, arg, "--verbose-llvm-bc=")) |rest| {1742 } else if (mem.cutPrefix(u8, arg, "--verbose-llvm-bc=")) |rest| {
1744 verbose_llvm_bc = rest;1743 verbose_llvm_bc = rest;
1745 } else if (mem.eql(u8, arg, "--verbose-cimport")) {
1746 verbose_cimport = true;
1747 } else if (mem.eql(u8, arg, "--verbose-llvm-cpu-features")) {1744 } else if (mem.eql(u8, arg, "--verbose-llvm-cpu-features")) {
1748 verbose_llvm_cpu_features = true;1745 verbose_llvm_cpu_features = true;
1749 } else if (mem.cutPrefix(u8, arg, "-T")) |rest| {1746 } else if (mem.cutPrefix(u8, arg, "-T")) |rest| {
...@@ -3650,7 +3647,6 @@ fn buildOutputType(...@@ -3650,7 +3647,6 @@ fn buildOutputType(
3650 .verbose_llvm_ir = verbose_llvm_ir,3647 .verbose_llvm_ir = verbose_llvm_ir,
3651 .verbose_llvm_bc = verbose_llvm_bc,3648 .verbose_llvm_bc = verbose_llvm_bc,
3652 .link_depfile = link_depfile,3649 .link_depfile = link_depfile,
3653 .verbose_cimport = verbose_cimport,
3654 .verbose_llvm_cpu_features = verbose_llvm_cpu_features,3650 .verbose_llvm_cpu_features = verbose_llvm_cpu_features,
3655 .time_report = time_report,3651 .time_report = time_report,
3656 .stack_report = stack_report,3652 .stack_report = stack_report,
...@@ -4289,7 +4285,7 @@ fn serve(...@@ -4289,7 +4285,7 @@ fn serve(
4289 var arena_instance = std.heap.ArenaAllocator.init(gpa);4285 var arena_instance = std.heap.ArenaAllocator.init(gpa);
4290 defer arena_instance.deinit();4286 defer arena_instance.deinit();
4291 const arena = arena_instance.allocator();4287 const arena = arena_instance.allocator();
4292 var output: Compilation.CImportResult = undefined;4288 var output: Compilation.TranslateCResult = undefined;
4293 try cmdTranslateC(comp, arena, &output, file_system_inputs, main_progress_node, environ_map);4289 try cmdTranslateC(comp, arena, &output, file_system_inputs, main_progress_node, environ_map);
4294 defer output.deinit(gpa);4290 defer output.deinit(gpa);
42954291
...@@ -4713,7 +4709,7 @@ fn updateModule(comp: *Compilation, color: Color, prog_node: std.Progress.Node)...@@ -4713,7 +4709,7 @@ fn updateModule(comp: *Compilation, color: Color, prog_node: std.Progress.Node)
4713fn cmdTranslateC(4709fn cmdTranslateC(
4714 comp: *Compilation,4710 comp: *Compilation,
4715 arena: Allocator,4711 arena: Allocator,
4716 fancy_output: ?*Compilation.CImportResult,4712 fancy_output: ?*Compilation.TranslateCResult,
4717 file_system_inputs: ?*std.ArrayList(u8),4713 file_system_inputs: ?*std.ArrayList(u8),
4718 prog_node: std.Progress.Node,4714 prog_node: std.Progress.Node,
4719 environ_map: *process.Environ.Map,4715 environ_map: *process.Environ.Map,
...@@ -4735,7 +4731,7 @@ fn cmdTranslateC(...@@ -4735,7 +4731,7 @@ fn cmdTranslateC(
4735 Compilation.cache_helpers.hashCSource(&man, c_source_file) catch |err|4731 Compilation.cache_helpers.hashCSource(&man, c_source_file) catch |err|
4736 fatal("unable to process '{s}': {t}", .{ c_source_file.src_path, err });4732 fatal("unable to process '{s}': {t}", .{ c_source_file.src_path, err });
47374733
4738 const result: Compilation.CImportResult = if (try man.hit()) .{4734 const result: Compilation.TranslateCResult = if (try man.hit()) .{
4739 .digest = man.finalBin(),4735 .digest = man.finalBin(),
4740 .cache_hit = true,4736 .cache_hit = true,
4741 .errors = std.zig.ErrorBundle.empty,4737 .errors = std.zig.ErrorBundle.empty,
...@@ -4744,7 +4740,7 @@ fn cmdTranslateC(...@@ -4744,7 +4740,7 @@ fn cmdTranslateC(
4744 arena,4740 arena,
4745 &man,4741 &man,
4746 Compilation.classifyFileExt(c_source_file.src_path),4742 Compilation.classifyFileExt(c_source_file.src_path),
4747 .{ .path = c_source_file.src_path },4743 c_source_file.src_path,
4748 translated_basename,4744 translated_basename,
4749 comp.root_mod,4745 comp.root_mod,
4750 prog_node,4746 prog_node,
...@@ -4976,7 +4972,6 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,...@@ -4976,7 +4972,6 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,
4976 var verbose_generic_instances = false;4972 var verbose_generic_instances = false;
4977 var verbose_llvm_ir: ?[]const u8 = null;4973 var verbose_llvm_ir: ?[]const u8 = null;
4978 var verbose_llvm_bc: ?[]const u8 = null;4974 var verbose_llvm_bc: ?[]const u8 = null;
4979 var verbose_cimport = false;
4980 var verbose_llvm_cpu_features = false;4975 var verbose_llvm_cpu_features = false;
4981 var fetch_only = false;4976 var fetch_only = false;
4982 var fetch_mode: Package.Fetch.JobQueue.Mode = .needed;4977 var fetch_mode: Package.Fetch.JobQueue.Mode = .needed;
...@@ -5141,8 +5136,6 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,...@@ -5141,8 +5136,6 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,
5141 verbose_llvm_ir = rest;5136 verbose_llvm_ir = rest;
5142 } else if (mem.cutPrefix(u8, arg, "--verbose-llvm-bc=")) |rest| {5137 } else if (mem.cutPrefix(u8, arg, "--verbose-llvm-bc=")) |rest| {
5143 verbose_llvm_bc = rest;5138 verbose_llvm_bc = rest;
5144 } else if (mem.eql(u8, arg, "--verbose-cimport")) {
5145 verbose_cimport = true;
5146 } else if (mem.eql(u8, arg, "--verbose-llvm-cpu-features")) {5139 } else if (mem.eql(u8, arg, "--verbose-llvm-cpu-features")) {
5147 verbose_llvm_cpu_features = true;5140 verbose_llvm_cpu_features = true;
5148 } else if (mem.eql(u8, arg, "--color")) {5141 } else if (mem.eql(u8, arg, "--color")) {
...@@ -5542,7 +5535,6 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,...@@ -5542,7 +5535,6 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,
5542 .verbose_generic_instances = verbose_generic_instances,5535 .verbose_generic_instances = verbose_generic_instances,
5543 .verbose_llvm_ir = verbose_llvm_ir,5536 .verbose_llvm_ir = verbose_llvm_ir,
5544 .verbose_llvm_bc = verbose_llvm_bc,5537 .verbose_llvm_bc = verbose_llvm_bc,
5545 .verbose_cimport = verbose_cimport,
5546 .verbose_llvm_cpu_features = verbose_llvm_cpu_features,5538 .verbose_llvm_cpu_features = verbose_llvm_cpu_features,
5547 .cache_mode = .whole,5539 .cache_mode = .whole,
5548 .reference_trace = reference_trace,5540 .reference_trace = reference_trace,
...@@ -5550,7 +5542,7 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,...@@ -5550,7 +5542,7 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, io: Io, args: []const []const u8,
5550 .environ_map = environ_map,5542 .environ_map = environ_map,
5551 }) catch |err| switch (err) {5543 }) catch |err| switch (err) {
5552 error.CreateFail => fatal("failed to create compilation: {f}", .{create_diag}),5544 error.CreateFail => fatal("failed to create compilation: {f}", .{create_diag}),
5553 else => fatal("failed to create compilation: {s}", .{@errorName(err)}),5545 else => fatal("failed to create compilation: {t}", .{err}),
5554 };5546 };
5555 defer comp.destroy();5547 defer comp.destroy();
55565548
src/print_zir.zig-4
...@@ -429,7 +429,6 @@ const Writer = struct {...@@ -429,7 +429,6 @@ const Writer = struct {
429 .block_inline,429 .block_inline,
430 .suspend_block,430 .suspend_block,
431 .loop,431 .loop,
432 .c_import,
433 .typeof_builtin,432 .typeof_builtin,
434 => try self.writeBlock(stream, inst),433 => try self.writeBlock(stream, inst),
435434
...@@ -555,8 +554,6 @@ const Writer = struct {...@@ -555,8 +554,6 @@ const Writer = struct {
555554
556 .tuple_decl => try self.writeTupleDecl(stream, extended),555 .tuple_decl => try self.writeTupleDecl(stream, extended),
557556
558 .c_undef,
559 .c_include,
560 .set_float_mode,557 .set_float_mode,
561 .wasm_memory_size,558 .wasm_memory_size,
562 .int_from_error,559 .int_from_error,
...@@ -579,7 +576,6 @@ const Writer = struct {...@@ -579,7 +576,6 @@ const Writer = struct {
579 },576 },
580577
581 .builtin_extern,578 .builtin_extern,
582 .c_define,
583 .error_cast,579 .error_cast,
584 .wasm_memory_grow,580 .wasm_memory_grow,
585 .prefetch,581 .prefetch,
test/cases/compile_errors/cimport.zig deleted-13
...@@ -1,13 +0,0 @@
1const b = @cDefine("foo", "1");
2const c = @cImport({
3 _ = @TypeOf(@cDefine("foo", "1"));
4});
5const d = @cImport({
6 _ = @cImport(@cDefine("foo", "1"));
7});
8
9// error
10//
11// :1:11: error: C define valid only inside C import block
12// :3:17: error: C define valid only inside C import block
13// :6:9: error: cannot nest @cImport
test/cases/compile_errors/unable_to_evaluate_expr_inside_cimport.zig deleted-13
...@@ -1,13 +0,0 @@
1const c = @cImport({
2 if (foo == 0) {}
3});
4extern var foo: i32;
5export fn entry() void {
6 _ = c;
7}
8
9// error
10//
11// :2:13: error: unable to evaluate comptime expression
12// :2:9: note: operation is runtime due to this operand
13// :1:11: note: operand to '@cImport' is evaluated at comptime
test/standalone/build.zig.zon-6
...@@ -36,9 +36,6 @@...@@ -36,9 +36,6 @@
36 .compile_asm = .{36 .compile_asm = .{
37 .path = "compile_asm",37 .path = "compile_asm",
38 },38 },
39 .issue_794 = .{
40 .path = "issue_794",
41 },
42 .issue_5825 = .{39 .issue_5825 = .{
43 .path = "issue_5825",40 .path = "issue_5825",
44 },41 },
...@@ -84,9 +81,6 @@...@@ -84,9 +81,6 @@
84 .dep_shared_builtin = .{81 .dep_shared_builtin = .{
85 .path = "dep_shared_builtin",82 .path = "dep_shared_builtin",
86 },83 },
87 .dep_lazypath = .{
88 .path = "dep_lazypath",
89 },
90 .dirname = .{84 .dirname = .{
91 .path = "dirname",85 .path = "dirname",
92 },86 },
test/standalone/dep_lazypath/build.zig deleted-42
...@@ -1,42 +0,0 @@
1const std = @import("std");
2
3pub fn build(b: *std.Build) void {
4 const test_step = b.step("test", "Test it");
5 b.default_step = test_step;
6
7 const optimize: std.builtin.OptimizeMode = .Debug;
8
9 {
10 const write_files = b.addWriteFiles();
11 const generated_main_c = write_files.add("main.c", "");
12 const exe = b.addExecutable(.{
13 .name = "test",
14 .root_module = b.createModule(.{
15 .root_source_file = null,
16 .target = b.graph.host,
17 .optimize = optimize,
18 }),
19 });
20 exe.root_module.addCSourceFiles(.{
21 .root = generated_main_c.dirname(),
22 .files = &.{"main.c"},
23 });
24 b.step("csourcefiles", "").dependOn(&exe.step);
25 test_step.dependOn(&exe.step);
26 }
27 {
28 const write_files = b.addWriteFiles();
29 const dir = write_files.addCopyDirectory(b.path("inc"), "", .{});
30 const exe = b.addExecutable(.{
31 .name = "test",
32 .root_module = b.createModule(.{
33 .root_source_file = b.path("inctest.zig"),
34 .target = b.graph.host,
35 .optimize = optimize,
36 }),
37 });
38 exe.root_module.addIncludePath(dir);
39 b.step("copydir", "").dependOn(&exe.step);
40 test_step.dependOn(&exe.step);
41 }
42}
test/standalone/dep_lazypath/inc/foo.h deleted-1
...@@ -1 +0,0 @@
1#define foo_value 42
test/standalone/dep_lazypath/inctest.zig deleted-8
...@@ -1,8 +0,0 @@
1const std = @import("std");
2const c = @cImport({
3 @cInclude("foo.h");
4});
5comptime {
6 std.debug.assert(c.foo_value == 42);
7}
8pub fn main() void {}
test/standalone/glibc_compat/build.zig+32
...@@ -180,12 +180,44 @@ pub fn build(b: *std.Build) void {...@@ -180,12 +180,44 @@ pub fn build(b: *std.Build) void {
180 }180 }
181 }181 }
182182
183 const malloc_translation = b.addTranslateC(.{
184 .root_source_file = b.path("include_malloc.h"),
185 .target = target,
186 .optimize = .Debug,
187 .link_libc = true,
188 });
189 const stdlib_translation = b.addTranslateC(.{
190 .root_source_file = b.path("include_stdlib.h"),
191 .target = target,
192 .optimize = .Debug,
193 .link_libc = true,
194 });
195 const string_translation = b.addTranslateC(.{
196 .root_source_file = b.path("include_string.h"),
197 .target = target,
198 .optimize = .Debug,
199 .link_libc = true,
200 });
183 const exe = b.addExecutable(.{201 const exe = b.addExecutable(.{
184 .name = t,202 .name = t,
185 .root_module = b.createModule(.{203 .root_module = b.createModule(.{
186 .root_source_file = b.path("glibc_runtime_check.zig"),204 .root_source_file = b.path("glibc_runtime_check.zig"),
187 .target = target,205 .target = target,
188 .link_libc = true,206 .link_libc = true,
207 .imports = &.{
208 .{
209 .name = "malloc.h",
210 .module = malloc_translation.createModule(),
211 },
212 .{
213 .name = "stdlib.h",
214 .module = stdlib_translation.createModule(),
215 },
216 .{
217 .name = "string.h",
218 .module = string_translation.createModule(),
219 },
220 },
189 }),221 }),
190 });222 });
191 // We disable UBSAN for these tests as the libc being tested here is223 // We disable UBSAN for these tests as the libc being tested here is
test/standalone/glibc_compat/glibc_runtime_check.zig+3-11
...@@ -8,17 +8,9 @@ const std = @import("std");...@@ -8,17 +8,9 @@ const std = @import("std");
8const builtin = @import("builtin");8const builtin = @import("builtin");
9const assert = std.debug.assert;9const assert = std.debug.assert;
1010
11const c_malloc = @cImport(11const c_malloc = @import("malloc.h"); // for reallocarray
12 @cInclude("malloc.h"), // for reallocarray12const c_stdlib = @import("stdlib.h"); // for atexit
13);13const c_string = @import("string.h"); // for strlcpy
14
15const c_stdlib = @cImport(
16 @cInclude("stdlib.h"), // for atexit
17);
18
19const c_string = @cImport(
20 @cInclude("string.h"), // for strlcpy
21);
2214
23// Version of glibc this test is being built to run against15// Version of glibc this test is being built to run against
24const glibc_ver = builtin.os.versionRange().gnuLibCVersion().?;16const glibc_ver = builtin.os.versionRange().gnuLibCVersion().?;
test/standalone/glibc_compat/include_malloc.h created+1
...@@ -0,0 +1 @@
1#include <malloc.h>
test/standalone/glibc_compat/include_stdlib.h created+1
...@@ -0,0 +1 @@
1#include <stdlib.h>
test/standalone/glibc_compat/include_string.h created+1
...@@ -0,0 +1 @@
1#include <string.h>
test/standalone/issue_794/a_directory/foo.h deleted-1
...@@ -1 +0,0 @@
1#define NUMBER 1234
test/standalone/issue_794/build.zig deleted-17
...@@ -1,17 +0,0 @@
1const std = @import("std");
2
3pub fn build(b: *std.Build) void {
4 const test_step = b.step("test", "Test it");
5 b.default_step = test_step;
6
7 const test_artifact = b.addTest(.{ .root_module = b.createModule(.{
8 .root_source_file = b.path("main.zig"),
9 .target = b.graph.host,
10 }) });
11 test_artifact.root_module.addIncludePath(b.path("a_directory"));
12
13 // TODO: actually check the output
14 _ = test_artifact.getEmittedBin();
15
16 test_step.dependOn(&test_artifact.step);
17}
test/standalone/issue_794/main.zig deleted-7
...@@ -1,7 +0,0 @@
1const c = @cImport(@cInclude("foo.h"));
2const std = @import("std");
3const testing = std.testing;
4
5test "c import" {
6 try comptime testing.expect(c.NUMBER == 1234);
7}
test/standalone/simple/build.zig-1
...@@ -108,7 +108,6 @@ const cases = [_]Case{...@@ -108,7 +108,6 @@ const cases = [_]Case{
108 .os_tag = .freestanding,108 .os_tag = .freestanding,
109 },109 },
110 },110 },
111 .{ .src_path = "issue_12471/main.zig" },
112 .{ .src_path = "guess_number/main.zig" },111 .{ .src_path = "guess_number/main.zig" },
113 .{ .src_path = "main_return_error/error_u8.zig" },112 .{ .src_path = "main_return_error/error_u8.zig" },
114 .{ .src_path = "main_return_error/error_u8_non_zero.zig" },113 .{ .src_path = "main_return_error/error_u8_non_zero.zig" },
test/standalone/simple/issue_12471/main.zig deleted-12
...@@ -1,12 +0,0 @@
1const c = @cImport({
2 @cDefine("FOO", "FOO");
3 @cDefine("BAR", "FOO");
4
5 @cDefine("BAZ", "QUX");
6 @cDefine("QUX", "QUX");
7});
8
9pub fn main() u8 {
10 _ = c;
11 return 0;
12}
tools/doctest.zig+1-14
...@@ -185,10 +185,6 @@ fn printOutput(...@@ -185,10 +185,6 @@ fn printOutput(
185 try shell_out.print("-fno-llvm", .{});185 try shell_out.print("-fno-llvm", .{});
186 }186 }
187 }187 }
188 if (code.verbose_cimport) {
189 try build_args.append("--verbose-cimport");
190 try shell_out.print("--verbose-cimport ", .{});
191 }
192 for (code.additional_options) |option| {188 for (code.additional_options) |option| {
193 try build_args.append(option);189 try build_args.append(option);
194 try shell_out.print("{s} ", .{option});190 try shell_out.print("{s} ", .{option});
...@@ -223,11 +219,7 @@ fn printOutput(...@@ -223,11 +219,7 @@ fn printOutput(
223 }219 }
224 const exec_result = run(arena, io, environ_map, tmp_dir_path, build_args.items) catch220 const exec_result = run(arena, io, environ_map, tmp_dir_path, build_args.items) catch
225 fatal("example failed to compile", .{});221 fatal("example failed to compile", .{});
226222 _ = exec_result;
227 if (code.verbose_cimport) {
228 const escaped_build_stderr = try escapeHtml(arena, exec_result.stderr);
229 try shell_out.writeAll(escaped_build_stderr);
230 }
231223
232 if (code.target_str) |triple| {224 if (code.target_str) |triple| {
233 if (mem.startsWith(u8, triple, "wasm32") or225 if (mem.startsWith(u8, triple, "wasm32") or
...@@ -853,7 +845,6 @@ const Code = struct {...@@ -853,7 +845,6 @@ const Code = struct {
853 link_libc: bool,845 link_libc: bool,
854 link_mode: ?std.builtin.LinkMode,846 link_mode: ?std.builtin.LinkMode,
855 disable_cache: bool,847 disable_cache: bool,
856 verbose_cimport: bool,
857 just_check_syntax: bool,848 just_check_syntax: bool,
858 additional_options: []const []const u8,849 additional_options: []const []const u8,
859 use_llvm: ?bool,850 use_llvm: ?bool,
...@@ -915,7 +906,6 @@ fn parseManifest(arena: Allocator, source_bytes: []const u8) !Code {...@@ -915,7 +906,6 @@ fn parseManifest(arena: Allocator, source_bytes: []const u8) !Code {
915 var target_str: ?[]const u8 = null;906 var target_str: ?[]const u8 = null;
916 var link_libc = false;907 var link_libc = false;
917 var disable_cache = false;908 var disable_cache = false;
918 var verbose_cimport = false;
919 var use_llvm: ?bool = null;909 var use_llvm: ?bool = null;
920910
921 while (it.next()) |prefixed_line| {911 while (it.next()) |prefixed_line| {
...@@ -940,8 +930,6 @@ fn parseManifest(arena: Allocator, source_bytes: []const u8) !Code {...@@ -940,8 +930,6 @@ fn parseManifest(arena: Allocator, source_bytes: []const u8) !Code {
940 link_libc = true;930 link_libc = true;
941 } else if (mem.eql(u8, line, "disable_cache")) {931 } else if (mem.eql(u8, line, "disable_cache")) {
942 disable_cache = true;932 disable_cache = true;
943 } else if (mem.eql(u8, line, "verbose_cimport")) {
944 verbose_cimport = true;
945 } else {933 } else {
946 fatal("unrecognized manifest line: {s}", .{line});934 fatal("unrecognized manifest line: {s}", .{line});
947 }935 }
...@@ -956,7 +944,6 @@ fn parseManifest(arena: Allocator, source_bytes: []const u8) !Code {...@@ -956,7 +944,6 @@ fn parseManifest(arena: Allocator, source_bytes: []const u8) !Code {
956 .link_libc = link_libc,944 .link_libc = link_libc,
957 .link_mode = link_mode,945 .link_mode = link_mode,
958 .disable_cache = disable_cache,946 .disable_cache = disable_cache,
959 .verbose_cimport = verbose_cimport,
960 .just_check_syntax = just_check_syntax,947 .just_check_syntax = just_check_syntax,
961 .use_llvm = use_llvm,948 .use_llvm = use_llvm,
962 };949 };
tools/migrate_langref.zig-5
...@@ -249,7 +249,6 @@ const Code = struct {...@@ -249,7 +249,6 @@ const Code = struct {
249 link_libc: bool,249 link_libc: bool,
250 link_mode: ?std.builtin.LinkMode,250 link_mode: ?std.builtin.LinkMode,
251 disable_cache: bool,251 disable_cache: bool,
252 verbose_cimport: bool,
253 additional_options: []const []const u8,252 additional_options: []const []const u8,
254253
255 const Id = union(enum) {254 const Id = union(enum) {
...@@ -326,7 +325,6 @@ fn walk(arena: Allocator, io: Io, tokenizer: *Tokenizer, out_dir: Dir, w: anytyp...@@ -326,7 +325,6 @@ fn walk(arena: Allocator, io: Io, tokenizer: *Tokenizer, out_dir: Dir, w: anytyp
326 var link_libc = false;325 var link_libc = false;
327 var link_mode: ?std.builtin.LinkMode = null;326 var link_mode: ?std.builtin.LinkMode = null;
328 var disable_cache = false;327 var disable_cache = false;
329 var verbose_cimport = false;
330 var additional_options = std.array_list.Managed([]const u8).init(arena);328 var additional_options = std.array_list.Managed([]const u8).init(arena);
331329
332 const source_token = while (true) {330 const source_token = while (true) {
...@@ -340,8 +338,6 @@ fn walk(arena: Allocator, io: Io, tokenizer: *Tokenizer, out_dir: Dir, w: anytyp...@@ -340,8 +338,6 @@ fn walk(arena: Allocator, io: Io, tokenizer: *Tokenizer, out_dir: Dir, w: anytyp
340 mode = .ReleaseSafe;338 mode = .ReleaseSafe;
341 } else if (mem.eql(u8, end_tag_name, "code_disable_cache")) {339 } else if (mem.eql(u8, end_tag_name, "code_disable_cache")) {
342 disable_cache = true;340 disable_cache = true;
343 } else if (mem.eql(u8, end_tag_name, "code_verbose_cimport")) {
344 verbose_cimport = true;
345 } else if (mem.eql(u8, end_tag_name, "code_link_object")) {341 } else if (mem.eql(u8, end_tag_name, "code_link_object")) {
346 _ = try eatToken(tokenizer, .separator);342 _ = try eatToken(tokenizer, .separator);
347 const obj_tok = try eatToken(tokenizer, .tag_content);343 const obj_tok = try eatToken(tokenizer, .tag_content);
...@@ -419,7 +415,6 @@ fn walk(arena: Allocator, io: Io, tokenizer: *Tokenizer, out_dir: Dir, w: anytyp...@@ -419,7 +415,6 @@ fn walk(arena: Allocator, io: Io, tokenizer: *Tokenizer, out_dir: Dir, w: anytyp
419415
420 if (link_libc) try code.print("// link_libc\n", .{});416 if (link_libc) try code.print("// link_libc\n", .{});
421 if (disable_cache) try code.print("// disable_cache\n", .{});417 if (disable_cache) try code.print("// disable_cache\n", .{});
422 if (verbose_cimport) try code.print("// verbose_cimport\n", .{});
423418
424 if (link_mode) |m|419 if (link_mode) |m|
425 try code.print("// link_mode={s}\n", .{@tagName(m)});420 try code.print("// link_mode={s}\n", .{@tagName(m)});