2415 Commits

Author SHA1 Message Date
mlugg
37a9a4e0f1
compiler: refactor Zcu.File and path representation
This commit makes some big changes to how we track state for Zig source
files. In particular, it changes:

* How `File` tracks its path on-disk
* How AstGen discovers files
* How file-level errors are tracked
* How `builtin.zig` files and modules are created

The original motivation here was to address incremental compilation bugs
with the handling of files, such as #22696. To fix this, a few changes
are necessary.

Just like declarations may become unreferenced on an incremental update,
meaning we suppress analysis errors associated with them, it is also
possible for all imports of a file to be removed on an incremental
update, in which case file-level errors for that file should be
suppressed. As such, after AstGen, the compiler must traverse files
(starting from analysis roots) and discover the set of "live files" for
this update.

Additionally, the compiler's previous handling of retryable file errors
was not very good; the source location the error was reported as was
based only on the first discovered import of that file. This source
location also disappeared on future incremental updates. So, as a part
of the file traversal above, we also need to figure out the source
locations of imports which errors should be reported against.

Another observation I made is that the "file exists in multiple modules"
error was not implemented in a particularly good way (I get to say that
because I wrote it!). It was subject to races, where the order in which
different imports of a file were discovered affects both how errors are
printed, and which module the file is arbitrarily assigned, with the
latter in turn affecting which other files are considered for import.
The thing I realised here is that while the AstGen worker pool is
running, we cannot know for sure which module(s) a file is in; we could
always discover an import later which changes the answer.

So, here's how the AstGen workers have changed. We initially ensure that
`zcu.import_table` contains the root files for all modules in this Zcu,
even if we don't know any imports for them yet. Then, the AstGen
workers do not need to be aware of modules. Instead, they simply ignore
module imports, and only spin off more workers when they see a by-path
import.

During AstGen, we can't use module-root-relative paths, since we don't
know which modules files are in; but we don't want to unnecessarily use
absolute files either, because those are non-portable and can make
`error.NameTooLong` more likely. As such, I have introduced a new
abstraction, `Compilation.Path`. This type is a way of representing a
filesystem path which has a *canonical form*. The path is represented
relative to one of a few special directories: the lib directory, the
global cache directory, or the local cache directory. As a fallback, we
use absolute (or cwd-relative on WASI) paths. This is kind of similar to
`std.Build.Cache.Path` with a pre-defined list of possible
`std.Build.Cache.Directory`, but has stricter canonicalization rules
based on path resolution to make sure deduplicating files works
properly. A `Compilation.Path` can be trivially converted to a
`std.Build.Cache.Path` from a `Compilation`, but is smaller, has a
canonical form, and has a digest which will be consistent across
different compiler processes with the same lib and cache directories
(important when we serialize incremental compilation state in the
future). `Zcu.File` and `Zcu.EmbedFile` both contain a
`Compilation.Path`, which is used to access the file on-disk;
module-relative sub paths are used quite rarely (`EmbedFile` doesn't
even have one now for simplicity).

After the AstGen workers all complete, we know that any file which might
be imported is definitely in `import_table` and up-to-date. So, we
perform a single-threaded graph traversal; similar to what
`resolveReferences` plays for `AnalUnit`s, but for files instead. We
figure out which files are alive, and which module each file is in. If a
file turns out to be in multiple modules, we set a field on `Zcu` to
indicate this error. If a file is in a different module to a prior
update, we set a flag instructing `updateZirRefs` to invalidate all
dependencies on the file. This traversal also discovers "import errors";
these are errors associated with a specific `@import`. With Zig's
current design, there is only one possible error here: "import outside
of module root". This must be identified during this traversal instead
of during AstGen, because it depends on which module the file is in. I
tried also representing "module not found" errors in this same way, but
it turns out to be much more useful to report those in Sema, because of
use cases like optional dependencies where a module import is behind a
comptime-known build option.

For simplicity, `failed_files` now just maps to `?[]u8`, since the
source location is always the whole file. In fact, this allows removing
`LazySrcLoc.Offset.entire_file` completely, slightly simplifying some
error reporting logic. File-level errors are now directly built in the
`std.zig.ErrorBundle.Wip`. If the payload is not `null`, it is the
message for a retryable error (i.e. an error loading the source file),
and will be reported with a "file imported here" note pointing to the
import site discovered during the single-threaded file traversal.

The last piece of fallout here is how `Builtin` works. Rather than
constructing "builtin" modules when creating `Package.Module`s, they are
now constructed on-the-fly by `Zcu`. The map `Zcu.builtin_modules` maps
from digests to `*Package.Module`s. These digests are abstract hashes of
the `Builtin` value; i.e. all of the options which are placed into
"builtin.zig". During the file traversal, we populate `builtin_modules`
as needed, so that when we see this imports in Sema, we just grab the
relevant entry from this map. This eliminates a bunch of awkward state
tracking during construction of the module graph. It's also now clearer
exactly what options the builtin module has, since previously it
inherited some options arbitrarily from the first-created module with
that "builtin" module!

The user-visible effects of this commit are:
* retryable file errors are now consistently reported against the whole
  file, with a note pointing to a live import of that file
* some theoretical bugs where imports are wrongly considered distinct
  (when the import path moves out of the cwd and then back in) are fixed
* some consistency issues with how file-level errors are reported are
  fixed; these errors will now always be printed in the same order
  regardless of how the AstGen pass assigns file indices
* incremental updates do not print retryable file errors differently
  between updates or depending on file structure/contents
* incremental updates support files changing modules
* incremental updates support files becoming unreferenced

Resolves: #22696
2025-05-18 17:37:02 +01:00
mlugg
4296727050
Sema: improve "called from here" notes
To an average user, it may be unclear why these notes are not just in
the reference trace; that's because they are more important, because
they are inline calls through which comptime values may propagate. There
are now 3 possible wordings for this note:

* "called at comptime here"
* "called inline here"
* "generic function instantiated here"

An alternative could be these wordings:

* "while analyzing comptime call here"
* "while analyzing inline call here"
* "while analyzing generic instantiation here"

I'm not sure which is better -- but this commit is certainly better than
status quo.
2025-05-16 13:28:15 +01:00
mlugg
d717c96877
compiler: include inline calls in the reference trace
Inline calls which happened in the erroring `AnalUnit` still show as
error notes, because they tend to make very important context (e.g. to
see how comptime values propagate through them). However, "earlier"
inline calls are still useful to see to understand how something is
being referenced, so we should include them in the reference trace.
2025-05-16 13:28:15 +01:00
mlugg
70040778fb
Compilation: fix reference trace behavior without -freference-trace
When `-freference-trace` is not passed, we want to show exactly one
reference trace. Previously, we set the reference trace root in `Sema`
iff there were no other failed analyses. However, this results in an
arbitrary error being the one with the reference trace after error
sorting. It is also incompatible with incremental compilation, where
some errors might be unreferenced. Instead, set the field on all
analysis errors, and decide in `Compilation.getAllErrorsAlloc` which
reference trace[s] to actually show.
2025-05-16 11:55:35 +01:00
Matthew Lugg
f4e9846bca
Merge pull request #23263 from mlugg/comptime-field-ptr
Sema: fix pointers to comptime fields of comptime-known aggregate pointers
2025-05-03 20:10:42 +01:00
Andrew Kelley
8facd99d41
Merge pull request #23708 from ziglang/memmove-followups
`@memmove` followups
2025-04-28 15:06:18 -04:00
mlugg
d038676a1f Sema: fix a few indexing bugs
* Indexing zero-bit types should not produce AIR indexing instructions
* Getting a runtime-known element pointer from a many-pointer should
  check that the many-pointer is not comptime-only

Resolves: #23405
2025-04-28 19:43:58 +01:00
dweiller
365ed0ed68 sema: do checked cast when resolving aggregate size 2025-04-28 16:48:45 +01:00
Andrew Kelley
7bd3207921 make @memcpy and @memmove share panic handlers 2025-04-27 23:30:00 -07:00
xdBronch
410298271e Sema: fix memcpy with C pointers 2025-04-28 05:09:12 +01:00
mlugg
95932e98e5
Sema: fix alignment of runtime field pointer of underaligned tuple 2025-04-28 01:14:24 +01:00
mlugg
d4c5396646
Sema: fix pointers to comptime fields of comptime-known aggregate pointers
Resolves: #23190
2025-04-28 01:14:22 +01:00
Alex Rønne Petersen
5ed8bd5c85 Sema: Fix some ptr alignment checks to handle a potential ISA tag bit.
Closes #23570.
2025-04-27 23:54:54 +01:00
dweiller
898ca82458 compiler: add @memmove builtin 2025-04-26 13:34:16 +10:00
mlugg
8c9c24e09b
compiler: integrate @compileLog with incremental compilation
Compile log output is now separated based on the `AnalUnit` which
perfomred the `@compileLog` call, so that we can omit the output for
unreferenced ("dead") units. The units are also sorted when collecting
the `ErrorBundle`, so that compile logs are always printed in a
consistent order, like compile errors are. This is important not only
for incremental compilation, but also for parallel analysis.

Resolves: #23609
2025-04-20 18:11:53 +01:00
Jacob Young
06eebafadd AstGen: redistribute inline asm limits 2025-04-10 06:04:09 -04:00
Alex Rønne Petersen
7415739e36
Sema: Prevent tail calls of std.builtin.returnError().
LLVM 20 started tail-calling it in some of our test cases, resulting in:

    error: AndMyCarIsOutOfGas
    /home/alexrp/Source/ziglang/zig-llvm20/repro.zig:2:5: 0x103ef9d in main (repro)
        return error.TheSkyIsFalling;
        ^
    /home/alexrp/Source/ziglang/zig-llvm20/repro.zig:6:5: 0x103efa5 in main (repro)
        return error.AndMyCarIsOutOfGas;
        ^
    /home/alexrp/Source/ziglang/zig-llvm20/lib/std/start.zig:656:37: 0x103ee83 in posixCallMainAndExit (repro)
                const result = root.main() catch |err| {
                                        ^

instead of the expected:

    error: AndMyCarIsOutOfGas
    /home/alexrp/Source/ziglang/zig-llvm20/repro.zig:2:5: 0x103f00d in main (repro)
        return error.TheSkyIsFalling;
        ^
    /home/alexrp/Source/ziglang/zig-llvm20/repro.zig:6:5: 0x103f015 in main (repro)
        return error.AndMyCarIsOutOfGas;
        ^
    /home/alexrp/Source/ziglang/zig-llvm20/repro.zig:11:9: 0x103f01d in main (repro)
            try bar();
            ^
2025-04-04 06:08:10 +02:00
Mason Remaley
06ee383da9
compiler: allow @import of ZON without a result type
In particular, this allows importing `build.zig.zon` at comptime.
2025-04-02 05:53:22 +01:00
David Rubin
1b62a22268 Sema: increment extra index even if return type is generic 2025-04-02 01:34:17 +02:00
mlugg
d53cc5e5b2 Sema: allow @ptrCast slice of zero-bit type to slice of non-zero-bit type
This is actually completely well-defined. The resulting slice always has
0 elements. The only disallowed case is casting *to* a slice of a
zero-bit type, because in that case, you cna't figure out how many
destination elements to use (and there's *no* valid destination length
if the source slice corresponds to more than 0 bits).
2025-03-31 19:03:08 -04:00
David Rubin
acfdad8581 Sema: convert slice sentinel to single pointer correctly 2025-03-30 03:41:00 +01:00
mlugg
eee752ea5a compiler: "illegal behavior", not "undefined behavior", in errors 2025-03-29 18:40:23 -04:00
Андрей Краевский
aac800ec65
std.meta.FieldType -> @FieldType 2025-03-27 03:49:38 +00:00
mlugg
26fdb81c16 Sema: fix in-memory coercion of functions introducing new generic parameters
While it is not allowed for a function coercion to change whether a
function is generic, it *is* okay to make existing concrete parameters
of a generic function also generic, or vice versa. Either of these cases
implies that the result is a generic function, so comptime type checks
will happen when the function is ultimately called.

Resolves: #21099
2025-03-24 04:32:45 +00:00
Jacob Young
c5c1c8538d x86_64: rewrite wrapping multiplication 2025-03-21 21:51:08 -04:00
Ali Cheraghi
c1977bf0fb Sema: error on illegal code when targeting spirv 2025-03-17 21:56:14 +03:30
mlugg
2a4e06bcb3 Sema: rewrite comptime arithmetic
This commit reworks how Sema handles arithmetic on comptime-known
values, fixing many bugs in the process.

The general pattern is that arithmetic on comptime-known values is now
handled by the new namespace `Sema.arith`. Functions handling comptime
arithmetic no longer live on `Value`; this is because some of them can
emit compile errors, so some *can't* go on `Value`. Only semantic
analysis should really be doing arithmetic on `Value`s anyway, so it
makes sense for it to integrate more tightly with `Sema`.

This commit also implements more coherent rules surrounding how
`undefined` interacts with comptime and mixed-comptime-runtime
arithmetic. The rules are as follows.

* If an operation cannot trigger Illegal Behavior, and any operand is
  `undefined`, the result is `undefined`. This includes operations like
  `0 *| undef`, where the LHS logically *could* be used to determine a
  defined result. This is partly to simplify the language, but mostly to
  permit codegen backends to represent `undefined` values as completely
  invalid states.

* If an operation *can* trigger Illegal Behvaior, and any operand is
  `undefined`, then Illegal Behavior results. This occurs even if the
  operand in question isn't the one that "decides" illegal behavior; for
  instance, `undef / 1` is undefined. This is for the same reasons as
  described above.

* An operation which would trigger Illegal Behavior, when evaluated at
  comptime, instead triggers a compile error. Additionally, if one
  operand is comptime-known undef, such that the other (runtime-known)
  operand isn't needed to determine that Illegal Behavior would occur,
  the compile error is triggered.

* The only situation in which an operation with one comptime-known
  operand has a comptime-known result is if that operand is undefined,
  in which case the result is either undefined or a compile error per
  the above rules. This could potentially be loosened in future (for
  instance, `0 * rt` could be comptime-known 0 with a runtime assertion
  that `rt` is not undefined), but at least for now, defining it more
  conservatively simplifies the language and allows us to easily change
  this in future if desired.

This commit fixes many bugs regarding the handling of `undefined`,
particularly in vectors. Along with a collection of smaller tests, two
very large test cases are added to check arithmetic on `undefined`.

The operations which have been rewritten in this PR are:

* `+`, `+%`, `+|`, `@addWithOverflow`
* `-`, `-%`, `-|`, `@subWithOverflow`
* `*`, `*%`, `*|`, `@mulWithOverflow`
* `/`, `@divFloor`, `@divTrunc`, `@divExact`
* `%`, `@rem`, `@mod`

Other arithmetic operations are currently unchanged.

Resolves: #22743
Resolves: #22745
Resolves: #22748
Resolves: #22749
Resolves: #22914
2025-03-16 08:17:50 +00:00
mlugg
aa3db7cc15 Sema: correctly handle empty by-ref initializers
Resolves: #23210
2025-03-16 03:05:33 +00:00
Matthew Lugg
d0911786c9
Merge pull request #22397 from Techatrix/type-safe-ast
improve type safety of std.zig.Ast
2025-03-12 02:22:41 +00:00
mlugg
423907c270 Sema: fix handling of @This() on opaques
Resolves: #22869
2025-03-11 13:13:52 +00:00
Andrew Kelley
539f3effd3
Merge pull request #21933 from kcbanner/comptime_nan_comparison
Fix float vector comparisons with signed zero and NaN, add test coverage
2025-03-09 15:06:25 -04:00
Ian Johnson
0bce4a4e05 Sema: handle generated tag enums in union field order check
Fixes #23059

The "note: enum field here" now references the field in the base union type rather than crashing.
2025-03-08 14:29:20 -05:00
Techatrix
ca6fb30e99
std.zig.Ast: improve type safety
This commits adds the following distinct integer types to std.zig.Ast:
- OptionalTokenIndex
- TokenOffset
- OptionalTokenOffset
- Node.OptionalIndex
- Node.Offset
- Node.OptionalOffset

The `Node.Index` type has also been converted to a distinct type while
`TokenIndex` remains unchanged.

`Ast.Node.Data` has also been changed to a (untagged) union to provide
safety checks.
2025-03-07 22:22:01 +01:00
kcbanner
981f84157c Value: fix comparison of NaN in compareHeteroAdvanaced
Sema: fix equality comparison of signed zeroes and NaN in compareScalar
tests: add test coverage for vector float comparisons
2025-03-03 15:35:07 -05:00
Andrew Kelley
6b6c1b1b0e Revert "Merge pull request #22898 from kristoff-it/deprecated-proposal"
This reverts commit dea72d15da4fba909dc3ccb2e9dc5286372ac023, reversing
changes made to ab381933c87bcc744058d25a876cfdc0d23fc674.

The changeset does not work as advertised and does not have sufficient
test coverage.

Reopens #22822
2025-02-28 01:37:10 -08:00
Andrew Kelley
f74a856d84 reword deprecated error slightly
"found" -> "reached" to match "reached unreachable code"
2025-02-26 14:41:33 -05:00
Loris Cro
466fa311b1 @deprecated: optimize sema implementation
mlugg suggested a better way of implementing analysis of an istruction
that cannot be referenced by other instructions.
2025-02-26 14:41:33 -05:00
Loris Cro
c75fdd96d2 @deprecated: add tests 2025-02-26 14:41:33 -05:00
Loris Cro
fff8eff2bd initial implementation of @deprecated 2025-02-26 14:41:33 -05:00
mlugg
84da520c44
Sema: remove legacy coercion
This was meant to be removed in #21817, but was somehow missed.
2025-02-26 00:17:09 +00:00
Alex Rønne Petersen
ecc76348e6
Merge pull request #22154 from alexrp/disable-intrinsics
compiler: Implement `@disableIntrinsics()` builtin function.
2025-02-24 08:25:23 +01:00
mlugg
5e20e9b449 Sema: allow @ptrCast of slices changing the length
Also, refactor `Sema.ptrCastFull` to not be a horrifying hellscape.
2025-02-23 08:28:58 +00:00
Alex Rønne Petersen
6ba785584a
compiler: Implement @disableIntrinsics() builtin function.
Closes #21833.
Closes #22110.
2025-02-23 04:08:56 +01:00
Andrew Kelley
eb3c7f5706 zig build fmt 2025-02-22 17:09:20 -08:00
Alex Rønne Petersen
fc7a0c4878 Sema: Fix fnptr alignment safety checks to account for potential ISA tag.
As seen on e.g. Arm/Thumb and MIPS (MIPS16/microMIPS).

Fixes #22888.
2025-02-22 04:12:46 +01:00
Alex Rønne Petersen
481b7bf3f0
std.Target: Remove functions that just wrap component functions.
Functions like isMinGW() and isGnuLibC() have a good reason to exist: They look
at multiple components of the target. But functions like isWasm(), isDarwin(),
isGnu(), etc only exist to save 4-8 characters. I don't think this is a good
enough reason to keep them, especially given that:

* It's not immediately obvious to a reader whether target.isDarwin() means the
  same thing as target.os.tag.isDarwin() precisely because isMinGW() and similar
  functions *do* look at multiple components.
* It's not clear where we would draw the line. The logical conclusion before
  this commit would be to also wrap Arch.isX86(), Os.Tag.isSolarish(),
  Abi.isOpenHarmony(), etc... this obviously quickly gets out of hand.
* It's nice to just have a single correct way of doing something.
2025-02-17 19:18:19 +01:00
Alex Rønne Petersen
ce8c61b0fc
std.Target: Move Cpu.Arch.supportsAddressSpace() up to Cpu.
This allows it to inspect CPU features which is needed for Propeller, and AVR in
the future.
2025-02-17 19:17:56 +01:00
Alex Rønne Petersen
0048166867
std.Target: Make Cpu.Arch.supportsAddressSpace() take an optional context.
Allows deduplicating the code in Sema.
2025-02-17 19:17:56 +01:00
Alex Rønne Petersen
e0f8d4e68e
std.builtin: Rename CallingConvention.wasm_watc to wasm_mvp. 2025-02-17 19:17:56 +01:00
Alex Rønne Petersen
9c015e6c2b
std.builtin: Remove CallingConvention.arm_(apcs,aapcs16_vfp).
* arm_apcs is the long dead "OABI" which we never had working support for.
* arm_aapcs16_vfp is for arm-watchos-none which is a dead target that we've
  dropped support for.
2025-02-17 19:17:56 +01:00