Compare commits

...
Author SHA1 Message Date
Chandler Carruth 733b76efea Add a permissions restriction
Assisted-by: Antigravity with Gemini
2026-04-24 02:09:42 +00:00
Richard Smith 69d745c6d7 Don't allow merging PRs with the dependent label. 2026-04-22 20:15:37 +00:00
Chandler Carruth d6a741f208 Add bootstrapping flags to the build system (#7084)
This takes the bootstrap support that was added and makes it available
under convenient user-facing flags for while we're doing development.

For example, to build a bootstrap compiler and use it to build and run
the tests under `//common/...` you can now use:

```
bazel test --//:bootstrap_stage=1 --//:bootstrap_exec_config=true //common/...
```

This will use the stage1 bootstrap compiler, and it will build that
compiler in the exec config (so it is optimized and the above even works
when cross-building with Bazel).

Assisted-by: Antigravity with Gemini
2026-04-21 00:59:10 +00:00
Dana Jansens 1e3906177c Update the name of the bazel target to build the nightly tarball (#7080)
The target was renamed in `82fad290285baf9763132a13b1f73de1e7919074`
from `//toolchain/install:carbon_toolchain_tar_gz_rule` to
`//toolchain/install:carbon_toolchain_tar_gz`
2026-04-20 17:59:55 +00:00
Dana Jansens 5e2f693db1 Preserve ErrorInst in TryGetTypeIdForTypeConstantId (#7079)
An ErrorInst::ConstantId constant can be used as a type, and should
result in an ErrorInst::TypeId
2026-04-20 17:11:53 +00:00
David BlaikieandGeoff Romer 1cc699ddda Make heterogenous hash table lookup opt-in (#6950)
This still only works if the hash of the distinct types are identical
(so it still doesn't address the derived pointer v base pointer case -
well, not in the way we would want to address it, we could use this
change to make derived pointer and base pointer not compare equal, but
that's not very ergonomic)

I think in a follow up maybe I can use a `TranslatingKeyContext` to
translate `Derived*` to `Base*` in general.

No test coverage for this change, since it's a no-compile situation and
we don't seem to generally do no-compile tests.
    
Discovered while working on #6940

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-04-18 01:32:39 +00:00
Geoff Romer ad0a4ea8a4 Restructure action-dependence APIs (#7074)
- Rename `ActionIsDependent` to `ActionIsPerformable` (with negated
meaning), because that name is more concrete and, um, actionable.
- Replace `OperandIsDependent` with `OperandDependence`, which returns a
`ConstantDependence` instead of a bool. We need this additional
generality for handling form actions, where we sometimes need to ask
whether something has _any_ dependence, not just whether it has template
dependence.
2026-04-17 19:03:21 +00:00
Richard Smith f91990aa87 Override Clang class layout for Carbon class types. (#7071)
Use the Carbon-determined size and alignment for Carbon-defined classes,
rather than allowing Clang to work one out for itself using the C++
rules.
2026-04-17 00:03:29 +00:00
Geoff Romer e7626f46cc Get rid of AddPatternInst (#7075)
Instead, use the inst category to select the right block stack. This
simplifies the API for adding insts, and in subsequent changes it will
enable certain inst kinds like `SpliceInst` to seamlessly function as
either procedural insts or pattern insts.
2026-04-16 23:31:31 +00:00
Geoff Romer af04d08965 Track declared form with an InstId instead of a ConstantId. (#7072)
This is mainly in order to track a location associated with the form.
2026-04-16 23:14:31 +00:00
Richard Smith a6061d975c Compute type layouts in SemIR / Check (#7066)
Instead of allowing lower to pick whatever type layout it desires,
compute the layouts of types as part of completing the type, and make
lower build types that match that representation.

For now we assume that all pointers are 64-bit, since we don't have
access to target information. We allow tail padding reuse for structs
and tuple types (and by extension, for classes, since they use structs
as their object representation), but not for arrays.

In order to build matching LLVM types, we create LLVM packed structs
where necessary, and we insert inter-field padding on the end of the
previous field so that GEP indexes still always match Carbon's
ElementIndexes.

We don't yet use the computed alignment much in LLVM IR generation -- in
particular, `alloca`s, `load`s, and `store`s should probably use the
computed type alignment, but don't.

Assisted-by: Gemini via Antigravity
2026-04-16 22:37:48 +00:00
Chandler Carruth 896338d281 Remove duplicate file and fix to include the bin directory (#7073)
Noticed this when testing the Carbon toolchain with a more complex
environment, don't have any way to observe this at the moment in Bazel
though.

Assisted-by: Antigravity with Gemini
2026-04-16 21:42:06 +00:00
Chandler Carruth d8fe95cccb Test and fix make-variable expansion in our toolchains (#7070)
This worked correctly in the system Clang toolchain, but was not
configured correctly in the Carbon toolchains. The test is designed to
let us cover all of these.

Assisted-by: Antigravity with Gemini
2026-04-16 21:08:37 +00:00
Geoff Romer df33276f6b Revert accidental change from #7063 (#7069) 2026-04-16 20:31:54 +00:00
Chandler Carruth 327cb2396a Add a Bazel skill (#7061)
Hopefully this significantly reduces how often agents try to run `bazel`
directly without repeatedly including that in prompts. Also tried to
generally give useful skills for building, testing, and running things.

Also added a specific admonition to the `AGENTS.md` as there is a chance
that agents don't think they need to look at any skills for "standard"
build system commands like `bazel`, as those are "trivial". It seems
like a small chunk of context to spend to avoid churning with bad build
commands.

Assisted-by: Antigravity with Gemini
2026-04-16 18:58:34 +00:00
Richard Smith 1d5113649b Allow non-constant calls to constexpr functions. (#7067)
These turn up frequently in real-world code, for example when converting
a mutable global `Cpp.std.string_view` to a `Cpp.std.string`. Only
reject a non-constant call if the callee is `consteval`, not if it's
`constexpr`.
2026-04-16 17:10:48 +00:00
Chandler Carruth cdfa57f230 Pull in a fix to the new compile commands system (#7068)
This pulls in my PR:
https://github.com/wolfd/bazel-compile-commands/pull/3

Fixes #7065

Assisted-by: Antigravity with Gemini
2026-04-16 16:58:29 +00:00
Richard Smith 46f46a538d Preliminary reverse interop support for base classes. (#7059)
Create a Clang AST representation of the base specifier.
2026-04-16 00:29:40 +00:00
Nicholas Bishop 114cf401c2 Support C++ calling Carbon functions with non-() return type (#7051)
For calling non-`()` functions, the Carbon->Carbon thunk now takes an
extra reference parameter and writes the target function's return value
out to that parameter. (At the SemIR level this is how returns already
work, but adding this extra reference parameter is needed so that the
function is lowered correctly.) The C++ thunk now creates a local
variable to be initialized by the Carbon thunk, and then returns that
value to the original C++ caller.
2026-04-16 00:29:38 +00:00
rit 7c94878c10 fixed a crash when lowering a ref return initialized by value expression (#7049)
Restructured `else-if` into `InitForm` case so that diagnostics are
emitted correctly and does not lead to a crash.
Conversation:
https://discord.com/channels/655572317891461132/1052653651895779359/1492278198405431397

Closes #6891
2026-04-15 20:52:56 +00:00
Chandler Carruth 82fad29028 Switch to conventionally use a name parameter for a macro (#7053)
This is important to allow tools like buildozer to manipulate macro
invocation.
2026-04-15 05:18:25 +00:00
Chandler CarruthandDana Jansens 26ddada3ae Switch from Bazel platforms to build settings (#7052)
The runtimes and bootstrap Bazel logic was previously built around
defining custom Bazel platforms constrained with `constraint_settings`.
The use of platforms added significant complexity, including the need to
"save" and "restore" the original platform, and other complexity
stemming from changing the platform as a whole.

This PR switches to use the simpler tool of build settings, and
`target_settings` on the toolchain rather than platform compatibility.
This remove the entire need to save and restore the platform, and also
generally simplifies things.

This PR also fixes some bugs in the bootstrap that were hidden by the
use of platforms, such as the need to carefully manage the different
inputs to the runtimes build so that generated inputs pick up the
correct exec configuration -- the exec transition happened to do this
"automatically", but it seems better to handle explicitly. And it cleans
up an extraneous copy of `carbon_runtimes.bzl` that snuck in somehow.

Assisted-by: Antigravity with Gemini

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-04-14 21:52:48 +00:00
Geoff Romer bab35c114e Remove the leading /proc/self/cwd/ from file paths in the debug info. (#7060)
Some tools like VS Code don't understand `/proc/self/cwd` in places like
terminal stack dumps, but do understand paths relative to the workspace
root.
2026-04-14 19:34:32 +00:00
Chandler Carruth 96529e16bd Fully switch to the new compilation database system (#7057)
This has been working really well for me, is incredibly faster than the
other approach, and some commits continue to hit bugs in the old system
where files that aren't even going to be run through `clangd-tidy` end
up tripping up the execution. Hopefully all of that is resolved with the
new version.
2026-04-14 13:41:33 +00:00
Richard Smith 43867a678b Reverse interop support for type aliases. (#7043)
Allow any type that has a mapping from Carbon to C++ to be exposed to
C++ via name lookup. This also exposes the logic to export Carbon
classes to C++ to apply during type mapping, which gives very slight
support for passing Carbon types to C++ functions from Carbon, but not
really enough to sensibly test yet.

Depends on #7042.
2026-04-14 00:18:33 +00:00
Richard Smith 5b1de7633c Use the raw import ID, not the tagged ID, as an array index. (#7058)
Previously we'd create a *huge* array here as the tagged ID produced a
very large index value, and spend multiple seconds allocating it and
filling it with zeroes the first time `GetCppLocation` was called.

Reduces test runtime from 26s -> 6s wall time, 450s -> 320s total time
on my machine for `-c dbg`.
2026-04-13 23:53:25 +00:00
Richard Smith f31e1685fd Only export each class or namespace to C++ once. (#7042)
Instead of exporting a class or namespace each time a new C++ name
lookup discovers it, track that we have exported the entity on its name
scope, and if a new name lookup finds the same entity, produce the same
clang declaration.
2026-04-13 19:43:44 +00:00
Christopher Di BellaandDana Jansens 3cdb159067 consistently uses the caller's specific to get the callee's pattern type id (#7036)
`DoVarPreWorkImpl` was provided an incorrect pattern type while trying
to match `var` parameters, which caused the toolchain to crash in
`Convert`. This commit changes `DoVarPreWorkImpl`'s API so it derives
the pattern type from the work item's pattern ID, rather than relying on
an external source.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-04-13 17:41:54 +00:00
Dana Jansens 12d7574636 Include extended named constraints in the type of .Self for a where clause (#7048)
The `.Self` should see all extended constraints from the LHS of the
`where`, which is both interfaces and named constraints.
2026-04-10 18:05:22 +00:00
Dana JansensandRichard Smith cc5a42691e Add where T impls X constraints into the FacetTypeInfo (#7038)
This makes them part of the identified facet type, and we can see the
constraints as part of stringify and format output.

But this does not do enough to make them useful yet: Any `T impls X`
constraint must contain a reference to `.Self` somewhere. And `.Self`
references do not get substituted, so neither `T(.Self) impls X` and `T
impls X(.Self)` will match against an incoming facet value derived from
an `impl T(U) as X` or `impl T as X(U)`, since `U` and `.Self` are never
the same thing until `.Self` can be substituted.

Now that impl lookup runs into facet values containing `.Self` (a
symbolic binding), such as in `C(.Self)`, we were crashing assuming the
type of `.Self` is a FacetType, but it can be `type` in the case of
`type where C(.Self) impls...`. Instead, use an empty facet type for the
type of `.Self` so it is always a facet. This assists with substituting
other facets into it, without having to insert an extra FacetAccessType.
`MakePeriodSelfFacetValue()` now enforces this requirement.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-04-10 14:29:36 +00:00
Chandler Carruth 19efec93be Fix missing runtimes file in the installation (#7044)
Fixes #7031

Also switches the previous symlinks test to be a more full integration
test. While a bit slow, it does seem worthwhile to have something that
tests things end-to-end, both with the prebuilt runtimes and the
on-demand runtimes. This test is already reasonably well separated from
the rest of the toolchain so incremental development shouldn't be
negatively impacted. And since we turned off ASan by default, it isn't
completely infeasibly expensive.

Assisted-by: Antigravity with Gemini
2026-04-09 21:49:19 +00:00
Chandler Carruth 3db691ecef Add ASan to post-merge CI and improve the action structure for GitHub (#7012)
Note that this will require changing the branch protections to use new
names for all of the checks and be somewhat disruptive. There aren't any
really good ways I could find of fixing this. Some options that I
explored:

- Have a single `pre-merge` workflow file that contains all of the other
workflows, splitting as much of the logic as we can into re-usable
files. This would basically merge testing, `pre-commit`, and
`clangd-tidy` checking into a single workflow file. However, it would
also delay the pre-commit suggestions action to only run once _all_ of
these finish, rather than as soon as pre-commit finishes.

- Serialize `pre-commit` and the rest of `pre-merge` to get the effect
of the above option but without the downside. Instead, the downside
would be serializing some of our actions.

- Have a single `pre-merge` workflow that triggers whenever any of the
other workflows completes, and have it check whether all the others have
completed. It will fail until it reaches that point. This requires
passing in GitHub keys to the workflow so that it can check the status
of other checks, and documentation online seems to indicate it is
sometimes flaky, I assume because of racing triggers of events or
check-status not being guaranteed consistent in the queries.

- Have a single `pre-merge` workflow that polls, waiting for all the
other workflows to finish using some Python logic. This requires
building and maintaining code to poll GitHub, keys to authorize that
polling, and handling all of the failure modes of a polling operation --
timeouts, network issues, etc.

Maybe there are others, but not sure what they look like. Suggestions
welcome here.

I'm hesitant to either delay the pre-commit suggestions or serialize
pre-commit execution. And the complexity or flakiness of the other two
options seem worse than having to re-work the branch protections each
time the naming here changes. But interested if folks think a different
direction would be better.

Assisted-by: Antigravity with Gemini
2026-04-09 20:37:23 +00:00
Dana JansensandChandler Carruth 6cc08ae6e6 Remove SymbolicBinding step in TypeIterator (#7039)
TypeIterator has both SymbolicType and SymbolicBinding and these overlap
in their meaning. Clarify the API by removing SymbolicBinding and just
using SymbolicType for `SymbolicBinding` insts and when they are
converted to `type` to make a `SymbolicBindingType` inst. Add the
EntityNameId to the SymbolicType for when it is available, when the
instruction is just a simple reference to a binding.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-04-09 13:25:16 +00:00
Richard Smith ab977ee04d Bump vscode extension to 0.0.8. (#7041) 2026-04-09 00:06:39 +00:00
Richard Smith be0c07dc7e Give Carbon -> C++ thunks internal linkage. (#7040)
Also declare them `inline` since we're putting the `always_inline`
attribute on them. Use the `internal_linkage` attribute rather than
`SC_Static` since it's a more precise mechanism and matches what we do
for static member functions in reverse interop (where `SC_Static` means
something else and would not give the function internal linkage).
2026-04-08 21:14:30 +00:00
Dana Jansens b79d9adeca Avoid crashing in custom witness for FacetTypes and symbolic object representations (#7033)
The type must be complete to look for a witness for Destroy. Do this
check through type completion rather than just checking to see if the
ClassInfo says the definition is closed, since completing the type has
side effects (resolves the self specific definition).

Then look for whether the class is abstract through the CompleteTypeInfo
instead of just looking at the inheritance type on ClassInfo, like type
completion does.

Last, FacetTypes are trivially destroyed just like TypeType.
2026-04-08 20:09:03 +00:00
Richard Smith b74e0d1260 Superficial support for exporting complete class types to C++. (#7029)
We don't yet populate the bases or fields, so the class types show up as
empty classes in C++ for now. But we do allow calls to static member
functions.
2026-04-08 19:29:25 +00:00
dependabot[bot] 9f1a0c816c Bump addressable from 2.8.7 to 2.9.0 in /website in the bundler group across 1 directory (#7037)
Bumps the bundler group with 1 update in the /website directory:
[addressable](https://github.com/sporkmonger/addressable).

Updates `addressable` from 2.8.7 to 2.9.0
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/sporkmonger/addressable/blob/main/CHANGELOG.md">addressable's
changelog</a>.</em></p>
<blockquote>
<h2>Addressable 2.9.0 <!-- raw HTML omitted --></h2>
<ul>
<li>fixes ReDoS vulnerability in Addressable::Template#match (fixes
incomplete
remediation in 2.8.10)</li>
</ul>
<h2>Addressable 2.8.10 <!-- raw HTML omitted --></h2>
<ul>
<li>fixes ReDoS vulnerability in Addressable::Template#match</li>
</ul>
<h2>Addressable 2.8.9 <!-- raw HTML omitted --></h2>
<ul>
<li>Reduce gem size by excluding test files (<a
href="https://redirect.github.com/sporkmonger/addressable/issues/569">#569</a>)</li>
<li>No need for bundler as development dependency (<a
href="https://redirect.github.com/sporkmonger/addressable/issues/571">#571</a>,
<a
href="https://github.com/sporkmonger/addressable/commit/5fc1d93">5fc1d93</a>)</li>
<li>idna/pure: stop building the useless <code>COMPOSITION_TABLE</code>
(removes the <code>Addressable::IDNA::COMPOSITION_TABLE</code> constant)
(<a
href="https://redirect.github.com/sporkmonger/addressable/issues/564">#564</a>)</li>
</ul>
<p><a
href="https://redirect.github.com/sporkmonger/addressable/issues/569">#569</a>:
<a
href="https://redirect.github.com/sporkmonger/addressable/pull/569">sporkmonger/addressable#569</a>
<a
href="https://redirect.github.com/sporkmonger/addressable/issues/571">#571</a>:
<a
href="https://redirect.github.com/sporkmonger/addressable/pull/571">sporkmonger/addressable#571</a>
<a
href="https://redirect.github.com/sporkmonger/addressable/issues/564">#564</a>:
<a
href="https://redirect.github.com/sporkmonger/addressable/pull/564">sporkmonger/addressable#564</a></p>
<h2>Addressable 2.8.8 <!-- raw HTML omitted --></h2>
<ul>
<li>Replace the <code>unicode.data</code> blob by a ruby constant (<a
href="https://redirect.github.com/sporkmonger/addressable/issues/561">#561</a>)</li>
<li>Allow <code>public_suffix</code> 7 (<a
href="https://redirect.github.com/sporkmonger/addressable/issues/558">#558</a>)</li>
</ul>
<p><a
href="https://redirect.github.com/sporkmonger/addressable/issues/561">#561</a>:
<a
href="https://redirect.github.com/sporkmonger/addressable/pull/561">sporkmonger/addressable#561</a>
<a
href="https://redirect.github.com/sporkmonger/addressable/issues/558">#558</a>:
<a
href="https://redirect.github.com/sporkmonger/addressable/pull/558">sporkmonger/addressable#558</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/sporkmonger/addressable/commit/0c3e8589b23d4402903a9b4e1fdeba4e43c52ca4"><code>0c3e858</code></a>
Revving version and changelog</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/91915c1f7aafa3e2c9f42e2f4e21d948c7a861b8"><code>91915c1</code></a>
Fixing additional vulnerable paths</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/a091e39ff02fc321b21dea3a0df585bef2ba3744"><code>a091e39</code></a>
Add many more adversarial test cases to ensure we don't have any ReDoS
regres...</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/463a819665a3b85ce5ce894c90bd7bfa3b9d2e15"><code>463a819</code></a>
Regenerate gemspec on newer rubygems</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/0afcb0b9672bee301e5e96ed850fec05b2fcabb0"><code>0afcb0b</code></a>
Improve from O(n^2) to O(n)</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/c87f768f22ab00376ed2f8cb106f59c9d0652d3a"><code>c87f768</code></a>
Fix a ReDoS vulnerability in URI template matching</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/0d7e9b259fb0940d1a85064b04f678a7984409a5"><code>0d7e9b2</code></a>
Fix links for 2.8.9 in CHANGELOG (<a
href="https://redirect.github.com/sporkmonger/addressable/issues/573">#573</a>)</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/e2091200b31553f19248eb871f071852409796f8"><code>e209120</code></a>
Update version, gemspec, and CHANGELOG for 2.8.9 (<a
href="https://redirect.github.com/sporkmonger/addressable/issues/572">#572</a>)</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/387587492b6536748ed12a11c3fdb44a48885f28"><code>3875874</code></a>
Reduce gem size by excluding test files (<a
href="https://redirect.github.com/sporkmonger/addressable/issues/569">#569</a>)</li>
<li><a
href="https://github.com/sporkmonger/addressable/commit/3e57cc6018f94231aabb47fd341acd1b40f1e71a"><code>3e57cc6</code></a>
CI: back to <code>windows-2022</code> for MRI job</li>
<li>Additional commits viewable in <a
href="https://github.com/sporkmonger/addressable/compare/addressable-2.8.7...addressable-2.9.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=addressable&package-manager=bundler&previous-version=2.8.7&new-version=2.9.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-08 19:05:36 +00:00
Geoff Romer 6f02354d62 Fix malformed split (#7035) 2026-04-08 00:31:43 +00:00
Nicholas Bishop 0635f4628f Add support for C++ calling Carbon functions with parameters (#7024)
This works by generating two thunks, one in C++ and one in Carbon. For
example, given this input:
```c++
// Carbon:
fn Callme(f: f32) {}

// C++:
void F() {
  // This will call `Callme__cpp_thunk`
  Carbon::Callme(1.0);
}
```

These functions are generated:
```c++
// Carbon:
fn Callme__carbon_thunk(ref f: f32) {
  // Call the target function.
  Callme(f);
}

// C++:

// C++ declaration for the Carbon thunk.
void Callme__carbon_thunk(float& f);

void Callme__cpp_thunk(float f) {
  // Call the Carbon thunk with args passed by reference.
  Callme__carbon_thunk(f);
}
```

For now, all arguments are passed by reference, even if they are simple
types like pointers or i32.

Functions with non-void return types are not supported yet.
2026-04-07 23:25:57 +00:00
Dana Jansens d1dc8e820d Resolve the specific definition for a function that is evaluated (#7034)
The function body may make use of values from the specific, so the
specific definition must be resolved before the function is evaluated.
2026-04-07 21:53:54 +00:00
Dana Jansens e1f30669af Remove TODO in impl lookup for discarding unused witnesses (#7032)
In #6972 we stopped finishing instructions added just for EvalOrAddInst,
which prevents adding the instruction to the containing generic eval
block.
2026-04-07 18:11:08 +00:00
Dana Jansens f483a28f2f Refactor WhereExpr evaluation into smaller helper functions (#7006)
This splits off the functionality to handle the base facet type,
rewrites, and impls constraints into separate functions.

We use the Context instead of EvalContext throughout, as the goal is to
move this code to EvalConstantInst in time. That means we do not apply
specifics to the functions in the requirements inst block. That is fine
because WhereExpr never evaluates to an WhereExpr, so this instruction
never survives as a constant value long enough to be re-evaluated with a
specific applied to it.
2026-04-07 13:52:56 +00:00
Richard Smith cc4fd39238 Support round-tripping entities through C++ and Carbon. (#7022)
Use the same C++ -> Carbon map for both interop directions, and when
importing an entity from Carbon -> C++, check whether it was originally
a C++ entity and if so return the original.

Assisted-by: Gemini via Google Antigravity
2026-04-07 08:10:21 +00:00
Chandler Carruth 013a417ea5 Add the static keyword to various syntax highlighting (#7026)
This follows #7016 which suggests using `static var` for non-instance
class data members.

Assisted-by: Antigravity with Gemini
2026-04-06 19:32:24 +00:00
Chandler Carruth 8fd4156616 Update tree_sitter for the new self syntax and static var (#7025)
This implements p7016 for tree_sitter. It also updates the build and
source file to allow this to build successfully and documents how to
successfully run these tests with Bazel given that it is fundamentally
not hermetic.

Assisted-by: Antigravity with Gemini
2026-04-06 19:31:54 +00:00
Richard Smith 05ba1d7356 Add a conversion impl from T* to const T* (#7010)
This is already allowed as a builtin conversion, but the impl allows the
generics system to know about it, so that conversions like
`Optional(T*)` to `Optional(const T*)` are allowed. This in turn allows
a C++ `T*` to be implicitly converted to a C++ `const T*` in Carbon
code.
2026-04-03 22:07:53 +00:00
Richard Smith 8e0d856725 Improve InPlaceInitializing conversion. (#7021)
Fix some situations where we'd drop the storage argument when building
an in-place initializing expression. We now guarantee that an expression
with the in-place initializing category always has a storage argument.
2026-04-03 21:28:54 +00:00
Richard SmithandGeoff Romer ea409f7cbf Fix crash lowering call to generic function with concrete type in signature (#7009)
When a function call appears in a generic, and calls another generic
that has a concrete type in its call-site signature, that concrete type
will be completed only in the file that contains the call. The generic
containing the call won't require completeness to be checked again when
forming a specific call, because the type was concrete. This means that
when lowering the call instruction, there is no single file that is
guaranteed to contain complete types for all of the callee's parameters
-- the file containing the specific callee won't necessarily have
completed the concrete parts of the signature, and the files containing
the definition and call won't necessarily have completed the symbolic
parts of the signature.

To handle this, look at both versions of the function when building its
lowered signature -- the version that we saw when forming the `call`
instruction and the version corresponding to the concrete, specific
callee, and combine information from both to form the LLVM function
type.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-04-03 21:24:00 +00:00
Chandler Carruth fed9e8c878 Create skills for using the gh tool (#7019)
This covers basic usage and using it to make API calls to GitHub. It
also works to establish some reasonable safety guards to avoid
inappropriate commands.

Also introduces a skill specifically for ingesting the content in GitHub
issues using the command line tool. This is especially useful as
otherwise agents may try to browse the web version of an issues that is
significantly slower and harder to ensure the agent correctly gets all
of the context into its window and is able to leverage it.

This also disables the Google documentation style checking for agent
skills, as we want to instead try to follow the conventions, phrasing,
and other patterns that map best for agents' training sets. For example,
this avoids replacing `repo` with `repository` and avoids replacing
`e.g.` with `for example`. While these replacements make lots of sense
for our human-facing documentation, the agent-facing docs probably
benefit from being terse and using the exact patterns that agents are
trained on.

Assisted-by: Antigravity with Gemini
2026-04-03 20:35:39 +00:00
Dana JansensandChandler Carruth 451b50a3ad Add storage for <type> impls <facettype> in the FacetTypeInfo (#7005)
We don't yet actually add any in check, but this adds the storage for
them, and capabilities to import them, evaluate them, substitute into
them with specifics, name them, format them, and stringify them.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-04-03 00:19:57 +00:00
rit 912825feaf Add basic test for lowering choice value acquisition (#7014)
Added test for lowering choice value acquisition. Before PR #6992 the
code in issue #6862 would crash/assert saying the instruction
`AcquireValue` is not concrete. I added this test as the fix did not
have one to test this particular case.
2026-04-03 00:01:21 +00:00
Richard Smith 81ed4d829d Perform CppThunkRef conversion as part of category conversion. (#7020)
Instead of recursing back into Convert, make CppThunkRef conversion just
add an extra step to category conversion, performing a copy conversion
followed by an ephemeral reference binding conversion.
2026-04-02 23:39:25 +00:00
Jon Ross-Perkinsandjonmeow 9266ced4e3 Improve CanDestroyType to handle remaining cases (#6943)
This is only fixing the decision about *whether* to produce a witness.
Implementation of the witness is still a TODO, though where a body is
generated, it should also precisely reflect where one _needs_ to be
generated.

Note the tests:

- toolchain/lower/testdata/function/generic/import_core_witness.carbon
- toolchain/lower/testdata/function/generic/import_unused_def.carbon

These tests can probably be produced _without_ Core.Destroy, but I found
the essence of them while trying to build //examples with Core.Destroy
and a simpler minimization wasn't striking me.

Assisted-by: Google Antigravity with Gemini

---------

Co-authored-by: jonmeow <jperkins@google.com>
2026-04-02 22:54:58 +00:00
Dana Jansens 1fa7a64cd4 Add missing named constraints and self in facet type debugger dump (#7018) 2026-04-02 20:50:59 +00:00
Dana Jansens 562b423830 Always dump summaries (single line output) on bulleted details lines (#7017)
The debugger dump format looks something like

```
id: summary
 - detail 1
 - detail 2
```

But if the detail is a full Dump of some other id, then the details
start to combine and get confusing. For instance if you Dump an
interface id as the detail, you get

```
id: summary
  - interface id: summary
  - complete: yes  <-- about the interface
  - detail 2  <-- not about the interface
```

This mixes the contents of multiple Dumps and is super confusing. So
introduce DumpFooSummary for everything that is dumped on a bulleted
details line, and always use the summary version in that situation.
2026-04-02 20:19:57 +00:00
Richard Smith 6f0ec37a8b Make C++ enum types impl Core.Copy. (#7013)
Remove special-case handling in conversion logic for C++ enum types,
synthesize a custom witness of `Core.Copy` using the `primitive_copy`
builtin function.
2026-04-02 19:23:42 +00:00
Geoff Romer 0851d657c8 Add comment and test for special case in NameRef lowering (#7008) 2026-04-02 19:13:06 +00:00
Chandler Carruth 07afa07127 Fix missing include for std::log2 (#7015)
Some standard libraries require this include for the code to compile.
2026-04-02 18:27:46 +00:00
Chandler Carruth f7a767a77b Update LLVM (again) to pick up a workaround crashes the compiler when building with ASan (#7011)
Assisted-by: Antigravity with Gemini
2026-04-02 01:23:21 +00:00
Richard Smith be283a0744 Improve handling of incomplete signatures. (#7004)
Assert cleanly if we try to emit a definition or a call of a function
whose signature we were not able to emit exactly. This should make such
issues a lot easier to debug, as we were previously failing in quite
mysterious ways in this case.
2026-04-01 21:49:57 +00:00
Jon Ross-Perkins cd6ab7ce8e Switch jj settings to 'jj config set' because of repo (#7007)
jj moved the repo config outside the repo. The config.toml might exist
as a symlink in older repos (probably migration), but not clean repos.
So, overall, just switching the advice setup to make it a bit more
robust with config locations.

Also adding "trunk" to the repo config.

Assisted-by: Google Antigravity with Gemini
2026-04-01 21:36:56 +00:00
Nicholas Bishop 0075d530b9 Support const eval when calling a C++ thunk (#6947)
This makes it possible to do const eval when calling a constexpr C++
function with params and return types other than 32/64-bit integers.

Most of the new logic is in `MaybeModifyCppThunkCallForConstEval`, which
is called by `MakeConstantForCall`. This checks if the callee is a C++
thunk (using a new `SpecialFunctionKind::CppThunk` variant), and if so
it:
* Changes the callee from the C++ thunk to the thunk's callee
* Remaps parameters that are passed by pointer to the thunk to the
underlying value
* Drops the return value parameter, if present
2026-04-01 21:34:41 +00:00
Richard SmithandJon Ross-Perkins 5b7c908e8b Add documentation for setting up jj b a. (#6996)
This gives a setup where `jj b a` / `jj bookmark advance` can reliably
be used to advance a bookmark for a github pull request, without
advancing other bookmarks such as `trunk` or pointing the bookmark at an
empty commit.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-04-01 16:46:14 +00:00
Chandler Carruth 2bbcfa5e1a Remove ASan from the default build mode (#7003)
Also increases the default optimization to `-Og` which is likely to give
faster turn-around time which is what we want to optimize for here. This
should also _substantially_ shrink binary sizes, etc.

ASan is still available via `--config=asan`, and is added to the CI
infrastructure. However, my current thought is to only run it after push
rather than in PRs and in the merge queue.
2026-04-01 16:45:53 +00:00
Richard Smith dfac728571 Fix pointer sizes in debug info. (#7002)
The size is in bits, so 8 is an unlikely value. Also, don't hardcode a
size, ask the data layout for it.
2026-04-01 16:35:12 +00:00
Dana Jansens 8f3b057179 Don't qualify names after a . in an ImplWitnessAccess when stringifying (#7000)
After the `.` comes a member of the target of the ImplWitnessAccess.
It's already qualified, don't add the namespace/package to the name.
2026-04-01 15:24:57 +00:00
Dana Jansens 17180558e5 Diagnose where clause without a designator (#6995)
> We don’t allow a where constraint unless it applies a restriction to
the current type. This means referring to some
[designator](https://docs.carbon-lang.dev/docs/design/generics/details.html#kinds-of-where-constraints),
like .MemberName, or
[.Self](https://docs.carbon-lang.dev/docs/design/generics/details.html#recursive-constraints).


https://docs.carbon-lang.dev/docs/design/generics/details.html#constraints-must-use-a-designator
2026-04-01 04:16:35 +00:00
Chandler Carruth 39eac6f277 Update LLVM and fix a couple of API usages (#6998)
The `TemplateArgLocInfo` change is more interesting than usual as this
isn't enforced in the type system, and only shows up as a crash.
2026-04-01 00:00:11 +00:00
Chandler Carruth 2787089247 Switch to a Bazel-based runtimes build, and add bootstrapping (#6989)
This also switches to a more Bazel-based install layout, skipping the
FHS-based synthetic layout. The FHS-based layout is still reconstructed
explicitly when building an installable tar-ball.

The biggest change is to configure the just-built install as a Bazel
toolchain, including allowing it to build its own runtime libraries as
native Bazel libraries. This removes the need for a monolithic runtimes
build, all of that code logic is removed.

This should also pave the way to using the just-built toolchain for
doing a full 3-stage bootstrap. Building the 2nd stage is included here
as it was a particularly effective way to test that the Bazel
integration was fully working. Adding a 3rd-stage check for stability is
future work, but should be pretty easy.

There is a down-side: this uses the busybox to do the runtimes
compilation, which means they will be re-built after ~any change to
Carbon. However, the integration with Bazel should largely pay for this,
and we can continue to factor the tests away from depending on built
runtimes in most cases.

Now that we're building and testing the runtimes more directly, this
surfaced a problem with the layout of runtimes on macOS that is fixed
here. All of the Darwin OSes use a custom layout for their resource
directory compared to other targets. We now model this in both the C++
built runtimes and the Bazel built runtimes.

Assisted-by: Gemini via Antigravity
2026-03-31 23:38:03 +00:00
Richard Smith 3578dd6b91 Avoid copying Lower::FunctionInfo. (#7001)
This type is not small and contains two `SmallVector`s.
2026-03-31 22:58:42 +00:00
Richard Smith 8b59e85b16 Add support for inline Cpp declarations. (#6994)
For #6830, add support for inline C++ fragments as a declaration rather
than as a packaging directive. For now, this uses `inline Cpp
<string-literal>;` as syntax. The prior `import Cpp inline
<string-literal>;` is left alone for the time being. We can decide
separately whether to remove that.

`inline Cpp` requires that there was at least one `import Cpp`. It's not
clear to me if that's the right design long-term, but it seems
reasonable for now.

Assisted-by: Gemini via Google Antigravity
2026-03-31 22:27:43 +00:00
Geoff RomerandRichard Smith 47e9d62fd5 Model thunk call as a pattern match (#6988)
This makes the thunk-call logic more general and more supportable by
reusing the existing pattern-matching logic.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-03-31 21:50:06 +00:00
Geoff Romer f4260feee4 Clean up pattern matching (#6987)
The key changes here are:
- The different kinds of pattern match are represented as alternatives
of a `variant`, instead of enumerators of an `enum`, so that they can
hold their own state instead of having a bunch of conditionally-usable
members of `MatchContext`.
- The public API of `MatchContext` is a `Match` operation that's applied
to a single pattern and scrutinee; the worklist is no longer directly
accessible.
- `Match` has a counterpart `MatchWithResult` that returns the result of
matching the pattern.
- `Context` is now a member of `MatchContext` instead of a parameter to
most of its methods.
2026-03-31 20:38:42 +00:00
Geoff Romer aec2534e9d Fix formatting of compound-type variable declarations in macros (#6997)
By default clang-format interprets function-like macro invocations as
function calls. E.g. the argument of `CARBON_KIND(llvm::ListSeparator*
sep)` is interpreted as an expression, meaning the `*` is an infix
binary operator, so it inserts a space before the `*`. This change
teaches clang-format that `CARBON_KIND(x)` and
`CARBON_ASSIGN_OR_RETURN(x)` rewrite to `x`, which is close enough to
the truth to enable it to format them correctly. See the [clang-format
docs](https://clang.llvm.org/docs/ClangFormatStyleOptions.html#macros)
for details.
2026-03-31 19:41:26 +00:00
Richard Smith 2e0d9dc709 Add syntax highlighting for SemIR. (#6958)
This applies to files named *.semir, but more interestingly also to
Carbon source lines starting `// CHECK:STDOUT:`.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-31 18:49:02 +00:00
Nicholas Bishop 396756c151 Handle Temporary values when const-evaling AcquireValue (#6992)
This will be used for const-evaling functions. Splitting into a separate
commit since it touches a lot of test files, and a couple fail_todo
tests are no longer failing.
2026-03-31 15:50:54 +00:00
Nicholas Bishop bf6a14ac39 Support Temporary constants (#6983)
Evaluate `Temporary` constants to a `Temporary` with the `storage` field
set to `None`.
2026-03-30 19:07:46 +00:00
Dana Jansens 9ed045ec25 Add a link to the docs on testing the toolchain to CONTRIBUTING.md (#6981)
It takes a bit of work to track down instructions on running file tests
and autoupdate. Add a link to them directly from CONTRIBUTING.md, since
all searches start there.
2026-03-28 06:21:14 +00:00
Dana Jansens 2318294eb5 Add tests for name lookup through named constraints (#6979)
Tests combinations of extend and impls in a facet type and inside a
named constraint. Name scopes are only extended if the named constraint
extends an interface, and the facet type extends the named constraint.
2026-03-28 04:15:24 +00:00
Richard Smith d9b901394b Add agent skill for producing toolchain tests. (#6986)
Assisted-by: Gemini via Google Antigravity
2026-03-28 00:48:08 +00:00
Richard Smith 181a592b8c Support for parsing expression patterns (#6977)
When parsing a pattern, if we encounter something that isn't pattern
syntax, try parsing as an expression instead. We only need one-token
lookahead to distinguish pattern syntax from expression syntax.

Track a precedence group through pattern parsing so that we can allow
different kinds of expressions in a top-level pattern (such as the
operand of `let`) and in a nested pattern (such as a subpattern of a
tuple pattern or within grouping parens). For example, we do not allow
`case if ...`, and for now I've chosen to also not allow logical or
relational operators at the top level of a pattern, so `case 1 + 1` is
OK, but `case 1 == 1` and `case true and false` require parentheses.
This decision should be ratified or revisited by a design proposal.

Very basic check support is also provided, only sufficient to form an
`ExprPattern` instruction and nothing beyond that. For now, all pattern
matching against an `ExprPattern` fails with a TODO error. To support
that, I've switched from calling `BeginSubpattern` in the parent handler
of a pattern and `EndSubpatternAs*` in the pattern handler itself to
calling both functions in parent handlers, with `EndSubpattern`
converting an expression into an expression pattern where needed.

Depends on #6976.

Assisted-by: Gemini via Google Antigravity
2026-03-28 00:06:06 +00:00
Nicholas Bishop 1ef35e8299 Fix name mangling for Carbon functions called from C++ (#6984)
Since this requires using the `Mangler` class from `toolchain/check`,
moved it from `toolchain/lower` to `toolchain/sem_ir`.

The mangled name is then attached to the `FunctionDecl` with an
`AsmLabelAttr`.
2026-03-27 22:52:11 +00:00
Richard Smith aa8e96ac72 Fix skill file to parse correctly. (#6985)
The license header needs to go after the YAML in order for it to parse.
2026-03-27 21:46:08 +00:00
Dana Jansens 5503f643c6 Introduce typed-inst accessors for ConstantValueStore (#6980)
Add `InstIs`, `GetInstAs`, and `TryGetInstAs` which act on the
underlying constant instruction in a constant value, to save an explicit
call to `GetInstId`.

```carbon
context.insts().GetAs<InstT>(context.constant_values().GetInstId(const_id))
```
can now be written as simply
```carbon
context.constant_values().GetInstAs<InstT>(const_id)
```

For future work, we might provide `GetInst()` so that
`context.insts().Get(context.constant_values().GetInstId(const_id)` can
be shortened also.
2026-03-27 21:41:04 +00:00
Richard SmithandGeoff Romer 899e54de36 Treat (pattern) as grouping parens. (#6976)
Do not treat it as a 1-tuple pattern as we used to. The design indicates
that `(pattern)` is invalid, but this appears to be an oversight, and
grouping parens appear to be the intended interpretation.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-03-27 21:13:57 +00:00
Jon Ross-Perkins a2ba7f1262 Have Specific track whether regions contain errors (#6982)
This removes some loops in type completion, but is motivated by the
thought that eval probably wants to query it.

Assisted-by: Google Antigravity with Gemini
2026-03-27 19:36:52 +00:00
Jon Ross-Perkins 2b1fe7c292 Small improvements to RuntimeVerified logic (#6973)
The `NodeKind` vs `InstKind` naming seems to be an old mistake.

I'm cleaning up to specific `ImportRef` handling after verifying those
were the only actual cases where inst kinds won't be compatible (or are
always compatible, depending on your point of view).

Assisted-by: Google Antigravity with Gemini
2026-03-27 19:32:12 +00:00
Dana Jansens a0416a1250 Don't finish the non-canonical instruction created in EvalOrAddInst (#6972)
EvalOrAddInst has to create a non-canonical instruction for evaluating a
few typed insts, such as LookupImplWitness which uses an InstId to
provide a location for diagnostics.

But the output of the function is a ConstantId. We do not have access to
the non-canonical InstId after the function returns. But if the constant
value was symbolic, it was being attached to the inst, and the inst
would be added to the eval block of the enclosing generic. This
needlessly added semir for a symbolic value.

The ConstantId returned by EvalOrAddInst can be used immediately, such
as to evaluate an ImplWitnessAccess. In that case, the final evaluated
result is all we need to keep in semir.

If the ConstantId needs to be replaced by specifics, it is only as part
of some other instruction, since ConstantIds themselves are not modified
by specifics, instructions are. In that case, the canonical instruction
in the constant value would have been added to some other (now symbolic)
instruction, which would be replaced by a specific.

This has no functional change, but it reduces runtime overhead and semir
output for LookupImplWitness and ImplWitnessAccess.
2026-03-27 19:29:34 +00:00
Christopher Di Bella c68c4007ab removes unused parameters from deep stack (#6971)
`best_impl_type_structure` and `best_impl_loc_id` are required to solve
the problem discussed in #6166. We don't address that issue issue yet.
Requiring them to be propagated through any function depending on
`GetFunctionId` is very tedious.

This commit removes them from `GetFunctionId` until we have a clear
design for how they should be used.
2026-03-27 16:59:25 +00:00
cui 1f7d8e4675 Fix ValueStore::GetRawIndex DCHECK to use id.index in diagnostic (#6975)
## Summary

`ValueStore::GetRawIndex` formatted the first `CARBON_DCHECK` with
`index` before the local `index` is declared. Use `id.index` so the
diagnostic matches the condition being checked.

## Test plan

- `bazelisk build //toolchain/base:base` (or `//toolchain/...` as
appropriate)
2026-03-27 12:48:46 +00:00
cui 557039648b Fix FacetTypeInfo::Print guard for self impls named constraints (#6974)
## Summary

Fixes a copy-paste bug in `FacetTypeInfo::Print`: the "self impls named
constraint" section was gated on `self_impls_constraints.empty()`
instead of `self_impls_named_constraints.empty()`.

## Test plan

- `bazelisk build //toolchain/sem_ir:sem_ir` (not run in this
environment; no Bazel installed)
2026-03-27 12:17:12 +00:00
Richard Smith 786e02cb3e clang-format: Turn off trailing commas in braced lists lint. (#6978)
Our codebase does not conform to this rule, and it's causing havoc for
automated tooling that tries to "fix" it.
2026-03-27 12:03:58 +00:00
Geoff Romer 262e24a2a0 Remove indirection through NameRefs when building a thunk call (#6965)
This reduces the SemIR size of the thunk call, and ensures that the
emitted SemIR remains correct if `pretty_name_id` is not populated.
2026-03-26 19:17:05 +00:00
Geoff Romer 18f87e4f79 Include the type in the location of binding insts (#6963) 2026-03-26 18:43:29 +00:00
Nicholas Bishop 85da6cae01 Support calling simple Carbon functions from C++ (#6967)
For now, only functions with no parameters and a `()` return type are
supported.
2026-03-26 18:14:39 +00:00
Dana Jansens d6be20641c Use earlier require decls inside a named constraint to provide witnesses for Self (#6915)
Performing a lookup against `Self` inside the definition of the named
constraint leads to cycles, as described in the document [Self
contradictions in Named
Constraints](https://docs.google.com/document/d/17rn2XmME8o2MM4OJqatSVuMa1iYZ1PAgcNrf0PXR9Q4/edit?tab=t.0).
To prevent those cycles, this change introduces a large refactoring of
impl lookup.

The impl lookup done inside eval is reduced to only performing
monomorphization. That is it:
- Only looks for an provides final witnesses.
- Is not allowed to identify the facet type of the query self.
- Returns either a final witness or None (or an error)

The paths for finding non-final witnesses are now done outside of eval,
directly in the initial `LookupImplWitness()` function. If no final
witness it found through eval, the resulting non-final
`LookupImplWitness` instruction witness is returned. It does not produce
cycles to identify the facet type of query self outside of eval, since
that does not result in repeating the identification when resolving
specifics of the named constraint or require decl.

Move the ArrayStack for Context::require_impls_stack into a new class
which tracks a NamedConstraintId (or InterfaceId) for each frame of
RequireImplsIds, so that in type completion we always can find the
correct frame for a given named constraint which is still being defined,
in order to find the RequireImplsIds in the in-progress definition.
2026-03-26 15:26:56 +00:00
Dana JansensandRichard Smith 4a0c1ddd8e Identification of a named constraint during definition (#6902)
Allow partially identifying a named constraint inside its definition,
and allow the query self in an impl lookup with a non-identified facet
type to be used to provide witnesses from that facet type. This allows
impl lookup on `Self` to find `require` decls that have been written
earlier in the named constraint, so that the named constraint to be used
to provide witnesses from inside its definition.

But disallow an incomplete named constraint from being part of an
identified facet type, to prevent forming facet values that store a
witness set that can be invalidated as the named constraint adds
interfaces to its identified facet type.

This was discussed in open discussion [on
2026-03-12](https://docs.google.com/document/d/1mjllGO3ZCL4qGt9uJHUtcxKoHAGEY7Y999ie4EtBWB8/edit?tab=t.0#heading=h.1dvbbrp5a6t3).

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-03-26 14:24:45 +00:00
Jon Ross-Perkins 5ae3629e49 Change GEMINI.md to AGENTS.md (#6969)
Per https://antigravity.google/changelog, supported in 1.20.5. Also note
https://agents.md

Assisted-by: Google Antigravity with Gemini
2026-03-26 01:00:13 +00:00
Jon Ross-Perkins 25b85a55ae Remove myself from SECURITY.md (#6964)
Assisted-by: Google Antigravity with Gemini
2026-03-26 00:52:16 +00:00
dependabot[bot] 15dabbfb0d Bump requests from 2.32.4 to 2.33.0 in /github_tools in the pip group across 1 directory (#6968)
Bumps the pip group with 1 update in the /github_tools directory:
[requests](https://github.com/psf/requests).

Updates `requests` from 2.32.4 to 2.33.0
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/psf/requests/releases">requests's
releases</a>.</em></p>
<blockquote>
<h2>v2.33.0</h2>
<h2>2.33.0 (2026-03-25)</h2>
<p><strong>Announcements</strong></p>
<ul>
<li>📣 Requests is adding inline types. If you have a typed code base
that uses Requests, please take a look at <a
href="https://redirect.github.com/psf/requests/issues/7271">#7271</a>.
Give it a try, and report any gaps or feedback you may have in the
issue. 📣</li>
</ul>
<p><strong>Security</strong></p>
<ul>
<li>CVE-2026-25645 <code>requests.utils.extract_zipped_paths</code> now
extracts contents to a non-deterministic location to prevent malicious
file replacement. This does not affect default usage of Requests, only
applications calling the utility function directly.</li>
</ul>
<p><strong>Improvements</strong></p>
<ul>
<li>Migrated to a PEP 517 build system using setuptools. (<a
href="https://redirect.github.com/psf/requests/issues/7012">#7012</a>)</li>
</ul>
<p><strong>Bugfixes</strong></p>
<ul>
<li>Fixed an issue where an empty netrc entry could cause malformed
authentication to be applied to Requests on Python 3.11+. (<a
href="https://redirect.github.com/psf/requests/issues/7205">#7205</a>)</li>
</ul>
<p><strong>Deprecations</strong></p>
<ul>
<li>Dropped support for Python 3.9 following its end of support. (<a
href="https://redirect.github.com/psf/requests/issues/7196">#7196</a>)</li>
</ul>
<p><strong>Documentation</strong></p>
<ul>
<li>Various typo fixes and doc improvements.</li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/M0d3v1"><code>@​M0d3v1</code></a> made
their first contribution in <a
href="https://redirect.github.com/psf/requests/pull/6865">psf/requests#6865</a></li>
<li><a href="https://github.com/aminvakil"><code>@​aminvakil</code></a>
made their first contribution in <a
href="https://redirect.github.com/psf/requests/pull/7220">psf/requests#7220</a></li>
<li><a href="https://github.com/E8Price"><code>@​E8Price</code></a> made
their first contribution in <a
href="https://redirect.github.com/psf/requests/pull/6960">psf/requests#6960</a></li>
<li><a href="https://github.com/mitre88"><code>@​mitre88</code></a> made
their first contribution in <a
href="https://redirect.github.com/psf/requests/pull/7244">psf/requests#7244</a></li>
<li><a href="https://github.com/magsen"><code>@​magsen</code></a> made
their first contribution in <a
href="https://redirect.github.com/psf/requests/pull/6553">psf/requests#6553</a></li>
<li><a
href="https://github.com/Rohan5commit"><code>@​Rohan5commit</code></a>
made their first contribution in <a
href="https://redirect.github.com/psf/requests/pull/7227">psf/requests#7227</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/psf/requests/blob/main/HISTORY.md#2330-2026-03-25">https://github.com/psf/requests/blob/main/HISTORY.md#2330-2026-03-25</a></p>
<h2>v2.32.5</h2>
<h2>2.32.5 (2025-08-18)</h2>
<p><strong>Bugfixes</strong></p>
<ul>
<li>The SSLContext caching feature originally introduced in 2.32.0 has
created
a new class of issues in Requests that have had negative impact across a
number
of use cases. The Requests team has decided to revert this feature as
long term
maintenance of it is proving to be unsustainable in its current
iteration.</li>
</ul>
<p><strong>Deprecations</strong></p>
<ul>
<li>Added support for Python 3.14.</li>
<li>Dropped support for Python 3.8 following its end of support.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/psf/requests/blob/main/HISTORY.md">requests's
changelog</a>.</em></p>
<blockquote>
<h2>2.33.0 (2026-03-25)</h2>
<p><strong>Announcements</strong></p>
<ul>
<li>📣 Requests is adding inline types. If you have a typed code base
that
uses Requests, please take a look at <a
href="https://redirect.github.com/psf/requests/issues/7271">#7271</a>.
Give it a try, and report
any gaps or feedback you may have in the issue. 📣</li>
</ul>
<p><strong>Security</strong></p>
<ul>
<li>CVE-2026-25645 <code>requests.utils.extract_zipped_paths</code> now
extracts
contents to a non-deterministic location to prevent malicious file
replacement. This does not affect default usage of Requests, only
applications calling the utility function directly.</li>
</ul>
<p><strong>Improvements</strong></p>
<ul>
<li>Migrated to a PEP 517 build system using setuptools. (<a
href="https://redirect.github.com/psf/requests/issues/7012">#7012</a>)</li>
</ul>
<p><strong>Bugfixes</strong></p>
<ul>
<li>Fixed an issue where an empty netrc entry could cause
malformed authentication to be applied to Requests on
Python 3.11+. (<a
href="https://redirect.github.com/psf/requests/issues/7205">#7205</a>)</li>
</ul>
<p><strong>Deprecations</strong></p>
<ul>
<li>Dropped support for Python 3.9 following its end of support. (<a
href="https://redirect.github.com/psf/requests/issues/7196">#7196</a>)</li>
</ul>
<p><strong>Documentation</strong></p>
<ul>
<li>Various typo fixes and doc improvements.</li>
</ul>
<h2>2.32.5 (2025-08-18)</h2>
<p><strong>Bugfixes</strong></p>
<ul>
<li>The SSLContext caching feature originally introduced in 2.32.0 has
created
a new class of issues in Requests that have had negative impact across a
number
of use cases. The Requests team has decided to revert this feature as
long term
maintenance of it is proving to be unsustainable in its current
iteration.</li>
</ul>
<p><strong>Deprecations</strong></p>
<ul>
<li>Added support for Python 3.14.</li>
<li>Dropped support for Python 3.8 following its end of support.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/psf/requests/commit/bc04dfd6dad4cb02cd92f5daa81eb562d280a761"><code>bc04dfd</code></a>
v2.33.0</li>
<li><a
href="https://github.com/psf/requests/commit/66d21cb07bd6255b1280291c4fafb71803cdb3b7"><code>66d21cb</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/psf/requests/commit/8b9bc8fc0f63be84602387913c4b689f19efd028"><code>8b9bc8f</code></a>
Move badges to top of README (<a
href="https://redirect.github.com/psf/requests/issues/7293">#7293</a>)</li>
<li><a
href="https://github.com/psf/requests/commit/e331a288f369973f5de0ec8901c94cae4fa87286"><code>e331a28</code></a>
Remove unused extraction call (<a
href="https://redirect.github.com/psf/requests/issues/7292">#7292</a>)</li>
<li><a
href="https://github.com/psf/requests/commit/753fd08c5eacce0aa0df73fe47e49525c67e0a29"><code>753fd08</code></a>
docs: fix FAQ grammar in httplib2 example</li>
<li><a
href="https://github.com/psf/requests/commit/774a0b837a194ee885d4fdd9ca947900cc3daf71"><code>774a0b8</code></a>
docs(socks): same block as other sections</li>
<li><a
href="https://github.com/psf/requests/commit/9c72a41bec8597f948c9d8caa5dc3f12273b3303"><code>9c72a41</code></a>
Bump github/codeql-action from 4.33.0 to 4.34.1</li>
<li><a
href="https://github.com/psf/requests/commit/ebf71906798ec82f34e07d3168f8b8aecaf8a3be"><code>ebf7190</code></a>
Bump github/codeql-action from 4.32.0 to 4.33.0</li>
<li><a
href="https://github.com/psf/requests/commit/0e4ae38f0c93d4f92a96c774bd52c069d12a4798"><code>0e4ae38</code></a>
docs: exclude Response.is_permanent_redirect from API docs (<a
href="https://redirect.github.com/psf/requests/issues/7244">#7244</a>)</li>
<li><a
href="https://github.com/psf/requests/commit/d568f47278492e630cc990a259047c67991d007a"><code>d568f47</code></a>
docs: clarify Quickstart POST example (<a
href="https://redirect.github.com/psf/requests/issues/6960">#6960</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/psf/requests/compare/v2.32.4...v2.33.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=requests&package-manager=pip&previous-version=2.32.4&new-version=2.33.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-26 00:40:18 +00:00
Jon Ross-Perkins 25793358c3 Remove jonmeow from pre-commit config (#6966)
Removing this exception before I forget it's there

Assisted-by: Google Antigravity with Gemini
2026-03-25 23:01:20 +00:00
Richard Smith 37b238fa28 Make C++ types impl Core.Default. (#6962)
C++ classes that are default-constructible now implement `Core.Default`
by calling the default constructor.
2026-03-25 21:07:24 +00:00
Jon Ross-Perkins 311670c84a Improve vscode extension ownership (#6960)
Updates the way to access vscode marketplace for publishing. I've
adjusted CarbonInfraBot's attached email to match.

The `#editor-integrations` change is for inconsistent markdown handling
by MS...
https://marketplace.visualstudio.com/items?itemName=carbon-lang.carbon-vscode
looks fine at the moment, but I was seeing rendering as a title -- maybe
a bug that won't be rolled out, but backticks seem fair here.

Assisted-by: Google Antigravity with Gemini
2026-03-25 20:29:09 +00:00
Richard Smith 965879a9a9 Support for in-place return in eval fn. (#6954)
Ignore storage arguments when evaluating a call, like we do for other
kinds of instruction. Create a placeholder constant to represent each
out parameter so that it can be used in the function body to form more
storage arguments.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-25 16:03:44 +00:00
David Blaikie 415cd6f8f0 Reverse Interop: Class declarations (#6955)
Generate class declarations for Carbon classes referenced from C++

Based on #6940, review from eb62070a01
onwards
2026-03-25 04:50:08 +00:00
Richard Smith 7345f4e860 Use a per-file width for the line number gutter. (#6959)
In in the VSCode extension, use the same width for the per-split line
number gutter across all splits. This makes the visuals more consistent.
2026-03-24 21:55:48 +00:00
Richard Smith 29a8b315d3 Improve vscode line number display for test files. (#6957)
In the Carbon vscode extension, in /testdata/ files with file splits,
add a line number column within the split next to the line number column
for the overall file line number.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-24 21:34:03 +00:00
Jon Ross-Perkins e0305684b0 Add MakeVerifiedLocIdAndInst for runtime validation (#6942)
This follows up on a discussion about wanting to use `Any*` inst
clusters to handle boilerplate construction, with the issue that
`UncheckedLoc` use removes validation. Some context is at
https://github.com/carbon-language/carbon-lang/pull/6930#discussion_r2963157428.

This folds in `MakeImportedLocIdAndInst` because the logic is related,
particularly for `LocId` values which are `ImportIRInstId`, and it
eliminates questions of what the right function is to use.

This uncovers an error in the `NodeKind` associated with
`FormBindingPattern`. For now I'm just adding a TODO regarding that.

Assisted-by: Google Antigravity with Gemini
2026-03-24 20:56:44 +00:00
David BlaikieandJon Ross-Perkins 2af5f971da Reverse Interop: Nested namespace support (#6940)
Start recording the clang::DeclContext* -> InstId mapping for use in
later operations.

The test update includes removing the initial fail_* test because I
hadn't thought about the use of namespace aliases as a way to test for
the presence of a namespace without the failure caused by not finding
the thing inside the namespace.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-03-24 19:55:25 +00:00
Nicholas Bishop f9e1806c4a Improve diagnostics for EvaluateAsConstantExpr (#6956)
Initialize the `Diag` field `EvalResult` to get notes from clang when
`EvaluateAsConstantExpr` fails, then emit them using clang's diagnostic
infrastructure.

Also set valid source locations in a couple places, otherwise clang's
diagnostics code crashes.
2026-03-24 19:40:09 +00:00
Geoff Romer e0c6800ab3 Reverse nesting structure of parameter patterns (#6930)
See
[here](https://docs.google.com/document/d/1rWcueFwIfZox6GKVGxiUG4cBzjrZ6djXiIDGyJDtrE4/edit?tab=t.0#heading=h.7mi143mdhr2h)
for an overview of the changes and their rationale.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-23 20:38:20 +00:00
a345a74145 prepares vscode extension for open-vsx (#6834)
We'd like to add the Carbon vscode extension to open-vsx.org so it's
available on vscode-compatible projects (see #6766). This commit
updates documentation so that we're recommending the correct package,
and updates our dependencies to ensure users have the latest security
patches.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-03-23 16:57:54 +00:00
Chandler Carruth 86d05b598b Move the logic for preparing the installed runtimes files to its own (#6946)
directory

This cleans up the `//toolchain/install/BUILD` file and the tree
generally to be more focused on arranging the actual installation rather
than preparing inputs to that installation.

I picke `//toolchain/runtimes` so we can put other runtimes preparation
logic there, but open to any other suggested organization.

There are other runtimes things that would in theory make sense to move
such as the `prebuilt_runtimes` logic, but a subsequent PR will delete
those and so I'm leaving them where they are for now.
2026-03-23 16:39:45 +00:00
cui 7b6e3dfbb0 Fix ReadlinkSlow buffer when lstat reports zero size (#6948)
When the symlink target length from lstat was 0, the code resized the
buffer using status.size() instead of buffer_size, so the first
allocation stayed empty instead of using MinBufferSize. Align the resize
with the buffer_size path used for readlinkat.
2026-03-23 16:28:51 +00:00
Dana Jansens 17657d0586 CHECK if a SymbolicOnly instruction produces a concrete value of the same inst type (#6938)
The contract for SymbolicOnly is that the instructions are only allowed
to have a symbolic value unless their value is a different instruction
type.
2026-03-23 16:15:56 +00:00
dependabot[bot] 3ef991466d Bump flatted from 3.3.2 to 3.4.2 in /utils/vscode in the npm_and_yarn group across 1 directory (#6944)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [flatted](https://github.com/WebReflection/flatted).

Updates `flatted` from 3.3.2 to 3.4.2
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/WebReflection/flatted/commit/3bf09091c3562e17a0647bc06710dd6097079cf7"><code>3bf0909</code></a>
3.4.2</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/885ddcc33cf9657caf38c57c7be45ae1c5272802"><code>885ddcc</code></a>
fix CWE-1321</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/0bdba705d130f00892b1b8fcc80cf4cdea0631e3"><code>0bdba70</code></a>
added flatted-view to the benchmark</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/2a02dce7c641dec31194c67663f9b0b12e62da20"><code>2a02dce</code></a>
3.4.1</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/fba4e8f2e113665da275b19cd0f695f3d98e9416"><code>fba4e8f</code></a>
Merge pull request <a
href="https://redirect.github.com/WebReflection/flatted/issues/89">#89</a>
from WebReflection/python-fix</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/5fe86485e6df7f7f34a07a2a85498bd3e17384e7"><code>5fe8648</code></a>
added &quot;when in Rome&quot; also a test for PHP</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/53517adbefe724fe472b2f9ebcdb01910d0ae3f0"><code>53517ad</code></a>
some minor improvement</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/b3e2a0c387bf446435fec45ad7f05299f012346f"><code>b3e2a0c</code></a>
Fixing recursion issue in Python too</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/c4b46dbcbf782326e54ea1b65d3ebb1dc7a23fad"><code>c4b46db</code></a>
Add SECURITY.md for security policy and reporting</li>
<li><a
href="https://github.com/WebReflection/flatted/commit/f86d071e0f70de5a7d8200198824a3f07fc9c988"><code>f86d071</code></a>
Create dependabot.yml for version updates</li>
<li>Additional commits viewable in <a
href="https://github.com/WebReflection/flatted/compare/v3.3.2...v3.4.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=flatted&package-manager=npm_and_yarn&previous-version=3.3.2&new-version=3.4.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-23 15:09:36 +00:00
cui 44f2a68ee0 Fix iN/uN type literal width check for multiples of 8 (#6949)
The diagnostic requires bit widths to be multiples of 8, but the test
used a mask of 3 (lower two bits), which only enforces multiples of 4.
Use a mask of 7 so values like 12 incorrectly pass the check.
2026-03-22 02:03:48 +00:00
Jon Ross-Perkins 81215e873e Add missing library in test (#6945)
Adding a library to lower the odds of tripping someone up in the future
(I don't plan to modify this file now)

Assisted-by: Google Antigravity with Gemini
2026-03-20 23:07:21 +00:00
bc38deb16c adds witness support for associated types (#6937)
This commit creates an instance for any associated types in an interface
with a custom witness table. This unlocks interfaces designed for C++
interop that rely on arbitrary return types. For example,
`CppUnsafeDeref` becomes usable as of this commit.

This commit may have also implemented support for non-type associated
constants, but since we're lacking a practical test case, they're still
marked as TODO for the time being.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-03-20 22:03:52 +00:00
Dana Jansens 6d2387cb77 Return a NewAnyPhase result for RequireCompleteType with a CompleteTypeWitness value (#6939)
The `CompleteTypeWitness` can be concrete. This avoids making a symbolic
`CompleteTypeWitness` value which itself has a concrete
`CompleteTypeWitness` value with the same operands.
2026-03-20 20:00:08 +00:00
Geoff Romer 000b4f3fa5 Handle errors in form binding without crashing. (#6936)
Closes #6920
2026-03-20 18:25:00 +00:00
Richard Smith e06eb8f532 Create a placement operator new directly. (#6941)
Instead of injecting code to declare an `operator new`, generate AST for
it directly. In order to use this, directly generate a `CXXNewExpr`
rather than asking Clang to build one.

This is less of a hack, and doesn't visibly leak an `operator new`
declaration that inline C++ code or template instantiations might see.
It also avoids generating a warning in C++26 and later that the
`constexpr` declaration of `operator new` is used but not defined.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-20 16:50:37 +00:00
Geoff Romer 8e824d02be Restructure pattern matching to support producing results (#6929)
See
[here](https://docs.google.com/document/d/1rWcueFwIfZox6GKVGxiUG4cBzjrZ6djXiIDGyJDtrE4/edit?tab=t.0#heading=h.o26vowcup0iq)
for the motivation. Note that this change only provides the
infrastructure for producing and consuming results; the actual usage is
in a separate PR.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-20 16:47:04 +00:00
Geoff Romer 8e5b358ec2 Add the form ID to FormParamPattern (#6928)
This enables some nice simplifications, and it's also a step toward a
broader restructuring of binding and parameter patterns.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-20 01:08:38 +00:00
Richard SmithandGeoff Romer ce50f181f1 Add an interface for initialization of vars without an explicit initializer (#6934)
When a `var` is not explicitly given an initializer, initialize it in
one of two ways:

* If its type implements the new interface `Core.Default`, call
`Core.Default.Op` to initialize it.
* Otherwise, if its type implements `UnformedInit`, leave it in an
unformed state. For now, this is always an uninitialized state, but that
will change in the future.
* If neither of those apply, the `var` declaration is ill-formed.

This is a step towards implementing leads decision #6739 and proposals
#257 and #5913.

Assisted-by: Gemini 3.1 Pro via Antigravity

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-03-19 23:46:06 +00:00
Christopher Di BellaandDana Jansens fd2d210c63 changes LookupCppImpl's return to handle multiple associated entities (#6916)
`LookupCppImpl` handles exactly one function ID, so core interfaces with
multiple associated entities were regarded as unsupported. This commit
adds support for a single associated function with a single associated
constant.

Note: associated constants are still TODO.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-03-19 22:03:39 +00:00
Geoff Romer 08148f3a3a Refactor AddBindingPattern into composable pieces (#6927)
This is part of some bigger changes in pattern matching, factored out
because it causes some test churn.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-19 19:20:03 +00:00
Dana Jansens 10beae2c20 Avoid crashing if a C++ type was used to look for an IntFitsIn witness (#6924)
Originally this was handled in LookupCppImpl in the switch on the
CoreInterface, but in subsequent refactorings it was lost, and we now
assume we are always looking for a C++ witness and CHECK that the
interface is not `IntFitsIn`.

Refactor LookupCppImpl to have a single switch up front on the
CoreInterface enum, instead of multiple. It's a quick early out for
`IntFitsIn` and delegates work to helper functions specific to each
other CoreInterface value.
2026-03-19 18:34:45 +00:00
Geoff Romer 6d1130f657 Allow no-op conversions on incomplete types. (#6926)
This resolves some todos, and makes `Convert` safer to call, which
unblocks some changes in pattern matching that I'm working on.

Assisted-by: Gemini 3.1 Pro via Antigravity
2026-03-19 17:08:23 +00:00
David Blaikie 14b72f16da SemIR::Namespace->clang::NamespaceDecl interop (#6935)
Rough-in with TODO for caching and scoping/nesting, this only handles
top level namespaces and doesn't nest them appropriately.
2026-03-18 23:33:49 +00:00
Jon Ross-Perkins 7b3f120f97 Make Any* macros reusable (#6933)
Use parens to delay macro expansion to address the comma separator case,
allowing reuse in AnyBindingOrExportDecl. Also add
CARBON_INST_CATEGORY_ANY_EXPAND to reduce some boilerplate.

Assisted-by: Google Antigravity with Gemini
2026-03-18 19:27:46 +00:00
Nicholas Bishop 0482b27c6b Support more types in MapConstantToAPValue by refactoring code out of ConvertArgToTemplateArg (#6923)
This doesn't change any of the current tests, but will be useful for
calling constexpr functions with bool/float params.
2026-03-18 16:11:42 +00:00
Richard SmithandDana Jansens 98e2567524 Add a skill to produce a summary report for changes to testdata files. (#6925)
Example output from Gemini:
https://gist.github.com/zygoloid/b4aaaf919173d639cf0ffa90fd0898e4

Assisted-by: Gemini 3.1 Pro via Antigravity

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-03-18 16:05:10 +00:00
Jon Ross-Perkins d47b6221ae Fix invalid digit caret (#6921)
Stumbled on this playing with numeric literals

Assisted-by: Google Antigravity with Gemini
2026-03-17 18:13:55 +00:00
Dana Jansens 87fc05750b Test that a named constraint can't be used inside its definition through an alias to its name (#6922)
We only want to allow using the named constraint through `Self`, as
proposed in #6902.
2026-03-17 17:31:20 +00:00
Jon Ross-Perkins 2e32f309eb Small improvements to APInt handling (#6918)
I was looking for uses of APInt that care about the bit width we're
using, just searching for uses of "64", since #6908 started applying the
minimum with of 64 bits more explicitly.

- numeric_literal.cpp: piping through the sign bit request, allowing
`exponent` to assume it's already 64-bit (putting the CHECK in to just
expose the logic, keeping it outside the `if` because the `if` is an
edge case and I was thinking to avoid edge case inconsistencies slipping
by)
- inst_fingerprinter.cpp: reducing logic to copy words

Assisted-by: Google Antigravity with Gemini
2026-03-17 17:11:30 +00:00
Geoff Romer 1d71e7a707 Change .size() == 0 to .empty() (#6917)
This resolves a readability-container-size-empty clang-tidy finding.
2026-03-17 11:35:04 +00:00
Jon Ross-PerkinsandChandler Carruth 613a139bef Add support for octal numbers (#6909)
This implements the leads decision made in #6821, proposal #6910. The
proposal is pending, but I figured it's relatively safe to just do given
the decision.

Assisted-by: Google Antigravity with Gemini

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-03-16 21:28:37 +00:00
Jon Ross-Perkins c5761d2d16 Improve parsing large integers (#6908)
Though I started this thinking about performance of parse of large
decimal integers, I extended it to generally improve performance of
integer values (TBH I hadn't expected such a difference for binary/hex,
but I'll take it).

Note I think tests change because I'm making subtle changes to bit
widths. The changes themselves appear harmless to me, but happy to make
changes if it'd help.

Bumping up the number of digits by 10x because it's not really a
performance issue anymore (eh, maybe somebody will want to specify a
256-byte value in binary). But, at a certain point it still seems like a
mistake if somebody has that many digits in a row.

Fixes #980

Highlighting benchmark differences:
```diff
- BM_ComputeValue_IntDecimalN/1           37.1 ns         37.1 ns     18887116
+ BM_ComputeValue_IntDecimalN/1           21.9 ns         21.9 ns     31902433
- BM_ComputeValue_IntDecimalN/10000 1251228680 ns   1250457559 ns            1
+ BM_ComputeValue_IntDecimalN/10000     458818 ns       458626 ns         1523
- BM_ComputeValue_IntBinaryN/1            29.0 ns         29.0 ns     24058533
+ BM_ComputeValue_IntBinaryN/1            22.2 ns         22.1 ns     31566949
- BM_ComputeValue_IntBinaryN/10000     1390557 ns      1389782 ns          506
+ BM_ComputeValue_IntBinaryN/10000       16402 ns        16396 ns        42744
- BM_ComputeValue_IntHexN/1               34.0 ns         34.0 ns     20562432
+ BM_ComputeValue_IntHexN/1               22.4 ns         22.4 ns     31238055
- BM_ComputeValue_IntHexN/10000        5387942 ns      5385262 ns          130
+ BM_ComputeValue_IntHexN/10000          39249 ns        39233 ns        17859
```

Benchmark before:
```
----------------------------------------------------------------------------
Benchmark                                  Time             CPU   Iterations
----------------------------------------------------------------------------
BM_Lex_Float                            10.6 ns         10.6 ns     66138191
BM_Lex_Int                              15.5 ns         15.4 ns     45149703
BM_Lex_IntDecimalN/1                    3.11 ns         3.11 ns    225524908
BM_Lex_IntDecimalN/10                   11.8 ns         11.8 ns     56719805
BM_Lex_IntDecimalN/100                   102 ns          102 ns      6867468
BM_Lex_IntDecimalN/1000                  943 ns          942 ns       745313
BM_Lex_IntDecimalN/10000                9465 ns         9461 ns        73970
BM_ComputeValue_Float                   61.6 ns         61.6 ns     11377463
BM_ComputeValue_Int                      106 ns          106 ns      6587381
BM_ComputeValue_IntDecimalN/1           37.1 ns         37.1 ns     18887116
BM_ComputeValue_IntDecimalN/10          87.7 ns         87.7 ns      7960837
BM_ComputeValue_IntDecimalN/100         7963 ns         7956 ns        88858
BM_ComputeValue_IntDecimalN/1000     1212577 ns      1211906 ns          578
BM_ComputeValue_IntDecimalN/10000 1251228680 ns   1250457559 ns            1
BM_ComputeValue_IntBinaryN/1            29.0 ns         29.0 ns     24058533
BM_ComputeValue_IntBinaryN/10           69.4 ns         69.4 ns     10108642
BM_ComputeValue_IntBinaryN/100           963 ns          962 ns       726982
BM_ComputeValue_IntBinaryN/1000        21562 ns        21551 ns        32506
BM_ComputeValue_IntBinaryN/10000     1390557 ns      1389782 ns          506
BM_ComputeValue_IntHexN/1               34.0 ns         34.0 ns     20562432
BM_ComputeValue_IntHexN/10              70.4 ns         70.4 ns      9953165
BM_ComputeValue_IntHexN/100             1474 ns         1473 ns       472776
BM_ComputeValue_IntHexN/1000           61818 ns        61762 ns        11363
BM_ComputeValue_IntHexN/10000        5387942 ns      5385262 ns          130
```

Benchmark after:
```
----------------------------------------------------------------------------
Benchmark                                  Time             CPU   Iterations
----------------------------------------------------------------------------
BM_Lex_Float                            10.9 ns         10.9 ns     63993114
BM_Lex_Int                              15.1 ns         15.1 ns     46869766
BM_Lex_IntDecimalN/1                    3.16 ns         3.16 ns    220923300
BM_Lex_IntDecimalN/10                   12.2 ns         12.2 ns     57731654
BM_Lex_IntDecimalN/100                   102 ns          102 ns      6875516
BM_Lex_IntDecimalN/1000                  942 ns          942 ns       742359
BM_Lex_IntDecimalN/10000                9353 ns         9350 ns        75096
BM_ComputeValue_Float                   44.9 ns         44.9 ns     15619691
BM_ComputeValue_Int                     48.9 ns         48.9 ns     14361507
BM_ComputeValue_IntDecimalN/1           21.9 ns         21.9 ns     31902433
BM_ComputeValue_IntDecimalN/10          30.3 ns         30.3 ns     23134117
BM_ComputeValue_IntDecimalN/100          224 ns          223 ns      3092567
BM_ComputeValue_IntDecimalN/1000        5834 ns         5830 ns       117469
BM_ComputeValue_IntDecimalN/10000     458818 ns       458626 ns         1523
BM_ComputeValue_IntBinaryN/1            22.2 ns         22.1 ns     31566949
BM_ComputeValue_IntBinaryN/10           32.9 ns         32.9 ns     21306927
BM_ComputeValue_IntBinaryN/100           198 ns          198 ns      3545277
BM_ComputeValue_IntBinaryN/1000         1671 ns         1669 ns       419656
BM_ComputeValue_IntBinaryN/10000       16402 ns        16396 ns        42744
BM_ComputeValue_IntHexN/1               22.4 ns         22.4 ns     31238055
BM_ComputeValue_IntHexN/10              47.8 ns         47.7 ns     14694407
BM_ComputeValue_IntHexN/100              436 ns          436 ns      1609794
BM_ComputeValue_IntHexN/1000            3966 ns         3962 ns       177109
BM_ComputeValue_IntHexN/10000          39249 ns        39233 ns        17859
```

Assisted-by: Google Antigravity with Gemini
2026-03-16 20:00:51 +00:00
Nicholas Bishop 943cd41924 Support constexpr pointers (#6907)
This moves the LValue path code from macros.cpp to constant.cpp, so that
it can be called from `MapAPValueToConstant`. TODO messages are updated
accordingly to avoid referring to macros. Added a constexpr pointer test
to `constexpr.carbon` to show the result of this change.
2026-03-16 19:19:20 +00:00
Jon Ross-Perkins c006013e0c Change multi-input error to warning (#6914)
Mainly so that Compiler Explorer's command line doesn't need to change.

Assisted-by: Google Antigravity with Gemini
2026-03-16 17:35:58 +00:00
dependabot[bot] aeed8f608b Bump undici from 6.21.3 to 6.24.0 in /utils/vscode in the npm_and_yarn group across 1 directory (#6911)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [undici](https://github.com/nodejs/undici).

Updates `undici` from 6.21.3 to 6.24.0
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/nodejs/undici/releases">undici's
releases</a>.</em></p>
<blockquote>
<h2>v6.24.0</h2>
<h1>Undici v6.24.0 Security Release Notes (LTS)</h1>
<p>This release backports fixes for security vulnerabilities affecting
the v6 line.</p>
<h2>Upgrade guidance</h2>
<p>All users on v6 should upgrade to <strong>v6.24.0</strong> or
later.</p>
<h2>Fixed advisories</h2>
<ul>
<li>
<p><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-2mjp-6q6p-2qxm">GHSA-2mjp-6q6p-2qxm</a>
/ CVE-2026-1525 (Medium)<br />
Inconsistent interpretation of HTTP requests (request/response smuggling
class issue).</p>
</li>
<li>
<p><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-f269-vfmq-vjvj">GHSA-f269-vfmq-vjvj</a>
/ CVE-2026-1528 (High)<br />
Malicious WebSocket 64-bit frame length handling could crash the
client.</p>
</li>
<li>
<p><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-4992-7rv2-5pvq">GHSA-4992-7rv2-5pvq</a>
/ CVE-2026-1527 (Medium)<br />
CRLF injection via the <code>upgrade</code> option.</p>
</li>
<li>
<p><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-v9p9-hfj2-hcw8">GHSA-v9p9-hfj2-hcw8</a>
/ CVE-2026-2229 (High)<br />
Unhandled exception from invalid <code>server_max_window_bits</code> in
WebSocket permessage-deflate negotiation.</p>
</li>
<li>
<p><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-vrm6-8vpv-qv8q">GHSA-vrm6-8vpv-qv8q</a>
/ CVE-2026-1526 (High)<br />
Unbounded memory consumption in WebSocket permessage-deflate
decompression.</p>
</li>
</ul>
<h2>Not applicable to v6</h2>
<ul>
<li><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-phc3-fgpg-7m6h">GHSA-phc3-fgpg-7m6h</a>
/ CVE-2026-2581 affects <code>&gt;= 7.17.0 &lt; 7.24.0</code> only.</li>
</ul>
<h2>Affected and patched ranges (v6)</h2>
<ul>
<li>CVE-2026-1525: affected <code>&lt; 6.24.0</code>, patched
<code>6.24.0</code></li>
<li>CVE-2026-1528: affected <code>&gt;= 6.0.0 &lt; 6.24.0</code>,
patched <code>6.24.0</code></li>
<li>CVE-2026-1527: affected <code>&lt; 6.24.0</code>, patched
<code>6.24.0</code></li>
<li>CVE-2026-2229: affected <code>&lt; 6.24.0</code>, patched
<code>6.24.0</code></li>
<li>CVE-2026-1526: affected <code>&lt; 6.24.0</code>, patched
<code>6.24.0</code></li>
</ul>
<h2>References</h2>
<ul>
<li>GitHub Security Advisories: <a
href="https://github.com/nodejs/undici/security/advisories">https://github.com/nodejs/undici/security/advisories</a></li>
<li>NVD CVE-2026-1525: <a
href="https://nvd.nist.gov/vuln/detail/CVE-2026-1525">https://nvd.nist.gov/vuln/detail/CVE-2026-1525</a></li>
<li>NVD CVE-2026-1528: <a
href="https://nvd.nist.gov/vuln/detail/CVE-2026-1528">https://nvd.nist.gov/vuln/detail/CVE-2026-1528</a></li>
<li>NVD CVE-2026-1527: <a
href="https://nvd.nist.gov/vuln/detail/CVE-2026-1527">https://nvd.nist.gov/vuln/detail/CVE-2026-1527</a></li>
<li>NVD CVE-2026-2229: <a
href="https://nvd.nist.gov/vuln/detail/CVE-2026-2229">https://nvd.nist.gov/vuln/detail/CVE-2026-2229</a></li>
<li>NVD CVE-2026-1526: <a
href="https://nvd.nist.gov/vuln/detail/CVE-2026-1526">https://nvd.nist.gov/vuln/detail/CVE-2026-1526</a></li>
</ul>
<h2>v6.23.0</h2>
<h2>⚠️ Security Release</h2>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/nodejs/undici/commit/8873c947271faf1ebc455bdc6158ecbc022ecfa9"><code>8873c94</code></a>
Bumped v6.24.0</li>
<li><a
href="https://github.com/nodejs/undici/commit/411bd01a42e7917009bbf686f7628b99d67bbce9"><code>411bd01</code></a>
test(websocket): use node:assert for Node 18 compatibility</li>
<li><a
href="https://github.com/nodejs/undici/commit/844bf59699d778944f78a24ae819c0e8f295766e"><code>844bf59</code></a>
test: fix http2 lint regressions in backport</li>
<li><a
href="https://github.com/nodejs/undici/commit/a444e4f13e8958b4e1ac42bc0d53ace7fba0a9c1"><code>a444e4f</code></a>
test: stabilize h2 and tls-cert-leak under current test runner</li>
<li><a
href="https://github.com/nodejs/undici/commit/dc032a1050d5489b8ce9b4c22aafba98a942f87b"><code>dc032a1</code></a>
fix: h2 CI (<a
href="https://redirect.github.com/nodejs/undici/issues/4395">#4395</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/4cd3f4b3a2ef910ba728c47ae78294d956410450"><code>4cd3f4b</code></a>
test: increase bitness in <code>test/fixtures/*.pem</code> (<a
href="https://redirect.github.com/nodejs/undici/issues/3659">#3659</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/7df6442194b7a54e9ac734335e6e0a56a9bc6666"><code>7df6442</code></a>
fix: adapt websocket frame-limit handling for v6 parser</li>
<li><a
href="https://github.com/nodejs/undici/commit/4e0179ae643e6f4380f24cc3683c1b1ca2afb094"><code>4e0179a</code></a>
fix: reject duplicate content-length and host headers</li>
<li><a
href="https://github.com/nodejs/undici/commit/5a97f0893b53ba7d1d5549d3df7e55d9c2673f89"><code>5a97f08</code></a>
Fix websocket 64-bit length overflow</li>
<li><a
href="https://github.com/nodejs/undici/commit/e43e898603dd5e0c14a75b08b83257598d664a39"><code>e43e898</code></a>
fix: validate upgrade header to prevent CRLF injection</li>
<li>Additional commits viewable in <a
href="https://github.com/nodejs/undici/compare/v6.21.3...v6.24.0">compare
view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by [GitHub Actions](<a
href="https://www.npmjs.com/~GitHub">https://www.npmjs.com/~GitHub</a>
Actions), a new releaser for undici since your current version.</p>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=undici&package-manager=npm_and_yarn&previous-version=6.21.3&new-version=6.24.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-16 15:54:05 +00:00
Jon Ross-Perkins 8b907b5a60 Support octal literals (#6910)
Support octal literals, mainly for migrating Unix file permissions.
Reflects leads decision #6821.
2026-03-14 00:50:58 +00:00
6f1f59a385 Initial Reverse Interop implementation (#6901)
Add a clang::ExternalASTSource to begin exposing Carbon entities to
Clang - initially only a single `Carbon` top level namespace.

Subsequent work will add Carbon entities to this namespace.

Likely this CarbonExternalASTSource will be refactored into another
file, tie into/reference SemIR::File and CppFile, etc eventually - but
that'll wait for future patches.

If there's mechanical problems with the current implementation - how I'm
creating the new NamespaceDecl, etc - I'm all ears. It's very much in
the "it seems to work" state, not much more than that.

This does break Clang Modules (header modules, C++20 modules,
precompiled headers, etc) since they're implemented as an
ExternalASTSource as well, and Clang's ASTContext only supports one
ExternalASTSource at a time. To fix that regression we'll need to
implement some kind of ExternalASTSource multiplexing support - either
in Clang or Carbon (unclear which).

This regression of modules support can be observed by the following:
`A.h`
```
inline void f1() { }
```
`module.modulemap`
```
module A {
  header "A.h"
  export *
}
```
`test.carbon`
```
import Cpp inline '''
// Hardcode the pragma to ensure this isn't silently falling back to
// textual inclusion.
void f2() {
  f1();
}
''';
```
```
carbon compile test.carbon -- -I . -fmodules -fimplicit-modules -fmodules-cache-path=module_cache
```

I wrote a `file_test` test for this, but it doesn't /quite/ work because
`file_test` provides an in-memory filesystem for tests to make them more
hermetic, but Clang's Filesystem abstrtaction is for reading only - so
the module that's written out successfully can't be found when it needs
to be read back in - so the test doesn't pass as a baseline. Clang does
have support for `llvm::vfs::OutputBackend` which allows virtualizing
output - which I guess we could tie together with the InMemoryFilesystem
we use for input to make such a test work. But I guess that's not worth
the effort here?

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-03-13 23:04:49 +00:00
Dana Jansens 27cc14848a Use a single work queue in RequireIdentifiedFacetType (#6904)
Use a single vector instead of two. This reduces the number of memory
allocations required.
2026-03-13 22:16:41 +00:00
Jon Ross-Perkins fbe917b949 Create a UnifiedDiffMatcher to make golden test failures easier to understand (#6897)
Right now I think everyone has the habit of doing an autoupdate then
using source control for a diff. This is offering an option of better
diff output from the test.

For example:

```
TEST: toolchain/driver/testdata/fail_flush_errors.carbon !
Ran 1 tests in 81 ms wall time, 8 ms across threads
testing/file_test/file_test_base.cpp:264: Failure
Value of: SplitOutput(test_file.actual_stderr)
Expected: matches elements with union diff
  Actual: { "fail_flush_errors.carbon:22:3: error: name `undeclared1` not found [NameNotFound]", "  undeclared1;", "  ^~~~~~~~~~~", "", "fail_flush_errors.carbon:31:3: error: `Core.String` implicitly referenced here, but package `Core` not found [CoreNotFound]", "  \"undec\\x6Cared2\";", "  ^~~~~~~~~~~~~~~~", "", "fail_flush_errors.carbon:35:3: error: name `undeclared2` not found [NameNotFound]", "  undeclared2;", "  ^~~~~~~~~~~", "", "fail_flush_errors.carbon:43:3: error: name `undeclared3` not found [NameNotFound]", "  undeclared3;", "  ^~~~~~~~~~~", "", "" }, union diff (- expected, + actual):
=== diff in expected elements 0 to 2:
+ fail_flush_errors.carbon:22:3: error: name `undeclared1` not found [NameNotFound]
    undeclared1;
    ^~~~~~~~~~~

=== diff in expected elements 4 to 9:
    "undec\x6Cared2";
    ^~~~~~~~~~~~~~~~

+ fail_flush_errors.carbon:35:3: error: name `undeclared2` not found [NameNotFound]
    undeclared2;
    ^~~~~~~~~~~

=== diff end

Stack trace:
  0x55e476d29efd: Carbon::Testing::FileTestCase::TestBody()
  0x55e476dbd1f2: testing::internal::HandleExceptionsInMethodIfSupported<>()
  0x55e476dbcf57: testing::Test::Run()
  0x55e476dbf0bf: testing::TestInfo::Run()
... Google Test internal frames ...


To test this file alone, run:
  bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/driver/testdata/fail_flush_errors.carbon

testing/file_test/file_test_base.cpp:277: Failure
Failed
Autoupdate would make changes to the file content. Run:
bazel run //toolchain/testing:file_test -- --autoupdate --file_tests=toolchain/driver/testdata/fail_flush_errors.carbon
Stack trace:
  0x55e476d2a5f0: Carbon::Testing::FileTestCase::TestBody()
  0x55e476dbd1f2: testing::internal::HandleExceptionsInMethodIfSupported<>()
  0x55e476dbcf57: testing::Test::Run()
  0x55e476dbf0bf: testing::TestInfo::Run()
... Google Test internal frames ...

[  FAILED  ] ToolchainFileTest.toolchain/driver/testdata/fail_flush_errors.carbon, where GetParam() = toolchain/driver/testdata/fail_flush_errors.carbon (93 ms)
```

Assisted-by: Google Antigravity with Gemini
2026-03-13 21:39:21 +00:00
Dana Jansens bad9beddc7 Diagnose using named constraint's name inside its definition (#6906)
Using a named constraint inside itself is problematic:
- If there were not require decls written above, it identifies as an
empty set. This makes `Z(Self)` essentially disappear in the identified
facet type, which produces "no use of Self" diagnostics while the user
can see a use of Self in the code.
- It won't include require decls that are written after, and so `require
T impls Z` won't actually enforce that `T` impls all of `Z`.

Previously this was an error because using the named constraint would
require it to be identified, and it's not identified until it is
complete. But this will change in proposal #6902. So that proposal also
includes changes to preserve diagnostics for incorrect use of a named
constraint before it's complete, which is implemented here.

Discussed in open discussion [on
2026-03-12](https://docs.google.com/document/d/1mjllGO3ZCL4qGt9uJHUtcxKoHAGEY7Y999ie4EtBWB8/edit?tab=t.0#heading=h.1dvbbrp5a6t3).

The new tests exposed a bug where we're not copying named constraints in
a facet type on the RHS of `where .Self impls` into the facet type on
the left, which is now fixed. The
`fail_require_impls_incomplete_self_in_period_self_impls.carbon` test
would not diagnose its error without this fix.
2026-03-13 16:54:58 +00:00
Jon Ross-Perkins 6706162582 Error when passing multiple input files with --output (#6896)
Fixes #6895

Note this is just a short-term fix to avoid confusion, as the compile
structure needs to change on the whole.

Assisted-by: Google Antigravity with Gemini
2026-03-13 16:07:12 +00:00
Christopher Di Bella ffe8f8f67d Revert "refactors LookupCppImpl to handle multiple associated functions (#6816)" (#6900)
We discussed whether associated functions should be processed in a
general manner. Since many associated functions will have some amount of
unique processing, we're probably better off not having a general
utility, and we can return to the original `CoreInterface`, which was
much simpler in design.

This reverts commit 4d0003765d.
2026-03-13 15:09:42 +00:00
Dana Jansens 5d1973ab93 Support --remote in new_proposal script with jj (#6903) 2026-03-12 21:57:56 +00:00
Jon Ross-Perkins 610094ccfd Make included files insert before main files (#6899)
This is so that the last file is more likely what we're trying to
compile in tests. Just splitting out the churn-y change of reordering.

Assisted-by: Google Antigravity with Gemini
2026-03-12 21:01:16 +00:00
Christopher Di BellaandRichard Smith 4df2b6ea9d adds checking support for CppUnsafeDeref witness (#6890)
Iterators, smart pointers, optional, and expected types depend on
`operator*`. This commit adds `CppUnsafeDeref` as a core interface, with
an associated function, so that the compiler can dereference
user-defined C++ types.

Things not implemented in this commit:

* `operator*` overload resolution
* SemIR lowering

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-03-12 18:02:34 +00:00
Jon Ross-Perkins 1e9708e2cc Update python version for black (#6877)
This is making it consistent with other places we set a Python version:
- contribution_tools.md
- .python-version
- bench_runner.py
- build-setup-common/action.yml

Assisted-by: Google Antigravity with Gemini
2026-03-12 16:45:58 +00:00
Dana Jansens 4c69a1baf0 Use min-prelude in fail_assoc_const_alias.carbon (#6894)
Remove the local `Core` package from the test file and use the
`convert.carbon` min-prelude.
2026-03-12 16:10:23 +00:00
Nicholas Bishop c1fd771242 Support calling constexpr functions at compile time (#6878)
Example:

```carbon
import Cpp inline '''
constexpr int f(int a, int b) { return a + b; }
''';

let a: array(i32, Cpp.f(1, 2)) = (1, 2, 3);
```
2026-03-12 01:45:31 +00:00
Chandler CarruthandDana Jansens 5d41529590 Introduce a Bazel-integrated build for the installed runtimes (#6872)
This shifts the Bazel toolchain configuration of our installation to
build all of the Clang runtimes Carbon uses on-demand natively in Bazel.
We export the information about how to build into a generated Starlark
file, and emit BUILD files and Starlark logic into the installation to
orchestrate the build.

This requires some complex management of Bazel toolchains -- we need to
first set-up a "runtimes toolchain" that doesn't have runtimes of its
own, but can be used to _build_ runtimes. Then we build the runtimes
using that toolchain, and assemble them into the standard layout for a
Carbon runtimes tree. Finally we configure the _actual_ toolchain with
this built tree.

Currently, this is only setup for the installed toolchain, but I plan to
factor this runtimes build into one that can be used directly as well to
break up the monolithic runtimes build step into Bazel-integrated build
of the runtimes. This will also serve as the foundation for adding
bootstrapping support directly to our Bazel build.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-03-12 01:24:56 +00:00
Richard Smith 0a4fd2cb7e Fix thunk generation for &&-qualified methods. (#6881)
Use the object parameter type when creating a reference to the thunk
parameter so that we create an xvalue rather than an lvalue for the
`*this` expression in the thunk.
2026-03-11 20:34:18 +00:00
Richard Smith 2e5b195813 Make {} as Class an initializing expression. (#6882)
Previously we forced a temporary materialization, resulting in it being
treated as an ephemeral reference expression. This change allows

```carbon
var x: Class = {} as Class;
```

even when `Class` is not copyable.
2026-03-11 20:21:21 +00:00
Nicholas Bishop 6ac561afe9 Add "Fixing conflicts with trunk" to code_review.md (#6889) 2026-03-11 19:30:20 +00:00
Jon Ross-Perkins 70c401f85f Updates the llvm-raw commit to HEAD as of 2026-03-09 (#6879)
Test changes are the result of autoupdate_testdata.py

Assisted-by: Google Antigravity with Gemini
2026-03-11 14:47:40 +00:00
Richard Smith 39fd358059 Map Carbon value expressions to const-qualified C++ prvalues. (#6880)
In C++ overload resolution, when mapping a Carbon value expression into
a C++ argument, produce a const-qualified argument where possible. This
has two effects:

* Overload resolution does not consider non-const-qualified member
functions to be viable for a prvalue self any more. This is desirable
since such functions are not actually callable with a prvalue self, and
permits overload resolution to pick a const-qualified overload instead.

* Overload resolution does not allow a Carbon value expression to be
passed to a C++ `T&&` parameter any more. This is desirable since it's
not correct to move from a value expression. Previously we allowed this
and moved from the value!
2026-03-11 03:42:19 +00:00
Geoff Romer ba6257891e Remove ValueParamPattern case from deduction (#6869)
This case is redundant: when deducing against a runtime parameter
pattern, the type is all that matters, and the type is added to the
deduction earlier. Additionally deducing the same argument against
parameter's subpattern just creates duplicate work, because the
subpattern has the same type.
2026-03-10 21:15:38 +00:00
Ilya 6304df1db9 Fix crash in character literal lexing (#6805)
When lexing a hash-prefixed character literal, the lexer assumed that
the hash level of escape sequences inside the literal was zero, which
allowed unclosed escape sequences inside the literal which crashed the
compiler.

Closes #6799
2026-03-10 20:25:29 +00:00
Richard Smith 99bde2acb3 Refactor match parse nodes. (#6870)
Use the same node kind for the body of `case` and `default` handlers. We
don't need to distinguish these in check, so don't create extra node
kinds for them.

In order to make the nodes properly delimited, make the label (`case
...` or `default`) nodes be children of the `=>` node rather than
siblings. This allows us to use the node kind of the `=>` as the
bracketing node for the complete handler, rather than having two
different bracketing node kinds, one for each kind of label.
2026-03-10 20:04:28 +00:00
Chandler Carruth 9e2d0a887f Factor out textual headers from libcxx and libcxxabi (#6863)
Also cleans up how the filegroups from these rules are organized --
separately tracking srcs, hdrs, and textual-srcs.
2026-03-10 07:48:08 +00:00
Richard Smith c297344937 Support conversion between integer types. (#6856)
Add an `IntFitsIn` interface with a custom witness, such that `T impls
IntFitsIn(U)` if `T` is an integer type all of whose values fit
losslessly into the integer type `U`. Use it to constrain implicit
conversions between integer types.

So far, this has not been extended to the
`CppCompat.[U]{Long32,LongLong64}` types, only to `Core.Int(N)` and
`Core.UInt(N)`.

Assisted-by: Gemini 3 Pro via Antigravity
2026-03-10 01:40:16 +00:00
Geoff RomerandJon Ross-Perkins 18cfeb7476 Add support for ->? return forms (#6849)
This includes checking and lowering for concrete form literals. Support
for symbolic forms is future work.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-03-09 22:30:16 +00:00
Chandler Carruth 5ad9b1a35d Lift builtins build logic into Starlark (#6859)
This moves the most complex of the logic fully into Starlark: both the
many different platform sources list, and the overriding of generic
files with architecture specific files.

This also fixes significant bugs in the AArch64 build where we were
skipping numerous files: all of the outlined atomics and `emupac.cpp`.
This PR forcibly disables `emupac.cpp` as fixing that will require a
more significant change.
2026-03-09 19:41:11 +00:00
Jon Ross-Perkins a1b6f1c4bd Allow uploads.github.com (#6866)
Reported at
https://discord.com/channels/655572317891461132/707150492370862090/1480625413808984136

Assisted-by: Google Antigravity with Gemini
2026-03-09 18:21:08 +00:00
Jon Ross-Perkins 3e3a97593d Remove obsolete llvm patch (#6865)
#6771 removed the use of this patch, but not the patch itself.

Assisted-by: Google Antigravity with Gemini
2026-03-09 15:55:21 +00:00
Jon Ross-Perkins 4b076291c9 pre-commit autoupdate (#6845)
Assisted-by: Google Antigravity with Gemini
2026-03-09 15:49:11 +00:00
Jon Ross-Perkins bee2633946 Try out wolfd_bazel_compile_commands (#6851)
Noticed this in bazel central registry, I'm interested in trying it out.
It's using a faster approach, but leaving the other around for the
moment in case it doesn't work out well.

Assisted-by: Google Antigravity with Gemini
2026-03-09 15:34:43 +00:00
Jon Ross-Perkins 1a47c02e5d Update tool versions in script_utils (#6852)
Assisted-by: Google Antigravity with Gemini
2026-03-09 15:34:23 +00:00
Nicholas Bishop 8a4888c3df Support assigning to a struct field through a macro (#6843)
Example:

```carbon
import Cpp inline '''
struct B {
  int c;
};
struct A {
  B b;
};
A a;
#define m a.b.c
''';

fn F() {
  Cpp.m = 2;
}
```
2026-03-09 15:31:16 +00:00
Dana JansensandChandler Carruth 744b1290cf Roll LLVM b20d7d02..6811a83c815 (#6844)
Roll LLVM to `6811a83c81500ee373adfc0d9978ff9625a4cf1c`.

This includes https://github.com/llvm/llvm-project/pull/183831 which
moved the functionality of `finish()` on `DiagnosticConsumer`s into the
destructors, and removed the `finish()` method. So, our callers to
`finish()` are migrated to cause the destructor to run at that time
instead.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-03-09 15:00:21 +00:00
Jon Ross-Perkins 6b2d55d289 Adjust tool usage notes (#6853)
Trying to work on some behaviors:

- Using `black` to format Python files (using `pre-commit` makes better
use of allow-listed commands)
- Writing Python code over 80 columns (adding more style notes)
- Running `bazel` (being more emphatic about `bazelisk`, splitting tool
usage out to its own skill to try making clear it's not
toolchain-specific)

Assisted-by: Google Antigravity with Gemini
2026-03-09 14:56:41 +00:00
Nicholas Bishop cdcd3ab66c Handle pack expansion for dependent non-type template params (#6850)
https://github.com/carbon-language/carbon-lang/issues/6717
2026-03-09 14:49:31 +00:00
Jon Ross-Perkins 0dac40e793 Update clangd-tidy endpoint whitelist (#6855)
Missed in #6848 (had it sitting in my workspace uncommitted, apparently
have gotten too used to jj; using git here)

Assisted-by: Google Antigravity with Gemini
2026-03-09 03:23:22 +00:00
Jon Ross-Perkins f27f8838d0 Switch llvm-raw to a git_override rule (#6854)
By using git_override, we get some validation from the sha, while
removing the sha256 on the .tar.gz which has been brittle lately. Note
the difference between downloading via sha is this still locally
validates content.

Versus something like #6844, this doesn't update the llvm version, just
how we get it.

Assisted-by: Google Antigravity with Gemini
2026-03-07 03:30:43 +00:00
Jon Ross-Perkins 6786edd6ff Update action versions (#6848)
In addition to the general updates, this switches to a required python
3.10 for pre-commit (3.9 is losing support from black).

Note endpoints for build actions are expanding significantly: see
https://app.stepsecurity.io/github/carbon-language/carbon-lang/actions/runs/22779388360?tab=recommendations&jobId=66080970460
for example, I think just the sources are being increased as a
side-effect of updates (and possibly also things not performing as well
as they should have before).

Similarly allowing sudo in pre-commit because it was actually causing
errors in part of build setup, which used sudo to remove files.

Assisted-by: Google Antigravity with Gemini
2026-03-06 22:19:44 +00:00
Jon Ross-Perkins 53c257d2e2 Switch libpfm and boost.unordered to BCR versions (#6847)
Assisted-by: Google Antigravity with Gemini
2026-03-06 21:57:23 +00:00
Geoff RomerandDavid Blaikie 2e155567bd Disallow :? within var (#6812)
Co-authored-by: David Blaikie <dblaikie@gmail.com>
2026-03-06 21:08:22 +00:00
Jon Ross-Perkins 53729325a0 Update bazel module versions (#6846)
Adds a script that queries bazel central registry and other sources to
get the latest versions. Gemini generated something similar on the fly
for checks, and I figured it's helpful to formalize.

```
- BCR:
  - abseil-cpp: 20260107.1
  - bazel_skylib: 1.9.0
  - google_benchmark: 1.9.5
  - googletest: 1.17.0.bcr.2
  - libpfm: 4.13.0
  - platforms: 1.0.0
  - protobuf: 34.0.bcr.1
  - re2: 2025-11-05.bcr.1
  - rules_bazel_integration_test: 0.37.1
  - rules_cc: 0.2.17
  - rules_pkg: 1.2.0
  - rules_python: 1.9.0
  - rules_shell: 0.6.1
  - tcmalloc: 0.0.0-20250927-12f2552
  - tree-sitter-bazel: 0.26.5
  - zlib-ng: 2.0.7
  - zstd: 1.5.7.bcr.1
- GitHub Tag:
  - libpfm: v4.13.0
- Git HEAD:
  - bazel_clang_tidy: c4d35e0d0b838309358e57a2efed831780f85cd0
  - hedron_compile_commands: abb61a688167623088f8768cc9264798df6a9d10
```

Assisted-by: Google Antigravity with Gemini
2026-03-06 20:48:46 +00:00
21291b4cc3 Remove InitForm::index (#6817)
This ensures that equal forms always have equal representations (because
the index depends on how the form is used, not on the value of the form
itself).

As a byproduct, also remove `NextCallParamIndex`.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Nicholas Bishop <nicholasbishop@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Boaz Brickner <brickner@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: MK4070 <60286678+MK4070@users.noreply.github.com>
Co-authored-by: Christopher Di Bella <cjdb@google.com>
2026-03-06 17:35:48 +00:00
Jon Ross-PerkinsandRichard Smith 2327b62b5f Add jj and AI notes to contribution tools (#6841)
Giving both of these their own sections under optional tools because I'm
mainly doing this to share example configs.

Assisted-by: Google Antigravity with Gemini

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-03-06 16:13:00 +00:00
Jon Ross-Perkins 97af347490 Switch GEMINI.md to skills (#6842)
This is a refactoring to .agent/skills structure, which should also work
for more AI assistants.

Assisted-by: Google Antigravity with Gemini
2026-03-05 23:30:12 +00:00
Jon Ross-PerkinsandRichard Smith 1257ef2fd0 More GEMINI.md file work (#6840)
We may want to split some out to skills, I'm just trying to merge in
some info of my own now.

Assisted-by: Google Antigravity with Gemini 3 Flash

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-03-05 21:35:40 +00:00
josh11bandJosh L c837c004bc Fix comment to match case of parameter name (#6839)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-03-05 21:20:44 +00:00
Richard Smith 6a650941d2 Don't run clang to link when fuzzing. (#6835)
The clang driver is too easy to crash with fuzzer-generated command
lines, and it's not interesting to find those bugs.
2026-03-05 20:01:44 +00:00
Richard Smith bf6f21b8e9 Add a GEMINI.md. (#6838)
Assisted-by: Gemini 3 Pro via Antigravity
2026-03-05 19:56:13 +00:00
Christopher Di BellaandCarbon Infra Bot a9f1e17ecb codifies Carbon specifier and qualifier order (#6831)
The Carbon style guide prefers `const` to be on the left wherever
possible, and also has a de-facto standard for specifier order. Since
the order of specifiers and qualifiers tends to become a part of
muscle-memory, deferring the checking of this to tooling should lift a
small burden on both contributors and reviewers.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-03-05 19:04:21 +00:00
Nicholas Bishop e5957037fb Support assigning to a variable through an imported macro (#6827)
Support assigning to a variable through an imported macro

Example:

```carbon
import Cpp inline '''
int v = 1;
#define m v
''';

fn F() {
  Cpp.m = 2;
}
```
2026-03-05 18:24:32 +00:00
Jon Ross-Perkins 002b7c74ea Support CARBON_KIND with Any types (#6828)
This uses the `CARBON_KIND_ANY(AnyImportRef, auto import_ref):` syntax
that seemed to be favored [on
Discord](https://discord.com/channels/655572317891461132/655578254970716160/1478486848207720478).

This converted uses in the `sem_ir` directory to show it works
initially, then added `check` for full coverage plus validating the
`SemIR::` namespace discard.

Note in inst_namer.cpp, AnyBindingPattern includes FormBindingPattern
which wasn't previously handled.

I'm disabling clang-format because I think it formats with readability
issues, e.g.:

```
#define CARBON_KIND_ANY_EXPAND_AnyBinding(X, SEP)                        \
  X(::Carbon::SemIR::AliasBinding)                                       \
  SEP X(::Carbon::SemIR::FormBinding) SEP X(::Carbon::SemIR::RefBinding) \
      SEP X(::Carbon::SemIR::SymbolicBinding)                            \
          SEP X(::Carbon::SemIR::ValueBinding)
```

Since `SEP` is typically a comma, it's also a nuisance to treat as an
argument to `X` (which could get better results).

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-03-05 01:20:37 +00:00
Christopher Di BellaandGeoff Romer 4d0003765d refactors LookupCppImpl to handle multiple associated functions (#6816)
`LookupCppImpl` is used to find associated functions for a witness. As
some witnesses contain multiple associated functions, we need robust
mechanims for looking up C++ components.

The logic in `LookupCppImpl` is primarily concerned with finding exactly
one C++ declaration at a time. In order to handle witnesses with more
than one associated function, we move the bulk of `LookupCppImpl` to a
new function called `FindCppAssociatedFunction`. This frees up
`CppLookupImpl` to delegate to `FindCppAssociatedFunction` when a
witness has only one associated function, and to functions that are able
to compose multiple associated functions.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-03-04 20:56:25 +00:00
Christopher Di Bella b28e899a8c refactors PerformCppOverloadResolution to take CppOverloadSet (#6829)
`PerformCppOverloadResolution` computes an overload set from a
`CppOverloadSetId`, but the compiler sometimes needs to synthesise a
local overload set for witnesses. `PerformCppOverloadResolution` now
requires callers to produce the `CppOverloadSet` to address this
problem.
2026-03-04 19:02:33 +00:00
1c7a4030ab Parse invalid lambdas without crashing (#6826)
Fixes a compiler crash that occurs when a malformed lambda is provided
as an operand to an operator that strictly expects an expression

Changes:
- Emits an `InvalidParse` dummy node at the current position to act as a
placeholder for the missing body
- Changed state transitions so that `LambdaIntroducer` gets properly
wrapped into a `Lambda` node


Closes #6823

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-03-04 14:57:48 +00:00
Richard SmithandCarbon Infra Bot 15680ba101 Support calling functions with explicit template arguments. (#6814)
Treat the initial sequence ofarguments in a call to a C++ function up to
and including the last argument that is a type or template as being the
explicit template arguments for the call, rather than rejecting them
because they can't be converted to the parameter types.

Implements the current direction on leads issue #6768, except that no
syntax for explicitly annotating an argument as being a template
argument is provided.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-03-03 00:26:33 +00:00
Geoff RomerandJon Ross-Perkins 6dba8ee111 Remove index fields from ParamPatterns (#6815)
This is a step toward removing the index from `InitForm`, so that equal
form values always have equal representations.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-03-03 00:19:47 +00:00
9ff6b0a682 C++ Interop: API importing and semantics (#6358)
This proposal defines the concrete technical mechanisms for C++
interoperability. It specifies the precise syntax and semantics for
importing
C++ APIs. This includes the `import Cpp library "..."` and implicitly
importing
C++ built-in entities, and the establishment of the `Cpp` package as the
dedicated namespace for all imported entities.

This PR also includes high level language C++ Interop design and the
basics of importing C++ APIs and function calling.
Leaving plenty of TODOs to make it easier to fill in more details in
followups.

Part of #4666.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-03-02 22:35:47 +00:00
Nicholas Bishop 069c6f4447 Refactor TryEvaluateMacroToConstant to simplify and dedup code (#6820)
For integral and float types, `TryEvaluateMacroToConstant` now calls
`MapAPValueToConstant` to directly convert from an APValue, rather than
converting the `APValue` to an expression and importing it with
`MapConstant`.

`MapConstant` is still used, but only for string literals and nullptrs.
Since it's only used by `TryEvaluateMacroToConstant`, moved it to
`macros.cpp` and removed the code for other types of expressions.
2026-03-02 21:00:07 +00:00
Dana Jansens 6359e3f550 Dedupe self values in identify facet type (#6819)
The self value can be a facet-value or a facet-value-as-type. The self
value used in `require` decls is the former. The the self value used for
identifying the facet type is the latter, we end up with two different
required interfaces in the identified facet type: one for each self
value.

Always canonicalize the self value to a facet value in identification.
Then dedupe the list of extend interfaces when constructing the
`IdentifiedFacetType` before counting them. And then impl lookup needs
to canonicalize its query self for comparing with the result from the
`IdentifiedFacetType`.
2026-03-02 19:09:10 +00:00
Jon Ross-Perkins b14015602b Make Destroy.Op functions able to have a body (#6729)
This is iterating on how `Destroy.Op` generates, to start adding body
capabilities. This changes the way the signature is created, and adds a
`CoreWitness` function kind so that mangling can prevent name
collisions. The result is that what _was_ `DestroyOp` is now
`Core.Destroy.Op` or, as can be seen in
toolchain/lower/testdata/interop/cpp/nullptr.carbon,
`_COp.<hash>:core.Destroy.Core` where `:core` is indicating that it's a
core witness (taking a note from `:thunk`).

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-03-02 17:57:31 +00:00
Nicholas Bishop 2389590230 Support pointer template params (#6810)
https://github.com/carbon-language/carbon-lang/issues/6717
2026-03-02 16:07:23 +00:00
dependabot[bot] ef0bb898ac Bump minimatch from 3.1.3 to 3.1.5 in /utils/vscode in the npm_and_yarn group across 1 directory (#6818)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [minimatch](https://github.com/isaacs/minimatch).

Updates `minimatch` from 3.1.3 to 3.1.5
-
[Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.3...v3.1.5)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 3.1.5
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-02 15:08:58 +00:00
Özgür 067378ba37 Fix syntax errors in docs observe examples (#6813) 2026-02-27 23:07:24 +00:00
Geoff Romer 34764d0d0e Fix issues from #6745 (#6811)
- Typo in the definition of `Core.Form`
- Resolved TODO to add test coverage
- Restored lexicographic order in a switch
2026-02-27 22:47:00 +00:00
Nicholas Bishop 3b49b51956 Support bool template params (#6808)
https://github.com/carbon-language/carbon-lang/issues/6717
2026-02-27 19:22:08 +00:00
Jon Ross-Perkins 93faac45af Mark mangled enclosed entities (#6809)
This overlapped a little with `Destroy` work; adding the `:enclosed`
identifier (similar to `:thunk`) just to make it easier to identify. I
believe the TODO still applies.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-27 19:05:10 +00:00
Dana Jansens cea52ad2d8 Format the InterfaceWithSelf and NamedConstraintWithSelf generic name with its ".WithSelf" suffix (#6798)
We used the ".WithSelf" suffix when formatting a parent scope, but
missed the suffix when formatting the scope name on its own.
2026-02-27 13:50:56 +00:00
Richard SmithandDavid Blaikie d5ec82e7ac Don't crash if clang setup fails. (#6804)
Defer creating the CppContext until we have all of its components, so
that we know they're not null. Don't track the action on the context,
since it's not a reliable way of getting back to the compiler invocation
on failure. Don't flush the diagnostics emitter from the emitter
destructor since the derived class emitter will already have been
destroyed at that point. Distinguish between clang setup failing and
clang merely producing errors, and don't connect the check context to
clang if clang setup failed.

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2026-02-27 02:44:08 +00:00
Nicholas Bishop a6a0e55167 Support float template params (#6801)
https://github.com/carbon-language/carbon-lang/issues/6717
2026-02-27 01:30:40 +00:00
Richard Smith 41dd256d56 Support for initialization of classes with abstract base classes. (#6802)
When initializing `.base` in class initialization, use `partial Base` as
the destination type rather than `Base`. Treat `partial Base` as not
being abstract even when `Base` is.

Allow conversion from a `partial T` initializer to a `T` initializer.
Store the vptr while performing the conversion. Do not store the vptr
when performing a `partial T` initialization, only when performing a
non-partial `T` initialization.
2026-02-27 01:27:25 +00:00
Richard Smith be88dfd744 Formatter: don't crash on unexpected SemIR. (#6787)
The formatter is used as a debugging tool, so shouldn't crash if the
SemIR is in an unexpected shape.
2026-02-27 01:02:53 +00:00
Richard Smith b83dcd4348 Fix backtrace symbolization. (#6803)
We previously set `LLVM_SYMBOLIZER_PATH` to a bogus path ending
`.../binllvm-symbolizer`. Because this var was set, LLVM's symbolizer
lookup would also skip looking in `$PATH`, so this was causing
symbolization to never happen unless `LLVM_SYMBOLIZER_PATH` was
explicitly set in the environment.
2026-02-26 23:15:04 +00:00
bf9219d30e Check support for form literals and :? bindings (#6747)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-02-26 23:01:24 +00:00
Richard Smith f9ab963bd6 Add a type_literal instruction to represent syntactic type literals. (#6781)
This allows us to capture the location at which a type literal was used,
even in the cases where we don't otherwise need to create a new
instruction to represent the type such as for `char` or `str`.

The logic used to build the underlying type is now marked as desugaring.
For cases such as `iN`, this causes the call to `Core.Int` to no longer
be added as a dedicated IR instruction, and instead its constant value
is used directly as the value of the `type_literal`. This results in
this being on balance a reduction in the size of the IR.

This also fixes a crash in C++ interop when using a `char` literal as a
template argument. The crash was caused by the template argument not
having an associated location when mapping to a C++ location. See
changes to check/testdata/interop/cpp/template/type_param.carbon for an
example that used to crash before this change.

Update alias handling to allow an alias to point at any type literal,
reinstating support for aliases for type literals such as `bool` and
`i32` that had previously worked but stopped working when we
transitioned those types to being defined in the prelude. See changes to
toolchain/check/testdata/alias/builtins.carbon.

All the test changes other than the two mentioned above are mechanical
autoupdate changes switching to the new instruction.
2026-02-26 20:10:50 +00:00
Nicholas Bishop 96f163f114 Support floats in MapAPValueToConstant (#6800)
This allows `constexpr float` to be properly imported as a constant.
2026-02-26 19:48:19 +00:00
Özgür d11ee4b2b1 Implement parsing observe declarations (#6674)
This implements parsing of the
[`observe`](https://docs.carbon-lang.dev/docs/design/generics/details.html#observing-a-type-implements-an-interface)
declarations.

- Added states and node kinds.
- Added node categories.
- Added a diagnostic for invalid keywords/operators.
- Implemented parser state handlers.
- Added structs to `typed_nodes.h`.
- Added parser tests.
2026-02-26 19:21:19 +00:00
Jon Ross-Perkins 34651f429f Clean up some of the TODOs in unused.carbon (#6794)
Fixes ordering (using DIAGNOSTIC_ON_SCOPE). Removes an obsolete TODO to
add an error that's adjacent to the indicated error.

Also moves the file to patterns: it was the only file in `dataflow`, and
patterns also contains the related underscore binding tests.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-26 18:57:15 +00:00
Richard Smith 980ab7fab3 Fix handling of compatible conversions in initialization. (#6797)
Stop using "performed builtin conversion" as a proxy for whether we
created an initializing expression with a correctly-set storage
argument. That isn't correct in the case where the builtin conversion
creates a new initializing expression without setting its storage, such
as by creating an `AsCompatible` wrapper around an existing initializing
expression.

Instead look at whether the storage argument is a `TemporaryStorage`,
and only overwrite in that case, otherwise assuming that the storage
argument has been set correctly.

This fixes a miscompile that was already visible in our lowering tests!
2026-02-26 18:25:06 +00:00
Jon Ross-PerkinsandChandler Carruth 17897bb05d Add transient error retries to bazel integration tests (#6796)
e.g. for failures like
https://github.com/carbon-language/carbon-lang/actions/runs/22418738440/job/64911093548

We work around this similarly in run_bazel.py already; this is mirroring
over some of the logic (sharing would require work on Python's set up).

Assisted-by: Google Antigravity with Gemini 3 Flash

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-02-26 17:36:51 +00:00
Ivana Ivanovska d9570b4d37 Carbon/C++ Interop: Importing C/C++ object-like macros (#6676)
A proposal for importing C/C++ object-like macros into Carbon.

Based on the design doc: [Carbon: C++ interop for C/C++ object-like
macros](https://docs.google.com/document/d/1CCB05gi3uHfDAXUy6DvOHxsn0spXcSrL_2Ye9QOSwrs/edit?tab=t.0).

Part of https://github.com/carbon-language/carbon-lang/issues/6303
2026-02-26 01:07:58 +00:00
Jon Ross-Perkins 3163af2563 Prevent CARBON_DIAGNOSTIC_ON_SCOPE from use with notes (#6795)
Just a small validation, to avoid irrelevant uses.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-25 23:42:32 +00:00
Jon Ross-Perkins 3df256cfa9 Rewrite the FormatterChunks API (#6784)
This is a refactoring change with no output changes.

The chunk logic already separates the concepts of "nodes with children"
and "nodes with content" in practice, but it's not obvious in the API.
This rewrites the logic to make the separation clearer.

This also subtly takes advantage of the API to avoid creating lots of
empty chunks... Right now, there's always an empty chunk between two
tentative chunks. With this change, it lazily creates a chunk only when
`out()` is used (which it often isn't), which should substantially
reduce the number of chunks created.
2026-02-25 23:18:09 +00:00
Richard Smith c5931a036d Add subdirectories for some of the check class tests (#6790)
We had around a hundred files in check/testdata/class. Move some of them
to subdirectories to make them a bit more manageable. This still leaves
nearly 50 unorganized test files, but it's at least an improvement.
2026-02-25 22:05:02 +00:00
Jon Ross-PerkinsandDana Jansens c6bc033af8 Add a SemIR scope for generated entities (#6792)
This currently doesn't include much, but we expect to be generating more
entities, such as `Destroy`, which I'm aiming to get more clearly
categorized here instead of `imports`.

Assisted-by: Google Antigravity with Gemini 3 Flash

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-02-25 22:00:59 +00:00
Dana Jansens af368dbadd Add a test that shouldnt diagnose identify during deduce (#6782) 2026-02-25 21:04:08 +00:00
Nicholas Bishop 157de6e370 Support dependent non-type template parameters (#6791)
https://github.com/carbon-language/carbon-lang/issues/6717
2026-02-25 20:50:04 +00:00
Dana Jansens 142596b49c Diagnose unidentified type-of-self in impl lookup query (#6769)
The type of the query self is looked into for a witness, but that type
may be unable to be identified. For example when the query is against
`Self` inside the declaration of a named constraint. Before this PR, we
would crash when identification failed. Now we produce a diagnostic.

This makes `RequireIdentifiedFacetType` take a `ContextScope` callback
(like it used to with an `AnnotationScope` callback) since all callers
now expect to handle diagnostics, and can provide useful context.

This is a followup to #6761.
2026-02-25 20:23:21 +00:00
Dana Jansens fbc8d59d32 Introduce Diagnostics::ContextScope and remove diagnoser callbacks in type completion (#6761)
Introduces `Context` and `SoftContext` messages, which can be introduced
through a `ContextBuilder`:
- The `Context` messages come before the diagnostic in the output.
- The first `Context` message steals the diagnostic level from the main
diagnostic, and turns the main diagnostic into a Note attached to the
context.
- A `SoftContext` message works similarly, but if it's preceeded by a
`Context` or `SoftContext` message, then it is dropped. This can be used
as a default/backup scope when nothing more interesting is provided up
the stack, such as in `TryEvalBlockForSpecific`.

The `ContextBuilder` is provided to a callback through
`Diagnostics::ContextScope`, an RAII type `AnnotationScope` but for
context messages.

This allows a high level operation to provide a context message like
"failed to identify facet type {0}" which will then be used as the error
if a diagnostic is produced during identification, with the latter
diagnostic attached as a note to explain why the contextual operation
failed.

In particular, this allows monomorphization errors (such as an array
bound being negative) to be attached to a higher lever operation instead
of being top-level diagnostics themselves, with the monomorphization
site being a note. This inverts the source code locations that appear in
the diagnostic, so that the top-level diagnostic points to the "user
code" which causes the monomorphization.

This is presented as an alternative strategy to #6753, which plumbed
diagnoser callbacks around to achieve the same goals.

We replace the diagnoser callbacks in type completion and operators with
ContextScope callbacks instead, which now provide better diagnostics for
monomorphization errors. Other callers to MakeSpecific do not yet have
ContextScopes introduced in order to turn monomorphization errors into
more interesting diagnostics.
2026-02-25 15:15:29 +00:00
Jon Ross-Perkins e2bdbe8507 Make semir scope labels only print when non-empty (#6780)
This shifts logic a little so that empty top-level scopes are printed
less often. This affects imports mainly for now, but should be expected
to affect the soon-to-be-added generated scope more significantly.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-25 00:28:59 +00:00
dependabot[bot] c46cd65bd0 Bump minimatch from 3.1.2 to 3.1.3 in /utils/vscode in the npm_and_yarn group across 1 directory (#6788)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [minimatch](https://github.com/isaacs/minimatch).

Updates `minimatch` from 3.1.2 to 3.1.3
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/isaacs/minimatch/commit/00c323b188b704e5d4bc534ecec2268cfa70a32a"><code>00c323b</code></a>
3.1.3</li>
<li><a
href="https://github.com/isaacs/minimatch/commit/30486b2048929264f44d18822891cfffa02af78b"><code>30486b2</code></a>
update CI matrix and actions</li>
<li><a
href="https://github.com/isaacs/minimatch/commit/9c31b2d4e0af72a6c2d2d62c5dbc2247da669802"><code>9c31b2d</code></a>
update test expectations for coalesced consecutive stars</li>
<li><a
href="https://github.com/isaacs/minimatch/commit/46fe687857cf02f6cf45469cc593b97e11b10c96"><code>46fe687</code></a>
coalesce consecutive non-globstar * characters</li>
<li><a
href="https://github.com/isaacs/minimatch/commit/5a9ccbda64befc5d94b965534dbea2853c92aebd"><code>5a9ccbd</code></a>
[meta] update publishConfig.tag to legacy-v3</li>
<li>See full diff in <a
href="https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.3">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=minimatch&package-manager=npm_and_yarn&previous-version=3.1.2&new-version=3.1.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-24 23:44:29 +00:00
Nicholas Bishop f210f4ab04 Add initial support for importing C++ constexprs as Carbon constants (#6770)
This allows a C++ constexpr to be used as an argument to a non-type
template parameter.

https://github.com/carbon-language/carbon-lang/issues/6717
2026-02-24 20:59:24 +00:00
Jon Ross-Perkins 1a3f762dba Factor out FormatterChunks logic (#6779)
I'm looking at making `constants { ... }` etc omitted when empty,
because in turn I'm looking at adding a third section, and seeing more
boilerplate empty sections just seems awkward to me. This PR starts down
the path by factoring out the chunk logic, which I may want to refactor
further.

This changes the `size_t` chunk id into a wrapped type for type safety.

This PR is just a refactoring, and doesn't make any behavior changes.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-24 19:07:31 +00:00
little KitchenandRichard Smith 8edd5eb9a1 fix: reject {} initialization for non-aggregate C++ classes (#6675)
## Summary

Fixes the toolchain incorrectly allowing `{}` initialization for
non-aggregate C++ classes.

## Problem

When importing an empty C++ class, the toolchain was treating it as a
Carbon empty struct, which allowed initialization from `{}`. This is
incorrect for non-aggregate classes (e.g., those with user-declared
constructors).

```carbon
import Cpp inline '''
struct X { X(); };  // non-aggregate (has user-declared constructor)
''';

fn Make() {
  var x: Cpp.X = {};  // incorrectly accepted, should be rejected
}
```

## Solution

Added a check for `clang_def->isAggregate()` in `ImportClassObjectRepr`
so that only aggregate classes get the empty struct representation.

**Before:**
```cpp
if (clang_def->isEmpty() && !clang_def->getNumBases()) {
```

**After:**
```cpp
if (clang_def->isEmpty() && !clang_def->getNumBases() &&
    clang_def->isAggregate()) {
```

## Testing

Added test file
`toolchain/check/testdata/interop/cpp/class/non_aggregate_init.carbon`
with:
- Non-aggregate class (`struct X { X(); }`) - should reject `{}`
initialization
- Aggregate class (`struct Y {}`) - should accept `{}` initialization

Note: I couldn't run tests locally due to clang version requirements
(needs >= 19, have 17). The CI should validate the changes.

Closes #6669

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-02-24 18:19:50 +00:00
Jon Ross-Perkins 9915e155a3 Replace clang version with regex (#6778)
Also replace some `.*`'s that seem like they should stay non-empty with
`.+`.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-24 00:38:27 +00:00
Geoff Romer 4a0cf6c1fb Track the start of a signature more accurately (#6760)
This change ensures that a function signature always starts with an
`IdentifierNameMaybeBeforeSignature` node (renamed from
`IdentifierNameBeforeParams`), even in the case of function declarations
like `fn F -> T` that have no parameter list. As a consequence, this
ensures that we push new entries onto `pattern_block_stack` and
`full_pattern_stack` when we start processing the function signature.
2026-02-23 22:46:03 +00:00
Chandler Carruth 375a736c42 Update LLVM to a more recent commit (#6771)
This includes the major version bump and some changes to output in
various tests.
2026-02-23 20:30:55 +00:00
Nicholas Bishop 393e6e4f9a Fix typos in eval_inst.h (#6775) 2026-02-23 16:48:23 +00:00
Roopesh SandRichard Smith 41f47c0e87 Fix crash on generic call to local function (#6671) (#6679)
## Summary
- Avoid crash in `MangleInverseQualifiedNameScope` by skipping missing
name scopes (local functions have no parent scope).
- Add regression test:
toolchain/lower/testdata/function/generic/local_function.carbon.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-02-20 22:16:18 +00:00
Chandler CarruthandRichard Smith c3eb393c6a Split build information for CRT into Starlark (#6765)
This isn't as interesting as others, as it only involves compile
options.

It also adds a missing flag of `-fno-lto` as these objects can't be
LTO-ed.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-02-20 10:35:53 +00:00
fdb188ccfd Implement unused pattern bindings, continued (#6518)
Implementation of unused pattern bindings #2022, continued.

Whereas previous PR #6460 took care of parsing, and PR #6479 prepared
the stage by using _ in some test cases, this PR has the the actual
implementation, using a simple dataflow analysis.

---------

Co-authored-by: Burak Emir <bqe@google.com>
Co-authored-by: jonmeow <jperkins@google.com>
2026-02-19 23:33:36 +00:00
Richard Smith bea24a8bee Never ask the mangler to mangle a C++ declaration. (#6764)
This cleans up some logic that was left behind when we stopped emitting
C++ function declarations ourselves. We would ask our mangler for a
mangling for a C++ function declaration and then not use it.
2026-02-19 21:56:28 +00:00
Dana Jansens e991657e1d Use the canonical instructions to get SpecificIds in GetCallee (#6726)
GetCallee returns a structure with SpecificIds in it, and then those
specifics are used to later get constant values. This is fine when those
specifics are canonical, but it's problematic when they are not, because
non-canonical specifics (from a generic eval block) do not ever have any
resolved decl/defn blocks.

Formatting in particular works with non-canonical instructions when it
formats a generic eval block. We want to be able to format the block,
but those specifics are not useful for constant value mapping/lookup.
GetCallee grabs (non-canonical) instruction ids out of other
instructions. When getting a SpecificId out of an instruction, it should
map that instruction to the canonical value first. This means the
specific will be resolved and can be used for constant value mapping
later.

Fixes #6677
2026-02-19 20:36:35 +00:00
Geoff Romer 6a3529f4b5 Add Core.Form to prelude (#6745)
Unfortunately, currently it has to be a function rather than a constant.
2026-02-19 19:26:56 +00:00
Chandler CarruthandJon Ross-Perkins e00394ea92 Teach the link subcommand to accept Clang-style LDFLAGS (#6741)
Add an optional additional set of positional parameters that can be
passed to the `link` subcommand for Clang-style (or GCC-style)
`LDFLAGS`. These can _also_ contain object files, etc., and in fact it
is useful to allow them to contain object files in order to integrate
the `carbon link` subcommand into a build system that mixes both link
flags and object files. This at least happens with Bazel, and I suspect
is common.

Eventually, it would be nice to have sufficient semantics to handle all
the varieties of links we want without resorting to this escape hatch,
but that's likely a long way away and so it seems especially useful to
allow falling back to Clang's flags as needed for now.

This does somewhat directly surface the Clang implementation detail in
the command line syntax, but I don't see a lot of good alternatives.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-02-19 17:00:40 +00:00
Dana Jansens 46fb941b3c Don't create ErrorInst in Convert without producing a diagnostic (#6762)
While convert has the option to avoid diagnostics, when that flag is
false, ErrorInst results must also produce a diagnostic. Otherwise we
end up with errors in the semir but not error provided to the user.

The new diagnostics reveal that a number of tests for abstract types
were passing incorrectly. They had errors in the semir but no
diagnostics. A TODO is added in convert to allow an abstract conversion
target type when not initializing.
2026-02-19 16:36:57 +00:00
Dana Jansens 917a6ea971 Add an interface-with-self generic to each interface and same for constraints (#6667)
Currently each interface has a `Self` facet internally that becomes a
binding to every entity inside the interface: associated constants,
functions, and require decls. Each of these has to be independently
generic as a result. This makes is challenging in extended name lookup
to move into an extended scope of an interface, as we have a specific
for the interface, but the names within require a different specific
that includes a `Self` facet value.

We generalize this relationship by adding a second generic to Interface,
called `generic_with_self`. When we want to work with entities inside
the interface, we move from the interface-without-specific to the
interface-with-self specific by adding a Self to the specific. This is
done independently of any particular entity inside the Interface, as
those entities are now all members of the interface-with-self generic.

Associated constants no longer need a generic of their own, as they do
not have separate generic bindings. Functions retain a generic, but if
the function has no generic arguments, it will have no bindings of its
own now.

Require decls retain a generic so that their specific can be
instantiated separately from the interface. Requiring the interface to
be complete does not require the types in a require decl to be complete
unless it is modified by `extend`. So we allow them to be completed
later by keeping them in a separate generic.

Named constraints look like interfaces and gain the additional inner
generic-with-self, with the same relationship to require decls.

This removes the need for name lookup to perform Substitution of a Self
facet into the extended scope instruction. Instead, the
`SpecificConstant` instruction inserted by a `require` decl is part of
the interface-with-self generic. When looking through a FacetType for
extended scopes, for each interface, we push the scope with the specific
for the interface-with-self. Then the constant value of the
`SpecificConstant` is correctly modified by the provided self
automatically through applying that specific.
2026-02-19 16:24:07 +00:00
Chandler Carruth e5b094fdad Start moving runtimes building logic into Starlark (#6701)
The goal here is to be able to construct a build of the runtimes
directly in Bazel, or by emitting `BUILD` files, or by emitting into C++
code and using that on-demand. For that, we want a single source of
truth, and that source in Starlark.

This should also make the information more generally useful, and so I'm
moving as much as I can into the LLVM Bazel build. Apologies as that
makes the diffs extra annoying.

I do plan on upstreaming the Bazel parts of this, but would like to get
everything working in Carbon and stabilized first.

While here, I've also made a change suggested for the future in the
initial review by lifting the C++ template out of a string literal in
the `.bzl` file, and into an actual separate C++ file.

This only moves libc++, libc++abi, and libunwind. I want to get those
three working end-to-end before I work on the builtins or `crtbegin` and
`crtend`, as those have a bunch of additional complexity.

This also only uses the info in the C++ on-demand build. It seemed like
a reasonable increment to start code review, and my plan is to work on
other build strategies in a follow-up PR. If that doesn't work, let me
know and I'll come back once I have at least a second use of the info
here.
2026-02-19 07:47:56 +00:00
Prabhat Sachdeva a5a4c756a7 Only treat top-level Run in Main as the entry point (#6757)
Fix IsEntryPoint to only recognize `Run` as the program entry point when
it is declared at package scope in the `Main` package, not when it
appears inside a namespace or via C++ interop.

Closes #6755
2026-02-18 22:17:15 +00:00
Chandler Carruth 82e4c3a8af Add response file expansion to the busybox and improve -Xcarbon (#6750)
When the response file contains the subcommand itself, or when there are
`-Xcarbon` flags within the response file that we need to re-organize,
we need to hoist the expansion into the busybox itself.

I've left the response file expansion in the `ClangRunner` so that
library users can still use them, including in the VFS of the runner.

It's also useful to handle `-Xcarbon`-style flags even when using
subcommands rather than a symlink to the busybox: build systems often
have a facility to append flags, but appending doesn't let us inject
flags easily into the `carbon` driver itself. So this PR moves the
`-Xcarbon` reorganization to happen in all cases, and to insert them
before the first subcommand or positional parameter. When teaching Bazel
to link by running `carbon link ...` commands, this lets us do things
like `bazel build --linkopt=-Xcarbon=-v` to enable verbose logging.

I've not added a test here as we don't really have much testing of the
busybox. I can move the current symlinks test to be more of an
integration test of the busybox logic if desired, but would be a
somewhat larger change and maybe worth separating out. This will end up
tested in the Bazel example in a subsequent PR that starts using it in
the installed crosstool configuration.
2026-02-18 13:39:23 +00:00
Richard Smith 108277c3f3 Support if expressions in eval fn. (#6725)
Add support for `BranchWithArg` and `BlockArg` during compile-time
function execution. We only track the most recent block arg value for
now, because that's all we need -- we never look at a block argument for
any block other than the current one.

Also refactor `FunctionExecContext` to better encapsulate the blocks
list.
2026-02-18 13:32:45 +00:00
Richard Smith 768582d8d3 Propagate some target options from Clang to Carbon's target. (#6759)
Turn a few section options on by default in Clang's options, and
propagate the setting from Clang to Carbon. These settings can't be
different between the two sides of the compilation, so merging the
behavior of Carbon's defaults and Clang's flags seems best.
2026-02-18 03:14:31 +00:00
Jon Ross-Perkins de3147ce3e Note issue on C++ fingerprint TODO (#6758)
Link: #6728
2026-02-18 00:14:14 +00:00
Richard Smith 2cee87683e Allow more signatures for Main.Run. (#6751)
Allow an argc parameter and an argv parameter to be passed. For now we
check that argc is an i32 and argv is a pointer. The rules here are not
yet decided -- see #6735 -- but we should at least allow C-style access
to argv for now in order to unblock experimentation.
2026-02-18 00:06:04 +00:00
Nicholas Bishop 6df9d5ba32 Add initial support for non-type template parameters (#6740)
This adds basic support for using templates with integer parameters.

https://github.com/carbon-language/carbon-lang/issues/6717
2026-02-17 21:34:06 +00:00
Geoff Romer 8a8dd01302 Correct stray instance of "value binding" to new terminology. (#6754) 2026-02-17 20:48:08 +00:00
Geoff Romer f21e0e17ac Introduce ExprCategory::Dependent (#6744)
This is needed to model things like the category of `x` in the body of
`fn Foo(F:! Core.Form, x:? F)`, where the category of `x` is determined
by the concrete value of `F` (see #5389 for the design of `:?`
bindings).

This will be used in a follow-up PR.
2026-02-17 20:28:15 +00:00
Geoff Romer f1b6e818d1 Rename FormExpr fields for clarity/consistency. (#6746) 2026-02-17 17:10:35 +00:00
Richard Smith 1aa1a2a373 Fix crash when referring to a C++ variable whose type's scope has not been imported. (#6743) 2026-02-16 22:47:01 +00:00
dependabot[bot] 0300d35cf6 Bump qs from 6.14.1 to 6.14.2 in /utils/vscode in the npm_and_yarn group across 1 directory (#6749)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [qs](https://github.com/ljharb/qs).

Updates `qs` from 6.14.1 to 6.14.2
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.14.2</strong></h2>
<ul>
<li>[Fix] <code>parse</code>: mark overflow objects for indexed notation
exceeding <code>arrayLimit</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/546">#546</a>)</li>
<li>[Fix] <code>arrayLimit</code> means max count, not max index, in
<code>combine</code>/<code>merge</code>/<code>parseArrayValue</code></li>
<li>[Fix] <code>parse</code>: throw on <code>arrayLimit</code> exceeded
with indexed notation when <code>throwOnLimitExceeded</code> is true (<a
href="https://redirect.github.com/ljharb/qs/issues/529">#529</a>)</li>
<li>[Fix] <code>parse</code>: enforce <code>arrayLimit</code> on
<code>comma</code>-parsed values</li>
<li>[Fix] <code>parse</code>: fix error message to reflect arrayLimit as
max index; remove extraneous comments (<a
href="https://redirect.github.com/ljharb/qs/issues/545">#545</a>)</li>
<li>[Robustness] avoid <code>.push</code>, use <code>void</code></li>
<li>[readme] document that <code>addQueryPrefix</code> does not add
<code>?</code> to empty output (<a
href="https://redirect.github.com/ljharb/qs/issues/418">#418</a>)</li>
<li>[readme] clarify <code>parseArrays</code> and
<code>arrayLimit</code> documentation (<a
href="https://redirect.github.com/ljharb/qs/issues/543">#543</a>)</li>
<li>[readme] replace runkit CI badge with shields.io check-runs
badge</li>
<li>[meta] fix changelog typo (<code>arrayLength</code> →
<code>arrayLimit</code>)</li>
<li>[actions] fix rebase workflow permissions</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ljharb/qs/commit/bdcf0c7f82387c18ac8fabfccd2f440645cef47b"><code>bdcf0c7</code></a>
v6.14.2</li>
<li><a
href="https://github.com/ljharb/qs/commit/294db90c812ddbe7d7a35d5687c505fd21a2d6a2"><code>294db90</code></a>
[readme] document that <code>addQueryPrefix</code> does not add
<code>?</code> to empty output</li>
<li><a
href="https://github.com/ljharb/qs/commit/5c308e5516c270a78caa6f278465914090f91ec6"><code>5c308e5</code></a>
[readme] clarify <code>parseArrays</code> and <code>arrayLimit</code>
documentation</li>
<li><a
href="https://github.com/ljharb/qs/commit/6addf8cf738d529c54d91f6f3ffb6c1be91bbfdc"><code>6addf8c</code></a>
[Fix] <code>parse</code>: mark overflow objects for indexed notation
exceeding <code>arrayLimit</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/cfc108f662326d6ab540f3545ef0b832baf83cdf"><code>cfc108f</code></a>
[Fix] <code>arrayLimit</code> means max count, not max index, in
<code>combine</code>/<code>merge</code>/`pars...</li>
<li><a
href="https://github.com/ljharb/qs/commit/febb64442a80e49200211fa38d3c96b58024ac77"><code>febb644</code></a>
[Fix] <code>parse</code>: throw on <code>arrayLimit</code> exceeded with
indexed notation when `thr...</li>
<li><a
href="https://github.com/ljharb/qs/commit/f6a7abff1f13d644db9b05fe4f2c98ada6bf8482"><code>f6a7abf</code></a>
[Fix] <code>parse</code>: enforce <code>arrayLimit</code> on
<code>comma</code>-parsed values</li>
<li><a
href="https://github.com/ljharb/qs/commit/fbc5206c25b4d1851cea683f02c10756c521d15a"><code>fbc5206</code></a>
[Fix] <code>parse</code>: fix error message to reflect arrayLimit as max
index; remove e...</li>
<li><a
href="https://github.com/ljharb/qs/commit/1b9a8b4e78c6aff4c22fa559107227f02fd0216a"><code>1b9a8b4</code></a>
[actions] fix rebase workflow permissions</li>
<li><a
href="https://github.com/ljharb/qs/commit/2a35775614e0fb46ac8a3060201a32a7c23a7fda"><code>2a35775</code></a>
[meta] fix changelog typo (<code>arrayLength</code> →
<code>arrayLimit</code>)</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.14.1...v6.14.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=qs&package-manager=npm_and_yarn&previous-version=6.14.1&new-version=6.14.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-16 22:45:34 +00:00
Richard Smith 773837e1bb Ask Clang to emit C++ global variables. (#6748)
Don't emit them ourselves. This was leading to our emitted variable
being renamed away from the proper symbol name, leading to link errors.

Fixes #6742.
2026-02-14 03:07:48 +00:00
Geoff RomerandChandler Carruth f289592dfa Clarify and partially enforce inst-order precondition on splicing (#6722)
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-02-14 01:40:51 +00:00
Jon Ross-Perkins 64e3fab43a Skip C++ types when generating Destroy witnesses (#6732)
This TODO had been written before C++ types were generating destroy
implementations, which is resolved now.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-14 00:43:11 +00:00
Geoff Romer b3d57aff7a Diagnose if a NodeIdOneOf argument isn't a typed node. (#6738) 2026-02-13 22:44:23 +00:00
Geoff Romer 3c324e4877 Add category to parameter format, and share some code. (#6730) 2026-02-13 22:20:05 +00:00
611aba3cc2 Clang IRGen in Carbon (#6641)
Clang performs the equivalent of Carbon's `lower` progressively,
interleaved with parsing/semantic analysis. This is in conflict with
Carbon's phase-based approach and leads to bugs in missing functionality
in Clang's generated IR during Carbon/C++ interop.

I surveyed other uses of Clang's APIs (originally written up in
[this](https://docs.google.com/document/d/1wi85FRiWh4X9A-gCYMVGKR40-q5fM6-3JaSpePk-XCY/edit?tab=t.0#heading=h.j7j8nwhzao5n)
doc - though the contents in this proposal are now more complete than
the doc) to better understand how Clang's constraints might effect
projects and how they've addressed them. In the mean time, Carbon
changes made more stable approaches viable that were eventually
implemented in #6569.

This proposal then aims to formalize the analysis that lead to #6569 for
posterity in case these design decisions need to be revisited in the
future.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-02-13 21:48:10 +00:00
Geoff Romer 1c885a629e Format FormType as "Core.Form" (#6734) 2026-02-13 19:44:21 +00:00
Dana Jansens 9a90f19c60 Add two tests for how a non-self require decl in an interface connects (#6737)
A non-self require decl in an interface does not mean that a type
implementing that interface also implements the required interface. But
it does mean that whatever the self-type is will implement the required
interface.
2026-02-13 18:47:48 +00:00
Jon Ross-Perkins 74969cab04 Generate non-final Destroy witnesses for symbolics (#6731)
This is related to #6727, but is generally a necessary fix even without
that issue. I'm not adding a specific test of #6727 because it should
also be covered by the tests in #6726.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-13 17:46:50 +00:00
ÖzgürandDana Jansens 2184663511 Improve vscode syntax highlighting (#6543)
This PR improves the vscode syntax highlighting.

- Added `comment` keys.
- Added highlighting of invalid numbers such as `0x`, `0b`, `0xa`, etc.
- Restricted highlighting of numeric type literals to common types to
avoid highlighting identifiers such as `i1`.
- Changed the highlighting of named operators (e.g., `as`).
- Added `char` and `str` to type literals.
- Added `const` to modifier keywords.
- Removed `addr` keyword.
- Refactored some rules to use `begin`/`end` to handle line breaks.
- Added highlighting to `choice` values as `enum` values.
- Updated the rules for matching `types`.
- Added highlighting to rhs of `adapt`, `alias`, `choice`, `constraint`,
`impl`, `interface`, `as`, and `impls`.
    - Added highlighting to rhs of bindings.
    - Added highlighting to function return types.
- Updated the rules for matching `functions`.
- Updated the rules for matching `variables`.
- Added highlighting unidentified words as `variable`. 
- Added examples and before/after screenshots.

| Before | After |
| :---: | :---: |
| <img width="424" alt="before"
src="https://github.com/user-attachments/assets/e84d0ff9-237b-40c2-845b-ec550b8f7bea">
| <img width="431" alt="now"
src="https://github.com/user-attachments/assets/2c18640b-318a-4cd5-952c-bad61d3fdbca">
|

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-02-13 16:50:18 +00:00
Chandler CarruthandJon Ross-Perkins b267ec85cf Reduce ../ traversal in busybox logic (#6721)
This removes support for strange symlink structures _within_ an
install-shaped tree, but AFAIK, that is not one of the (frustratingly
many) cases where we need them. Avoiding this significantly shortens and
reduces repetition in the commandline formed by the busybox, and also
appears to work better when running the busybox from inside a Bazel
checkout.

The motivation here is to fix issues that arose when more heavily using
the installed toolchain with the example Bazel project. As more of that
functionality lands, this should also be tested there.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-02-13 09:29:19 +00:00
Geoff Romer 7f29436d4e Restore the name of GetCompileTimeBindValue. (#6733)
It had been renamed to GetCompileTimeAcquireValue in #6281 due to an
overzealous find/replace.
2026-02-13 00:54:23 +00:00
Jon Ross-PerkinsandChandler Carruth d39fdfcfad char redesign (#6710)
- Add a `char` type literal mapping to `Core.Char` and equivalent to
C++'s
    `char`.
    -   8 bits, unsigned, treated as a single UTF-8
[code unit](https://en.wikipedia.org/wiki/Character_encoding#Code_unit).
-   Add a `Core.CharLiteral` type for character literals, similar to
    `Core.IntLiteral`.
- Allow operations for `char` and `Core.CharLiteral` which reinforce the
    "character" concept, versus an integer value.
-   Revokes and replaces
[#1964: Character
Literals](https://github.com/carbon-language/carbon-lang/pull/1964).

Assisted-by: Google Antigravity with Gemini 3 Flash

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-02-12 16:56:09 +00:00
Geoff Romer 3719d200d6 Drop redundant parameter from ConsumeAndAddCloseSymbol (#6724) 2026-02-12 01:56:15 +00:00
Jon Ross-Perkins 320096da67 Rename import functions as Import instead of Make/Add (#6723)
This was motivated by `MakeFunctionDecl`, which has been added to
function.h as a helper function for making function declarations (an
unintentional naming collision).

I was wondering about renaming these functions to mark them as more
clearly import-specific, reducing the chance of name collisions like
this. Note the `Add` functions renamed here are typically updating an
imported declaration with a definition -- not sure whether `Make...Decl`
+ `Add...Definition` vs `Import...Decl` + `Import...Definition` is
actually losing anything though, since both seem to still require an
understanding of the two-stage import process.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-11 20:32:12 +00:00
Jon Ross-PerkinsandGeoff Romer e2f451dc9c Update adding features (#6719)
Trying to update obsolete mentions in the "adding features" info (this
is just a skim, I may have mistakes and/or missed items).

Assisted-by: Google Antigravity with Gemini 3 Flash

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-02-11 19:43:12 +00:00
Chandler Carruth 8b967943d3 Move the build-runtimes option up to the top-level driver (#6720)
Multiple subcommands all need the ability to disable on-demand runtime
building, and this may be needed outside of using _prebuilt_ runtimes.
For example, with Bazel the plan is to not build runtimes at all and
have Bazel provide them as native Bazel libraries.

Updates the `link` subcommand to respect this flag when running Clang to
perform links.

We didn't have any real testing of the `link` subcommand, in part
because it was difficult -- it would try to link runtime libraries. Now
that we can prevent building them on demand, we can use that to test the
link command. That in turn helped uncover a couple of bugs that are
fixed here.

1) The `driver_env_` member of the `Driver` was re-used across
   `RunCommand` invocations. Some of its fields are constant across
   these, others can be updated, and still more are not necessarily
   something we would expect to be re-used. This fixes that by removing
   the `driver_env_` member, and replacing it with members for just the
   fields of `DriverEnv` that we want to set initially based on the
   construction of the `Driver` object. This causes multiple, sequential
   `RunCommand` calls to not clobber or erroneously inherit state.

2) The temporary directory support in the driver unittest didn't allow
   the driver to observe the things it wrote to the temporary directory.
   This PR updates the test logic to create an overlay VFS so that both
   the in-memory test inputs are observed, but so are the real files
   written into the temporary directory.

3) The Clang runner, when asked to run Clang without runtimes would
   still attempt to include runtimes in any link command. This isn't
   quite what we want, as the whole reason to use this without building
   runtimes is to reuse ones built in some other way and potentially in
   some other location. For now, this PR uses a hack to suppress these
   issues so that we can have a basic test, but in the future we'll need
   a better solution here.

4) The driver test didn't include the actual driver in the install data.
   The test even worked around this, but it makes it impossible to link
   reliably as the `lld` binary isn't available. This adds the data
   dependency and updates the test to the available digest, etc.
2026-02-11 19:16:38 +00:00
Jon Ross-Perkins 628b6c8a73 Inject IntAsSelect into example diagnostic (#6718)
Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-11 19:10:21 +00:00
Jon Ross-PerkinsandChandler Carruth 45b3f47349 Diagnostic sorting (#6699)
Change `SortingConsumer` from sorting by last processed token
(per-phase) to
additionally allow diagnostics to request sorting by start position
(line and
column) when the last processed token is the same.

Assisted-by: Google Antigravity with Gemini 3 Flash

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-02-11 17:14:16 +00:00
Jon Ross-Perkins 13d5fe9eed Move toolchain alternatives to proposals (#6716)
As part of using the evolution process with the toolchain, alternatives
should
be in proposals. This proposal migrates existing alternatives here.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-11 17:10:12 +00:00
Richard Smith 1b2ae912fc Add basic support for eval fn and musteval fn. (#6694)
Add support for compile-time functions. `eval fn` is analogous to C++
`constexpr`, and is evaluated at compile time when it has compile-time
arguments. `musteval fn` is analogous to C++ `consteval`, and requires
that its arguments be available at compile time and is always evaluated
at compile time. For now we require the modifier to match across
redeclarations of the function. The specific modifier syntax here is a
placeholder and not yet part of an approved design.

Limitations: Only very basic support for evaluation is provided. So far
there's no support for mutable state or `if` expressions, but otherwise
control flow and passing and returning values should work. Carbon
evaluation recursion is modeled by C++ recursion for now, so you can
overflow the toolchain stack easily. Functions that use in-place
initialization will generally not work yet, as they are modeled as
passing a non-compile-time-constant reference to a temporary to the
call.

Add missing categorization of `name_binding_decl` as `NotExpr` to match
other similar declaration instructions like `FunctionDecl`, so that we
can uniformly skip over them when they occur within function bodies.

Assisted-by: Gemini 3 Pro and Flash via Antigravity
2026-02-11 02:08:16 +00:00
2d5e5e9692 Expression form basics (#5545)
This proposal introduces the concept of a _form_, which is a
generalization of
"type" that encompasses all of the information about an expression
that's
visible to the type system, including type and expression category.
Forms can be
composed into _tuple forms_ and _struct forms_, which lets us track the
categories of individual tuple and struct literal elements.

The proposal PR also adds `ref` bindings to the pattern matching
documentation,
but that is not part of the proposal itself; it's just bringing the
documentation
up to date with proposal
[#5434](https://github.com/carbon-language/carbon-lang/pull/5434).

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-02-10 17:44:50 +00:00
Karthik Bhattar 09b9746251 Fix SIGSEGV when comparing member without self (#6707)
This fixes a crash when a member is compared without `self.`.

**Repro:**
```carbon
class Stack {
  fn Empty[self: Self]() -> bool {
    return size == 0;
  }

  var size: i32;
}
```

Prior to this change, this path crashed with a fatal in
[type_iterator.cpp](https://github.com/carbon-language/carbon-lang/blob/7938d9a8d0556498754feb12695776702984c235/toolchain/sem_ir/type_iterator.cpp)
due to an unhandled type instruction.

This was caused by `TypeIterator::ProcessTypeId` not handling
`UnboundElementType`.

**What changed:**
- Handle `UnboundElementType` in `TypeIterator::ProcessTypeId`.
- Added a regression check in
[fail_unbound_field.carbon](https://github.com/carbon-language/carbon-lang/blob/7938d9a8d0556498754feb12695776702984c235/toolchain/check/testdata/class/fail_unbound_field.carbon)
for `field == 0`.

Closes #6703
2026-02-10 00:10:33 +00:00
Nicholas Bishop f292972816 Fix unnecessary duplication in builtins tests (#6711)
This fixes up some mistakes from
https://github.com/carbon-language/carbon-lang/pull/6702. In removing
repeated casts I ended up transforming some test code such that it
duplicated existing lines.
2026-02-09 22:27:42 +00:00
Jon Ross-Perkins 2c6d9c7f66 Rename type's GetInstId to GetTypeInstId, reflecting returned type (#6708)
Discussed briefly [on
Discord](https://discord.com/channels/655572317891461132/655578254970716160/1470442830118912265),
done to reduce confusion.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-09 22:00:21 +00:00
Nicholas Bishop a465018fec Remove SemIR dump from AssertSameType int tests (#6705)
Dropping the SemIR dump significantly decreases the size of these test
files. This is a good tradeoff since the interesting signal from these
tests is provided by `AssertSameType` not causing an error.

```
...n/check/testdata/interop/cpp/builtins.llp64.carbon | 3152 ----------------------
...in/check/testdata/interop/cpp/builtins.lp64.carbon | 3328 ------------------------
2 files changed, 0 insertions(+), 6480 deletions(-)
```
2026-02-09 15:26:30 +00:00
Geoff Romer 7938d9a8d0 Lex/parse support for ->?, :?, and form literals (#6695)
See #5389 (pending) for the language design.
2026-02-07 02:41:22 +00:00
Nicholas Bishop 1382a8645a Replace convert_checked with convert in some ImplicitAs impls (#6704)
`convert_checked` is for conversions that are checked at compile time.
Since these conversions do not require a constant value they should use
`checked` instead.

(Split out from
https://github.com/carbon-language/carbon-lang/pull/6673, explanation of
convert/convert_checked derived from the [Jan 20, 2026 meeting
notes](https://docs.google.com/document/d/1YlxEOJ0r-o19o19TCJbFl4Ln1U88yn_Vj23y1Hr5vTk/edit?tab=t.tjeylv584s7j#heading=h.ih31dlc0ma58).)
2026-02-06 21:50:59 +00:00
Jon Ross-Perkins 70614da67e Add jj support to new_proposal.py (#6700)
Also scrutinizing how it runs from another directory, because that's
what I did to test these changes. Switching to the repo root is to make
it easier to just look for ".jj".

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-06 19:53:35 +00:00
Nicholas Bishop c7a7688d21 Avoid repeated casts in builtins.lp64/llp64 tests to reduce SemIR size (#6702)
This reduces the size of a couple large test files by a few hundred
lines:
```
toolchain/check/testdata/interop/cpp/builtins.llp64.carbon | 4033 +++++++++++++++++++++---------------------------
toolchain/check/testdata/interop/cpp/builtins.lp64.carbon  | 4019 ++++++++++++++++++++---------------------------
2 files changed, 3355 insertions(+), 4697 deletions(-)
```
2026-02-06 19:09:45 +00:00
Jon Ross-PerkinsandIvana Ivanovska 68182ba37b C++ interop type mapping for integer and floating-point literals (#6668)
Provides bidirectional mappings for types of integer and floating-point
literals
between Carbon and C++. For example, given a literal `123`, defines the
interop
type.

Co-authored-by: Ivana Ivanovska <iivanovska@google.com>
2026-02-06 16:10:07 +00:00
Jon Ross-Perkins 1d0bf72508 Fix pluralization mismatch on compile_time_binding/s (#6696)
Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-05 23:50:35 +00:00
Jon Ross-Perkins f0e04c89c3 Share more function logic between custom/thunk/C++ functions. (#6690)
I need to do more work on the custom witness functions. This is trying
to make it easier to see the differences between the approaches before I
resume work there (e.g. this helps flag a possible reason I was having
trouble switching definitions when it came to generics, I think those
are mishandled right now).

This changes the thunk test because it was doing
`CheckFunctionDefinitionSignature` in a different order from
`handle_function.cpp`, and I think `handle_function.cpp` is more
canonical here (changing that affects tests with defined functions).

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-05 18:44:55 +00:00
Dana Jansens 7d97389642 Add .swp vim file name to the .gitignore (#6693) 2026-02-05 16:14:40 +00:00
Geoff Romer 8efb4aa989 Resolve "DO NOT SUBMIT" comment (#6692)
Whoops.
2026-02-05 01:18:57 +00:00
Jon Ross-Perkins 45e4c71703 Add a way for diagnostics to sort on more than last_byte_offset. (#6687)
The intent is that `last_byte_offset` is still the main sorting key.
Diagnostics issued normally (e.g. in an expression) will keep sorting
the same, and come before the new diagnostic sort. Diagnostics issued at
the end of a scope (e.g. `unused`) can request sorting by their start
location, and would become interleaved through that.

Choosing "on scope" because I think that's the main way we'll use this
functionality (on scope changes); can always rename later if usage
expands.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-04 21:13:13 +00:00
Dana JansensandJon Ross-Perkins c860c178d4 Add 2025 conference talks to the README and note some upcoming ones in 2026 (#6689)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2026-02-04 20:58:28 +00:00
Dana Jansens f63d0a6266 When re-declaring, find the original decl of an associated function in an interface (#6688)
Functions in an interface definition are wrapped in an AssociatedEntity
instruction, which the logic for finding a previous declaration must
unwrap to find the FunctionDecl.

This is controlled by the NameScope::is_interface_definition() flag,
which is true for interfaces, and causes this extra wrapping to occur
when adding the function to the scope.
2026-02-04 19:22:35 +00:00
Jon Ross-Perkins 45ca3d28f5 Drop "diagnostic" from some filenames in the "diagnostics" folder (#6686)
Mainly because "sorting_diagnostic_consumer" is legacy, since
`SortingDiagnosticConsumer` became `SortingConsumer`. Also better
reflecting contents of these files.

Where I'm not renaming, I'm less positive about dropping "diagnostics"
from "file_diagnostics" and "null_diagnostics" (which contain both a
consumer and emitter, and "null.h" seems like poor naming), so not doing
that here. Also "diagnostic.h" contains `struct Diagnostic`, so is a
decent fit.

Assisted-by: Google Antigravity with Gemini 3 Flash
2026-02-04 17:24:55 +00:00
Geoff RomerandRichard Smith e5b05a1fac ExprCategory for guaranteed-in-place initializing expressions (#6623)
The primary change in this PR is to split the `Initializing` expression
category into separate `ReprInitializing` and `InPlaceInitializing`
categories, depending on whether initialization uses the types
initializing representation, or is guaranteed to be in place. It also
rationalizes and documents the SemIR-level semantics of those categories
(including where #5545's "ephemeral entire reference" category will
fit), and introduces two new inst kinds to close gaps exposed in the
process.

Some additional secondary changes:
- Consistently format the storage arguments of initializers with `to`,
regardless of whether initialization is in-place, and document the `to`
notation.
- Rename some inst kinds and functions, and restructure some of the
code, for clarity and consistency with the new documentation.
- Resolve a TODO to handle more category conversions in
`CategoryConverter`, in order to make it easier to reason about category
conversions.

See #6588 and the review history of this PR for background.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-02-04 02:27:12 +00:00
Nicholas Bishop 2980e6bcbb Fix typo in CONTRIBUTING.md (#6685) 2026-02-03 20:51:43 +00:00
Jon Ross-Perkins 917ce5bd6b Fix a duplicate diagnostic on incomplete return types. (#6684)
For example, see toolchain/check/testdata/class/fail_incomplete.carbon
for the diagnostic changes. `IncompleteTypeInFunctionReturnType` should
remain, while the redundant `IncompleteTypeInFunctionParam` is removed.

Note I'm deliberately trying to validate the return type after other
parameters, because I think that's the better user experience. This does
also incrementally change IR.
2026-02-03 17:57:51 +00:00
Justin Horvitz fb05ed2447 Avoid depending on the value of --stamp if stamp = 0 is passed (#6681)
This avoids reading the value of `--stamp` when it's not necessary,
which enables some additional google-internal build caching.
2026-02-02 23:57:15 +00:00
Richard Smith c0b24047dd Interop support for initialization via std::initializer_list. (#6672)
Add a new builtin function `cpp.std.initializer_list.make` that takes an
array and returns a `std::initializer_list`, initialized to refer to
that array. When C++ initialization wants to perform a
`std::initializer_list`-from-array construction, synthesize a
declaration of a matching builtin function and use that to perform the
initialization.

Ideally we would specify this conversion as an impl of `ImplicitAs` in
the prelude instead of hardcoding it in the interop layer, but
unfortunately that's not currently possible, for various reasons -- we
can't make the conversion form-generic, we can't deduce the array length
from the initializer, and we can't deduce against the arguments of
imported C++ class templates yet -- so for now synthesizing a builtin
function on demand is the best we can do.

Assisted-by: Gemini 3 Pro via Antigravity
2026-01-30 22:24:18 +00:00
Jon Ross-Perkins 20a5c43e95 Update bazel to 8.5.1, plus module updates. (#6664)
This is a mostly routine update, with some edits for a benchmark API
change.

I'm not updating LLVM here, since that could conflict with other ongoing
work.
2026-01-30 08:49:16 +00:00
Richard Smith 666cf7e10e Fix usage of IDs with wrong SemIR::File. (#6670)
Found by inspection; I haven't found a way to cause this to manifest,
and I'm not sure it's possible. Refactor slightly to make it harder for
this bug to recur.

Also make a CHECK a bit more informative. (Unrelated, but I was
investigating a failure of that CHECK when I found this.)
2026-01-29 22:25:40 +00:00
Dana Jansens f64d084f27 Use the IdentifiedFacetType when mangling an ImplDecl (#6665)
The code was going through the raw `constraint_id` facet type, which
could be a named constraint. To get the interface being impl'd, use the
IdentifiedFacetType.

Import was adding an IdenfiedFacetTypeId for the facet type when
importing an ImplDecl, however it was using an attached self constant.
Then later lookups using `constant_values().GetConstantId(...)` from the
`self_id` would give an unattached constant and not find the
IdentifiedFacetTypeId. So have import do what we do when making an
ImplDecl locally, and use the unattached constant for the
RequireIdentifiedFacetType call.

We add a test of mangling an `impl as` for a named constraint, which
crashes before this change.
2026-01-29 18:02:53 +00:00
Ivana Ivanovska 9f69ebf6de Add heterogeneous bitwise operators for CppCompat.Long32 (#6661)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-29 16:04:46 +00:00
Chandler Carruth 529dcfcfec Test that the built toolchain works with the example Bazel project (#6653)
I wasn't sure I'd be able to really test this code path, but then
I remembered that Bazel has a whole platform for running Bazel from
within an integration test, and it turns out to work brilliantly. It
even lets us point the child Bazel invocations to the just-built
toolchain.

This should both give us confidence that we don't accidentally hit
a Bazel incompatibility with the example project, and it should ensure
that if something about the installed toolchain would stop being
compatible with building via Bazel we'll catch it early.

The tests are integration tests and so a bit slow: 15s or so. But
`//examples/...` is already pretty expensive and no other testing
patterns are impacted.
2026-01-29 02:14:17 +00:00
Jon Ross-PerkinsandEvan Brown ee97511496 Fix IsCarbonMap invocations to avoid build failures for non-Carbon map types (not sure when this broke). (#6662)
Also, update the multiplication constant for carbon hashing for improved
probing.

Co-authored-by: Evan Brown <ezb@google.com>
2026-01-29 01:44:13 +00:00
Jon Ross-Perkins a376a2b27d Update pre-commit versions (#6666)
Most versions are through `pre-commit autoupdate --freeze`, clang-format
was manually updated to the latest at
https://github.com/ssciwr/clang-format-wheel

My read of the style changes here are that they seem fine, none of them
look like regressions (which has caused me to delay/adjust updates in
the past).
2026-01-28 22:47:18 +00:00
Ivana Ivanovska de4a2ee6c8 Add missing operators for CppCompat.LongLong64 (#6663)
Adds arithmetic and bitwise operators, compound assignments, and
increment/decrement operations for CppCompat.LongLong64.

Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-28 19:24:21 +00:00
Özgür bdcac5087d Allow incomplete types in associated constants (#6657)
Reference: #1084, [Example of declaring interfaces with cyclic
references](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/generics/details.md#example-of-declaring-interfaces-with-cyclic-references).
Part of #6411: "Associated constants shouldn't have to be complete".
2026-01-28 15:27:14 +00:00
b0ffed7c3e Make the Carbon toolchain a viable Bazel module exposing cc_toolchains (#6652)
This let's you point Bazel at an installed toolchain or download one of
our release archives. When you do, it will configure itself as a C++
Bazel toolchain. This toolchain works reasonably well, but doesn't cache
the C++ runtimes, and so linking is inefficient. The next step will be
to pivot the runtimes from the implicitly on-demand (which can't cache
when using a sandboxed build system like Bazel) to _explicit_ on-demand
runtimes directly with Bazel support.

I've included an example Bazel project that uses this and provides a
bunch of documentation and an example script that should let folks try
this out easily.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: David Blaikie <dblaikie@gmail.com>
2026-01-28 02:45:19 +00:00
Richard Smith e69c3fd978 Support list initialization of C++ classes that is performed via a constructor call. (#6660)
The general strategy here is to import the constructor with a signature
that directly matches the argument. The intent is that the imported
function will eventually be usable directly as the `ImplicitAs.Convert`
function in a generated `impl`.

For initialization from a tuple, for example `(1, 2)`, we import the
selected constructor with a signature that takes a tuple pattern:

  `fn Class.Class((a: i32, b: i32)) -> Class;`

In order to support that, this PR also adds support in general for tuple
patterns in function signatures. It turns out the implementation was
already very close to allowing this.

Assisted-by: Gemini 3 Pro via Antigravity
2026-01-27 22:04:21 +00:00
Jon Ross-Perkins 9f6e84cc02 Remove redundant ResolveSpecificDefinition (#6659)
Noted by danakj [on
Discord](https://discord.com/channels/655572317891461132/655578254970716160/1465435722205888748)
2026-01-27 18:16:10 +00:00
Ivana Ivanovska 3757a79f4c Add heterogeneous arithmetic operators for CppCompat.Long32 (#6644)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-27 17:39:36 +00:00
Chandler Carruth 04793ba525 Disable build stamping by default (#6654)
Previously, we left it on by default and only disabled it in CI.
However, as we have grown more and more examples, the cost of stamping
has steadily risen: every example has to be rebuilt because the busybox
binary and installation contain an updated stamp.

I noticed that I was almost never getting cache hits for these even when
I should and it seems like what was once true is no more for daily
development.

I've updated the default, the docs for the default, and explicitly
enabled stamping in the nightly release workflow. I left the explicit
disabling in the CI workflows as that seems harmless and a good defense
in case we want to shift the default again.

One alternative that I didn't pursue because of the complexity was to
create two distinct installation prefixes automatically, one with the
`.nostamp` suffixed binaries installed and one without that suffix. We
could then point example builds and other within-Bazel uses at the
non-stamped tree to get maximal caching. But it would create two whole
installation trees without much benefit. It seemed simpler to just
disable stamping by default for development builds.
2026-01-26 19:37:56 +00:00
Ivana Ivanovska ff38378efc Add comparisons for CppCompat.LongLong64 (#6643)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-26 11:29:40 +00:00
Richard Smith 093d5072db Add support for using C++ user-defined conversions via interop (#6646)
When performing an implicit conversion to or from a C++ class type, look
for a C++ implicit conversion, and if that conversion involves a
function call (to a constructor or conversion function), call that
function to perform the conversion.

Note that this is just a first pass at supporting implicit conversions.
There are a lot of other things that can happen in a C++ implicit
conversion, such as aggregate initialization or `std::initializer_list`
initialization that aren't handled here. In addition, we intentionally
leave all standard conversions to Carbon to perform, so that we will
reject conversions such as `i32 -> unsigned` that C++ would select but
Carbon considers to be invalid.

Also support `as` conversions. These are treated analogously, but
perform direct-initialization instead of copy-initialization, so they
also find `explicit` constructors and conversion functions.

In order to give good diagnostics, also track the original C++ source
location for imported C++ functions on the imported version of the
function.

Assisted-by: Gemini 3 Pro via Antigravity
2026-01-25 04:51:25 +00:00
Chandler Carruth 9836ba6e9c Extract the cc_toolchain feature generation to a helper function (#6651)
This is the last really generic part of the toolchain config that I can
see to factor out with a reasonably small API surface.
2026-01-24 02:53:52 +00:00
Jon Ross-Perkins f5a1579d4d Refactor LookupCopyImpl and LookupDestroyImpl to share logic. (#6649)
Assisted-by: Google Antigravity with Gemini 3 Flash
2026-01-23 23:07:15 +00:00
David Blaikie a1efc4be8f Mangle class declarations #6617 (#6648)
In some situations we need to mangle class declarations, which then are
not NameScopes (can't scope anything inside a declaration) - so make the
mangler able to cope with that situation by mangling the name of the
class directly rather than relying on generic NameScope mangling to
handle the class case.
2026-01-23 21:05:53 +00:00
Chandler Carruth 47912f7ac3 Remove unused parts of configuring a cc_toolchain (#6650)
These can be completely skipped at this point without issue.
2026-01-23 17:42:24 +00:00
Jon Ross-Perkins 7b36de761d Shift a TODO to a CHECK (#6645) 2026-01-22 21:32:50 +00:00
Chandler Carruth f772d266a4 Add the Clang sysroot to the config output (#6642) 2026-01-22 18:10:40 +00:00
f42352759f Adding support for UInt-to-char conversion (#6425)
This pull request adds support for integer-to-char conversion, allowing
the compiler to correctly handle character casting, implementing part of
the issue #5922.

```carbon
import Core library "io";

fn Run() -> i32 {
	var i : i32 = 65;
	var ch: char = (i as char); // Support implemented!
	Core.PrintChar(ch); // Print 'A'
	return 0;
}
```

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-01-21 21:48:49 +00:00
Chandler Carruth 08669493b5 Add a config subcommand for exposing build system info (#6637)
This makes it easy to wire up build systems like Bazel that need to know
the actual include paths used. It also gives us a convenient place to
export any other information that build systems or integrations need,
and to get debugging info from users.

Most of the complexity is computing the Clang header search paths, but
I couldn't see a direct way to get closer to the source-of-truth than
this, and it doesn't seem _too_ unreasonable.

Depends on #6636 - start review at commit
[643fdab1](6637/commits/643fdab1)
2026-01-21 21:28:22 +00:00
Richard Smith a2e4c31e8e Clean up after combination of #6634 and #6635. (#6640)
We can now cast directly from `T*` to `U*`; stop going via `void*`. Also
remove the conversion impl from `void*` as it's now subsumed by the
general impl.
2026-01-21 21:03:35 +00:00
Ivana Ivanovska c9dbf40f11 Add comparisons for CppCompat.Long32 (#6639)
Support for both homogeneous and heterogeneous comparisons are added for
CppCompat.Long32.

Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-21 19:11:48 +00:00
05ea0e77d9 Map structs and tuples to initializer lists in C++ overload resolution. (#6620)
When performing C++ overload resolution with an argument that is of
Carbon struct or tuple type, form a braced initializer list as the
placeholder argument. Note that this only affects overload resolution;
no new support for actually converting structs or tuples to C++ types is
added. In particular, while this does allow an empty class to be
initialized from `{}`, it does not allow a non-empty C++ class to be
initialized from a struct, as that is not yet supported in general.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2026-01-21 19:10:10 +00:00
Richard SmithandCarbon Infra Bot f3f498498f Add an example that listens on a port. (#6634)
Mostly generated by Gemini; TODO annotations added for cases where we
should support a better way of doing various parts of this.

Assisted-by: Gemini 3 Pro

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-01-21 18:54:39 +00:00
Chandler Carruth e2a9de5bad Propagate tags on prebuilt_runtimes to the filegroup (#6638)
These were already applied to the internal rule for the Clang-built
runtimes, but were then dropped from the filegroup which would often
negate their effect.
2026-01-21 18:17:30 +00:00
Jon Ross-PerkinsandRichard Smith 2dcde8a2ff CLI and separate compilation (#6333)
- Change the look-and-feel of the `carbon` compilation command set to
use
    `compile`, `link`, and `build`.
- Build library-to-file discovery for `Core`, but support it in a
general
    manner.

Drafted [in
Docs](https://docs.google.com/document/d/19UvmU0znIFDj32hMj7TvE_WkZ_zEHygQHfOiFELKiMU/edit?tab=t.0)

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-01-21 18:01:15 +00:00
Dana Jansens 7f7186c227 Extended name lookup replaces inner Self (#6632)
When doing name lookup into an extended scope of an interface or named
constraint, the containing scope has an inner `Self` facet which can
appear in the specific of the extended scope. For instance a constraint
`N` which requires an interface `Z(Self)`:

```js
constraint N {
  extend require impls Z(Self);
}
```

When doing member lookup into a facet constrained by `N`, we need to
find the specific interface `Z(...)` where the `Self` is replaced by the
self-type the member lookup is happening on in order for impl lookup to
find a witness later.

Inside that specific interface we repeat the name lookup to find an
associated entity. Then to produce a witness we perform impl lookup
against the specific interface that name lookup returned with the
self-type of the member access. So if we do member access into `A:! N`
for a member `F`, like `A.F`, we would be doing impl lookup with a query
self of `A` and looking for the interface `Z(...)` returned from name
lookup.

When impl lookup has a facet as the query self, which we do here as `A`,
it takes its type (a facet type) and identifies it to find all the
required interfaces, and it substitutes the query self into those
specific interfaces for `Self`. If the `Z(...)` we acquired from name
lookup is `Z(Self)` it will fail the lookup for `A as Z(Self)`, since in
the facet type of `A` it finds a witness for `Z(A)` instead.

Thus, we replace the inner `Self` in extended scopes, such as `N`, with
the self-type of the member access, which produces the extended scope
`Z(A)` for this example. This allows the impl lookup for `A as Z(A)` to
find a witness from the facet type of `A`.

In order to do this, we include an instruction for the inner self when
registering the extended scope. Then, when we find the extended scope in
name lookup, we can use its CompileTimeBindIndex to replace any instance
of that `Self` facet with a new facet. If the self-type of member access
is a type, we construct a FacetValue with an empty facet type that
refers to the type.
2026-01-21 17:48:18 +00:00
Chandler Carruth b2ab53e49c Fix an incompatiblitiy between our YAML and ErrorOr test helpers (#6636)
The YAML test helpers didn't use the `Printable` abstraction in one
place and instead directly used `<<` with a `std::ostream`. This matches
the `require`s expression in the `error_test_helpers.h` printing logic
for `ErrorOr`, but fails to provide the necessary implementation for
`llvm::formatv` to succeed with the `Yaml::Value` type.

The main fix is to use `Printable` and to define the `Print` method in
terms of `llvm::raw_ostream`. We already have all the mapping hooks in
place to also support `std::ostream` when needed based on that
definition.

This also adds some constraints to the printing in
`error_test_helpers.h` so it is a bit less under-constrained and more
understandable when it is correctly being used. These are just tidying
though, they aren't what makes these headers work together.

I've added a test to try and make sure these test helpers compose as
well.
2026-01-21 17:41:46 +00:00
Dana Jansens 114d892ac1 Clarify and fix diagnostic for missing Self in a require declaration (#6616)
If `Self` is not in the self type, then it must be an argument to every
interface required by the declaration. Specifically, this means the
interfaces in the identified facet type, and does not matter if `Self`
appears in the arguments of named constraints.

Fix the diagnostic to stop saying "constraint" incorrectly. And improve
clarity by including in the diagnostic which interface it found without
`Self` as an argument, since it may be found in some other named
constraint, rather than directly in the facet type as written.
2026-01-21 16:36:02 +00:00
Richard Smith 8353965ca3 Allow conversions between all pointer types with unsafe as. (#6635)
Previously we only allowed conversions from `void*` to `U*` this way,
requiring casting via `void*` to get from `T*` to `U*`. That seems like
an unnecessary circumlocution.
2026-01-21 15:47:51 +00:00
Ivana Ivanovska a448792207 Enable heterogeneous compound assignments for CppCompat.Long32 (#6628)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-21 13:27:58 +00:00
Jon Ross-PerkinsandDana Jansens 67163096b6 Replace OwningArrayRef with SmallVector (#6633)
OwningArrayRef is being removed upstream, per
https://github.com/llvm/llvm-project/pull/169126. This replaces uses
with `SmallVector`.

I've also made a separate commit which does init changes; these aren't
strictly necessary, but I added to make it a little more idiomatic in
spots.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-01-20 23:07:30 +00:00
Dana Jansens 4bb2935770 Look through extend require in an interface or named constraint in name lookup (#6630)
Add the required facet type as an extended scope of the containing
interface/named constraint, and teach name lookup to look for extended
scopes in named constraints.

This makes name lookup work properly when the facet type does not have a
specific that involves `Self`. Support for `Self` needs further work in
another PR.

Note that when an _interface_ requires another interface, this PR lets
us find the name, but we still fail to find a witness for the interface
named through `extend require`, and this is future work. For a named
constraint, things work correctly as the identified facet type chases
through the named constraint and includes the required interface, so
impl lookup is able to provide a witness.
2026-01-20 22:26:10 +00:00
Ivana Ivanovska c0e7198995 Implement copying for ULong32, LongLong64, ULongLong64 (#6627)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-20 20:36:17 +00:00
Dana Jansens 848eddc9dd Avoid cyclic lookup of an impl inside its own definition (#6629)
An interface A requiring another interface B means that an impl of A
must verify that the self-type also impls B. The instructions created
from this can involved a lookup that the self-type impls A, which end up
finding the impl being defined. This is not problematic of itself, but
it is problematic if these lookup instructions become part of the impl's
generic definition. When we find a specific of that `impl as A` during
impl lookup of A, and we resolve the specific definition, those lookup
instructions are replayed. Doing so does another lookup for `impl as A`,
which creates an infinitely recursive loop.

To break this loop we move the lookup instructions done to verify that
the self-type impls B outside of the definition of `impl as A`. This
prevents them from being specialized. But it doesn't prevent us from
diagnosing monomorphization errors properly. They just get diagnosed at
the use of that invalid specific, instead of inside the verification of
`impl as B` in the definition of `impl as A`.
2026-01-20 19:28:46 +00:00
Dana Jansens ee77aa4b67 Member access into a facet is not a "lookup in type of base" (#6631)
This gets us a step closer toward resolving TODOs in member access
around facets, by making the lookup into a facet value a "lookup in
base" operation instead of a "lookup in type of base". However the base
given to find scopes in still remains the facet type of the facet, which
is still a TODO.

Then we can simplify the "lookup in type of base" case a bit, with a
single code path doing the name lookup step. But we keep a TODO where if
the type of base is a facet, we change the lookup target to be the facet
type of the facet instead.

This is toward having name lookup into an interface that is extending a
named constraint work correctly with a `Self` in its specific. To
perform that name lookup, we will need to tell name lookup what is the
base, so that it can replace `Self` with the base. This change gets us
in a position where we can correctly provide the base in the `T.F()`
(lookup in facet) and `t.F()` (lookup in type of facet) correctly and
straightforwardly.

We provide a marginally improved diagnostic when looking into a facet
with an incomplete facet type, which will move into
AppendLookupScopesForConstant once we are looking into the facet
directly instead of its type.
2026-01-20 18:43:16 +00:00
Ivana Ivanovska 082b420f6e Provide increment and decrement operators for CppCompat.Long32 (#6622)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-19 22:58:56 +00:00
Ivana Ivanovska ec0a8a9b52 Implement copying for CppCompat.Long32 (#6625)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-19 15:25:48 +00:00
Ivana Ivanovska c252e7d31e Implement compound assignments for CppCompat.Long32 (#6621)
Only homogeneous compound assignments are supported for now.

Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-19 11:17:18 +00:00
Geoff Romer f53f837125 Remove ReturnTypeInfo (#6619) 2026-01-18 18:20:40 +00:00
Richard Smith cc204ead96 Allow NRVO in InventClangArgs. (#6624)
Attempt to avoid an unnecessary `SmallVector` copy.
2026-01-17 04:27:59 +00:00
David Blaikie 773b7136ef Use a single llvm::Module for C++ interop and Carbon IRGen (#6595)
Some module metadata changed - because rather than linking one module
with one module metadata value (eg: PIC Level 0, or unspecified) and one
module with a different one (PIC level 2, in clang) - we use Clang's
Module as-is, no merging required, so Clang's module metadata sticks
rather than being merged with default values from Carbon.

Also tweaked the name we use for Clang's module name so it matches the
carbon file name.

Otherwise the IR changes seem to be just reorderings - C++ interop goes
first, then Carbon, rather than the other way around.
2026-01-17 00:15:53 +00:00
Chandler Carruth 83aeddb5ec Move our project-specific features to their own file (#6614)
Also tidies up how we inject the project features so that they come last
and can override anything earlier.
2026-01-16 20:47:50 +00:00
Geoff RomerandCarbon Infra Bot 95eb7b16bb Expose C++ reference returns as Carbon reference returns (#6618)
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-01-16 18:08:42 +00:00
Chandler Carruth 94d9bff541 Use OS features for Bazel controlling features (#6613)
This requires re-working our config features to be usable in
feature-level `requires` clauses in addition to `with_feature_set` by
always including all of the features, but controlling whether the
features are enabled or disabled based on the target.

This is a little more verbose in the config features, but lets us use
them more widely and is a bit more principled.
2026-01-16 09:26:12 +00:00
Chandler Carruth cd605e5ad4 Use OS config features for linking and simplify (#6612)
This lets us use a single undconditional feature for linking with flag
sets that are enabled based on the underlying OS. While here, tidy up
the feature names a bit.

The diff here may look really bad without aggressive whitespace
ignoring, but none of the contents of the two flag sets changed --
they've just be indented more and placed into a single list.
2026-01-16 09:00:54 +00:00
Chandler Carruth d17609df5f Switch CPU flags to use feature-based selection and apply to links (#6611)
Now the CPU flags feature can be unconditionally added as part of the
optimization features and another of the conditions in the main
configuration goes away.

The failure to pass these to links was probably harmless, but it's
better to include it there as well.
2026-01-16 08:14:53 +00:00
Chandler Carruth 0b35bbdad8 Replace complex sysroot handling with simplicity (#6610)
We already know whether we found a sysroot that needs to be used, just
check that rather than trying different platforms.
2026-01-16 07:18:21 +00:00
Chandler CarruthandGeoff Romer a27fe000f2 Switch sanitizer features to use OS config features (#6609)
This removes another chunk of platform-specific feature construction and
simplifies the code further.

Also removes a now-stale comment about adding more platform-specific
features.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-01-16 04:05:25 +00:00
Chandler Carruth c23230140d Fix OS config features and use them to move OS-specific flags (#6608)
This PR merges the OS-specific Clang flags into the main Clang flags
features using feature-based constraints instead of separate features
conditionally added. Similarly for libc++. This also move flags to more
correctly live in the Clang flag set vs. the libc++ flag set as some of
these flags were specific to using libc++.

To make this change, the libc++ feature needs to be computed rather than
being fixed, as we need to add search paths based on the installed
location of LLVM and Clang.

All of this only works when the OS-config flags work. The earlier PR
adding these had a bug -- _none_ of the OS features would ever be
enabled. This didn't result in a problem as the initial use was only to
_disable_ flags on the wrong OS. Now that we're enabling flags, we have
to get it right by marking all of these as `enabled`.
2026-01-16 01:13:38 +00:00
Chandler Carruth acf9a8bfd4 Move the libc++ hardening to be part of libcxx_feature (#6607)
This also switches it to only apply to C++ compiles rather than all
compiles.
2026-01-16 00:01:29 +00:00
f9fef94aae Update to AI-based tooling policy (#6477)
The goal is to clarify that tool-generated submissions are fine, but
emphasize the requirements we have on the operators of these tools. The
inspiration for the two aspects emphasized comes from the discussion
around an update to LLVM's policy in
https://github.com/llvm/llvm-project/pull/154441, and in Fedora's
policy:

https://docs.fedoraproject.org/en-US/council/policy/ai-contribution-policy/

I've not used those policies _exactly_, as I think we may want somewhat
simpler and less formal guidance, but the goal is to remain
directionally aligned.

That said, I'm not attached to the current iteration of the wording, it
still feels a bit excessively formal or wordy to me. Suggestions on
wording improvements very welcome in addition to thoughts and feedback
on the overall direction.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-01-16 00:00:08 +00:00
Geoff Romer 75713908f4 Store and reuse lowered parameter order (#6593)
This resolves a longstanding TODO in `file_context.cpp`, and prepares
lowering to support compound return forms.
2026-01-15 23:15:48 +00:00
Richard SmithandGeoff Romer de0ad6730f Fix crash if a member of std::string_view is found in a derived class. (#6604)
Members of `std::string_view` can't be accessed directly, because that
type maps into Carbon's `str` type (`Core.String`), so member access
doesn't find the C++ members. But they can be named via qualified name
lookup into a derived type. That crashed because we didn't expect the
non-Cpp type `Core.String` to be the parent of a Cpp-imported member.

Plus add some more test coverage for related cases (not involving `str`)
that already worked.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-01-15 22:36:18 +00:00
Chandler CarruthandDana Jansens 355f700b4a Add a dependency for the StringRef.h header (#6605)
Without this we have problems with builds that enable header parsing.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-01-15 17:42:54 +00:00
Ivana Ivanovska 9ee2177dd4 Add bitwise homogeneous operators for CppCompat.Long32 (#6584)
Context: https://github.com/carbon-language/carbon-lang/issues/6275.

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2026-01-15 15:07:14 +00:00
Chandler Carruth 386a8a8a0b Extract C++-specific features into their own file (#6606)
This leaves behind project-specific features such as the system header
management of our dependencies and the fancy cache management string.

No expected changes here, but yet another slightly different order of
flags.
2026-01-15 14:40:29 +00:00
Chandler Carruth 7a203efd18 Refactor handling of -std and -stdlib in toolchain (#6601)
This introduces the first pieces of a cleaner way to configure toolchain
components on target dimensions: dedicated features for those target
dimensions.

With that, we extract a `libcxx_feature` that can always be present but
disables its flags on unsupported targets.

With `-stdlib` in its own feature, move `-std=c++20` to not require
a variable but directly live in the flags.

This should enable us to extract the largest remaining feature into its
own file cleanly by removing dynamic configuration of it, along with
libcxx.

Further refactoring of target-specific logic will follow in its
footsteps.
2026-01-15 08:07:23 +00:00
Dana Jansens a27ef24cd7 Use the name of the self and facet type as the inst name for a require decl scope (#6602)
This avoids using unstable id numbers as the name for the scope
2026-01-14 23:27:56 +00:00
Geoff Romer 4329a83e4c Form-aware textual format for return parameters and arguments (#6588)
The key changes are:
- Function output parameters are now prefixed with `out`, and more
consistently formatted as named parameters.
- Function and inst output arguments are now written as part of the inst
form, rather than as one of the inst arguments.

As a drive-by fix, this also changes `Temporary::storage_id` from
`DestInstId` to `InstId`, because it doesn't represent an output
parameter of the `Temporary` inst itself.

See the review of
[#6532](https://github.com/carbon-language/carbon-lang/pull/6532) and
[this Discord
discussion](https://discord.com/channels/655572317891461132/999638000126394370/1458268977020141589)
for additional background.
2026-01-14 23:27:21 +00:00
Chandler Carruth 9861c31476 Update LLVM to a recent commit (#6599)
This brings some fixes:
- The handling of `zlib` and `zstd` are much cleaner
- Three of our patches are no longer needed

This also includes the fixes from #6562

It also moves us from `zlib` to `zlib-ng` which is a much better basis
for what we want, and likely makes our toolchain faster when generating
debug info at least.

It fixes another API change in terms of which headers provide the
`createInvocation` we use.

Lastly, it cleans up the deps test to correctly recognize the wrappers
for `zlib-ng` and `zstd`, as well as improving the documentation for why
we allow dependencies on them.
2026-01-14 21:58:48 +00:00
Geoff Romer e78af4d745 Misc. improvements to raw/debug SemIR output (#6557)
- Distinguish attached vs. unattached constants.
- Add some missing value stores to the top-level output.
- Add missing fields to various Print methods.
2026-01-14 19:35:34 +00:00
Geoff Romer 9106f9533c Use lines instead of statements for readability-function-size clang-tidy (#6594) 2026-01-14 19:32:03 +00:00
d8adcf93f5 Consolidate debugging documentation. (#6596)
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-01-14 19:00:46 +00:00
Richard SmithandCarbon Infra Bot 7f0f402f95 Add advent of code 2024 day 14 and day 15 part 1 solutions (#6597)
I've had these kicking around for a year but never got around to pushing
them. They seem to cover a few things that previous examples didn't, so
I think we may as well include them.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-01-14 18:33:23 +00:00
Dana Jansens 32aa7cb1fa Make identifying a facet type an operation on a (self+facet type) pair (#6592)
Identifying a facet type takes both a self and facet type as a pair, and
then encode the self into the IdentifiedFacetType. This makes a
constraint that requires some _other_ type implements an interface
visible in the IdentifiedFacetType. And it will help to enable facet
types with `where T impls Z` for `T` that is not `.Self` in the future.

IdentifiedFacetTypes are now stored in a CanonicalValueStore instead of
a RelationalValueStore as they key is the combination of self and
(declared) facet type together now.

When the self-type is a facet value (has type FacetType) this is most
straightforward. But when it's a type we need to construct a FacetValue
to construct a specific for a require decl, to replace the generic
binding of the symbolic `Self`, which has type FacetType. To do so, we
make a FacetValue with an empty FacetType (equivalent to TypeType). This
prevents any looking for witnesses through the FacetType, which matches
what you can get from a type directly, requiring witnesses to come from
finding an `impl` decl.

Add additional InstNamer logic for such empty facet types so they print
as `<typename>.type.facet` if possible instead of as just `facet_value`.
2026-01-14 17:34:56 +00:00
Burak Emir 80639a02f0 [parse] Implement initial parsing support for Lambda expressions (#6583)
This adds the necessary parser infrastructure to recognize and parse
lambda expressions in Carbon.

Key changes:
- Added  and  Parse Node Kinds.
- Updated  to use  to accommodate the growing number of node kinds.
- Implemented parser states and handlers for lambda syntax ( or ).
- Added  structure to .
- Added diagnostics for missing lambda bodies.
- Added a stub in  phase to defer semantic analysis using .
- Added parser tests for lambdas.
2026-01-14 16:58:15 +00:00
Chandler Carruth 83651bb9ee Remove workaround for Clang versions <= 18 (#6600)
The flag name changed and the bug was introduced in that range, but
since we require a minimum of Clang 19, we don't need version-dependent
logic.
2026-01-14 15:57:57 +00:00
Chandler CarruthandGeoff Romer 3603ec7d54 Start refactoring toolchain config into separate files (#6587)
This moves the simplest parts of the toolchain config into separate
files. These parts are either unparameterized or trivially parameterized
and so easily extracted from the main file.

I tried to minimize the interesting edits here, but wasn't _completely_
successful I'm afraid. I'll try to describe them.

First, all of the interesting content of the new files is copied and
re-indented, no interesting edits were done.

The main file sees some more significant edits in order to realize this
refactoring:

- Extract the feature array building to a helper method.
- Collapse some extraneous features as there was no where to extract
them.
- Restructure how the array itself is built to support building it using
array fragments from the various files.

The only interesting semantic change I'm aware of here is that this
somewhat changes the order of command line flags in compiles and links.
The previous order was "fine", but not especially logical. I've tried to
more logically have features that should "override" or are "more
specific" come later here. However, that results in a slightly different
ordering. None of the current features had any flags that overlap, so
this should have no behavior change other than the changed flag order.

This is only the first step, however. There remain complex features in
the main configuration that I want to move out. However, to make those
moves simple requires some significant changes to how these remaining
features work and so I wanted to break them out. I've tried to leave
TODOs that can help as breadcrumbs on the parts of this refactoring that
aren't yet complete.

The comments also are mostly what we already had. I'm happy to try and
add some, but not sure how much I can cover as there is a _lot_ of code
here that I'm just moving around. Please let me know if there are
particularly places that would benefit from comments.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-01-14 06:19:26 +00:00
Chandler Carruth 67c6312a79 Prune deps to reduce compiles by ~30% (#6598)
The `install_paths` library depends on the `llvm_tools` library, which
depends on all of LLVM in order to allow _invoking_ the LLVM tools in
addition to listing and manipulating them. The `install_paths` also
depends on the Clang version number which for some reason depends
transitively on a large fraction of LLVM. That should probably be fixed,
but we don't actually need it anyways, we can just prune our dependency.

Because the digest builder is built in the _exec_ configuration, this
was pulling in most of LLVM and Clang to build in the exec configuration
as well, adding about 4000 actions or a roughly 30% overhead to complete
rebuilds. The time impact is likely closer to 2x because many of the
slowest actions are here.

Hopefully this makes our bots take much less time when rebuilding.
2026-01-14 03:02:56 +00:00
David Blaikie f1f6005d4a Perform Clang IRGen during check (#6569)
Background:
https://docs.google.com/document/d/1wi85FRiWh4X9A-gCYMVGKR40-q5fM6-3JaSpePk-XCY/edit?usp=sharing
And specifically this work is essentially an alternative to #5543

Clang's code generation is implemented through an ASTListener
(clang::CodeGenerator) that is attached throughout Clang's
parsing/sema/code
generation phases and acts on Clang AST incrementally throughout that
process.

Prior to this patch, Carbon has only created the CodeGenerator during
Carbon's
`lower` phase, missing out on key callbacks that would be made by Clang
during
`check`. Some of these issues were addressed by #6237 and #6483 - but
there were
still remaining cases where the delayed processing lead to missing
functionality.

With #6483 much of the Clang code that made multithreaded complexity of
#5543 is
no longer present, and we have access to the point of ASTListener
registration
so we can register the CodeGenerator there and consume its resulting
llvm::Module during lower.

Examples of some of the bugs this addresses are seen in the linked doc,
and
checked in as tests in this change in
`clang_code_generator_callbacks.carbon`

An indicental bug that's also fixed, and caused all the other test case
churn,
is that the `CodeGenerator` created during `lower` wasn't getting passed
the
Clang `CodeGenOpts` and was creating its own default - so, most notably,
optimization flags were not respected. This meant that the LLVM IR from
Clang
was always -O0 style IR (optnone, no inlinehint, no TBAA, etc). With
this
change, now the Clang IRGen gets the real `CodeGenOpts` and respects
optimization/other flags specified there.

This is only meant to be a rough proof of concept - I'm totally open to
reworking this in any way (even quite substantially) if folks have ideas
about
how this should be implemented most generally/elegantly/etc.
2026-01-14 00:54:37 +00:00
Dana Jansens c64117d0e0 Make IdTag typesafe (#6574)
The IdTag knows the type of the Id its tagging and the type of the Id
being used as the tag. This prevents mixing up tagged and untagged ids,
and avoids having to work with untyped integers.

Adds an Untagged marker struct that's used as the tag type in IdTag when
no tag is desired.

The complexity of ConstantIds and TypeIds became a bit visible: TypeIds
are concrete ConstantIds. And ConstantIds have two different tagging
schemes, one for concrete and one for symbolic ids. And ConstantIds are
actually re-cast InstIds with the same index. The LoweredTypeStore needs
to work with tagged TypeIds, but the tags actually come from an InstId
store in ConstantValueStore. Now this is expressed in the type system by
getting the tags for TypeIds from the ConstantValueStore.

ValueStores without an TagId type parameter are now visibly untagged.

IdTag is now only default constructible when it does not have a tag,
which means ValueStore is only default constructible when the TagId is
untagged. This forces tagged value stores to be constructed correctly
with a tag at compile time, and untagged ones to be constructed without.

FixedSizeValueStore has overloads for dealing with tagged and untagged
Ids, since it can't default-construct ValueStore for tagged ids, and no
longer requires passing in default-constructed tags when there is no tag
in the ids.
2026-01-13 22:44:38 +00:00
Richard Smith 7bfeae0fd5 Give internal linkage to global init function. (#6591)
The mangled name of the global init function is the same for all files
in a package, so giving it external linkage results in link errors if
more than one file in a package has global initializers. We never need
to refer to it from outside the file, so give it internal linkage.

This also requires that we stop eagerly emitting a declaration of it --
if it's empty, we don't emit a definition, and LLVM doesn't allow us to
emit an undefined declaration of an internal linkage symbol.
2026-01-13 22:02:12 +00:00
Richard Smith 050d1f0c30 Reduce libc++ hardening mode from debug to extensive in -c dbg. (#6589)
These checks include a full check that a red-black tree satisfies its
invariants on every erase. This leads to
`llvm::DWARFDebugAranges::construct` becoming quadratic in the number of
debug symbols in the binary, which means that in `-c dbg`, symbolization
of backtraces is astronomically slow, and in practice never completes.
(I left it for over 12 hours and it did not finish.)

Reduce the libc++ hardening mode from *debug* to *extensive* to turn off
the checks that have unbounded performance impact.
2026-01-13 21:58:38 +00:00
Geoff Romer a2737a3189 Add Call param patterns to Function (#6586) 2026-01-13 19:30:15 +00:00
Geoff Romer 4a47f1ebeb Remove some uses of ReturnTypeInfo (#6577)
As with #6572, this is a step toward supporting function calls that have
arbitrary numbers of initializing returns.
2026-01-13 17:23:27 +00:00
Chandler CarruthandGeoff Romer d66b2f899c Switch install to be based on the busybox root (#6579)
Previously, we used the FHS "prefix" concept as the basis of the
install, but this makes it hard to integrate an installed toolchain with
Bazel (or similar) build system where it wants the "root" of the
toolchain to have some specific files (`MODULES.bazel` or
`BUILD.bazel`), and cannot reference anything outside that directory
tree.

An easy solution is to make the `lib/carbon` directory the root of the
install and never walking up from it. Then we simply have a `bin/carbon`
symlink to the busybox that is useful for getting the command into the
PATH, but isn't used for anything else. The FHS-constrained install
paths surround a root we fully control the layout and files within.

While initially motivated by trying to make a single toolchain structure
that works both for installation and for Bazel, it actually makes the
paths we end up using in the toolchain much simpler. We no longer have
awkward `.../lib/carbon/../../lib/carbon/...` sequences in the toolchain
which is cleaner and even a (trivial) efficiency gain.

As I was doing this I noticed several out-of-date comments that I tried
to fix, and I tried to improve some code reuse rather than re-computing
paths.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-01-13 03:16:38 +00:00
Geoff Romer e1ec8d42d1 Give ReturnExpr a target only when initialization is in-place (#6570)
Also clarify and enforce that `ConversionTarget::init_id` is used only
as storage for in-place initialization, and correspondingly rename it to
`storage_id`.
2026-01-13 01:20:15 +00:00
Chandler Carruth 93c7c9ad96 Consolidate on @rules_cc and update it to the latest version (#6580)
Also consolidate on using `//bazel/cc_rules:defs.bzl` where appropriate.

Also update a couple of Bazel modules deps of `@rules_cc` to the latest
versions.
2026-01-13 01:06:45 +00:00
Chandler Carruth 33f7e3a28c Try to canonicalize toolchain config formatting (#6581)
Sadly, the formatter for starlark doesn't fully canonicalize the
formatting -- new lines and trailing `,`s can influence this formatting.
I've tried to pick a canonical format for these:

- Collapse as many balanced delimited sequences into a single line
without exceeding 80-columns.
- Collapse as many single comma-separated elements in a delimited region
into single lines with multiple opening constructs and single lines with
multiple closing constructs, reducing indentation and lines that consist
of only an opening delimited construct.

Generally, my goal with these heuristics was to minimize the number of
lines and indentation without creating irregularities, formatting
incompatible with `buildifier`, or egregiously long lines.

I've also tried to lexicographically sort named parameters where there
isn't any important ordering and currently there was a mixture just so
that we have a canonical ordering.

I've removed some redundant parentheses around arrays.

And lastly, I've reformatted some quite long lines to follow a pattern
that fits easily in 80-columns.

This shouldn't result in any behavior changes, just trying to tidy
things up here before making some more significant edits to refactor
this into composable logic instead of a single monolith.

If others have suggestions for different formatting, I'm happy to
change. I don't have any strong feelings about the formatting here, I
just wanted it to be consistent.
2026-01-12 19:12:51 +00:00
Richard Smith 31919afa24 Allow conversion between T* and Cpp.void*. (#6575)
Support an implicit conversion from `T*` to `Cpp.void*` and to `const
Cpp.void*`, and an `unsafe as` conversion in the opposite direction.

In order to support C++ calls taking and returning `void*` (which get
mapped to Carbon `Optional(Cpp.void*)`, also support conversions from
`Optional(T)` to `Optional(U)` if there's a conversion from `T` to `U`.

Fix a bug in `OptionalStorage` for `T*` where its `HasValue` was exactly
backwards.
2026-01-12 16:32:15 +00:00
Ivana Ivanovska d1b13194d5 Add arithmetic operators for CppCompat.Long32 (#6573)
`CppCompat.Long32` is a distinct type, mapped to C++ `long` on `LLP64`
(64-bit Windows).

Context: #6275.

Part of #5263.
2026-01-12 11:58:14 +00:00
Richard SmithandCarbon Infra Bot f5bb43bced Stop creating invalid clang identifier names. (#6578)
This doesn't appear to be causing any problems, but seems worth avoiding
anyway.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-01-11 21:06:22 +00:00
Richard Smith 935ccce2a6 Fix lowering of imported global variables. (#6567)
*   When a C++ static data member is imported, evaluate its address to a
    constant like we would for a namespace-scope variable.
*   When an imported variable is used in a way that doesn't require its
    type to be complete, emit the variable with an opaque type instead
    of skipping it (and potentially crashing later).
2026-01-11 19:22:43 +00:00
zadig 64fa9cc6ae Update tree-sitter-bazel to 0.26.3. (#6582)
Hi, `tree-sitter-bazel`'s maintainer here. :)

I just
[updated](https://github.com/bazelbuild/bazel-central-registry/pull/6486)
`tree-sitter-bazel` to `0.26.3`.

I figured that you may want to update as well, since `0.24.4` is one
year old.
2026-01-11 04:30:04 +00:00
Richard Smith 87e588c334 Add interop support for complement and subscript operators. (#6576)
Also add the code to support interop with simple assignment. This
doesn't yet work because we don't support overloaded simple assignment
in general yet.
2026-01-10 07:50:00 +00:00
Geoff Romer 6985ecb1d4 Replace GetCurrentReturnSlot with GetReturnedVarParam (#6571)
Not all functions have a return slot, and once we have composite forms,
functions will be able to have any number of return slots. Obtaining a
unique return slot for a function only makes sense in `returned var`
handling.
2026-01-10 01:56:32 +00:00
Boaz Brickner 3c70a9f59b C++ Interop: Toolchain Implementation for Function Calls (#6254)
This proposal details the toolchain implementation for calling imported
C++
functions from Carbon. It covers how C++ overload sets are handled, the
process
of overload resolution leveraging Clang, and the generation of "thunks"
(intermediate functions) when necessary to bridge Application Binary
Interface
(ABI) differences between Carbon and C++.
2026-01-10 00:21:21 +00:00
Geoff Romer 87b4ca54e6 Decouple PerformCallToFunction from ReturnTypeInfo (#6572)
`ReturnTypeInfo` is built around the assumption that a function call
results in exactly one initializing expression, but with `ref` returns
there may be zero, and in the future composite return forms will enable
there to be more than one. This change removes some usages of
`ReturnTypeInfo`, and restructures the calling code to be prepared for
multiple initializing returns.
2026-01-09 23:04:54 +00:00
Richard Smith 9727c628c4 Check that constants are lowered in the proper order. (#6566)
Instead of comparing `InstId` indexes, which aren't *necessarily* in the
same order as raw indexes, compare the raw indexes themselves. Convert
the test for out-of-order lowering into a `CHECK` failure if a constant
is found to refer to another constant with a later-created instruction.

In principle this is fixing a bug: if there were so many files and
instructions that the bits of the tag overlapped the bits of the
`InstId`, we could return `nullptr` for a constant that actually had a
value. But in practice this would be very hard to test, and even harder
to test reliably, so I'm not including a test here. The purpose of this
change is to add the `CHECK`, not to fix an obscure bug.
2026-01-09 01:31:30 +00:00
Richard Smith 7cf7d8697b Add testing for interop with C++ inline and thread_local variables. (#6568)
Inline variables already work fine; thread_local variables need more
work.
2026-01-09 01:31:27 +00:00
Richard Smith ead7803d60 Simplify importing of C++ global variables. (#6565)
Remove the unnecessary two-phase creation of variables in C++ import. We
don't need to create a placeholder and overwrite it here, so stop doing
so.

Also, add the patterns to the imports table and don't create a
NameBindingDecl. The NameBindingDecl would never be used for anything.
This matches what we do when importing a Carbon variable, and improves
the formatted SemIR output.
2026-01-09 00:16:27 +00:00
Geoff Romer 11d407b4a0 Add form to Function (#6561)
... and use the form to implement support for `ref` returns.
2026-01-08 18:55:53 +00:00
Dana Jansens 28b01118d0 Put IdTag in its own file (#6564) 2026-01-08 18:13:21 +00:00
dependabot[bot] 508a28457e Bump urllib3 from 2.6.0 to 2.6.3 in /github_tools in the pip group across 1 directory (#6563)
Bumps the pip group with 1 update in the /github_tools directory:
[urllib3](https://github.com/urllib3/urllib3).

Updates `urllib3` from 2.6.0 to 2.6.3
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/urllib3/urllib3/releases">urllib3's
releases</a>.</em></p>
<blockquote>
<h2>2.6.3</h2>
<h2>🚀 urllib3 is fundraising for HTTP/2 support</h2>
<p><a
href="https://sethmlarson.dev/urllib3-is-fundraising-for-http2-support">urllib3
is raising ~$40,000 USD</a> to release HTTP/2 support and ensure
long-term sustainable maintenance of the project after a sharp decline
in financial support. If your company or organization uses Python and
would benefit from HTTP/2 support in Requests, pip, cloud SDKs, and
thousands of other projects <a
href="https://opencollective.com/urllib3">please consider contributing
financially</a> to ensure HTTP/2 support is developed sustainably and
maintained for the long-haul.</p>
<p>Thank you for your support.</p>
<h2>Changes</h2>
<ul>
<li>Fixed a security issue where decompression-bomb safeguards of the
streaming API were bypassed when HTTP redirects were followed.
(CVE-2026-21441 reported by <a
href="https://github.com/D47A"><code>@​D47A</code></a>, 8.9 High,
GHSA-38jv-5279-wg99)</li>
<li>Started treating <code>Retry-After</code> times greater than 6 hours
as 6 hours by default. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3743">urllib3/urllib3#3743</a>)</li>
<li>Fixed <code>urllib3.connection.VerifiedHTTPSConnection</code> on
Emscripten. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3752">urllib3/urllib3#3752</a>)</li>
</ul>
<h2>2.6.2</h2>
<h2>🚀 urllib3 is fundraising for HTTP/2 support</h2>
<p><a
href="https://sethmlarson.dev/urllib3-is-fundraising-for-http2-support">urllib3
is raising ~$40,000 USD</a> to release HTTP/2 support and ensure
long-term sustainable maintenance of the project after a sharp decline
in financial support. If your company or organization uses Python and
would benefit from HTTP/2 support in Requests, pip, cloud SDKs, and
thousands of other projects <a
href="https://opencollective.com/urllib3">please consider contributing
financially</a> to ensure HTTP/2 support is developed sustainably and
maintained for the long-haul.</p>
<p>Thank you for your support.</p>
<h2>Changes</h2>
<ul>
<li>Fixed <code>HTTPResponse.read_chunked()</code> to properly handle
leftover data in the decoder's buffer when reading compressed chunked
responses. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3734">urllib3/urllib3#3734</a>)</li>
</ul>
<h2>2.6.1</h2>
<h2>🚀 urllib3 is fundraising for HTTP/2 support</h2>
<p><a
href="https://sethmlarson.dev/urllib3-is-fundraising-for-http2-support">urllib3
is raising ~$40,000 USD</a> to release HTTP/2 support and ensure
long-term sustainable maintenance of the project after a sharp decline
in financial support. If your company or organization uses Python and
would benefit from HTTP/2 support in Requests, pip, cloud SDKs, and
thousands of other projects <a
href="https://opencollective.com/urllib3">please consider contributing
financially</a> to ensure HTTP/2 support is developed sustainably and
maintained for the long-haul.</p>
<p>Thank you for your support.</p>
<h2>Changes</h2>
<ul>
<li>Restore previously removed <code>HTTPResponse.getheaders()</code>
and <code>HTTPResponse.getheader()</code> methods. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3731">#3731</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/urllib3/urllib3/blob/main/CHANGES.rst">urllib3's
changelog</a>.</em></p>
<blockquote>
<h1>2.6.3 (2026-01-07)</h1>
<ul>
<li>Fixed a high-severity security issue where decompression-bomb
safeguards of
the streaming API were bypassed when HTTP redirects were followed.
(<code>GHSA-38jv-5279-wg99
&lt;https://github.com/urllib3/urllib3/security/advisories/GHSA-38jv-5279-wg99&gt;</code>__)</li>
<li>Started treating <code>Retry-After</code> times greater than 6 hours
as 6 hours by
default. (<code>[#3743](https://github.com/urllib3/urllib3/issues/3743)
&lt;https://github.com/urllib3/urllib3/issues/3743&gt;</code>__)</li>
<li>Fixed <code>urllib3.connection.VerifiedHTTPSConnection</code> on
Emscripten.
(<code>[#3752](https://github.com/urllib3/urllib3/issues/3752)
&lt;https://github.com/urllib3/urllib3/issues/3752&gt;</code>__)</li>
</ul>
<h1>2.6.2 (2025-12-11)</h1>
<ul>
<li>Fixed <code>HTTPResponse.read_chunked()</code> to properly handle
leftover data in
the decoder's buffer when reading compressed chunked responses.
(<code>[#3734](https://github.com/urllib3/urllib3/issues/3734)
&lt;https://github.com/urllib3/urllib3/issues/3734&gt;</code>__)</li>
</ul>
<h1>2.6.1 (2025-12-08)</h1>
<ul>
<li>Restore previously removed <code>HTTPResponse.getheaders()</code>
and
<code>HTTPResponse.getheader()</code> methods.
(<code>[#3731](https://github.com/urllib3/urllib3/issues/3731)
&lt;https://github.com/urllib3/urllib3/issues/3731&gt;</code>__)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/urllib3/urllib3/commit/0248277dd7ac0239204889ca991353ad3e3a1ddc"><code>0248277</code></a>
Release 2.6.3</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/8864ac407bba8607950025e0979c4c69bc7abc7b"><code>8864ac4</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/70cecb27ca99d56aaaeb63ac27ee270ef2b24c5c"><code>70cecb2</code></a>
Fix Scorecard issues related to vulnerable dev dependencies (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3755">#3755</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/41f249abe1ef3e20768588969c4035aba060a359"><code>41f249a</code></a>
Move &quot;v2.0 Migration Guide&quot; to the end of the table of
contents (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3747">#3747</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/fd4dffd2fc544166b76151a2fa3d7b7c0eab540c"><code>fd4dffd</code></a>
Patch <code>VerifiedHTTPSConnection</code> for Emscripten (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3752">#3752</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/13f0bfd55e4468fe1ea9c6f809d3a87b0f93ebab"><code>13f0bfd</code></a>
Handle massive values in Retry-After when calculating time to sleep for
(<a
href="https://redirect.github.com/urllib3/urllib3/issues/3743">#3743</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/8c480bf87bcefd321b3a1ae47f04e908b6b2ed7b"><code>8c480bf</code></a>
Bump actions/upload-artifact from 5.0.0 to 6.0.0 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3748">#3748</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/4b40616e959c0a2c466e8075f2a785a9f99bb0c1"><code>4b40616</code></a>
Bump actions/cache from 4.3.0 to 5.0.1 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3750">#3750</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/82b8479663d037d220c883f1584dd01a43bb273b"><code>82b8479</code></a>
Bump actions/download-artifact from 6.0.0 to 7.0.0 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3749">#3749</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/34284cb01700bb7d4fdd472f909e22393e9174e2"><code>34284cb</code></a>
Mention experimental features in the security policy (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3746">#3746</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/urllib3/urllib3/compare/2.6.0...2.6.3">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=urllib3&package-manager=pip&previous-version=2.6.0&new-version=2.6.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-08 09:19:27 +00:00
Dana Jansens 30562826b8 Add Inst::IsOneOf to check if an inst is one of a few kinds (#6523)
Adds Inst::IsOneOf which takes a variadic generic parameter pack of
kinds to check against. Also add forwarding functions to TypeStore and
InstStore. Convert uses of the regex `Is<.*\|\|` to IsOneOf.

This is based on #6522
2026-01-07 21:41:05 +00:00
Dana Jansens f7fa83ead6 Fix comments in impl lookup to refer to identified facet types instead of complete ones (#6560)
The code has been changed to work with identified facet types, but the
text was missed.
2026-01-07 17:59:15 +00:00
Geoff Romer 2e59a0d520 Handle jj diff-style conflict markers in autoupdate (#6559) 2026-01-07 17:17:40 +00:00
Dana Jansens 3a7c44c5c4 Check required implementations when an enclosing interface is implemented (#6522)
If an interface contains `require impls`, then implementing the
interface requires each of the `require impls` statements to be true at
the point of the impl definition for the containing interface.
2026-01-07 17:05:41 +00:00
Chandler Carruth be884a8be0 Teach the Clang runner to expand response files (#6555)
This uses the existing Clang driver APIs for expanding response files
and so should be pretty carefully accurate to what is needed here.

Note that this doesn't try to generalize the expansion more widely for
the interop Clang invocation, but it would be straightforward to do so
if needed at some point.
2026-01-07 06:53:28 +00:00
Chandler Carruth eecbb7e508 Switch to BumpPtrAllocator for C-string storage (#6550)
This keeps the allocations cheap and simplifies the code. It was
inspired by the need to expand param files, but
no functionality changed yet.
2026-01-07 02:53:31 +00:00
Geoff Romer 505b1c86b9 Initial support for return forms (#6556)
The main changes here are:
- Introducing `InitForm` and `RefForm` to represent initializing and
reference forms (the two return forms currently supported by the
parser).
- Introducing the `FormType` singleton inst to represent their type
(i.e. `Core.Form`).
- Emitting an inst representing a function's declared return form as
part of handling the function signature.

The return form inst is currently ignored. Subsequent PRs will expose it
in `SemIR::Function` and use it to determine the form of call
expressions.
2026-01-07 00:54:18 +00:00
Chandler Carruth 444c18dfa3 Enable using our own C++ runtimes across the board (#6549)
This enables on-demand building of runtimes by default, and enables
their header files for all of the Clang invocations. This also switches
the default flags to use the LLVM-provided runtimes (compiler-rt,
libunwind, and libcxx).

This also switches even `llvm_symlinks_test` to use the Bazel prebuilt
runtimes, which requires having a way to pass a Carbon flag even when
invoking the busybox as `clang` or `clang++`. This uses the pattern that
has worked for other Clang wrappers of spelling flags:
`-X<tool-name>=--flag=value`

Last but not least, this updates the Carbon Bazel rules to use our
installed and the Bazel prebuilt runtimes. With that, we make the C++
interop hello-world be enabled by default as this should pass reliably
on both Linux and macOS now.
2026-01-07 00:16:50 +00:00
Chandler CarruthandRichard Smith be4a95aef3 Introduce a Bazel runtimes building system (#6548)
This allows us to re-use the on-demand runtimes building, but in
a framework that is (much) more Bazel compatible:

- It creates a Bazel rule to generate the runtimes tree
- The generated runtimes tree is adjusted to integrate with Bazel's
  output tracking and caching infrastructure so it doesn't need to be
  rebuilt when a cached set of runtimes is available
- The build occurs during the build phase and the action informs Bazel
  about the CPU usage to give Bazel a chance to not run other parts of
  the build when there are no execution resources available
- The binary is factored into a stand-alone program for the Clang
  runtimes, which depends on a minimal amount of Carbon and notably
  avoids the busybox or installation. This should cause almost all
  builds to get a cache hit here unless Clang itself is updated.

Some refactoring of the codegen options was done to support this. I've
tried to factor some of the code between this and the `build-runtimes`
subcommand, but it was challenging to do more without adding substantial
complexity or dependencies on more Carbon infrastructure than is
necessary. I think the result is tolerable, but open to suggestions
here if folks see specific changes that would improve things.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-01-06 22:24:15 +00:00
Geoff Romer 2380be2ae1 Add flag to dump the raw SemIR in the event of a crash. (#6558) 2026-01-06 21:56:08 +00:00
Geoff Romer 0e5832d3c2 Model ref tags as insts instead of annotations (#6541)
This continues the implementation of the proposed resolution of #6342.
2026-01-05 22:24:47 +00:00
Geoff Romer b72bfb918b Allocate CallParamIndexes eagerly (#6540)
This approach is more robust because there's no intermediate state where
the `ParamPattern` insts have been created, but don't yet have their
final values.
2026-01-05 19:38:52 +00:00
Chandler Carruth 08051393dc Fix support for zlib and zstd in LLVM (#6544) 2026-01-03 17:36:19 +00:00
Chandler Carruth e7eb3b7b5a Consolidate default Clang argument handling (#6545)
This unifies the default Clang arguments between the `clang` subcommand,
the `link` subcommand, and the `ClangInvocation` built for C++ interop.

This sets the stage to integrate either pre-built or on-demand runtimes
flags for both of these. However, this PR should have very little
practical difference. The biggest functional change is wrapping the
default arguments in flags to allow unused flags so that we can build a
collection of flags viable across compile and link.
2026-01-03 17:35:29 +00:00
Chandler Carruth e545929386 Pivot towards relative paths for installs and runtimes (#6547)
When building in Bazel actions, notably building runtimes, using
absolute paths makes the results non-hermetic and generally less
cache-friendly.

This restructures the code to only form an absolute path as part of the
`bazel run` change of working directory. It also tries to make the API
for doing this a bit more clear by taking the `exe_path` and
transforming it internally.

To support this, this PR also generalizes the `RemovingDir` to support
relative paths. While these can be tricky -- the working directory needs
to not change while they exist -- that isn't a reason to fully exclude
them and they're useful for implementing relative-path runtimes, etc.
2026-01-01 22:20:40 +00:00
dependabot[bot] 137695c1ca Bump qs from 6.13.1 to 6.14.1 in /utils/vscode in the npm_and_yarn group across 1 directory (#6552)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [qs](https://github.com/ljharb/qs).

Updates `qs` from 6.13.1 to 6.14.1
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.14.1</strong></h2>
<ul>
<li>[Fix] ensure arrayLength applies to <code>[]</code> notation as
well</li>
<li>[Fix] <code>parse</code>: when a custom decoder returns
<code>null</code> for a key, ignore that key</li>
<li>[Refactor] <code>parse</code>: extract key segment splitting
helper</li>
<li>[meta] add threat model</li>
<li>[actions] add workflow permissions</li>
<li>[Tests] <code>stringify</code>: increase coverage</li>
<li>[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code>, <code>npmignore</code>,
<code>es-value-fixtures</code>, <code>for-each</code>,
<code>object-inspect</code></li>
</ul>
<h2><strong>6.14.0</strong></h2>
<ul>
<li>[New] <code>parse</code>: add
<code>throwOnParameterLimitExceeded</code> option (<a
href="https://redirect.github.com/ljharb/qs/issues/517">#517</a>)</li>
<li>[Refactor] <code>parse</code>: use <code>utils.combine</code>
more</li>
<li>[patch] <code>parse</code>: add explicit
<code>throwOnLimitExceeded</code> default</li>
<li>[actions] use shared action; re-add finishers</li>
<li>[meta] Fix changelog formatting bug</li>
<li>[Deps] update <code>side-channel</code></li>
<li>[Dev Deps] update <code>es-value-fixtures</code>,
<code>has-bigints</code>, <code>has-proto</code>,
<code>has-symbols</code></li>
<li>[Tests] increase coverage</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ljharb/qs/commit/3fa11a5f643c76896387bd2d86904a2d0141fdf7"><code>3fa11a5</code></a>
v6.14.1</li>
<li><a
href="https://github.com/ljharb/qs/commit/a62670423c1ccab0dd83c621bfb98c7c024e314d"><code>a626704</code></a>
[Dev Deps] update <code>npmignore</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/3086902ecf7f088d0d1803887643ac6c03d415b9"><code>3086902</code></a>
[Fix] ensure arrayLength applies to <code>[]</code> notation as
well</li>
<li><a
href="https://github.com/ljharb/qs/commit/fc7930e86c2264c1568c9f5606830e19b0bc2af2"><code>fc7930e</code></a>
[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/0b06aac566abee45ef0327667a7cc89e7aed8b58"><code>0b06aac</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/64951f6200a1fb72cc003c6e8226dde3d2ef591f"><code>64951f6</code></a>
[Refactor] <code>parse</code>: extract key segment splitting helper</li>
<li><a
href="https://github.com/ljharb/qs/commit/e1bd2599cdff4c936ea52fb1f16f921cbe7aa88c"><code>e1bd259</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/f4b3d39709fef6ddbd85128d1ba4c6b566c4902e"><code>f4b3d39</code></a>
[eslint] add eslint 9 optional peer dep</li>
<li><a
href="https://github.com/ljharb/qs/commit/6e94d9596ca50dffafcef40a5f64eca89962cf34"><code>6e94d95</code></a>
[Dev Deps] update <code>eslint</code>,
<code>@ljharb/eslint-config</code>, <code>npmignore</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/973dc3c51c86da9f4e30edeb4b1725158d439102"><code>973dc3c</code></a>
[actions] add workflow permissions</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.13.1...v6.14.1">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=qs&package-manager=npm_and_yarn&previous-version=6.13.1&new-version=6.14.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-01 21:43:34 +00:00
Chandler Carruth 90e2359eee Build archives with only the basename as the name of members. (#6546)
This both better matches the behavior of `ar`, and avoids the full path
being long and in many cases containing unstable path components.
2026-01-01 16:48:43 +00:00
Chandler Carruth 65f35ad98e Add support for forcing a rebuild of runtimes (#6537)
This is useful during development, testing, and will also be useful for
a more bazel-integrated build step.

Also clean up the path management when creating runtimes:

- Teach the main runtimes code to handle making a relative path absolute
- Separate out methods for _creating_ a runtimes tree vs. opening an
existing one. Teach the creation path to create intervening directories
as needed. This provides a more useful and less surprising set of
behaviors.

Last but not least, also clean up a bunch of comments in the runtimes
cache code to talk generically about components -- these APIs are no
longer specific to the resource directory.
2025-12-31 01:59:19 +00:00
Geoff Romer 2078721e1c Always build ReturnTypeInfo from a function (#6490)
This is a step toward using it to represent the return form, not just
the return type.
2025-12-31 01:30:09 +00:00
Chandler Carruth 4197e6ca63 Add support for installing compiler-rt provided headers (#6542)
These are installed as part of the builtin headers, but located in a
different part of upstream LLVM.
2025-12-30 23:20:04 +00:00
Geoff Romerandjosh11b e940cb72b6 Parse ref as operator (#6539)
This is the first step of implementing the guidance in #6342.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-12-30 19:18:34 +00:00
Geoff RomerandChandler Carruth 9cdb9c803a Add support for jj conflict markers (#6536)
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-12-29 23:53:24 +00:00
Geoff Romer 0e5874b203 Model category conversion as a state machine. (#6535)
The fallthrough-based approach was unwieldy and error-prone, and
inherently couldn't support category conversions whose steps don't
follow the fixed order of the `switch` statement.
2025-12-26 22:06:53 +00:00
Richard Smith 531d063596 When importing a trivial destructor from C++, produce a no_op builtin. (#6531)
This avoids us trying to produce a reference to the C++ destructor,
which Clang won't emit because it believes it's unnecessary. This
previously led to link errors.

Fixe #6502.
2025-12-23 05:30:29 +00:00
Özgür 29018f38a6 Fix name mangling of generic impls (#6533)
### Description
Mangling collisions occur when implementing interfaces with generic
parameters. The mangler does not use the specific id, causing the same
symbol `_C[FunctionName].[PackageName]:[InterfaceName].[PackageName]` to
be generated for all of the implementations below:
```carbon
// Generic interface parameters ignored
impl C as I(A)
impl C as I(B)

// Generic class parameters ignored
impl D(A) as I
impl D(B) as I

// Both ignored
impl D(A) as I(A)
impl D(B) as I(B)
```

### Changes
Updated the mangling logic for `SemIR::ClassDecl` and
`SemIR::InterfaceDecl` to include the specific id. Now the mangling
ensures unique symbols for generic implementations using the format:

`_C[FunctionName].[FunctionSpecificId].[PackageName]:[InterfaceName].[InterfaceSpecificId].[PackageName]`.

Closes #6498
2025-12-23 00:36:03 +00:00
Dana Jansens 90f839e84e Add IR tagging to RequireImplsIds (#6525)
InstNamer is updated to print in hex for these, since the id is used in
the scope name for the declaration.
2025-12-19 23:43:51 +00:00
Jon Ross-PerkinsandDana Jansens fb58a41b11 Add a note about iterative coding style (#6528)
Adding the note about recursion because it occasionally comes up, and
I'm thinking it'd be helpful to document why we prefer iterative
algorithms.

Also moves a few long style points to headers so that they're easier to
link (I wasn't sure it makes sense to do to all of "syntax and
formatting", but either way what's remaining is shorter if that _is_
linked for reference).

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-12-19 21:00:14 +00:00
Dana Jansens 54a1c8213c Add lldb dumping for RequireImplsId and RequireImplsBlockId (#6524)
The dump of a block looks like:
```
(lldb) dump context require_impls_block_id
require_block60000001
  - require0: {self_id: inst60000019, facet_type_inst_id: inst6000001D, extend_self: true, parent_scope: name_scope60000002}
```

The dump of an individual RequireImplsId is shown above for `require0`.
2025-12-19 18:48:20 +00:00
Jon Ross-Perkins c5eba90317 Change Destroy to use a CustomWitness instead of a blanket impl (#6512)
Pursuant to recent decisions on #6124, switch `Destroy` to use a
`CustomWitness` for its implementation. Right now this is manufacturing
no-op implementation functions on each lookup, which obviously isn't
ideal but is intended as a first pass. I'm mostly trying to find the
right balance between updating the approach to reflect new decisions,
while still breaking apart work in a way.

The `CoreInterface` logic is intended to build on `CoreIdentifier`
support. We have a number of additional interfaces that require
specialized logic, and that'll extend pretty far with C++ interop, so it
seemed easiest to have a generic function for it. That's what's
replacing the logic inside C++ interop that was doing string comparisons
(which could have already been moved to `CoreIdentifier`, I just missed
it in my first pass).

This adds `CustomWitness` support because the `Destroy` witnesses can be
imported cross-file. `CustomWitness` was previously only used for C++
types, which don't yet support import, which is why that wasn't
previously an issue. The addition of `query_specific_interface_id` is
similarly needed in order to get correct sorting of witness blocks when
imported.

This PR also removes builtin constraint logic (note this is in a
separate commit to help review; it's not a separate PR because it's
difficult to split apart without tests breaking). This had been made
generic with the expectation that destroy, copy, move, and conversions
would all need related support. Under the new decision, we are not going
to do blanket impls and will instead just manufacture a `CustomWitness`
for everything.

A lot of SemIR fingerprints change, but that's probably because the
addition of `Destroy` on core classes is yielding structural changes.
2025-12-19 18:36:06 +00:00
Dana Jansens 1f0a3dcf37 Allow splitting the id type and the id number in lldb dumping (#6527)
This re-adds the ability to put a space between the id type and number.
In particular, when copy/pasting large hex-encoded id numbers that are
retrieved from `p/x`, such as an array of InstIds, putting a space
between allows faster editing. The space allows the previous command to
be reused, and then to delete the id in a single key command.
2025-12-19 18:22:32 +00:00
Dana Jansens 61ef19eb07 Allow copy-pasting 0x prefixed hex values as ids to the dump debugger command (#6526) 2025-12-19 17:35:01 +00:00
Özgür a4b5ab9df9 Reject unqualified private access to base members (#6521)
### Description
Currently, unqualified access to private members of the base class
compiles without error. This is due to `LookupUnqualifiedName` calling
`LookupQualifiedName` internally with `access_info` parameter set to
`std::nullopt`. This causes `IsAccessProhibited` to return `false`
immediately.
This PR fixes this issue.

### Changes
- Added a check where if the `access_info` is null and the current scope
we are looking is an extended scope (parent), initializes the
`access_info` with `highest_allowed_access` set to `Protected`.

Fixes #6239
2025-12-18 19:12:07 +00:00
Dana Jansens 8e577a5d28 Prevent accidental copies of TypeStructure (#6519)
The TypeStructure is pretty large, with multiple vectors inside, and we
don't want to do a bunch of mallocs for no reason. There is no need for
a copy ever at this time.

Based on #6517
2025-12-18 17:26:28 +00:00
Jon Ross-Perkins b34e349792 Push GetFacetAsType from impl_lookup to custom_witness (#6520)
This delays the conversion of `query_self_const_id` until the actual
witness creation, mainly so that users of `BuildCustomWitness` don't
need to do extra work to ensure `GetFacetAsType` logic is
shared/applied. This is coming up for destroy logic.
2025-12-18 15:37:53 +00:00
Richard Smithandjosh11b 4ddba4ab1e Modernize advent of code examples (#6496)
* Use generics in more places.
* Use `ref` in more places.
* Use `for` in more places.
* Use a little bit of C++ interop.
* Use an adapter for the `char`-or-EOF result of reading a char instead
of pure `i32`, and use char literals where possible.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-12-17 23:26:26 +00:00
Jon Ross-Perkins 2543d2ea4f Add CoreInterface for consistent tracking of CoreIdentifier interfaces (#6516)
We're going to want to track `Destroy` and some other interfaces in ways
similar to what the C++ logic wants. Rather than having both do their
own comparisons with similar values, this tries to centralize logic.

Note the prior
`context.identifiers().Get(interface.name_id.AsIdentifierId())` is also
obsolete due to #6486, this is just replacing it in a single swoop and
avoiding string comparisons as a consequence.
2025-12-17 23:11:52 +00:00
Jon Ross-Perkins 655932da0b Refactor BuildCustomWitness out to its own file (#6515)
Per request at
https://github.com/carbon-language/carbon-lang/pull/6512#discussion_r2627265838
2025-12-17 21:36:44 +00:00
Dana Jansens 5efed204a2 Make EvalLookupSingleImplWitness shorter (#6517)
This reduces the function size from ~180 to 133. It removes early outs
once we begin the process of doing an impl lookup so that we cache the
result unconditionally at the end. It removes a second fallback call to
look for a C++ witness by tracking additional information about the
`Impl` that was found (if any) and just do the C++ lookup in one place
afterward.
2025-12-17 21:18:24 +00:00
Dana Jansens 7c1798d96d Format impl witness instructions as part of the impl (#6485)
The impl's body block has to end before we make its ImplDecl
instruction, and the witness instructions come later, so they don't end
up in the body block. Currently they just end up in the enclosing (file,
typically, or class) scope block.

Add a new InstBlockId to Impl for holding witness instructions, and
explicitly insert them into that block. Then include those instructions
into the scope of the Impl for naming, and format them into the Impl
right after the body block.

This is based on #6484
2025-12-17 15:46:30 +00:00
Burak Emir 992d435023 Replace unused bindings with anonymous binding in lower/testdata. (#6479)
This updates lower/testdata to use _ instead of proper names, in order
to avoid the "unused binding" warnings from #2022 which are being
implemented. These changes do not depend on the implementation which
should make everything easier to review.

See #6460 with part 1 of the implementation. It was split upon request
in order to make reviewing easier, the original state of the PR was
updating hundreds of test cases.
The PR has thus been split, part 2 including test cases changes can be
viewed at
https://github.com/burakemir/carbon-lang/tree/unused_pattern_bindings_p2022_impl_part2
... many tests need to be updated, so it seems best to get those tests
out of the way that are not interesting.

These are not all tests in lower/testdata - a few of them are
interesting in the sense that they cannot use '_' because it leads to
failed redeclaration check. This is exactly the scenario described in
#3763 which requires the 'unused' marker. Those are left untouched here
but are updated in
https://github.com/burakemir/carbon-lang/tree/unused_pattern_bindings_p2022_impl_part2
2025-12-17 15:43:04 +00:00
Burak EmirandDana Jansens fec6ce2f9f Implement "unused pattern bindings" p2022 - parsing (#6460)
This implements proposal #2022, with changes from #3763 and leads
answers on #6448

Detection of unusedness is happening in
~~`toolchain/check/dataflow_analysis.cpp`~~ next PR. See
[here](https://github.com/burakemir/carbon-lang/tree/unused_pattern_bindings_p2022_impl_part2)
for preview.

~~All test cases with unused bindings were updated in order to avoid
polluting test output.~~

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-12-17 15:40:20 +00:00
Geoff Romer ad7ea755b0 Add Abstract enumerator to InitRepr::Kind (#6513)
This fixes a bug where `CheckFunctionReturnType` could sometimes fail to
diagnose an abstract return type.
2025-12-17 00:00:14 +00:00
Richard Smith 2e65d28a16 Support for passing C++ templates as arguments to template template parameters. (#6475)
Allow passing a C++ template as a template template argument to another
C++ template. Does not allow passing a Carbon generic as an argument.

Depends on #6474.
2025-12-16 19:00:49 +00:00
Jon Ross-Perkins 3ae6f96141 Remove IsPackage (#6497)
The work being done by `IsPackage` is more than is needed by callers.
2025-12-16 18:16:45 +00:00
Dana Jansens efec4e4658 Move generic stack operations into handle_impl.cpp (Refactor Impl construction 8/7) (#6484)
Instead of burying operations to pop the generic stack in
`GetOrAddImpl`, we move them up to handle_impl.cpp in `BuildImplDecl`,
which puts them at the same level as other operations on the generic
stack, like `StartGenericDecl` or `FinishGenericDefinition`.

To do so, we split `GetOrAddImpl` into a few pieces:
- `FindImplId` finds an existing Impl that matches the declaration, or
returns a LookupBucketRef and whether an error was diagnosed instead.
- `AddImpl` takes a fully built `Impl`, makes an `ImplId` for it, and
does additional steps for a new `Impl` verifying it and applying
`extend`.
- `AddImplWitnessForDeclaration` constructs the `Impl`'s witness, which
must be done between two generic steps in order to use the generic's
self specific but also add the witness instruction to the generic.

We group the logic to build the initial table in the definition and to
complete it in the definition together in `impl.cpp`. And we save a
lookup into the ImplStore by passing Impl by reference to
`FinishImplWitness`, as we now do for other similar functions in
`impl.h`.

This is based on #6470.
2025-12-16 15:32:56 +00:00
Jon Ross-Perkins 47e551141f Change the package namespace to use the package name (#6495)
Instead of naming the root namespace `package` (because it's accessed by
the `package` keyword), change it to use the current package name. Note,
buried in the checksum changes,
`toolchain/check/testdata/package_expr/fail_not_found.carbon`:

```
-  // CHECK:STDERR: fail_not_found.carbon:[[@LINE+4]]:16: error: member name `x` not found in `package` [MemberNameNotFoundInInstScope]
+  // CHECK:STDERR: fail_not_found.carbon:[[@LINE+4]]:16: error: member name `x` not found in `Main` [MemberNameNotFoundInInstScope]
```

for:

```
  // CHECK:STDERR:   var y: i32 = package.x;
  // CHECK:STDERR:                ^~~~~~~~~
```

I'll leave it to you if you prefer this; the alternative I see is to
just rename `IsCorePackage` to `IsImportedCorePackage`, and/or change it
to a helper that takes a `Context` and does the right thing with
`parse_tree` (which, I need for `Destroy`-related reasons and was my
default approach).
2025-12-16 01:33:53 +00:00
Özgür 2a3d0b71bb Reject abstract types in var function parameters (#6499)
### Description
Fixes an issue where the toolchain accepted abstract types in function
parameters declared with `var`.

### Changes
- Implemented a check for abstract types for function parameters with
`var` binding pattern in `HandleAnyBindingPattern`.
- Added a test case to
`toolchain/check/testdata/class/fail_abstract.carbon`.

**Note:** I did not use `AsConcreteType` like used in `case
FullPatternStack::Kind::NameBindingDecl`. Using it enforces type
completion, thus causing valid signatures such as `fn F[var self: Self]`
to fail.

Also the pre-commit checks fail due to a diagnostic name collision with
`toolchain/check/type_completion.cpp`. Should I add a function that just
checks if the type is abstract to share the diagnostic?

Fixes #6402
2025-12-15 20:17:34 +00:00
Jon Ross-Perkins 25f63140e6 Refactor CppWitness as CustomWitness (#6491)
This is in anticipation of using the same construct for all
implementations of `Destroy`, as well as other similar use-cases with
language-defined interfaces.
2025-12-15 19:41:14 +00:00
Richard Smith 6b28213b36 Add interop support for naming and "calling" C++ templates. (#6474)
Expose C++ class templates, variable templates, alias templates, and
concepts as callable values in Carbon, and map calls to them into
template-id formation, mirroring how Carbon generics behave. For now,
only type template parameters are supported; non-type and template
template parameters produce a TODO error.
2025-12-15 17:45:01 +00:00
Richard SmithandJon Ross-Perkins a8eca2ece6 Delay finishing the C++ translation unit until we reach the real EOF. (#6489)
Instead of parsing a complete C++ translation unit and then interacting
with the translation unit further after the fact, delay finishing the
translation unit until we finish the Carbon check phase. This fixes some
issues where we would produce duplicated or incorrect diagnostics at the
end of the C++ translation unit, particularly for unused declarations.
Now we're in control of how we parse the translation unit, also disable
parsing of C++20 modules if the syntax appears within `import Cpp
inline` code.

Keep the same clang parser alive throughout check, and use it instead of
building a new one when parsing macros. This resolves issues where the
translation unit scope was destroyed too early, resulting in unqualified
lookup within macros being unable to find global scope entities.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-12-13 00:56:30 +00:00
josh11bandJosh L 77caf3b9d8 Add Core.PrintStr and a "hello world" example (#6493)
Thanks to @ammaralassal for #6329 which did the heavy lifting to make
this possible!

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-12-12 20:07:05 +00:00
Dana Jansens fbcaf34494 Defer RequireCompleteType to impl definition (Refactor Impl construction 7/7) (#6470)
Explicitly run `RequireCompleteType` for an impl's facet type constraint
in two places:
- For a new `Impl` declaration that is `extend`
- At the start of the `Impl` definition

Stop trying to RequireCompleteType in the definition when constructing
the witness. If we have a rewrite of a name in `.Self`, then we can
construct a full witness, otherwise we defer to the definition.

Now GetOrAddImpl does not need to track `is_definition` anymore, so we
remove a lot of plumbing.

We inline the `AllocateFacetTypeImplWitness` since it has a single
caller and it is just 2 lines, to help improve understanding of the
steps and comments in setting up the impl definition.

Note that this puts the `RequreCompleteType` instruction into the
definition's generic eval block always, avoiding the issue of ensuring
that each generic redecl has the exact same instructions, and forcing
coordination to have `RequireCompleteType` inserted into every
declaration's eval block or none. The result also more closely matches
the design, with the complete type not being required until inside the
definition.

This is part of #6420 which is being split up into a chain of smaller
PRs. It is based on #6469.
2025-12-11 23:50:10 +00:00
Dana Jansens 463ba0e1db Clean up helpers for GetOrAddImpl (Refactor Impl construction 5/7 and 6/7) (#6469)
Make the `AssignImplIdInWitness` into a `static` helper function since
it's only used inside `GetOrAddImpl`. Restructure the diagnostic for
unused generic bindings to move more logic into the helper, and out of
`GetOrAddImpl` so that it has more clear steps.

This is part of #6420 which is being split up into a chain of smaller
PRs. It is based on #6468.
2025-12-11 22:22:43 +00:00
Jon Ross-Perkins c0b335b87f Add well-known identifier caching (#6486)
I'm doing this because I figured it'd be an incremental improvement for
all the operator lookups that we do. Even to the extent that we've
discussed witness caching, I think it'll still apply. It does add one
more step to adding new interfaces (before, you'd just write the string,
now you add it to the def file and reference it).

I'll claim it makes GetClangOperatorKind a lot friendlier to read/edit,
nevermind removing the string comparisons. :)
2025-12-11 21:41:47 +00:00
Ammar AlassalandDana Jansens a848ae11e4 Added string indexing (#6329)
Implemented string indexing for Core.string
Handles references or struct values. No runtime checks as per
https://discord.com/channels/655572317891461132/655578254970716160/1431015866270748682
Part of #6270

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-12-11 21:31:31 +00:00
Dana Jansens 35d505a985 Check the orphan rule for impls (#6488)
The orphan rule is defined here:
https://docs.carbon-lang.dev/docs/design/generics/details.html#orphan-rule

**Orphan rule:** Some name from the type structure of an `impl`
declaration must be defined in the same library as the `impl`, that is
some name must be *local*.

Update tests that were running afoul of the orphan rule unintentionally.
Add tests that do violate the rule intentionally and test edge cases.
2025-12-11 19:44:39 +00:00
Dana Jansens 14998d6045 Consolidate error handling behaviour for ApplyExtendImplAs (Refactor Impl construction 4/7) (#6468)
Propagate error state in an `extend impl` declaration out to the
enclosing scope. We can do this generically in `ApplyExtendImplAs` so we
don't have to do it explicitly in other places.

Collapse `DiagnoseExtendImplOutsideClass` into `ApplyExtendImplAs` as it
had only the one caller and is very small, so this simplifies the code,
making `ApplyExtendImplAs` a clear set of diagnostics. And push the
construction of the SpecificConstant down into `ApplyExtendImplAs` so it
is only constructed if it's needed, instead of constructing it and
throwing it away in error cases.

Ensure any error in the declaration results in the witness being an
ErrorInst so the impl will not be used in impl lookup. This simplifies
some branches by combining them into a single if statement.

This is part of #6420 which is being split up into a chain of smaller
PRs. It is based on #6467.
2025-12-11 19:05:17 +00:00
Geoff Romer a0d1e4b809 Handle SpecificImplFunction in GetCallee (#6487)
I need this in a forthcoming PR, to reliably get the `Function` that was
originally used to build a `Call` inst, but even as a stand-alone
change, it seems to nicely improve the textual SemIR.
2025-12-11 01:06:16 +00:00
Chandler CarruthandGeoff Romer ff8ce31e1b Factor out C-string argv building and simplify vlogs (#6478)
This extracts the C-string `argv`-like building routine to a more
broadly reusable location. It also sinks the verbose logging logic out
of it and into the relevant runners. In turn, it simplifies the verbose
logging logic significantly.

The biggest functional change is removing the implicit synthesis of a
tool's `-v` verbose flag from the presence of a `vlog` stream. I thought
this would be helpful, but in practice of debugging these layers it has
been more of a hindrance than a help -- I pretty often only want verbose
logging on one side or the other, and we have ways of explicitly passing
a `-v` flag to the underlying tools already. I think my instinct to do
this was just wrong, so rip it out and simplify.

This does add an unused feature -- prepending a prefix of arguments
while building the C-string variant. This isn't used in this PR but will
be used in subsequent PRs and it seemed more disruptive to undo that
logic and then re-do it in a later PR. Let me know if it's too confusing
here.

Assisted-by: Gemini Code Assist

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-12-10 22:07:01 +00:00
Dana Jansens 1c3d3e9284 Move forward-decl-only code out to the handler of the forward decl node (Refactor Impl construction 3/7) (#6467)
Rather than run the code for both decl and defn and make it conditional
on not being a definition, put the code in the handler for the
`Parse::ImplDeclId` node, which is handled when there's no definition.
This will help lead us to no longer needing to plumb around
`is_definition` later.

Make some naming consistent to call the reference to an `Impl` as `impl`
instead of sometimes `impl_info`.

This is part of #6420 which is being split up into a chain of smaller
PRs. It is based on #6466.
2025-12-10 21:55:01 +00:00
Richard Smith c4d162e5f5 Switch from clang::ASTUnit to clang::CompilerInstance. (#6483)
This gives us a lot more control over how the compiler is built and
invoked. But no functionality changes are intended in this PR.
2025-12-10 21:54:51 +00:00
Richard Smith 6114df59ee Factor out a Check::CppContext holding C++-specific check state (#6482)
* Move `Sema` access from `CppFile` into `CppContext`.
* Move the mangle context from `SemIR::File` into `CppContext`.
* Move source location mapping state from `Context` into `CppContext`.

Also factor out the `GenerateAst` function that builds the `CppContext`
and `CppFile` into its own file.
2025-12-10 18:55:22 +00:00
Geoff Romer bf45b1cbf5 Refactor function return type representation (#6463)
This separates the return type from the return pattern, and replaces the
return pattern with a block of return patterns. This is a step toward
support for `ref` returns (where there's no corresponding return
pattern) and compund-form returns (where there may be multiple return
patterns).
2025-12-10 18:34:23 +00:00
Jon Ross-Perkins 77918d023b Make symbolic local bindings a TODO (#6449)
Per discussion, makes all symbolic local bindings a TODO. We should
implement them more correctly before making them operable. Right now
things partially work, but because constants behave mostly right in the
symbolic situations under tests. More broadly, it has incorrect behavior
and crashes, thus the TODO.

This converts most tests using `let` to instead using parameters, but
leaves some behind where a conversion either didn't make sense (e.g. in
`let` tests) or a conversion was unclear to me (multi-layer `let`, which
relies more on planned behavior that seems more bespoke to a local
`let`).

In let's `fail_generic.carbon`, there's a "// TODO: Should this be
valid?" that I'm removing because my understanding is the code in
question should be valid (the file is merged into let's
`generic.carbon`).

Refactoring `HandleAnyBindingPattern` a little because there's a TODO to
make it shorter, and it seemed like a reasonable drive-by change (let me
know if you think there's more I should do, or if I should remove said
TODO even though it's still a bit long).

Fixes #5982
2025-12-10 18:11:58 +00:00
Jon Ross-Perkins efbebdb7b3 Remove unused code paths in EndAssociatedConstantDeclRegion (#6481)
I think these are obsolete, at least as far as I can tell. The former
appears tested (adding to be sure), the latter looks like it may no
longer occur.
2025-12-09 23:21:21 +00:00
Dana JansensandJon Ross-Perkins 3c8417947b Propagate errors in extend require up to the containing scope (#6480)
Just as names from an `extend` scope get included in the containing
scope, so do errors. Apply this logic to `extend require impls`,
propagating any errors up.

This is based on #6465.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-12-09 22:04:17 +00:00
Dana Jansens b07b8a122a Make StartImplDecl into a more explicit GetOrAddImpl (Refactor Impl construction 2/7) (#6466)
The GetOrAddImpl operation looks for an existing `Impl` with a matching
declaration and returns its ImplId, or finished the construction of a
new `Impl`, adds it to the store and returns a fresh `ImplId`.

This makes the case of reusing an existing `Impl` into a short
early-out, demonstrating more clearly that we are reusing existing work,
and avoiding duplicate work such as checking for diagnostics that would
have already been checked in the previous (matching) declaration.

The `ExtendImpl` helper is renamed to be more explicit about its
behaviour, as `ApplyExtendImplAs`, and it constructs the data it needs
from the `Impl` and the `extend_node_id`, eliminating the need for a
`ExtendImplDecl` struct.

This is part of #6420 which is being split up into a chain of smaller
PRs. It is based on #6465.
2025-12-09 22:02:50 +00:00
Richard Smith c7cd24e1b2 Support for calling C++ destructors. (#6453)
Synthesize an impl of `Destroy` for C++ classes in response to impl
lookup.
2025-12-09 21:03:27 +00:00
Dana Jansens 2d38978756 Diagnose explicit Self in extend in the parse node handler (Refactor Impl construction 1/7) (#6465)
We encode the state of looking that the parent scope is a Class into a
type so that we can avoid extra lookups. Then use that in refactoring
where diagnostics are generated for an explicit `Self` in an `extend
impl` declaration.

We add tests that we don't double-diagnose the Self type when it's
already an error, and make the behaviour of `extend require` match that
of `extend impl as`.

This avoids some fragile/complex parse-node lookups (such as
`context.parse_tree_and_subtrees().ExtractAs<Parse::ImplTypeAs>`) by
using the parse node at the point where we are handling it instead of
much later.

This is part of #6420 which is being split up into a chain of smaller
PRs.
2025-12-09 20:38:50 +00:00
Richard Smith 154e4012c4 Include the parent scope when fingerprinting an entity name. (#6473)
This is a prerequisite for support for interop with C++ template names.
No behavior change here, except that it sadly changes the fingerprinting
for a lot of tests.
2025-12-08 15:31:13 +00:00
dependabot[bot] d5bddcb3f1 Bump urllib3 from 2.5.0 to 2.6.0 in /github_tools in the pip group across 1 directory (#6471)
Bumps the pip group with 1 update in the /github_tools directory:
[urllib3](https://github.com/urllib3/urllib3).

Updates `urllib3` from 2.5.0 to 2.6.0
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/urllib3/urllib3/releases">urllib3's
releases</a>.</em></p>
<blockquote>
<h2>2.6.0</h2>
<h2>🚀 urllib3 is fundraising for HTTP/2 support</h2>
<p><a
href="https://sethmlarson.dev/urllib3-is-fundraising-for-http2-support">urllib3
is raising ~$40,000 USD</a> to release HTTP/2 support and ensure
long-term sustainable maintenance of the project after a sharp decline
in financial support. If your company or organization uses Python and
would benefit from HTTP/2 support in Requests, pip, cloud SDKs, and
thousands of other projects <a
href="https://opencollective.com/urllib3">please consider contributing
financially</a> to ensure HTTP/2 support is developed sustainably and
maintained for the long-haul.</p>
<p>Thank you for your support.</p>
<h2>Security</h2>
<ul>
<li>Fixed a security issue where streaming API could improperly handle
highly compressed HTTP content (&quot;decompression bombs&quot;) leading
to excessive resource consumption even when a small amount of data was
requested. Reading small chunks of compressed data is safer and much
more efficient now. (CVE-2025-66471 reported by <a
href="https://github.com/Cycloctane"><code>@​Cycloctane</code></a>, 8.9
High, GHSA-2xpw-w6gg-jr37)</li>
<li>Fixed a security issue where an attacker could compose an HTTP
response with virtually unlimited links in the
<code>Content-Encoding</code> header, potentially leading to a denial of
service (DoS) attack by exhausting system resources during decoding. The
number of allowed chained encodings is now limited to 5. (CVE-2025-66418
reported by <a
href="https://github.com/illia-v"><code>@​illia-v</code></a>, 8.9 High,
GHSA-gm62-xv2j-4w53)</li>
</ul>
<blockquote>
<p>[!IMPORTANT]</p>
<ul>
<li>If urllib3 is not installed with the optional
<code>urllib3[brotli]</code> extra, but your environment contains a
Brotli/brotlicffi/brotlipy package anyway, make sure to upgrade it to at
least Brotli 1.2.0 or brotlicffi 1.2.0.0 to benefit from the security
fixes and avoid warnings. Prefer using <code>urllib3[brotli]</code> to
install a compatible Brotli package automatically.</li>
<li>If you use custom decompressors, please make sure to update them to
respect the changed API of
<code>urllib3.response.ContentDecoder</code>.</li>
</ul>
</blockquote>
<h2>Features</h2>
<ul>
<li>Enabled retrieval, deletion, and membership testing in
<code>HTTPHeaderDict</code> using bytes keys. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3653">#3653</a>)</li>
<li>Added host and port information to string representations of
<code>HTTPConnection</code>. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3666">#3666</a>)</li>
<li>Added support for Python 3.14 free-threading builds explicitly. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3696">#3696</a>)</li>
</ul>
<h2>Removals</h2>
<ul>
<li>Removed the <code>HTTPResponse.getheaders()</code> method in favor
of <code>HTTPResponse.headers</code>. Removed the
<code>HTTPResponse.getheader(name, default)</code> method in favor of
<code>HTTPResponse.headers.get(name, default)</code>. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3622">#3622</a>)</li>
</ul>
<h2>Bugfixes</h2>
<ul>
<li>Fixed redirect handling in <code>urllib3.PoolManager</code> when an
integer is passed for the retries parameter. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3649">#3649</a>)</li>
<li>Fixed <code>HTTPConnectionPool</code> when used in Emscripten with
no explicit port. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3664">#3664</a>)</li>
<li>Fixed handling of <code>SSLKEYLOGFILE</code> with expandable
variables. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3700">#3700</a>)</li>
</ul>
<h2>Misc</h2>
<ul>
<li>Changed the <code>zstd</code> extra to install
<code>backports.zstd</code> instead of <code>zstandard</code> on Python
3.13 and before. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3693">#3693</a>)</li>
<li>Improved the performance of content decoding by optimizing
<code>BytesQueueBuffer</code> class. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3710">#3710</a>)</li>
<li>Allowed building the urllib3 package with newer setuptools-scm v9.x.
(<a
href="https://redirect.github.com/urllib3/urllib3/issues/3652">#3652</a>)</li>
<li>Ensured successful urllib3 builds by setting Hatchling requirement
to ≥ 1.27.0. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3638">#3638</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/urllib3/urllib3/blob/main/CHANGES.rst">urllib3's
changelog</a>.</em></p>
<blockquote>
<h1>2.6.0 (2025-12-05)</h1>
<h2>Security</h2>
<ul>
<li>Fixed a security issue where streaming API could improperly handle
highly
compressed HTTP content (&quot;decompression bombs&quot;) leading to
excessive resource
consumption even when a small amount of data was requested. Reading
small
chunks of compressed data is safer and much more efficient now.
(<code>GHSA-2xpw-w6gg-jr37
&lt;https://github.com/urllib3/urllib3/security/advisories/GHSA-2xpw-w6gg-jr37&gt;</code>__)</li>
<li>Fixed a security issue where an attacker could compose an HTTP
response with
virtually unlimited links in the <code>Content-Encoding</code> header,
potentially
leading to a denial of service (DoS) attack by exhausting system
resources
during decoding. The number of allowed chained encodings is now limited
to 5.
(<code>GHSA-gm62-xv2j-4w53
&lt;https://github.com/urllib3/urllib3/security/advisories/GHSA-gm62-xv2j-4w53&gt;</code>__)</li>
</ul>
<p>.. caution::</p>
<ul>
<li>
<p>If urllib3 is not installed with the optional
<code>urllib3[brotli]</code> extra, but
your environment contains a Brotli/brotlicffi/brotlipy package anyway,
make
sure to upgrade it to at least Brotli 1.2.0 or brotlicffi 1.2.0.0 to
benefit from the security fixes and avoid warnings. Prefer using
<code>urllib3[brotli]</code> to install a compatible Brotli package
automatically.</p>
</li>
<li>
<p>If you use custom decompressors, please make sure to update them to
respect the changed API of
<code>urllib3.response.ContentDecoder</code>.</p>
</li>
</ul>
<h2>Features</h2>
<ul>
<li>Enabled retrieval, deletion, and membership testing in
<code>HTTPHeaderDict</code> using bytes keys.
(<code>[#3653](https://github.com/urllib3/urllib3/issues/3653)
&lt;https://github.com/urllib3/urllib3/issues/3653&gt;</code>__)</li>
<li>Added host and port information to string representations of
<code>HTTPConnection</code>.
(<code>[#3666](https://github.com/urllib3/urllib3/issues/3666)
&lt;https://github.com/urllib3/urllib3/issues/3666&gt;</code>__)</li>
<li>Added support for Python 3.14 free-threading builds explicitly.
(<code>[#3696](https://github.com/urllib3/urllib3/issues/3696)
&lt;https://github.com/urllib3/urllib3/issues/3696&gt;</code>__)</li>
</ul>
<h2>Removals</h2>
<ul>
<li>Removed the <code>HTTPResponse.getheaders()</code> method in favor
of <code>HTTPResponse.headers</code>.
Removed the <code>HTTPResponse.getheader(name, default)</code> method in
favor of <code>HTTPResponse.headers.get(name, default)</code>.
(<code>[#3622](https://github.com/urllib3/urllib3/issues/3622)
&lt;https://github.com/urllib3/urllib3/issues/3622&gt;</code>__)</li>
</ul>
<h2>Bugfixes</h2>
<ul>
<li>Fixed redirect handling in <code>urllib3.PoolManager</code> when an
integer is passed
for the retries parameter.
(<code>[#3649](https://github.com/urllib3/urllib3/issues/3649)
&lt;https://github.com/urllib3/urllib3/issues/3649&gt;</code>__)</li>
<li>Fixed <code>HTTPConnectionPool</code> when used in Emscripten with
no explicit port.
(<code>[#3664](https://github.com/urllib3/urllib3/issues/3664)
&lt;https://github.com/urllib3/urllib3/issues/3664&gt;</code>__)</li>
<li>Fixed handling of <code>SSLKEYLOGFILE</code> with expandable
variables.
(<code>[#3700](https://github.com/urllib3/urllib3/issues/3700)
&lt;https://github.com/urllib3/urllib3/issues/3700&gt;</code>__)</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/urllib3/urllib3/commit/720f484b605f18887a48eef448d0084e2b76902d"><code>720f484</code></a>
Release 2.6.0</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/24d7b67eac89f94e11003424bcf0d8f7b72222a8"><code>24d7b67</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/c19571de34c47de3a766541b041637ba5f716ed7"><code>c19571d</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/816fcf04528bc0f89672e13398eb813dcc892490"><code>816fcf0</code></a>
Bump actions/setup-python from 6.0.0 to 6.1.0 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3725">#3725</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/18af0a10efc4c99dd028f7ad5a461470b9a8b0fd"><code>18af0a1</code></a>
Improve speed of <code>BytesQueueBuffer.get()</code> by using memoryview
(<a
href="https://redirect.github.com/urllib3/urllib3/issues/3711">#3711</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/1f6abac3e6d426c3939b8a17cf4afa099e691ab2"><code>1f6abac</code></a>
Bump versions of pre-commit hooks (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3716">#3716</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/1c8fbf787b8e6ed151842c5d6874c9d5bdbf1d0b"><code>1c8fbf7</code></a>
Bump actions/checkout from 5.0.0 to 6.0.0 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3722">#3722</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/7784b9eee95b7c90802c02b111e98df70259ae4f"><code>7784b9e</code></a>
Add Python 3.15 to CI (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3717">#3717</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/0241c9e7286d3008e3cce18effc13b40dc633385"><code>0241c9e</code></a>
Updated docs to reflect change in optional zstd dependency from
<code>zstandard</code> t...</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/7afcabb6489d9a8ea95a40e5afcb46463af17351"><code>7afcabb</code></a>
Expand environment variable of SSLKEYLOGFILE (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3705">#3705</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/urllib3/urllib3/compare/2.5.0...2.6.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=urllib3&package-manager=pip&previous-version=2.5.0&new-version=2.6.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-06 08:05:24 +00:00
Richard Smith 7fd62ff58d Stop using ImplWitness[Table] for a C++ synthesized witness. (#6451)
Add a `CppWitness` and use it instead of using `ImplWitness` with an
`ImplId` and `SpecificId` of `None`. This witness can be substantially
simpler because we never need a `SpecificId`.
2025-12-05 21:07:07 +00:00
Richard SmithandJon Ross-Perkins d208e950c7 Encapsulate clang::ASTUnit in SemIR::CppFile. (#6459)
This intends to avoid proliferation of dependencies on the exact API of
`clang::ASTUnit`, and would enable us to more easily switch to a
different approach that gives us more control over the construction of
the Clang AST.

Also remove some unnecessary tracking of the `CppFile` and instead
always retrieve it from the `SemIR::File`.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-12-04 21:05:40 +00:00
Dana Jansens 78025fed70 Document the relationship of AddCanonicalWitnessesBlock to IdentifiedFacetType (#6461)
The ordering of FacetTypeInfo is not important to the canonical ordering
of witnesses. The order that must match is that of the
IdentifiedFacetType::required_interfaces.
2025-12-04 17:49:30 +00:00
dependabot[bot] e462f430db Bump the npm_and_yarn group across 1 directory with 1 update (#6462)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [jws](https://github.com/brianloveswords/node-jws).

Updates `jws` from 3.2.2 to 3.2.3
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/brianloveswords/node-jws/releases">jws's
releases</a>.</em></p>
<blockquote>
<h2>v3.2.3</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, addressing a compatibility issue for
Node &gt;= 25.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/auth0/node-jws/blob/master/CHANGELOG.md">jws's
changelog</a>.</em></p>
<blockquote>
<h2>[3.2.3]</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, adressing a compatibility issue for
Node &gt;= 25.</li>
</ul>
<h2>[3.0.0]</h2>
<h3>Changed</h3>
<ul>
<li><strong>BREAKING</strong>: <code>jwt.verify</code> now requires an
<code>algorithm</code> parameter, and
<code>jws.createVerify</code> requires an <code>algorithm</code> option.
The <code>&quot;alg&quot;</code> field
signature headers is ignored. This mitigates a critical security flaw
in the library which would allow an attacker to generate signatures with
arbitrary contents that would be accepted by <code>jwt.verify</code>.
See
<a
href="https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/">https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/</a>
for details.</li>
</ul>
<h2><a
href="https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0">2.0.0</a>
- 2015-01-30</h2>
<h3>Changed</h3>
<ul>
<li>
<p><strong>BREAKING</strong>: Default payload encoding changed from
<code>binary</code> to
<code>utf8</code>. <code>utf8</code> is a is a more sensible default
than <code>binary</code> because
many payloads, as far as I can tell, will contain user-facing
strings that could be in any language. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</p>
</li>
<li>
<p>Code reorganization, thanks <a
href="https://github.com/fearphage"><code>@​fearphage</code></a>! (<!--
raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/7880050">7880050</a><!--
raw HTML omitted -->)</p>
</li>
</ul>
<h3>Added</h3>
<ul>
<li>Option in all relevant methods for <code>encoding</code>. For those
few users
that might be depending on a <code>binary</code> encoding of the
messages, this
is for them. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/auth0/node-jws/commit/4f6e73f24df42f07d632dec6431ade8eda8d11a6"><code>4f6e73f</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/auth0/node-jws/commit/bd0fea57f35a97b6749a632b19ae5100d6d35729"><code>bd0fea5</code></a>
version 3.2.3</li>
<li><a
href="https://github.com/auth0/node-jws/commit/7c3b4b411004c206af8901fa3f8e644127bbf8d9"><code>7c3b4b4</code></a>
Enhance tests for HMAC streaming sign and verify</li>
<li><a
href="https://github.com/auth0/node-jws/commit/a9b8ed999de8f8fff486ac9167514577a0fae323"><code>a9b8ed9</code></a>
Improve secretOrKey initialization in VerifyStream</li>
<li><a
href="https://github.com/auth0/node-jws/commit/6707fde62cbae465a7f11e52760fb994dbc0e0dc"><code>6707fde</code></a>
Improve secret handling in SignStream</li>
<li>See full diff in <a
href="https://github.com/brianloveswords/node-jws/compare/v3.2.2...v3.2.3">compare
view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by <a
href="https://www.npmjs.com/~julien.wollscheid">julien.wollscheid</a>, a
new releaser for jws since your current version.</p>
</details>
<br />

Updates `jws` from 4.0.0 to 4.0.1
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/brianloveswords/node-jws/releases">jws's
releases</a>.</em></p>
<blockquote>
<h2>v3.2.3</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, addressing a compatibility issue for
Node &gt;= 25.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/auth0/node-jws/blob/master/CHANGELOG.md">jws's
changelog</a>.</em></p>
<blockquote>
<h2>[3.2.3]</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, adressing a compatibility issue for
Node &gt;= 25.</li>
</ul>
<h2>[3.0.0]</h2>
<h3>Changed</h3>
<ul>
<li><strong>BREAKING</strong>: <code>jwt.verify</code> now requires an
<code>algorithm</code> parameter, and
<code>jws.createVerify</code> requires an <code>algorithm</code> option.
The <code>&quot;alg&quot;</code> field
signature headers is ignored. This mitigates a critical security flaw
in the library which would allow an attacker to generate signatures with
arbitrary contents that would be accepted by <code>jwt.verify</code>.
See
<a
href="https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/">https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/</a>
for details.</li>
</ul>
<h2><a
href="https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0">2.0.0</a>
- 2015-01-30</h2>
<h3>Changed</h3>
<ul>
<li>
<p><strong>BREAKING</strong>: Default payload encoding changed from
<code>binary</code> to
<code>utf8</code>. <code>utf8</code> is a is a more sensible default
than <code>binary</code> because
many payloads, as far as I can tell, will contain user-facing
strings that could be in any language. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</p>
</li>
<li>
<p>Code reorganization, thanks <a
href="https://github.com/fearphage"><code>@​fearphage</code></a>! (<!--
raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/7880050">7880050</a><!--
raw HTML omitted -->)</p>
</li>
</ul>
<h3>Added</h3>
<ul>
<li>Option in all relevant methods for <code>encoding</code>. For those
few users
that might be depending on a <code>binary</code> encoding of the
messages, this
is for them. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/auth0/node-jws/commit/4f6e73f24df42f07d632dec6431ade8eda8d11a6"><code>4f6e73f</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/auth0/node-jws/commit/bd0fea57f35a97b6749a632b19ae5100d6d35729"><code>bd0fea5</code></a>
version 3.2.3</li>
<li><a
href="https://github.com/auth0/node-jws/commit/7c3b4b411004c206af8901fa3f8e644127bbf8d9"><code>7c3b4b4</code></a>
Enhance tests for HMAC streaming sign and verify</li>
<li><a
href="https://github.com/auth0/node-jws/commit/a9b8ed999de8f8fff486ac9167514577a0fae323"><code>a9b8ed9</code></a>
Improve secretOrKey initialization in VerifyStream</li>
<li><a
href="https://github.com/auth0/node-jws/commit/6707fde62cbae465a7f11e52760fb994dbc0e0dc"><code>6707fde</code></a>
Improve secret handling in SignStream</li>
<li>See full diff in <a
href="https://github.com/brianloveswords/node-jws/compare/v3.2.2...v3.2.3">compare
view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by <a
href="https://www.npmjs.com/~julien.wollscheid">julien.wollscheid</a>, a
new releaser for jws since your current version.</p>
</details>
<br />


Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-04 17:43:08 +00:00
Jon Ross-Perkins 103c49a763 Canonicalize imported witness blocks on FacetValue (#6458)
The test has a more complete explanation of this; witnesses on the
FacetValue must have a canonical ordering.
2025-12-04 00:05:24 +00:00
f000194d8b Make a couple of parts of our infrastructure more robust. (#6455)
Don't CHECK-fail when trying to format invalid SemIR with an ImplWitness
whose table_id isn't an ImplWitnessTable. We use SemIR formatting as a
debugging aid, so it's good for it to be robust even in the presence of
invalid SemIR.

Don't crash if a typed instruction has no type_id field and has a
constant kind of Always. We don't have any instructions like that at the
moment.

These caused problems while working on #6451, and while I ended up not
needing either fix for that PR, they both seem like they may be worth
keeping to save some trouble for the next person who hits these.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-12-03 19:24:39 +00:00
Chandler Carruth 5d0d443c98 Move the :install_paths library to //toolchain/base (#6457)
Previously this was kept in `//toolchain/install` so it would be near to
the code that actually defines the installation layout. However, that
creates somewhat unfortunate dependency cycles between
`//toolchain/install` and other directories. Exacerbating this, a
subsequent PR is likely to add dependencies on it from
`//toolchain/base` itself that suggests that is the correct layering.

This PR just moves the code mechanically with as few other edits as
possible.
2025-12-03 17:14:34 +00:00
Ivana Ivanovska 4ddff65e8e Add support for macros pointing to a constexpr integer (#6441)
Similarly to the enums, these are for the moment only available when
referenced with a global scope “::”. Only integer constexpr are
available for now.

Part of #6303
2025-12-03 15:31:37 +00:00
Ivana Ivanovska a2821be1be Dump SemIR for all passing macros tests (#6454)
Some of the macros tests were not printing the SemIR. Printing it can
help spot issues (as in PR #6440), so added that now for all passing
tests.

Part of #6303
2025-12-03 12:28:32 +00:00
Richard Smith c77eebd15e Cache final impl lookup results. (#6452)
If an impl lookup finds a final result, cache that and reuse it if we
perform the same lookup later.

In addition to reducing repeated work, this allows us to produce the
same result for repeated lookups that find a C++ operator. This isn't a
great solution to that problem, as it's not clear how to extend it to
behave correctly across import, but we don't have a solution for that
for C++ interop in general.
2025-12-02 22:51:25 +00:00
Dana Jansens e5c94b193d Use the new IsFacetTypeOrError function (#6438)
It is introduced in #6434
2025-12-02 22:33:55 +00:00
Dana Jansens e32190a228 Stringify specifics of named constraints (#6444) 2025-12-02 19:31:13 +00:00
Dana Jansens 73e6994d44 Add a diagnostic note for errors during identifying facet types (#6445)
Errors that occur while constructing a specific should be tied back to
the facet type being identified. We don't have an InstId for the facet
type during identify, so provide the means to Stringify a FacetTypeId.

Depends on https://github.com/carbon-language/carbon-lang/pull/6435
2025-12-02 17:21:53 +00:00
372f632d9d Implement support for copying C++ classes. (#6434)
When performing impl lookup for `Core.Copy` for a C++ class type, look
for a copy constructor. If we find one, synthesize an impl witness that
calls the constructor.

This adds initial support for impl lookup to delegate to the C++ interop
logic for queries involving C++ types. For now, we don't implement the
rules from #6166 that compare a synthesized type structure for the C++
impl against the best Carbon type structure, but the framework for
building that support is established here.

Currently there is no caching of the lookup here, and we build unique
`ImplWitnessTable`s for each lookup, which leads to each impl lookup
producing a distinct facet value. This results in some errors in generic
contexts; this will be addressed in follow-up changes. This PR aims only
to support the non-generic case.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-12-02 02:52:23 +00:00
Dana Jansens 19660ccde0 Add lldbinit.py to the lldb launch command for VSCode (#6447)
This gives access to the `dump` command
2025-12-02 01:55:26 +00:00
Dana Jansens 6a60b80508 Remove the FacetTypeId in RequireImpls (#6437)
The FacetTypeId should never be used directly, since the RequireImpls is
a generic and the facet type may be parameterized by generic bindings.
So instead, it should be accessed through GetConstantValueInSpecific,
which works with the facet type InstId that is also already present on
RequireImpls. This change to use GetConstantValueInSpecific was done in
#6435, so the FacetTypeId is now unused except in formatting. So we can
remove it.

This depends on #6435.
2025-12-01 20:34:43 +00:00
Dana Jansens 25536cab67 Avoid a crash when the type of Self in an interface or constraint is an error (#6443)
The RequireImpls handler needs to deal with this gracefully.
2025-12-01 19:09:14 +00:00
Dana Jansens 0cf2448505 Get specific interfaces with correct specific from named constraints (#6435)
When forming an IdentifiedFacetType, we collect interfaces named by
require decls in named constraints that the facet type refers to. These
interfaces come with a specific, but the require decl is inside an named
constraint which may be generic. So we need the specific being applied
to the containing named constraint to also be applied to the require
decl and its target interfaces.

This uncovered that the facet type in require decls was not being
imported correctly, as it was not being attached to the require decl's
generic. This is fixed by making import of RequireImplsDecl multiphase,
so that the decl instruction exists before we resolve the facet type
within it. And by pointing the generic importing machinery to the
RequireImplsDecl, and from there to the RequireImpls structure to get
the generic id.

Then `ImplStore::GetOrAddLookupBucket` can use an IdentifiedFacetType to
correctly get the interface being impl'd, both in the local and the
imported named constraint case. Which allows us to correctly diagnose
redeclarations in the impl file of an impl of an interface through a
named constraint. And to correctly _not_ diagnose them when the specific
in the generic named constraint differs from other decls.
2025-12-01 18:59:02 +00:00
Ivana Ivanovska 108e39e095 Fix SemIR printout for string literals in macros (#6440)
Added SemIR printout for string literals in macros in the tests. Removed
adding the inst in the imports to make the printout succeed.

Part of #6303
2025-11-28 16:34:25 +00:00
Boaz Brickner 2073594d8a C++ Interop: Add implicit casting between int literals and CppCompat integers (#6442)
Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2025-11-28 08:49:47 +00:00
Chandler Carruth 217c7ba0b2 Begin building libc++ and libc++abi runtimes on demand (#6424)
This builds on the previous work to flesh out more on-demand runtimes
building. It adds building of the `libc++.a` archive runtime.

A number of changes are required for this to work:

- The runtimes build infrastructure needs to support building sources
  from multiple parts of LLVM rather than a single part. We do this by
  lifting the root of the runtimes source paths up a level to a common
  runtimes tree, and installing the runtimes sources below this
  directory.

- Both libc++ and libc++abi runtimes sources need to be installed, and
  we even need to install some interesting parts of llvm-libc that are
  used in the build of libc++.

- We need to generate the site configuration header file for libc++ from
  the CMake template. This includes both setting up a set of
  platform-independent defines and introducing some basic Bazel support
  for processing the CMake template itself.

Doing all of this also exposed some missing features and limitations of
the runtimes building infrastructure that are addressed here.

One note is that all of this just adds libc++ to the explicit
`build-runtimes` command for testing. It doesn't yet trigger
automatically building these prior to linking, or configuring any of the
other subcommands to automatically use these runtimes. All of that will
come in follow-up PRs.

Also, this makes the `clang_runtimes_test` ... _very_ slow in our
default build configuration. Compiling libc++, even with many threads on
a large Linux server requires up to 50 seconds. I'm open to any
suggestions on how to handle this, including disabling the test in
non-optimized builds. I have some ideas to speed this up, but
fundamentally building libc++ is... not cheap.

I did look at some of the existing Bazel tools to process the CMake
template, but they all seemed significantly more complex than what we
need and didn't have broad adoption. Given that, it seemed slightly
better to just roll our own given the simple format.

Two of the new LLVM patch are currently under review upstream and so
hopefully temporary:

- https://github.com/llvm/llvm-project/pull/169155
- https://github.com/llvm/llvm-project/pull/169292
2025-11-27 02:16:51 +00:00
Boaz Brickner bef92cf881 Add CppCompat.ULong32, CppCompat.LongLong64 and CppCompat.ULongLong64 (#6386)
This extends #6364 to allow having:
* `Cpp.unsigned_long` as a distinct type when `unsigned long` is 32
bits.
* `Cpp.long_long` and `Cpp.unsigned_long_long` as distinct types when
`long` and `unsigned long` are 64 bits.

Similarly to #6364, we only support implicit conversions from the
matching literal type (`u32`, `i64` and `u64`).

See #6275 for rationale.

Part of #5263.
2025-11-26 16:51:22 +00:00
Chandler Carruth 05fd656bdb Reduce the minimum benchmark batch size (#6436)
Even with `--benchmark_dry_run`, the benchmarks that use _batching_
still do one batch at a minimum as that's inherent to how batching works
in the benchmark framework.

This means that the minimum batch size can (and in practice does)
trigger timeouts by forcing 1k iterations in the test run that is just
trying to ensure the benchmark doesn't _crash_ in some way.

Reduce the minimum size to 128 instead of 1k for this benchmark which
should put it (much) further from any timeout limit. It also still seems
perfectly effective for getting good benchmark data -- I think the
original value was set _much_ too aggressively.
2025-11-26 16:23:31 +00:00
Ivana Ivanovska e7b71c031a Add a failing test for user-defined literals in macros (#6431)
These types of literals are not supported at the moment, adding a `todo`
test for it.

Part of #6303
2025-11-26 14:58:39 +00:00
David BlaikieandDana Jansens a179bd461b Start plumbing through debug info type information with function parameters/return value (#6410)
This adds just enough debug info for i32/int parameters and return
values, with a path forward for adding DWARF type metadata for other
types.

As it happens, return type information is carried separately from
parameter information:
* Return type information is carried in the `type` of the `DISubprogram`
  (as a `DISubroutineType` - which does carry parameter type information
  as well, but that's unused when the DWARF is emitted by LLVM)
* Parameter information is carried by `DILocalVariable`s with a non-zero
  `arg` value (representing the order of function parameters)

In the absence of locations for the parameters (future work), nothing
would usually keep the `DILocalVariable` live/reachable when emitting
DWARF - so for cases where this can happen (for clang, this happens in
optimized builds where all references to the parameter variable might be
optimized away) the variables can be "retained" in a list on the
`DISubprogram` - achieved by passing `AlwaysPreserve` parameter to
`createParameterVariable` (adds them to a list, then that list gets
attached to the `DISubprogram` when it's finalized later)

For now, any unsupported types are emitted as `void*` (except void
return, which is implemented as void) as a placeholder.

Given this example:
```
import Core library "io";
class MyClass {
}
fn Unsupported(v: MyClass) {
}
fn Ret() -> i32 {
  return 42;
}
fn Arg(x: i32) {
  Core.Print(x);
}
fn Run() {
}
```
this is the resulting DWARF:
```
DW_TAG_compile_unit
  DW_AT_name    ("test.carbon")
  DW_TAG_subprogram
    DW_AT_name  ("Unsupported")
    DW_TAG_formal_parameter
      DW_AT_type        (0x00000066 "void *")
  DW_TAG_subprogram
    DW_AT_name  ("Ret")
    DW_AT_type  (0x00000062 "int")
  DW_TAG_subprogram
    DW_AT_name  ("Arg")
    DW_TAG_formal_parameter
      DW_AT_type        (0x00000062 "int")
  DW_TAG_subprogram
    DW_AT_name  ("Run")
  DW_TAG_base_type
    DW_AT_name  ("int")
  DW_TAG_pointer_type
```
And the debugger:
```
(gdb) p Ret()
$1 = 42
(gdb) p Arg(4)
4
$2 = void
```

I'm not sure if there's a way this logic should be merged with the logic
for making the `llvm::Function` type (which the `DISubroutineType`
building code was inspired by/copied from) - since they're done at
different times/places, I don't think there's an easy way to do it in
one pass, but maybe the code can be shared (even if it's run twice) in
some generic `SemIR::Function` type walker.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-11-25 23:25:09 +00:00
0baa74d96f Type completeness in extend (#6395)
Define rules for `extend` declarations (`extend require`, `extend impl
as`, `extend base`, `extend adapt`) that say the target scope they name
must be complete at the point of the declaration. Define completeness
for a facet type to include all interfaces and named constraints that
provide unqualified name lookup through the facet type.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-11-25 22:45:34 +00:00
Richard Smith ec8c999bb1 Support passing Carbon Optional(T*) to C++ T* parameter. (#6422)
We already did this translation in the other direction, but we had no
mapping from `Optional(T)` to anything, so round-tripping a nullable
pointer from C++ through Carbon and back to C++ was previously rejected.
2025-11-25 22:30:14 +00:00
Jon Ross-Perkins 6b775b3014 Switch benchmark tests to dry_run from min_time (#6433)
Trying to work around failures such as
https://github.com/carbon-language/carbon-lang/actions/runs/19680163053/job/56371861907...
min_time is only setting the minimum number of iterations, so the
benchmark framework is validly choosing to run 1k times. dry_run should
only run 1 repetition, making this both faster and more reliable in
terms of execution time.
https://google.github.io/benchmark/user_guide.html#running-benchmarks
for flag documentation.
2025-11-25 20:15:05 +00:00
Jon Ross-Perkins 93a8c5230c Ensure a symbolic final impl has a definition produced (#6236)
Right now, the impl lookup can both fail to resolve the specific
definition because it's symbolic, and return a "final" constant because
it's a `final impl`. This is adding an instruction to help ensure the
specific is resolved.

The constant evaluation is fully recursive, but I'm not adding a TODO
since that's a known issue with impl lookup in general.
2025-11-25 18:59:25 +00:00
Ivana Ivanovska cf2c66c1b2 Add support for macros evaluating to an enum constant (#6432)
Enum constants in a macro replacement list are recognized only when
prefixed with “::”.
There is a `todo` test to make explicit that this still needs to be
fixed.
When prefixed with a global scope “::”, they are correctly found and
evaluated to a const.


Part of #6303
2025-11-25 17:44:07 +00:00
Jon Ross-Perkins 44d86e11bb Minor uses of import_* in import_ref (#6428)
Just refactoring calls to use shorter names.
2025-11-25 01:08:29 +00:00
Chandler Carruth 3a293a7c42 Update LLVM to trunk from 2025-11-22 (#6423)
This also adds requisite dependencies and updates.
2025-11-24 23:04:49 +00:00
Richard SmithandJon Ross-Perkins 054dfca685 Perform overload resolution immediately in C++ operator lookup. (#6416)
Don't attempt to defer overload resolution by creating a
`CppOverloadSet`; this was incorrect as we weren't saving the complete
clang::OverloadCandidateSet, resulting in template candidates not being
found. Moreover, saving the overload candidate set would be expensive,
as the representation is surprisingly large, and is unnecessary since
we're about to build a call.

In passing, improve the diagnostics for overload resolution failure to
use Clang's operator overload resolution messages rather than its call
overload resolution messages.

This fixes calls to templated operator overloads, which is the final
piece needed for us to successfully compile an iostream-based "Hello
world" program.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-11-24 23:01:28 +00:00
Jon Ross-Perkins 167b45ca35 Rewrite pending specifics to use the work stack (#6415)
I was trying to figure out the right way to get specifics to be added to
the work.

Technically, we could keep the pending_specific list; this is taking a
different approach of inserting inside the work stack, which will do
extra work moving entries, although typically that should be expected to
be small. One challenge of `pending_specifics` is that if we would need
to shift them to work after both `Done` (for immediate processing) and
`Retry` (for processing after the current instruction is later revisited
and done). That feels kind of awkward as additional tracking to do.
Also, the common case is probably that there's either 0 or 1 specifics
being added, so an additional vector may be significant overhead. That's
why I leaned more in this direction of just inserting them in the vector
of work.
2025-11-24 21:52:29 +00:00
Ivana Ivanovska 109e39c75c Add support for nullptr literals in macros (#6426)
Adding support for macros that evaluate to nullptr literal.

Demo:

```c++
// macros.h
void foo(int a[2]);
#define MyNullPtr nullptr
```
```c++
// macros.cpp
void foo(int a[2]) {
  if (!a) {
    printf("array a is nullptr\n");
    return;
  }
  printf("a[0] = %d \n", a[0]);
}
```

```c++
// main.carbon

library "Main";

import Cpp library "macros.h";

fn Run() -> i32 {
  Cpp.foo(Cpp.MyNullPtr);
  return 0;
}
```

```
$ clang -c macros.cpp;
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link macros.o main.o \--output=demo_carbon
$ ./demo_carbon
array a is nullptr
```

Part of #6303
2025-11-24 21:03:35 +00:00
Richard Smith 62cb185739 Fix typo in proposal rationale. (#6427) 2025-11-24 19:48:31 +00:00
Ivana Ivanovska 7be6538aec Add support for character literals in macros (#6419)
Adding support for macros with character literals.

Part of #6303
2025-11-24 13:54:17 +00:00
Ivana Ivanovska 093700b274 Add support for boolean literals in macros (#6418)
Adding support for macros with boolean literals.

Demo:

```c++
// main.carbon

library "Main";

import Core library "io";

import Cpp inline '''
  #define M_TRUE true
''';

fn Run() -> i32 {
  let a: bool = Cpp.M_TRUE;
  if (a) {
    Core.Print(1);
  } else {
    Core.Print(0);
  }
  return 0;
}
```

```
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o \--output=demo_carbon
$ ./demo_carbon
1
```

Part of #6303
2025-11-24 10:40:57 +00:00
Dana Jansens 201e408252 Type completion of facet types is separate from Identifying (#6385)
Identifying a facet type is an operation on a pair of (self type, facet
type). It substitutes that self in as the `Self` of any require
declarations in order to form the set of (self type, SpecificInterface)
pairs that constitute the requirements of the IdentifiedFacetType.
Currently we don't pass around any self type, and assume all require
declarations are written against `Self` but this will change in the
future.

By contrast, type completion is done in the abstract and does not form
specifics for the require declarations. The purpose of type completion
is to enumerate the scopes where name lookup can occur and ensure they
are completed.

With this change, type completion is:
- No longer built on top of identification for facet types.
- Recursively ensures all `extend` scopes are complete since name lookup
can find symbols in them.

We add some test cases that demonstrate consistency between a resolving
the specific of a generic class, and a generic interface/constraint,
both used in a type position. In all cases, an invalid specific is not
materialized for the type completion when the specific's arguments are
used in a non-extend context. But they specific is materialized and
checked for type completion when in an extend context (extend impl or
extend require).

Type completion itself does not need to recurse into named constraints
or interfaces as the `extend require` declarations require the type to
be complete immediately, just as for `extend impl` in a class.

We had a test (`fail_incomplete_where.carbon`) with `impl as J where
.Self impls K` and `J` is incomplete, which used to be diagnosed but no
longer is, because we don't require non-extend interfaces to be complete
in type completion, nor in identification. The test was trying to test
the presence of rewrite constraints though, which it didn't even use. So
we remove the diagnostic that we can't hit anymore and replaced it with
a TODO, and add a test that should reach that TODO once qualified
rewrite constraints work.
2025-11-21 22:28:08 +00:00
Chandler Carruth 56bbced70c Add basic testing of libunwind.a runtimes build (#6417)
This builds the archive and checks relevant symbols are defined. While
here, this refactors the runtimes test to share much more code between
the different runtimes.

Last but not least, this adds a convenience type-def for the libunwind
runtimes builder.

There is an inconsistency between how we spell things as `Libunwind` or
`LibUnwind`. We should canonicalize on the former as it matches the
underscores and other things we will spell in this space. I'm not fixing
existing spellings in this PR but will send follow-ups for those.
2025-11-21 19:55:29 +00:00
Richard Smith 13fbe3c1f3 Allow interop with classes with virtual base classes. (#6413)
For now, treat such classes as being final, since we can't correctly
derive from them.

This removes the last category of C++ class that we are entirely unable
to interop with, and is a prerequisite for interop with C++ iostreams
(which have a virtual base class).
2025-11-21 16:45:38 +00:00
Ivana Ivanovska 8866e39085 Add support for string literals in macros (#6408)
Adding support for macros with string literals.

Part of #6303
2025-11-21 12:33:18 +00:00
Chandler CarruthandDana Jansens 00ee693833 Teach create_compdb.py to propagate Bazel flags (#6406)
For example, when developing against a checkout of LLVM, it is useful to
be able to consistently pass an override flag to Bazel for that
repository.

This lets:

```console
bazel test --override_repository=+_repo_rules+llvm-raw=$HOME/src/llvm/llvm-project //toolchain/...
```

and

```console
./scripts/create_compdb.py --extra-bazel-flag=--override_repository=+_repo_rules+llvm-raw=$HOME/src/llvm/llvm-project
```

Share the same Bazel cache and use the same flags.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-11-21 01:41:36 +00:00
Jon Ross-Perkins 844c1366cb Remove TODO about generic import order (#6414)
Pointed out by danakj
2025-11-21 00:08:19 +00:00
Jon Ross-PerkinsandDana Jansens 01a7c79c41 Proposing helpers to reduce some facet type boilerplate (#6412)
About the same # of LOC, but maybe less work to analyze correctness?

Versus the template, could also stamp that out in the helper function
and still avoid the duplication of calls before/after HasNewWork.
Similar to how I've left `rewrite_constraints`.

Alternately I'm also kind of tempted to rename GetLocalSpecificInterface
and GetLocalSpecificNamedConstraint to instead be overloaded functions
(or to provide overloaded versions), which would allow this to drop the
function type parameters. But, naming is hard.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-11-20 23:07:04 +00:00
Jon Ross-Perkins 972854e834 In import, replace MakeSelfSpecific with GetOrAddLocalSpecific (#6409)
This is just making `self_specific_id` behave more consistently with
respect to other specific imports.
2025-11-20 21:44:10 +00:00
Chandler Carruth bff6ec4f82 Update dependency testing for the internal LLVM repo (#6407)
This test started failing with #6405, but it wasn't caught by our PR
testing or the merge queue as the test didn't _appear_ to be impacted by
the change (I think).

When run explicitly, as the post-commit actions do, it started failing
because of the new dependency edge.
2025-11-20 14:53:10 +00:00
Ivana Ivanovska 994e6c904d Add support for macros with floating-point literals (#6391)
Adding support for floating-point literals in macros.

Part of #6303
2025-11-20 12:49:43 +00:00
Chandler Carruth 13dd21878e Extract the CC1 logic to third_party location (#6405)
This clarifies that the CC1 logic is directly extracted from Clang.
There are probably some other places in the toolchain we should extract
code like this where we're replicating and customizing logic from LLVM,
but wanted to start here.
2025-11-20 05:13:05 +00:00
Jon Ross-Perkins 8779b8f64b Replace pending generic logic with work stack-based logic (#6404)
This continues work to eliminate pending generics/specifics and get them
to be interleaved with instruction imports. I'm trying to use
`FinishGenericOrDone` here as a way to help ensure that code correctly
handles generics, where the simple alternative would be for each
`TryResolveTypedInst` call `SetGenericData` directly (but which might
make it easier to call the wrong `ResolveResult` function, and we do
need the `GenericId`s to be passed).
2025-11-20 01:02:18 +00:00
Richard Smith 6c9a581a83 Switch GetExprCategory to be table-driven. (#6371)
Avoid using a large switch that needs to be manually extended when
adding a new kind of instruction. Instead, the expression category for
an instruction is now specified when defining the `InstKind`.

In passing, add a distinct expression category value for patterns. This
isn't used for much except some error checking at the moment, but it
keeps the number of instructions that we need to manually classify as
`NotExpr` despite having a type very low.
2025-11-20 00:09:10 +00:00
Dana Jansens 2b30157726 Use GlobalReplace for replacing unexpected insts with a regex (#6401)
Replace all unexpected instruction ids in a line, not just the first
one. Otherwise you get something like this:
```
// CHECK:STDOUT: impl @<null name>: <unexpected>.inst{{[0-9A-F]+}}.loc20_6 as <unexpected>.inst6000002E.loc20_11;
```
2025-11-19 22:34:49 +00:00
Jon Ross-Perkins 6b1ef75ac5 Make generic decl resolution happen during non-pending import flow (#6394)
This is just an incremental step towards removing pending logic. The
rest seems like it'll be more complex due to interdependencies (I've
been poking at behavior).
2025-11-19 21:54:25 +00:00
Dana Jansens 4a412e7ab0 Allow fingerprinting instructions to work for the special InstIds (#6400)
Use the index of the special id instead of crashing.

Fixes #6370.
2025-11-19 21:43:07 +00:00
Richard Smith 0678501038 Replace builtin CppVoidType with a prelude type. (#6403)
Following #6357, map C++ `void` to a prelude class type
`Core.CppCompat.VoidBase`, not to a builtin type. This is mostly just
moving logic around, but does notably change `Cpp.void` from being an
incomplete type to being a complete-but-abstract type.

Also change `NullptrT` to be an adapter for `void*` instead of `()*`, to
follow the approved design.

Implicit conversions to `void` and to `void*` are still absent.

Part of #6280.
2025-11-19 20:40:17 +00:00
Dana Jansens da8c9d6132 Avoid reallocation in RelationalValueStore (#6399)
Since `ValueStore` now separates its id and value types as two template
parameters, we can use a `ValueStore` of `optional<ValueType>` as the
storage instead of a `SmallVector`.
2025-11-19 20:15:19 +00:00
David Blaikie 7a400d22b4 Improve CHECK-failure when passing a negative id to a ValueStore #6370 (#6392)
Otherwise the value fails in confusing ways while untagging:

  CHECK failure at ./toolchain/base/value_store.h:71:
  index >= initial_reserved_ids_: When removing tagging bits,
  found an index that shouldn't've been tagged in the first place.

With this change:

  CHECK failure at ./toolchain/base/fixed_size_value_store.h:112:
  id.index >= 0: instFFFFFFFFFFFFFFFD
2025-11-19 18:20:49 +00:00
Dana Jansens f220359a9f Print special ids as their names and don't crash when dumping them (#6398) 2025-11-19 16:58:51 +00:00
Ivana Ivanovska 315b0ac241 Refactor identifier lookup in cpp/import.cpp (#6383)
Following up on the
[comment](https://github.com/carbon-language/carbon-lang/pull/6326#discussion_r2512160370)
from PR #6326, refactoring the identifier lookup to be only once,
instead of both in `LookupMacro` and `ClangLookupName`.

Part of #6303
2025-11-19 13:38:07 +00:00
Jon Ross-Perkins 4a8efd81e3 Rewrite generic binding imports to use AddLoadedImportRef (#6388)
This is part of trying to rewrite pending specific/generic code to make
use of the standard constant resolution flow. The LoadImportRef code was
a particular sticking point due to the recursion it does, which makes it
difficult to adapt over.
2025-11-19 00:56:17 +00:00
Dana Jansens eb0dcc8ce4 Import generic named constraints (#6376)
We add tests showing that `ImplStore::GetOrAddLookupBucket` is doing the
wrong thing for impls of a named constraint, as the impl-file
redeclarations of impls in the api file are not getting flagged as such.
To do the right thing requires us to be able to get the constraint from
a require declaration with the specific of the named
constraint/interface applied, which is future work as described in the
[open discussion
notes](https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.1ji9ixn9bbnn#heading=h.kijomnov90rz).
2025-11-18 22:32:49 +00:00
Geoff Romer 57a2715f10 Remove support for addr (#6375)
Every test that used `addr` before #6283 should be using `ref` after
this PR. In most cases that was done in #6283, but this PR transitions a
few that I missed in that first pass. In addition, #6283 cloned the old
`addr` tests from `foo.carbon` to `foo_addr.carbon` in order to maintain
test coverage during the transition; this PR removes those cloned tests.
2025-11-18 19:48:58 +00:00
Jon Ross-Perkins ee49d65e29 Remove a use of zip/to_array in eval (#6393)
The to_array was mainly needed for zip_equal, and the
GetBlockAsTypeInstIds is forming a vector that should also be size two.
But just writing this out should avoid memory allocations.

Of course, then I'm like "but maybe a lambda or function would be
clearer than a for loop"... So the second commit.
2025-11-18 19:19:40 +00:00
Richard Smith 7c1077c436 C++ Interop: Mapping pointer types (#6357)
This proposal defines direct, zero-overhead mappings from C++ object
pointer
types and `std::nullptr_t` to corresponding Carbon types.
2025-11-18 18:45:46 +00:00
David Blaikie bb9942823f DebugInfo: Emit as "C++" rather than "C" (#6361)
This helps at least lldb handle calling functions (currently the debug
info describes every function as `void()`, so no parameters or return
values are supported) - seems gdb and lldb both depend on demangling to
varying degrees in C code (marking a function as "prototyped" in C in
DWARF does seem to also address this problem).

Given:
```
fn PrintThree() {
  Core.Print(3);
}
```
Before:
```
  (lldb) p PrintThree()
  error: Couldn't look up symbols:
    PrintThree
  Hint: The expression tried to call a function that is not present in
    the target, perhaps because it was optimized out by the compiler.
```
After:
```
  (lldb) p PrintThree()
  3
  (lldb)
```
2025-11-18 18:28:56 +00:00
Chandler Carruth 35274f2620 Actually add the requested comment from review (#6390)
The review of #6380 suggested an expanded comment that I wrote but
apparently didn't hit "save" in the editor for. Doh! This adds it.
2025-11-18 16:42:19 +00:00
Chandler Carruth 3930fb13a5 Begin building libunwind.a as part of the runtimes (#6381)
This is the first real step towards building libc++ itself, and fleshes
out both the core runtimes management logic and the archive-based
runtimes logic for a quite simple runtime.

Nothing here causes us to _use_ libunwind, and in fact this doesn't
include even the "on-demand" aspect of building `libunwind`. Instead,
this just wires it up to the explicit `build-runtimes` subcommand for
simple testing. The full integration along side the target directory is
future work.
2025-11-18 08:23:29 +00:00
Chandler CarruthandDavid Blaikie 77808cd5d7 Refactor Clang runtimes building into async builder (#6380)
Previously, the Clang runtimes building only considered building the
target resource directory, and was only _internally_ asynchronous.
Because the asynchrony was only internal, it could use the function
frame as a context object throughout the build of the resource dir. This
is simple but doesn't generalize well to more runtimes: if we want to
add 2 or 3 more runtimes, we want them to _all_ build asynchronously.
That means using some asynchronous builder that maintains the context
and allows them to proceed concurrently with other work.

This also factors all the runtimes building code into a separate set of
files. These aren't separate libraries at this point due to the
`ClangRunner` in some cases wanting to build runtimes on-demand, but it
at least lets us organize the code more cleanly.

Because this splits code between `clang_runner.*` and
`clang_runtimes.*`, it also works to update the `#include`s for both to
be roughly accurate. I used ClangD's include cleaner for this and it
probably also did some latent cleaning as it went, but that's the reason
for the churn of `#include` lines.

The archive building is also factored out into a re-usable helper. This
is a bit "over factored" in this PR, but supports the next PR that uses
the same code to build archives for other runtimes.

This also overhauls the synchronization used -- it uses a simple `Latch`
construct introduced in a previous PR to coordinate between the steps of
building the runtimes.

Last but not least, it factors the "enable leaking" state out of a
boolean in the runner to a parameter. This is important in the face of
concurrent calls as otherwise toggling this boolean can create a race.

The next PR will layer building more runtimes on top of this new
factoring.

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2025-11-18 06:08:14 +00:00
Jon Ross-Perkins fbc7690157 Switch zip to zip_equal where possible (#6389)
There are two uses I'm not converting here, that seem to want the
"shortest" behavior. For everything else, I'm going to `zip_equal` since
it's more restrictive.

I wish `zip` were named `zip_shortest`.
2025-11-18 00:28:06 +00:00
Chandler Carruth 205aea9a3e Fix flakiness and improve cache test (#6387)
This fixes the flakiness caused by reuse of inode values when refreshing
stale cache entries by keeping the relevant directory open even as it is
unlinked from the filesystem.

It does this in two places, as technically we had the same flakiness in
two tests. However, the second test was broken and not testing what it
intended to due to confusing off-by-one naming and a typo. I've tried to
improve the naming, removed the typo, and added the parallel flakiness
fix.

This test was also egregiously slow because we ended up building too
many runtimes and trying to prune stale runtimes while holding a file
lock on _all_ runtimes -- a scenario that is not what the code was
designed for in the first place. Fixing that makes the test go from 10s
to 1s in runtime, and makes it much easier to test for flakiness.

Now appears to pass 100% of the 10k runs I did.

Closes #6168
2025-11-18 00:24:16 +00:00
Boaz Brickner b5bdfdd857 Rename TypeLiteralInfo to RecognizedTypeInfo (#6384)
Following
https://github.com/carbon-language/carbon-lang/pull/6364/files/d6f19812d2350df8714e6022560e7443470c1a18#r2525516156.

Part of #5263.
2025-11-17 16:06:14 +00:00
Richard Smith 5c7bb7a50d Clean up ConstantValueStore getters. (#6377)
Move `GetWithDefault` into the `ValueStore` base class, and avoid doing
the tag -> index mapping twice.

Call `ValueStore::Get` instead of `ConstantValueStore::GetAttached` in
`GetUnattachedConstant`. This is equivalent, since we never need a
default value here, and should be faster and less surprising.
2025-11-17 13:51:33 +00:00
dependabot[bot] 6451ae6024 Bump js-yaml from 4.1.0 to 4.1.1 in /utils/vscode in the npm_and_yarn group across 1 directory (#6378)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [js-yaml](https://github.com/nodeca/js-yaml).

Updates `js-yaml` from 4.1.0 to 4.1.1
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md">js-yaml's
changelog</a>.</em></p>
<blockquote>
<h2>[4.1.1] - 2025-11-12</h2>
<h3>Security</h3>
<ul>
<li>Fix prototype pollution issue in yaml merge (&lt;&lt;)
operator.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/nodeca/js-yaml/commit/cc482e775913e6625137572a3712d2826170e53a"><code>cc482e7</code></a>
4.1.1 released</li>
<li><a
href="https://github.com/nodeca/js-yaml/commit/50968b862e75866ef90e626572fe0b2f97b55f9f"><code>50968b8</code></a>
dist rebuild</li>
<li><a
href="https://github.com/nodeca/js-yaml/commit/d092d866031751cb27c12d93f3e2470ad74d678b"><code>d092d86</code></a>
lint fix</li>
<li><a
href="https://github.com/nodeca/js-yaml/commit/383665ff4248ec2192d1274e934462bb30426879"><code>383665f</code></a>
fix prototype pollution in merge (&lt;&lt;)</li>
<li><a
href="https://github.com/nodeca/js-yaml/commit/0d3ca7a27b03a6c974790a30a89e456007d62976"><code>0d3ca7a</code></a>
README.md: HTTP =&gt; HTTPS (<a
href="https://redirect.github.com/nodeca/js-yaml/issues/678">#678</a>)</li>
<li><a
href="https://github.com/nodeca/js-yaml/commit/49baadd52af887d2991e2c39a6639baa56d6c71b"><code>49baadd</code></a>
doc: 'empty' style option for !!null</li>
<li><a
href="https://github.com/nodeca/js-yaml/commit/ba3460eb9d3e4478edcbc29edabe17c2157fc9ce"><code>ba3460e</code></a>
Fix demo link (<a
href="https://redirect.github.com/nodeca/js-yaml/issues/618">#618</a>)</li>
<li>See full diff in <a
href="https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=js-yaml&package-manager=npm_and_yarn&previous-version=4.1.0&new-version=4.1.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-17 00:56:52 +00:00
Chandler Carruth 13bb660f7f Update LLVM and update APIs (#6147)
This also updates the patch file for compiler-rt as upstream has changed
a bit. No functional change.
2025-11-15 03:37:13 +00:00
Chandler CarruthandDana Jansens 4024d300bc Add a more friendly "latch" synchronization tool (#6372)
The standard `std::latch` is very restrictive in how it can be used, and
this makes it hard to easily leverage for simple coordination between a
set of dynamically scheduled tasks, where there isn't an interesting
synchronizing "merge" or future result.

This tool makes it easy to establish a latch, hand out handles to it,
and once all are destroyed, take whatever relevant action.

Note: this is split out of a larger change that uses it. I can wait
until the use case is ready, but seemed nice to review this separately.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-11-15 02:00:41 +00:00
Boaz Brickner bc734bb768 C++ Interop: Add Core.CppCompat.Long32 as a distinct type for Cpp.long when long is 32 bits (#6364)
For now, only support implicit conversions from and to `i32`.

See #6275 for rationale.

Part of #5263.
2025-11-14 23:26:43 +00:00
Dana Jansens e62678e682 Identify and complete facet types as needed for p5168 (#6369)
Proposal #5168 defines when a facet type must be identified or complete,
and what it means for an interface and a named constraint to be
identified or complete. This updates the toolchain to match the
requirements.

This implements identification of a facet type to require completed
named constraints and to include any interfaces from named constraints
into the resulting IdentifiedFacetType.

To complete a facet type, each interface in the IdentifiedFacetType, and
any interface named though a require declaration from them, must be
complete.
2025-11-14 19:24:02 +00:00
Dana Jansens 0183fa301f Import named constraints in a FacetType (#6368)
When importing a FacetType instruction, and the FacetTypeInfo, import
requirements on named constraints.
2025-11-14 18:32:16 +00:00
Dana Jansens 0177dc5677 Import contained RequireImpls when importing an Interface or NamedConstraint (#6344)
When importing an Interface or NamedConstraint, walk the block of
`RequireImplsId`s, and for each one:
- Import the RequireImplsDecl from it, which also imports the
`RequireImpls` structure and its id.
- Collect those decls and build a block of `RequireImplsId`s for the
local SemIR to reference from the Interface or NamedConstraint.

The import of RequireImplsDecl is done in a single phase instead of
three, unlike other decls. This is possible since require declarations
have no name, so they can't be referenced by instructions inside them,
thus there's no cycles to concern ourselves with.
2025-11-14 14:31:11 +00:00
Richard Smith b300f36e6f Use inline constexpr where appropriate. (#6374)
This fixes various violations of C++'s One Definition Rule, where we
accidentally gave the same static data member multiple definitions in
different translation units. Clang happens to emit such definitions with
weak linkage, which allows us to get away with this without link errors,
but it's still formally incorrect.

Also switch keyword order around for a handful of instances of
`constexpr inline`, per agreement in open discussion.

This happens to reduce the size of a `-c dbg` toolchain binary by 7.2
MiB, presumably by making more of our symbols and especially debug info
discardable.
2025-11-14 13:50:56 +00:00
Geoff Romer 2b8fdf3417 Switch the prelude to use ref instead of addr (#6359) 2025-11-14 00:40:26 +00:00
Geoff Romer 55e5675373 Clarify const semantics of Set and Map (#6351)
Also add missing `const` to `ForEach` on `Set` and `SetView`.

This is an alternative to #6347, depending on the const semantics we
want here.
2025-11-13 23:13:32 +00:00
Dana Jansens 54815d7a1f Make Subst recurse through named constraints in a FacetTypeInfo (#6367)
These were accidentally omitted when adding the fields to FacetTypeInfo.
2025-11-13 23:00:20 +00:00
Boaz Brickner 2ad26487b6 C++ Interop: Don't crash when trying to call a C++ function with undeduced return type (#6363)
This crashed on trying to build a C++ thunk because the error wasn't
propagated.

Part of #5436.
2025-11-13 20:53:03 +00:00
Dana Jansens 5ae5170421 Allow deduction of tuple and struct literals as symbolic generic facet types (#6365)
Give TupleLiteral and StructLiteral a constant value, if their contents
have constant values. Their constant values are TupleValue and
StructValue respectively. This supports their ability to convert to a
constant type (or facet type).

This way when deduce finds a TupleLiteral as the argument to a
_symbolic_ facet type, it can also find a constant value to use for that
argument. This allows deduction to move onto step two, where it can
substitute into the symbolic parameter from previous deduced arguments,
and then perform the conversion from the TupleValue to the desired facet
type.

Allow `PerformBuiltinConversion()` to convert from a canonical
TupleValue or StructValue to `type` instead of only from literals. Then,
also support conversion from a symbolic binding of type TupleType or
StructType to `type`.
2025-11-13 20:17:44 +00:00
Jon Ross-Perkins 877179d6d9 Refactor addition of imported locations and placeholders (#6354)
- Makes a little more use of `MakeImportedLocIdAndInst` instead of
`UncheckedLoc`
- Requires use of `MakeImportedLocIdAndInst` with `ImportIRInstId`;
previously optional
- Relevant `if constexpr` moves to `AddPlaceholderImportedInst`, but is
more narrowly scoped there.
- Refactors out `AddPlaceholderImportedInstInNoBlock` to reduce how many
spots do an explicit `imports().push_back(...)`

I'd also considered removing `MakeImportedLocIdAndInst` where possible,
but went this route so that changes to the expected parse node wouldn't
affect callers. When it's required, `MakeImportedLocIdAndInst` is always
there; when it's conditionally present, changing `Parse::NodeId` between
enforceable and not-enforceable would require refactoring any callsites
that assumed one or the other.
2025-11-13 18:34:13 +00:00
Dana Jansens acb7810e32 Avoid crashing when an impl decl has a missing definition (#6349)
When the missing definition is diagnosed at the end of the file, the
witness is set to an error. Impl lookup was skipping impls entirely when
the witness was an error, which means a non-final LookupImplWitness
could be later evaluated against a specific and crash since the lookup
fails instead of returning the error.

The same crash could also occur when verifying poisoned queries hadn't
changed, but now it can find an ErrorInst witness instead, so it is
changed to handle that gracefully.
2025-11-13 17:54:49 +00:00
Geoff Romer 0873777237 Import C++ ref parameters as ref parameters (#6360) 2025-11-13 17:04:58 +00:00
Richard Smith 86b02ee8af Interop support for nullptr and nullptr_t. (#6353)
Add a `Core.CppCompat.NullptrT` type that C++'s `nullptr_t` maps into.
Map `nullptr` to an uninitialized constant of that type -- `nullptr`
doesn't actually have any defined bits within it, despite having the
same representation as `void*`.
2025-11-12 23:23:48 +00:00
Jon Ross-Perkins 931039dcbc Refactor ResolveResult with its factory methods (#6356)
Right now some of the `ResolveResult` factories are on it, ones that
involve `ImportRefResolver` aren't; this more consistently makes callers
use `ResolveResult::` when returning a result.
2025-11-12 19:13:46 +00:00
Jon Ross-Perkins bf4d59bc20 Move ImportRefResolver function bodies out-of-line (#6355)
This is intended to be a rote refactoring, also dropping a couple
forward declarations that moving function bodies out-of-line renders
unnecessary.
2025-11-12 18:18:31 +00:00
Jon Ross-Perkins faada92cee Refactor AddLoadedImportRef, particularly for types (#6352)
I was looking at this due to the addition of more
`GetAsTypeInstId(AddLoadedImportRef(` in #6344. Looking at
`AddLoadedImportRef`, it also felt like the first declaration would be
clearer if collapsed into its overload (the overload is the only
caller). Note one benefit of using `ImportContext` in
`AddLoadedImportRef` is being able to call
`local_constant_values_for_import_insts` to handle the `GetRawIndex`
code.
2025-11-12 17:26:56 +00:00
Ivana Ivanovska b68b6ae1e7 Add support for more complex object-like macros (#6338)
Uses `clang::Parser::ParseConstantExpression()` to parse the macro
replacement tokens, added as a token stream to the preprocessor. This
extends the support from simple object-like macros with a single
replacement token, to multiple tokens like unary operators, binary
operators, casting, nested macros etc.
The support is still limited to macros that are evaluated to an integer
constant. More types to be added as a follow-up.

Part of #6303
2025-11-12 17:06:39 +00:00
Jon Ross-Perkins 8ba0274e81 Call GetAttached less frequently in import (#6350)
This has subtle effects on the number of imported instructions, but
seems more standard for how this code is being written...
`GetLocalConstantId` calls `GetLocalConstantValueOrPush` which does
`local_constant_values_for_import_insts().GetAttached`. So what this is
really doing is causing some intermediate import steps to be skipped.
But per test changes, that doesn't really affect SemIR and will probably
have negligible effect. This *seems* right to me, otherwise I'd expect
we should probably refactor all `GetLocalConstantId(InstId)` calls.
2025-11-12 00:12:46 +00:00
Geoff RomerandRichard Smith 43ffd721a4 Support ref tags on arguments to ref params (#6312)
The issue of whether/how to include `ref` tags in the textual and
in-memory SemIR (see discussion
[here](https://discord.com/channels/655572317891461132/655578254970716160/1431316355742961805))
is left as future work.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-11-11 20:30:19 +00:00
Dana Jansens b36f85c2a5 Add tests for when a require decl must be satisfied before impl as (#6348)
When we `impl as Z` and `Z` is an interface with a require relationship
to another interface `Y`, we produce an error at the definition if the
self type does not impl the required interface `Y`.

The require relationship need not be satisfied yet at the declaration of
the `impl as Z`, and a declaration of `impl as Y` is enough to write the
definition of `impl as Z`.
2025-11-11 18:42:35 +00:00
Dana JansensandJon Ross-Perkins ff0cea55f6 Add require decls to Interface and NamedConstraint (#6321)
They are not used for impl lookup or verifying anything yet, but now
they appear in the textual semir.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-11-11 16:36:15 +00:00
Dana Jansens 81e55bed8a Generate a RequireDecl instruction for require declarations (#6318)
The `RequireDecl` instruction points, via a `RequireImplsId` to a
`RequireImpls` structure in a `ValueStore`. That structure holds the
self-type and facet type, as well as the generic id and parent scope.
`RequireImpls` is always a generic since it only appears in an
`interface` or `constraint`, which both have a generic parameter `Self`
applied to all their members.

The `RequireDecl` instruction evaluates to itself, but drops the
decl_block_id since the instructions within the `require` declaration
are not required in the canonical value which is only used for import.
And import will want to import the `RequireImpls` structure along with
the `Interface` or `NamedConstraint` structure it is in, rather than
recreate it from the decl's instructions. This also avoids repeating all
the instructions within the `require` decl in the textual semir's
constants block.

Adding the `RequireImpls` to the `Interface` or `NamedConstraint`
structure is not yet done, so they are not available for impl lookup or
import yet.
2025-11-11 14:16:09 +00:00
Dana Jansens e087209f6f Add failing deduce tests for array from tuple and type inside a rewrite constraint (#6345)
Neither can deduce the implicit parameter right now, but they should be
able to.
2025-11-11 14:13:54 +00:00
Ivana Ivanovska 3b0dad9dd5 Add support for simple object-like macros (#6326)
Adds support for object-like macros with a single replacement
numeric-literal kind token. Only macros that evaluate to an integer
constant are supported for now. When detected at name lookup, they are
imported as a constant integer value in Carbon.

Demo:

```c++
// --- macros.h

#define CONFIG_VALUE 2
```

``` c++
// main.carbon
library "Main";

import Cpp library "macros.h";
import Core library "io";

fn Run() {
    let a: i32 = Cpp.CONFIG_VALUE;
    Core.Print(a);
}
```

```c++
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o \--output=demo_carbon
$ ./demo_carbon
2
```

Part of #6303
2025-11-11 11:24:20 +00:00
Richard Smithandjosh11b cb0edef45f Add line editor to RE2 example. (#6337)
Most inputs are matched against the current regex. An input that starts
and ends with `/` sets a new regex instead. EOF terminates the program.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-11-10 23:53:23 +00:00
Alexander Neundorf 711cd56c0f C++ interop: add a simple unit test for "using enum" (#6278)
This unit test uses "using UEnum = Enum;" and imports that into Carbon.

This is my very first try at contributing something to carbon, I'm
looking forward to your feedback.
The test is very basic. 
What other cases should it test ?
What other comments do you have ?
2025-11-10 22:21:24 +00:00
Richard Smith 1ece5000aa Always form a ConstType instruction for const. (#6341)
Do this even if the operand is a `ConstType` instruction. This better
preserves the source form of the type, and avoids a special case.
Repeated `const`s are already flattened in constant evaluation, and this
special case also didn't prevent forming a `ConstType` whose operand is
`const` in general, only cases where the operand happens to literally be
a `ConstType` instruction.

This reverts commit eed21f6439.
2025-11-09 18:17:09 +00:00
Richard Smith dfd9946dc2 Complete all pointer types. (#6340)
Completing a pointer type is trivial, but we still need to do it, and
fail to do so in a few places, which can lead to crashes during
lowering. Switch to completing pointer types when the type is created to
avoid the issue.
2025-11-08 00:45:12 +00:00
Dana Jansens 13a16270dc Include entity name in FacetAccessType formatted name (#6339)
Format the entity name into the instruction name for a FacetAccessType
of a SymbolicBinding. This means (T as type) gets formatted as
`T.as_type` instead of just as `as_type` for the non-canonical
FacetAccessType instruction. The same is already true for the canonical
SymbolicBindingType.
2025-11-07 19:10:11 +00:00
Richard Smith 8f19f7a7c0 Use the value representation of T as that of MaybeUnformed(T) where possible (#6334)
If the value representation of `T` is a copy representation, but it
copies all of the bits of `T`'s object representation, then it's OK to
use that as the value representation of `MaybeUnformed(T)` too.

This fixes the behavior of interop with nullable pointers, which are
represented as an adapter of `MaybeUnformed(T*)`, and need to be passed
to and returned from functions on the Carbon / C++ boundary as `T*`s.
2025-11-07 16:25:27 +00:00
Boaz Brickner d6c19442b2 C++ Interop: Use reference return values in operators tests (#6332)
I believe this is now possible following #6178.

Part of #5995 and #6148.
2025-11-07 10:31:38 +00:00
Boaz Brickner 7413e84ec9 C++ Interop: Add support for <<= and >>= (#6325)
C++ Interop Demo:

```c++
// my_number.h

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  auto value() const -> int { return value_; }
  auto set_value(int value) -> void { value_ = value; }

 private:
  int value_;
};

auto operator<<=(MyNumber& lhs, int rhs) -> MyNumber&;
auto operator>>=(MyNumber& lhs, int rhs) -> MyNumber&;
```

```c++
// my_number.cpp

#include "my_number.h"

auto operator<<=(MyNumber& lhs, int rhs) -> MyNumber& {
  lhs.set_value(lhs.value() << rhs);
  return lhs;
}
auto operator>>=(MyNumber& lhs, int rhs) -> MyNumber& {
  lhs.set_value(lhs.value() >> rhs);
  return lhs;
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn Run() -> i32 {
  var num: Cpp.MyNumber = Cpp.MyNumber.MyNumber(3);
  Core.Print(num.value());
  num <<= 2;
  Core.Print(num.value());
  num >>= 1;
  Core.Print(num.value());
  return 0;
}
```

```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
3
12
6
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
2025-11-07 08:38:26 +00:00
Richard Smith ae5db6303a Add tests for interop with variadic functions. (#6336) 2025-11-06 23:54:28 +00:00
Boaz Brickner b54f2dd592 Support import Cpp; to import Cpp namespace for using C++ builtins (#6320)
This allows writing
```
import Cpp;
```

Instead of writing
```
import Cpp inline "";
```

Part of #6330.
2025-11-06 08:45:28 +00:00
Dana Jansens ce109708bf Add dumping for NamedConstraintId and shorten untagged id printing (#6319)
Adds support to the `dump` debugger command for named constraint ids,
which are printed as `constraint<number>`. While doing so, we print
whether the `constraint` is complete or not, and add the same to
`interface` to match.

And we noticed that the printing of name and name scope ids, which are
not tagged, are very verbose by adding 7 `0`s to them for no reason. So
make the dump output easier to read by dropping 0 prefixes.

Before:
```
name_scope00000000: {inst: inst0000000E, parent_scope: name_scope<none>, has_error: false, extended_scopes: [], names: {name00000000: inst6000000F, name00000001: inst60000011}} {kind: Namespace, arg0: name_scope00000000, arg1: inst<none>, type: type(inst(NamespaceType))} `package`
```

After:
```
name_scope0: {inst: instE, parent_scope: name_scope<none>, has_error: false, extended_scopes: [], names: {name0: inst6000000F, name1: inst60000011}} {kind: Namespace, arg0: name_scope0, arg1: inst<none>, type: type(inst(NamespaceType))} `package`
```
2025-11-05 21:36:42 +00:00
Richard Smith 99cebcf0a3 Add lowering tests for pointer parameters and return values. (#6328) 2025-11-05 21:18:53 +00:00
Richard Smith f2e98c2047 Fix initialization of a variable via an ImplicitAs conversion. (#6327)
We used to generate initialization to a temporary instead, and leave the
variable uninitialized.
2025-11-05 21:05:34 +00:00
Jon Ross-PerkinsandDana Jansens 8166f9a7cf Formalize Cpp as a PackageNameId (#6306)
This turns `Cpp` into a keyword, and makes it map to `NameId::Cpp` and
`PackageNameId::Cpp`.

Per discussion with zygoloid, the keyword versus identifier question is
deliberately kept open by #4846. This PR switches to a keyword because
mapping to a specific `PackageNameId` works best with a special `NameId`
not backed by an `IdentifierId`. We could in theory make it work using
`IdentifierId` or a runtime-tracked `PackageNameId` for `Cpp` (e.g.
stored on `SemIR::File`), but this approach is consistent with `Core`
and so seemed like a good starting point.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-11-05 17:21:41 +00:00
Boaz Brickner ae50e0f623 Propagate location to CppOverloadSetValue instructions (#6317)
Part of #5915.
2025-11-05 16:53:04 +00:00
Dana Jansens b2c3e92132 Copy the complete flag when importing a named constraint (#6316)
And don't mark the imported named constraint as an interface scope.
2025-11-05 14:19:17 +00:00
Richard Smith 5db1141f52 Allow adding / removing const with ImplicitAs. (#6323)
If `T` implicitly converts to `U`, then:

 * `const T` implicitly converts to `U`,
 * `T` implicitly converts to `const U`, and
 * `T` implicitly converts to `Optional(U)`.
2025-11-05 07:38:09 +00:00
aa69a484eb Add support for running LLVM optimizer. (#6225)
Adds a flag `--optimize=<mode>` that specifies what to optimize for:

* `--optimize=none` turns off the optimizer as much as possible, but
still respects always_inline.
* `--optimize=debug` aims to be the equivalent of `-Og` / `-O1`, and
provides optimizations that don't affect the ability to debug the
program. This is the default.
* `--optimize=size` optimizes for the size of the produced program, and
aims to be the equivalent of `-Oz`.
* `--optimize=speed` optimizes for the execution time of the produced
program, and aims to be the equivalent of `-O3`.

Following the approach taken by Clang, the optimization level feeds into
both the configuration of the LLVM pass pipeline and the attributes
added to function definitions generated by the frontend.

Optimization is performed in a new phase, `optimize`, which runs between
`lower` and `codegen`.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-11-05 00:15:14 +00:00
David Blaikie db150ffc5c Remove TODO that was based on a misunderstanding on my part (#6322)
I was thinking that the incompleteness diagnostic for C++ types would've
been produced by Clang for record types, but seems they're produced by
Carbon & we already /are/ sharing that diagnostic (with #6302), and that
patch only adds an extra note rather than being a whole separate
codepath for effectively the same diagnostic.
2025-11-04 22:04:50 +00:00
Boaz Brickner 805600de43 C++ Interop: Preserve non-nullability when mapping const non-nullable pointers (#6293)
For non-nullable const pointers, we need to keep the non-nullability.

This is done by preserving non-nullability when mapping qualifiers.
2025-11-04 18:25:22 +00:00
Geoff Romer 114ecda725 Enable conversions to value-or-ref to use value_of_initializer (#6309)
As a byproduct, the only test that exercised the "address of a temporary
object" diagnostic now trigers the "address of a non-reference
expression" diagnostic. We could restore it by using a type that doesn't
support `value_of_initializer`, but it seems better to remove the
diagnostic altogether: not only does it simplify the code, I'd also
argue "non-reference expression" is more accurate as a user-facing
description of the operand.
2025-11-04 16:29:31 +00:00
Boaz Brickner 1324fad32b C++ Interop: Add basic tests for void* conversion (#6315)
Part of #6280.
2025-11-04 15:39:18 +00:00
Geoff Romer fd3b0b0bf9 Remove redundant function parameter (#6313) 2025-11-03 19:42:40 +00:00
Dana Jansens 30c3a35776 Import the full NamedConstraint from its decl (#6311)
This imports the entire `NamedConstraint` structure when importing
`NamedConstraintDecl`. This will be required to identify a facet type
that contains a named constraint, as we will need to pull the `require`
decls out of the `NamedConstraint` structure to do so.

I tried making the `InterfaceDecl` code path
[templated](https://github.com/carbon-language/carbon-lang/pull/6308#discussion_r2482655927)
to reuse it, but it was a lot of template parameters including field
pointers into `InterfaceDecl`, `GenericInterfaceType`,
`SpecificInterface`, and it was very hard to read so I gave up on that
approach here.
2025-11-03 16:25:41 +00:00
Boaz Brickner 94bb6be185 C++ Interop: Make CppVoidType always-incomplete (#6302)
Part of https://github.com/carbon-language/carbon-lang/issues/6280.
2025-11-03 09:43:39 +00:00
Dana Jansens ca3f95faa6 Make named constraint eval to a FacetType with itself in it (#6308)
This requires declared FacetTypes to hold NamedConstraintIds (along with
a specific) that are named in an extend or impls requirement. We add
support to stringify and formatter to display the named constraints in
the facet type, and special case when a facet type contains a single
extend named constraint, like we did for a single extend interface.

This means that `RequireIndentifiedFacetType` can now fail, if the facet
type contains a forward-declared named constraint. Add the appropriate
diagnostics for each call to this function, and note the ones that
should change to `RequireCompleteFacetType` in the future with TODOs.

We also add tests for using facet types that can or can't be identified,
or completed, with named constraints in them.
2025-10-31 22:10:35 +00:00
Dana Jansens ed31a6dbe8 Import NamedConstraintDecl instruction names (#6305)
For now, they are imported as their constant value, so there's little to
do, we just need to support getting their NameId. In the future we will
need to import the full named constraint in order to
["identify"](https://github.com/carbon-language/carbon-lang/blob/656150593c1e3fc2b6ccd83c7256a61e4bd04030/proposals/p5168.md#proposed-rules)
them. But we need FacetTypeInfo to hold named constraints first.
2025-10-31 20:23:28 +00:00
Dana Jansens bf72c43b6b Set the completed flag in NamedConstraint after the defn is complete (#6304)
A named constraint can not be
[identified](https://github.com/carbon-language/carbon-lang/blob/656150593c1e3fc2b6ccd83c7256a61e4bd04030/proposals/p5168.md#proposed-rules)
until its definition is complete, so this flag will be used to determine
if the named constraint is ready to be identified.
2025-10-31 20:21:51 +00:00
Dana Jansens 43e09e8e81 Type-check require declarations (#6286)
They don't get stored anywhere yet, but this type checks the
declarations and diagnoses errors in their form, such as not placing a
facet type after `impls` or a type before it.
2025-10-31 20:20:31 +00:00
Jon Ross-PerkinsandDana Jansens 42e2280150 Clean up singleton TypeId use (#6300)
#6289 absentmindedly added fields in more places, and this is undoing
that plus further fixes.

This does some cleanup of types with relation to singletons. For
`TypeType` and `ErrorInst`, they're always complete due to a
`SetComplete` call in `file.cpp`. For `CppVoidType`, it's intended to be
incomplete by construction, and so a `TypeId` should be okay. The intent
though on not generally providing these had been that `GetSingletonType`
needs to be called to get a type to be marked as complete.

In the case of `AutoType`, removing `TypeId`does change a small printing
detail. I think that's old legacy that's just been carried forward.

Otherwise, for both `InstType` and `AutoType`, I've added
`GetSingletonType` calls where they were used in order to ensure
completeness is applied correctly. These calls cause small SemIR
permutations.

This causes `AutoType` to be seen by lowering, so I'm adding a
placeholder for it. Also merging two functions that look like they're
identical in intent -- not sure why they're separate.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-30 22:50:59 +00:00
Dana Jansens f272198ce5 Don't elide Self when dumping the interface/constraint (#6297)
We give `Self` in an interface/constraint a location so it's not elided
when trying to dump the interface/constraint. We use the location of the
start of the definition, which is the scope for which the `Self` is
constructed and is available in.
2025-10-30 20:47:16 +00:00
Dana Jansens 656150593c Add the CheckIRId tag to NamedConstraintIds (#6298) 2025-10-30 20:06:47 +00:00
Jon Ross-Perkins 356ea7fd30 Fix Cpp.void stringification to be consistent with other singletons (#6301)
I missed this in #6279, just fixing it. See `IntLiteralType` in
typed_insts.h (or similar) for comparison.
2025-10-30 19:15:58 +00:00
Boaz Brickner d3762f9723 Remove unused ImportCppId and list of Cpp imports in File (#6290)
See discussion:
https://discord.com/channels/655572317891461132/655578254970716160/1432518191350808659

Part of #5245.
2025-10-30 18:03:34 +00:00
Jon Ross-Perkins 9b95944020 Mask unexpected inst ids (#6295)
Just more anti-churn work.
2025-10-29 22:07:33 +00:00
Dana Jansens ec3f7dd9bd Fix diagnostic for argument count mismatch on call to generic constraint (#6292)
The error message was saying "generic interface" but should say "generic
constraint"

There is one test that demonstrates the error message for interfaces,
but it's in tests for overloads, so add a more clearly dedicated test
for interface too.
2025-10-29 20:17:54 +00:00
Dana Jansens 9085e9ee49 Syntax highlight //@include-in-dumps as a valid comment (#6299) 2025-10-29 19:46:29 +00:00
Dana JansensandJon Ross-Perkins d2fbbd3c7a Actually do fingerprinting for InstFingerprinter::GetOrCompute with a CppOverloadSet (#6296)
Currently we schedule work on the CppOverloadSet but then never `Add()`
it to add its contents to be fingerprinted, and just immediately return
an empty fingerprint.

Use CARBON_KIND_SWITCH to prevent this sort of thing from happening in
the future, now that we can use it for std::variant.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-10-29 19:10:50 +00:00
Jon Ross-PerkinsandDana Jansens a1fd86cf27 Change ImplWitnessTablePlaceholder from instruction to InstId value (#6294)
`ImplWitnessTablePlaceholder` is the only non-type singleton instruction
(`ErrorInst` is a type; while `ImplWitnessTablePlaceholder` exposes
`TypeInstId`, it's only used as an `InstId`).

In order to allow simpler handling of singleton instructions, replace
`ImplWitnessTablePlaceholder::TypeInstId` uses with
`InstId::ImplWitnessTablePlaceholder`. Since the placeholder instruction
was never evaluated, this has no significant effect on behavior.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-29 18:10:24 +00:00
Jon Ross-PerkinsandDana Jansens 93dc369ebd Add a base struct for singleton type insts (#6289)
This is just reducing boilerplate in `typed_insts.h` because we have a
number of singleton types, and keep adding more.

The changes to `TemplateString` allow `TemplateString IrName` to be used
as a `StringLiteral`.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-29 16:52:46 +00:00
Geoff Romer 4821eec2f8 Add support for ref patterns (#6283)
Support for `bound`, and for the `ref` tag on arguments, is left as
future work.
2025-10-29 16:28:56 +00:00
Boaz Brickner fc8db6ac5c C++ Interop: Add a test that demonstrates that const non nullable pointers are wrongly mapped to nullable (optional) pointers (#6284)
Part of #5772.
2025-10-29 09:12:25 +00:00
Boaz Brickner 4d4d720ff0 C++ Interop: Support getting void* from C++ functions and passing void* it to C++ function (#6279)
This defines `Cpp.void` as a custom type.
`Cpp.void*` is mapped to C++ `void*`.

Not supported yet: Conversions from and to other pointer types.

C++ Interop Demo:

```carbon
// main.carbon

library "Main";

import Core library "io";

import Cpp inline '''
#include <cstdio>

auto GetPointer() -> void* _Nonnull {
  static int x = 8;
  return &x;
}

auto GetValue(void* _Nonnull ptr) -> int {
  return *static_cast<int*>(ptr);
}
''';

fn Run() -> i32 {
  let ptr: Cpp.void* = Cpp.GetPointer();
  Core.Print(Cpp.GetValue(ptr));
  return 0;
}
```

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o --output=demo
$ ./demo
8
```

Part of #6280.
2025-10-29 09:03:53 +00:00
David Blaikie 29d7e52a46 Add unit tagging to ImportCppId (#6288)
Another case of an id that isn't used in SemIR, but seems valuable to
tag them
just in case they evolve such a use.
2025-10-29 06:22:28 +00:00
Jon Ross-Perkins eed21f6439 Make applying const repeatedly to the same type have less additional effect. (#6287)
This is to avoid edge cases where there are multiple `ConstType`
instructions, which code may not handle appropriately. I was thinking
about this for #6279
2025-10-28 19:56:16 +00:00
Geoff Romer 0811d996e1 Finish renaming BindName and related insts. (#6281)
Resolves the TODO from #6235
2025-10-28 17:17:38 +00:00
Ivana Ivanovska 5e0201e5c8 Fix big integer literals type (#6234)
Following the C++ standard rules for assigning a type to a decimal
integer literal, when a Carbon integer literal is passed as a call
argument to a C++ function and it is too big to fit to `int`, `long` or
`long long`, it is assigned an extended integer type (`_int128`).
Discussed in the [interop
meeting](https://docs.google.com/document/d/1YlxEOJ0r-o19o19TCJbFl4Ln1U88yn_Vj23y1Hr5vTk/edit?tab=t.0#heading=h.zdrwb1soj9ms)
and documented in this [design
doc](https://docs.google.com/document/d/18u8z9UEuGH73XzXlDynTgyNK76q1Efl8YYWbpM5LX7o/edit?tab=t.0#heading=h.vxmw1gfg49f2).

Part of #5915
2025-10-28 15:01:43 +00:00
Richard Smith 6011040481 Rework handling of C++ references. (#6268)
For now, map C++ reference types to const-qualified Carbon pointer types
rather than picking between a (non-const) pointer or a value type. This
fixes misbehavior in lowering for reference members in classes and
reference return types.

Update the special-case handling for references as function parameters
so that it continues to map const reference parameters to Carbon
pass-by-value, and unify the code paths for `self` parameters and other
parameters, which were mostly doing the same thing but had some subtle
differences.

Add references to the list of types that we can pass to and from C++
directly, without needing an additional layer of thunks.
2025-10-28 00:33:26 +00:00
David Blaikie 33166ffc7a Add unit tagging to CustomLayoutId (#6271) 2025-10-27 23:11:23 +00:00
Richard Smith a1a35c207e Unify "needs thunk" logic. (#6277)
Remove duplication between determining whether a parameter needs custom
thunk mapping and whether a function needs a thunk. Now a function needs
a thunk if any parameter or the return type does.

This fixes some inconsistencies; previously:
- We would not require a thunk when passing an `unsigned int`, but if we
  had a thunk we'd pass `unsigned int` indirectly.
- We would always require a thunk for an enum parameter, even though
  we'd actually pass it directly if its underlying type is a 32- or
  64-bit integer.
- We would require a thunk for a nullable pointer, even though
  we arrange for all pointer types to have the same ABI in Carbon and
  C++, including nullable pointers / Optional(T*).

This also causes us to use a thunk for rvalue reference return types,
which we used to miscompile.

Depends on #6276.
2025-10-27 22:49:29 +00:00
Richard SmithandDavid Blaikie f022e91e45 Create a Call instruction directly when building a thunk call. (#6276)
Don't go through the `PerformCall` machinery a second recursive time --
this is redundant, creates additional unnecessary temporaries, and is in
theory wrong because `PerformCall` takes a syntactic argument list (one
argument per callee parameter pattern), but we have a call argument list
(one argument per callee parameter).

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2025-10-27 21:22:24 +00:00
David Blaikie 1aade74693 Add unit tagging to ExprRegionId (#6272)
This doesn't show up in the raw SemIR dumps (I don't think that's due to
a lack of coverage, but due to the fact that ExprRegionId isn't used as
an operand of any instructions).
2025-10-27 16:24:11 +00:00
David Blaikie 53ea894d0d Add unit tagging to ClangDeclId (#6274) 2025-10-24 20:18:18 +00:00
David Blaikie 184a39ed8b Add unit tagging to ClangSourceLocId (#6273) 2025-10-24 17:09:46 +00:00
Dana Jansens 0730d5385f Clarify that the Self must be in the type structure of the type or facet type in require (#6269)
It's not enough to have `Self` _somewhere_ in the facet type (after the
`where`).
2025-10-23 21:34:03 +00:00
Dana Jansens 26381f6eaf Handle parsing of require...impls declarations (#6255)
Check is not implemented yet, but some tests are added.
2025-10-23 18:34:52 +00:00
David Blaikieandjosh11b 4f1f0fc7c2 Add unit tagging to ImportIRId (#6265)
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-10-23 17:34:35 +00:00
josh11bandJosh L c329bce240 PrintChar from "io" library takes a char (#6264)
As [observed in
#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1428791603786416351),
this makes demo code nicer.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-10-23 16:38:20 +00:00
Geoff Romer 09710d102f Separate binding insts for refs and values (#6235)
This resolves a TODO in `expr_info.cpp` by using the inst kind rather
than the bound value to track the binding's category.

Since we're churning all the `bind_name` insts in testdata anyway, I'm
also taking this opportunity to align the inst naming with the design's
terminology, by calling these insts "bindings" (this aspect of the PR is
dependent on #6231 resolving an ambiguity in that terminology). For
consistency we'll need to rename several other insts as well (see the
TODO on `RefBinding`); I'm deferring that to a separate PR to minimize
the review load, but I think those name changes are in-scope for this
review.
2025-10-23 01:46:24 +00:00
David Blaikie c0879b2200 Add unit tagging to IdentifiedFacetTypeIds (#6267)
I don't /think/ these ids can appear in the raw SemIR dump, so this
change doesn't show up in any test updates - but it should still be
valuable for identifying bugs in the future.
2025-10-23 00:56:21 +00:00
David Blaikie d4a8cb96de Correct format string specifier to match number of parameters (#6266) 2025-10-23 00:30:31 +00:00
David Blaikie b02c6a8db4 Add unit tagging to SymbolicConstantId (#6262) 2025-10-22 23:39:00 +00:00
David Blaikie 79541ee50c Add unit tagging to StructTypeFieldId (#6260)
Based on #6259
2025-10-22 22:22:53 +00:00
David Blaikie 2dd9e7f0d7 Add unit tagging to CppGlobalVarId (#6263) 2025-10-22 21:44:18 +00:00
David BlaikieandDana Jansens 79dd1e362c Add unit tagging to InstBlockId (#6259)
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-22 21:02:48 +00:00
Dana Jansens 22580a47d3 Initial support for empty named constraints (#6245)
Type check named constraint decls and definitions. We don't correctly
error if you put a `fn` inside them. There is no support for `require`
or `alias` yet, so there's nothing useful you can do with them yet.

We have attempted to share code between `interface` and `constraint` as
they are quite similar. First by splitting out some of
handle_interface.cpp to a separate file. Second by sharing some code
paths when you want a facet type from either one, as they both turn into
a facet type.
2025-10-22 18:26:32 +00:00
David Blaikie a340808062 Add unit tagging to FacetTypeId (#6256) 2025-10-22 18:21:09 +00:00
David Blaikie c2ddf50892 Add unit tagging to EntityNameId (#6257) 2025-10-22 16:30:12 +00:00
Geoff Romer 39503a5561 Disambiguate "value binding" (#6231)
This proposal removes the definition of the term "value binding" as a
primitive
category conversion from reference to value, replacing it with the term
"value
acquisition". The other meaning of "value binding", a binding declared
by a
value binding pattern, is unchanged.
2025-10-22 00:38:55 +00:00
Richard Smithandgoogle-labs-jules[bot] 95b78b0173 For #1382: rename me -> self (#6261)
Rename a couple of remaining instances.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
2025-10-21 23:00:47 +00:00
Richard Smithandjosh11b b3c25ecfa2 Allow implicit conversion to a value expression to remove const. (#6253)
`const` doesn't mean much on the type of a value expression; it's valid
to remove it because we can't perform modifications to a const value
regardless.

We already allowed most of this, but only as part of adapter conversion
rather than in general, and we didn't previously allow it when the
source of the conversion was a reference expression.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-10-21 22:16:58 +00:00
David Blaikie 3ea16b8313 Add unit tagging to NameScopeId (#6258) 2025-10-21 20:06:09 +00:00
Boaz Brickner 840562feb3 C++ Interop: Fix access calculation to handle private member of base classes correctly (#6238)
Always take into account both the lookup access specifier and the
declaration. When set, lookup access specifier takes precedence. When
not set, we have two use cases:
1. This is not a record member, so no access is specified at all. Treat
this as public.
2. This is a record member of a base class. Treat this as private.
[Reference](https://github.com/llvm/llvm-project/blob/4b1d7827c07381610ad4fa7bd9d1a9659008b963/clang/include/clang/AST/DeclCXX.h#L1724).

Also, deduplicate access mapping between import and overload resolution.

Background:
https://github.com/carbon-language/carbon-lang/pull/6221#issuecomment-3407981790

Part of #5859.
2025-10-21 08:12:57 +00:00
David Blaikie 3d6810beb6 Add unit tagging to InterfaceId (#6243)
Based on #6241
2025-10-20 21:41:55 +00:00
David Blaikie 7663c38291 Add unit tagging to SpecificId (#6251) 2025-10-20 21:12:54 +00:00
David BlaikieandJon Ross-Perkins 016a28377a Fix up some comments related to the change to hex ids (#6247)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-10-20 20:08:15 +00:00
Boaz Brickner c1c70d5234 C++ Interop: Mapping std::string_view to Core.Str (#6177)
This proposal defines a direct, zero-cost mapping between C++'s
`std::string_view` and Carbon's `Core.Str` for C++ interoperability.
The goal is to make C++ APIs that use `std::string_view` feel native and
seamless when used from Carbon.
This mapping relies on the two types having an identical memory
representation, a condition that we will work to ensure across all
supported platforms.
2025-10-20 19:22:54 +00:00
David BlaikieandDana Jansens 0ed5d41a1b Avoid mismatched InterfaceId comparison between two files (#6241)
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-20 18:44:05 +00:00
Jon Ross-Perkins b1f734e1cd Switch EvalLookupSingleImplWitness from "concrete" to "final" terminology (#6246)
A `final impl` can have a symbolic witness, but that witness is still
final. Using "final" here per discussion on
[#generics-and-templates](https://discord.com/channels/655572317891461132/941071822756143115/1428851511672312120).

I'm also changing the variant a little because `concrete_witness` was
only called when `has_concrete_value` was true, so it can be more
careful about its contract. Having a more explicit `None` also
simplifies `has_value`. I think it doesn't change the overall cost much
past that.
2025-10-20 17:25:26 +00:00
David Blaikie 1df0d4566e Add unit tagging to GenericId (#6248) 2025-10-17 23:21:27 +00:00
Dana Jansens f761960c48 Documentation fixes for require and extend impl as (#6242)
Follow-up fixes for
https://github.com/carbon-language/carbon-lang/pull/6240
2025-10-17 18:57:39 +00:00
David Blaikie af013e8d79 More consistently use check_ir_id to initialize ValueStores (#6244) 2025-10-17 18:30:49 +00:00
Dana Jansens 820e997261 Documentation update for require and extend impl as in interfaces and named constraints (#6240)
Proposal [p5337](https://docs.carbon-lang.dev/proposals/p5337.html)
renamed and introduced new syntax for extending an interface or named
constraint with another.
- The `require` keyword can now be modified by `extend`, instead of it
being a separate thing altogether.
- Interfaces can `extend impl as I` to gain the members of `I` and
implicitly use them to implement `I`. Named constraints can not.

The `Identity` example is meant to not know anything about the type of
the object its passing through, but it ends up making a copy of it. Fix
the example to not by using a pointer.
2025-10-17 17:14:24 +00:00
Richard Smith 8cf4c4d10d [C++ interop] Pass top-level declarations to the code generator. (#6237)
This allows us to lower indirectly-referenced C++ functions and
variables.
2025-10-17 17:10:14 +00:00
gleb 4370acd1bb Snippets update (#6204)
~~Added explanatory comment about math package usage~~
Changed Main() entry point to Run() as per design and toolchain

This small update of front page code snippets will add
explanatory comment to highlight that provided Carbon code
is  hypothetical and meant to show the look and feel of the language.

Also it delivers change of Main() to Run() to
highlight correct entry point for Carbon lang.
2025-10-17 13:09:46 +00:00
Richard Smith 304d2056cc Map nullable C++ pointer types to Core.Optional(T*). (#6230) 2025-10-16 20:52:32 +00:00
Ivana Ivanovska 2a96b52780 Remove big float literals TODO (#6220)
A Carbon floating-point literal passed as a call argument to a C++
function is mapped to `double`. If the value is too large to fit in
`double`, an error is reported. This follows the C++ rules for assigning
types to floating-point literals, as discussed in the [interop
meeting](https://docs.google.com/document/d/1YlxEOJ0r-o19o19TCJbFl4Ln1U88yn_Vj23y1Hr5vTk/edit?tab=t.0#heading=h.9zzqn7n3o8lm)
and documented in this [design
doc](https://docs.google.com/document/d/18u8z9UEuGH73XzXlDynTgyNK76q1Efl8YYWbpM5LX7o/edit?tab=t.0#heading=h.6hkga1yq1f3o).

Added missing tests for this as well.

Part of #5915
2025-10-16 16:24:28 +00:00
Boaz Brickner 4e8810fa19 Add more extern "C" tests (#6232)
Add tests in `check`.
Add overload set tests in `lower`.

Part of #6233.
2025-10-16 16:07:02 +00:00
David Blaikie f64b08863a Dump all non-indexed ids as hex (#6228)
The indexed ids are kept in decimal since they won't get tagging because
their ordered-ness is significant to their usage, as I understand it.

Addressing
https://github.com/carbon-language/carbon-lang/pull/6215#discussion_r2430180953
feedback
2025-10-16 01:04:51 +00:00
Richard Smith 0716756c4e Stop passing a lambda as a non-type template argument. (#6229)
This creates ODR issues, as the "same" value store type in different
translation units can end up being treated as different types. In some
build configurations, such as `-c dbg` with Clang 19.1, this is
currently resulting in link-time errors.

Instead, make the customization mechanism for mapping keys to values be
a member function on the value type.
2025-10-16 00:30:00 +00:00
David Blaikie 4fdc08582a Add ValueStore ctor template for Id to use for IdTag (#6226)
Based on review feedback on
https://github.com/carbon-language/carbon-lang/pull/6215#discussion_r2430177644

There are some intermediate commits with alternatives, finding other
ways (non-templates) to address the layering boundaries between
`ValueStore` construction and `CheckIRId` tagging. But, yeah, template
seems like the way to go - certainly in terms of terseness and probably
in terms of extensibility to other Id tagging as/when needed.
2025-10-15 23:29:52 +00:00
Jon Ross-Perkins c7646b74c1 Reduce use of function return type deduction (#6227)
Trying to reduce use where we could have explicit return types because
it should make it a bit quicker to understand what's returned. We've
generally agreed to it for [local
variables](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#naming-variable-types-and-the-use-of-auto),
but even the [google style
guide](https://google.github.io/styleguide/cppguide.html#Type_deduction)
discourages it and says "Do not use decltype(auto) if a simpler option
will work; because it's a fairly obscure feature, it has a high cost in
code clarity."

(which to one point of discussion, feels like maybe we don't need a
specific rule about this -- the remaining couple uses I see feel like
they're harder to avoid)
2025-10-15 23:02:51 +00:00
Richard Smith 851da43c88 Make Optional support specializing its representation. (#6058)
Switch to using a pair of `MaybeUnformed(T)` and a `bool` as the normal
representation for `Optional(T)`. When `T` is a pointer type, add a
customized representation that uses `MaybeUnformed(T*)`, with a null
representation used for absent values.
2025-10-15 22:34:22 +00:00
David Blaikie 63118265f0 Add unit tagging to VtableId (#6216) 2025-10-15 20:48:31 +00:00
Boaz Brickner 45017bf65d Add tests for calling a base function without qualifications (#6221)
This demonstrates that we don't diagnose when trying to call a base
class private function when we refer to the function from a derived
class without qualifications.

Demo: https://godbolt.org/z/vbWs1P915
2025-10-15 20:14:08 +00:00
Jon Ross-Perkins 7050eb8789 Add a function to translate a canonical value to key. (#6222)
This is to address concerns about the `==` and hash duplication.
2025-10-15 19:58:00 +00:00
David Blaikie a486c12bd6 Add unit tagging to SpecificInterfaceId (#6215) 2025-10-15 18:09:29 +00:00
Boaz Brickner c2d21429f2 Avoid changing visiblity when inheriting in CodeContextRenderer (#6219)
This fixes clang-tidy `override-with-different-visibility`.
2025-10-15 15:50:47 +00:00
Boaz Brickner ffefa7711c Move the mapping from entity name to an imported C++ global variable declaration outside of EntityName (#6211)
This would save space for every `EntityName` that is not an imported C++
global variable.
C++ global variables include static data members.
Created `CppGlobalVarId`, `CppGlobalVarKey` and `CppGlobalVar` to allow
having `CanonicalValueStore` that maps `EntityNameId` (which is in
`CppGlobalVarKey` and `CppGlobalVar`) to `ClangDeclId` (which is also in
`CppGlobalVar`).
This is similar to `ClangDeclId`, `ClangDeclKey` and `ClangDecl` .
2025-10-15 13:33:32 +00:00
Boaz Brickner 3fa427b811 Make yaml_test easier to debug by outputing the actual text (#6218) 2025-10-15 13:17:59 +00:00
David Blaikie 2d1de16293 Add unit tagging to ImplId (#6214) 2025-10-15 01:41:37 +00:00
Jon Ross-Perkins 9010249936 Remove reallocation assumptions from generic code (#6217)
Rather than assume reallocations can occur, we've switched to providing
stable references, so simplify related code.

Only removing the comment in `BuildGeneric`, no refactoring, because I
don't feel a refactoring would be a significant improvement.
2025-10-14 21:53:48 +00:00
David Blaikie 1a9826bc29 Add unit tagging to FunctionId (#6213) 2025-10-14 20:52:56 +00:00
David Blaikie d0d2f18f37 Add unit tagging to CppOverloadSetId (#6212)
No update to lldbinit.py because we don't currently have
dumping/debugging support for CppOverloadSetId anyway.
2025-10-14 18:29:40 +00:00
Boaz Brickner a0ef7e7112 C++ Interop: Add test coverage for access control of static/instance data/function members (#6199)
This demonstrates two issues:
1. It seems like we wrongly treat private static data members the same
way we treat protected and allow access to them from within derived
classes member functions.
2. Calling instance member functions of a base C++ class using a derived
class as self (no implicit upcast) is not yet supported. This isn't
related to access control, but prevents us from testing some access
control use cases.

Part of #5859.
2025-10-14 17:56:24 +00:00
Dana Jansens e12d1b6d6d Handle a specific providing ImplWitnessAccess for a symbolic binding used as a type (#6201)
SymbolicBindingType evaluates to the type component of a symbolic facet
value (a type/witnesses pair), and that symbolic facet value has its
constant value replaced by a specific. That specific can provide a
FacetValue, in which case it just evaluates to that FacetValue's type
component. It can provide a BindSymbolicName of another binding, in
which case it points to that entity instead and awaits a further
specific. Currently the code only handles these two cases, and they
match the behaviour of the evaluation of FacetAccessType itself.

However FacetAccessType evaluation also handles cases beyond these, as
there are other instructions that occur as facet values, such as
ImplWitnessAccess, when accessing an associated constant of an interface
that has a facet type as its type.

Currently eval then crashes in this scenario. Instead of furthering to
reproduce the contents of FacetAccessType's evaluation, defer to calling
the `EvalConstantInst()` overload for it when evaluating
SymbolicBindingType against a new value from a specific. This means
SymbolicBindingType can evaluate back into a FacetAccessType, when it
was originally a FacetAccessType(BindSymbolicName) and becomes
FacetAccessType(ImplWitnessAccess) through a specific.

This comes with a test that crashed in eval before this change.
2025-10-14 15:29:46 +00:00
David Blaikie b2c2bdde3a Add unit tagging to AssociatedConstantId (#6207)
No update to lldbinit.py because we don't currently have
dumping/debugging support for AssociatedConstantId anyway.
2025-10-13 23:06:02 +00:00
Jon Ross-Perkins ad63950df2 Refine autoupdate crash output (#6209)
Before (after the stack):

```
Traceback (most recent call last):
  File "/usr/local/google/home/jperkins/dev/carbon-lang/toolchain/./autoupdate_testdata.py", line 100, in <module>
    main()
    ~~~~^^
  File "/usr/local/google/home/jperkins/dev/carbon-lang/toolchain/./autoupdate_testdata.py", line 95, in main
    subprocess.run(argv, check=True)
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.13/subprocess.py", line 577, in run
    raise CalledProcessError(retcode, process.args,
                             output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['/usr/local/google/home/jperkins/dev/carbon-lang/scripts/run_bazel.py', 'run', '-c', 'dbg', '--experimental_convenience_symlinks=ignore', '--ui_event_filters=-info,-stdout,-stderr,-finish', '//toolchain/testing:file_test', '--', '--autoupdate', '--print_slowest_tests', '0', '--file_tests=toolchain/check/testdata/interface/test.carbon']' returned non-zero exit status 255.
```

After:

```
Command `/usr/local/google/home/jperkins/dev/carbon-lang/scripts/run_bazel.py run -c dbg --experimental_convenience_symlinks=ignore --ui_event_filters=-info,-stdout,-stderr,-finish //toolchain/testing:file_test -- --autoupdate --print_slowest_tests 0 --file_tests=toolchain/check/testdata/interface/test.carbon` failed with exit code `255`
```
2025-10-13 22:52:03 +00:00
Richard Smith 90771414f5 Add builtins to form and detect null MaybeUnformed(T*) values. (#6208)
In preparation for modeling `Optional(T*)` as a null pointer value.

With this PR, pointers remain non-nullable, but `MaybeUnformed(T*)` has
a particular unformed state that has the same representation as a C++
null pointer, which is accessible and detectable via builtins.
2025-10-13 20:06:56 +00:00
Aiden Grossman 5714f4deb2 Use Overload of lookupTarget Accepting Triple (#6205)
The overload accepting a string/llvm::StringRef is deprecated and will
be removed when LLVM 22 branches.
2025-10-13 18:52:49 +00:00
Jon Ross-PerkinsandRichard Smith 6d9ee96584 Misc comment cleanups (#6200)
Just trying to apply a few scattered comment improvements that AI helped
flag.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-10-13 18:49:48 +00:00
Richard Smith 72754ff8ea Remove death tests checking for assertions. (#6202)
Fixes #5800 (flaky test timeouts under -c dbg), which were caused by
these death tests being extremely slow because they cause the symbolizer
to run on a large debug binary. Before this change, the test ran for
~30-90s depending on how long the symbolization happened to take; after
this change, it finishes in about 0.4s.

Using death tests here seems a bit excessive, especially as the process
dying in these cases isn't part of the contract of these functions, so
I'm just removing the death tests rather than trying to make them more
efficient. We have death tests in common/ that check our CARBON_CHECK
macros work.
2025-10-12 21:52:55 +00:00
David Blaikie 60b2b7f8c1 Add unit tagging to ClassId (#6195) 2025-10-11 05:36:18 +00:00
Richard Smith e26b6a35c2 Allow instance binding on tuple-valued expressions. (#6203)
Don't expect the right-hand operand of `a.(b)` to always be a tuple
index when `a` is of tuple type; it could also be a method name.

Fixes #6162.
2025-10-11 04:54:13 +00:00
Boaz Brickner 1ac1d11063 C++ Interop: Support reference types in fields and globals (#6187)
Implemented by generalizing the reference type support for parameters
and return values to other use cases.
The changes to the `method.carbon` test are due to to supporting the
reference types but not supporting the necessary conversions.

C++ Interop Demo:

```c++
// global.h

struct C {
  int member = 0;
  int& member_ref = member;
};

extern C& global;
```

```c++
// global.cpp

#include "global.h"

static C static_c;

C& global= static_c;
```

```carbon
// main.carbon

library "Main";

import Core library "io";

import Cpp library "global.h";

fn Run() -> i32 {
  Core.Print(Cpp.global->member);
  ++(*Cpp.global->member_ref);
  Core.Print(Cpp.global->member);
  ++(*Cpp.global->member_ref);
  Core.Print(Cpp.global->member);
  return 0;
}
```

```shell
$ clang++ -stdlib=libc++ -c global.cpp
$ bazel build toolchain:carbon && bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link global.o main.o --output=demo
$ ./demo
0
1
2
```

**Without this change**:
```shell
main.carbon:10:14: error: semantics TODO: `Unsupported: var type: C &`
  Core.Print(Cpp.global->member);
             ^~~~~~~~~~
main.carbon:10:14: note: in `Cpp` name lookup for `global`
  Core.Print(Cpp.global->member);
             ^~~~~~~~~~
```

Part of #6006 and #6186.
2025-10-10 23:15:31 +00:00
Boaz Brickner 0365467872 Merge toolchain/check/testdata/interop/cpp/class/struct.carbon into class.carbon (#6198)
The tests are almost identical and test the same logic so basically
duplicated.
The extra coverage that was in `struct.carbon` is added to
`class.carbon`.
One basic test in `struct.carbon` was left just to make sure `struct` is
supported.

Part of #5150.
2025-10-10 22:37:25 +00:00
Boaz Brickner 46c5209f2f C++ Interop: Set location when creating a return pattern (#6185)
This requires changing `ReturnSlotPattern` and `OutParamPattern`
definitions to use untyped node id, so they can have any associated
node.

Follow up of #5197.
Part of #5064.
2025-10-10 15:32:14 +00:00
Boaz Brickner 9441c278df Avoid using clang::UnresolvedSetImpl (#6197)
Avoid relying on implementation details.
Also, use `DeclAccessPair::operator->` instead of `.getDecl()->`.
2025-10-10 15:29:53 +00:00
Alina Sbirlea 96a3c1e41f [Specific coalescing] Do not update canonical when is exists. (#6196)
Only update the canonical for itself if it has no value, otherwise a
"better" canonical was previously added and the chain will be followed
when deleting specifics.
2025-10-10 14:33:03 +00:00
Dana Jansens 0679b779fb Return SymbolicBindingType separately in TypeIterator (#6193)
A SymbolicBindingType is going to only have EntityNameId as its field,
and we will use the ScopeStack to use that to find a facet. The
ScopeStack is a check/ thing, so this won't be possible in
SemIR::TypeIterator. And TypeStructure throws away the details for
symbolic types anyways. So this drops the TODO and returns the
EntityName from TypeIterator for any future user who would want it in
check/.
2025-10-10 12:37:37 +00:00
Boaz Brickner f713964db4 C++ Interop: Set location when creating param patterns (#6184)
Follow up of #5197.
Part of #5064.
2025-10-10 09:00:00 +00:00
Alina Sbirlea fd15949fe5 [Specific coalescing] Remove non-canonical from processing. (#6191)
When a pair of specifics is found to be equivalent, the current logic
would always remove the second one (j indexed) from further processing,
assuming that i was the canonical. That's not always the case, when the
j is the canonical, the i indexed specific should be the one removed.
Update logic to reflect that.
Adding testcase.
2025-10-09 23:51:04 +00:00
Jon Ross-Perkinsandjosh11b 75417b2f37 Add a small nolint related to #if handling (#6194)
e.g.
https://github.com/carbon-language/carbon-lang/actions/runs/18390546411/job/52399625057?pr=6182

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-10-09 23:31:01 +00:00
Dana Jansens 3d592ebe59 Support member access into the type of (facet as type) expressions as being into the facet's type (#6190)
When we do member access `x.F` we attempt to look into the type of `x`
for `F`. If `x` is a facet, we look at its FacetType to find `F`. We
want `facet` and `facet as type` expressions to be generally treated as
equivalent, so we need to get at the "canonical facet value" of `x` in
order to look into its type. Add a new operation that allows us to
preserve the non-canonical `base_id` in the member access for
diagnostics if no conversion to a canonical facet value was needed.
2025-10-09 22:06:02 +00:00
Jon Ross-Perkins 5c3d6ce9b4 Add special-casing for tidy with boost_unordered (#6192)
Tested locally in relation to
https://github.com/carbon-language/carbon-lang/pull/6182, difficult to
test server-side because of the action change combined with the
edge-case issue.
2025-10-09 21:52:13 +00:00
Jon Ross-Perkins 63adcea9f0 Fix typename in forward (#6183)
This was noted by another Googler.
2025-10-09 16:53:49 +00:00
Dana Jansens e682a6660d Avoid adding extraneous local instructions while importing witness table entries (#6180)
When deducing arguments for generic parameters of an `impl`, the
deduction calls `Convert` on the input arguments. Often, the input
argument is a facet, and needs to be converted to a type via
FacetAccessType in order to produce a different facet. These
instructions end up being added to the semir, but only their constant
values are needed for the resulting specific returned from Deduce.

In the best case, these extra instructions are just noise in the semir,
or they just cause instruction names to get differentiated with larger
suffixes.

In the worst case, these extra instructions contain references to
instructions from a generic context, and leak them out of that generic
context and into another. In particular, when importing a
LookupImplWitness instruction, the re-evaluation of it can do deduce
(when the lookup is against a generic `impl`). The instructions created
in Deduce are not part of the import, and end up referring to imported
instructions from the local context, which leads to confusion in the
toolchain, and can crash.

The `import_self_specific.carbon` test demonstrates this. It causes the
`I.F` function to be imported from the `I` interface when building the
witness table for the `impl`. Doing so imports the specific of `C` which
includes a LookupImplWitness for `Self.Accoc` in `I`. The `Self` is a
BindSymbolicName with generic binding index 0, in `I`. When Convert
creates instructions in the generic `impl forall D`, however, they end
up referencing and including this BindSymbolicName into its eval block.
But the generic binding 0 in the `impl` is a very different thing (a
value of type `E`). This confusion leads to crashes.
2025-10-09 16:07:30 +00:00
Ivana Ivanovska 1fe3316f8e Remove unnecessary TODO (#6188)
When importing the overload set the dependencies are not imported
anymore, so this TODO is unnecessary.

Part of #5915
2025-10-09 11:46:08 +00:00
Dana Jansens 93b79f159e Change InstId dumping to hex numbers that include the tag (#6175)
This change makes dumping and debugging work again with InstIds that are
now tagged with the CheckIRId. The textual representation of an InstId
is changed from `irN.instM` back to `instM` but the `M` is now a hex
value with the tag as part of it, which is the same number that is
physically in the `InstId::index` field. This prevents any cases where
we would potentially print incorrect values for large InstIds.

We teach the `dump` command in lldb to parse hex values for InstId so
that we can paste these numbers back into the debugger.
2025-10-08 18:45:35 +00:00
Boaz Brickner c254e9fd75 C++ interop: Correctly report the unsupported param type when using explicit object param (#6179)
This fixes a bug, which seems to have been introduced in #6108.

In the new test, without this change, we will diagnose with
```
error: semantics TODO: `Unsupported: parameter type: ExplicitObjectParam` [SemanticsTodo]
```
2025-10-08 17:01:11 +00:00
Dana Jansens fd74e49fd2 Add tests of .Self given for an interface parameter that has constraints (#6181)
This tests that `.Self` in an interface generic parameter preserves the
facet type information of the binding when returned, and allows compound
member lookup back into that interface.

And add a failing-todo test that `.Self` gets implied constraints which
can be satisfied through `&` for the facet type `I(.Self)` is part of.
2025-10-08 16:51:23 +00:00
Boaz Brickner bfc4d2b127 C++ interop: Add return reference types support (#6178)
This is a follow up of #6082, which added support for reference types,
but not for return types.

C++ Interop Demo:

```carbon
// main.carbon

library "Main";

import Core library "io";

import Cpp inline '''
struct C {
  auto Inc() -> void { ++x; }
  int x = 0;
};
auto GetC() -> C& {
  static C c;
  return c;
}
''';

fn Run() -> i32 {
  Core.Print(Cpp.GetC()->x);
  Cpp.GetC()->Inc();
  Core.Print(Cpp.GetC()->x);
  Cpp.GetC()->Inc();
  Core.Print(Cpp.GetC()->x);
  return 0;
}
```

```shell
$ bazel build toolchain:carbon && bazel-bin/toolchain/carbon compile main.carbon && bazel-bin/toolchain/carbon link main.o --output=demo && ./demo
0
1
2
```

**Without this change**:
```shell
main.carbon:19:14: error: semantics TODO: `Unsupported: return type: C &`
  Core.Print(Cpp.GetC()->x);
             ^~~~~~~~~~
```

Part of #6148.
2025-10-08 16:33:09 +00:00
Dana Jansens ba8ed99eb0 Add failing tests for exposing the value of .Self through an interface (#5957)
We test using .Self in a generic parameter of an interface and as the
value of an associated constant.
2025-10-08 15:53:55 +00:00
Boaz Brickner 7c13bddc92 C++ interop: Support C++20 operator and overload resolution for expression rewriting (#6171)
This allows to find the spaceship `operator<=>` when a comparison
operator is not available, and `operator==` when `operator!=` is not
available.
Support added to both lookup and overload resolution, by adding
`OperatorRewriteInfo` and propagating it in `CppOverloadSet`.
In case overload resolution chooses to use an operator which requires
rewriting, we emit a `TODO` since rewriting is not yet supported.

Part of #6170.
2025-10-08 06:28:50 +00:00
Jon Ross-Perkins c9bb6b11a4 Use an import_ir prefix and handle special IR values (#6176)
This is to try to improve clarity of values printed when debugging, with
[special values as
requested](https://discord.com/channels/655572317891461132/655578254970716160/1424792667338051756).
2025-10-07 22:54:09 +00:00
Boaz Brickner 49213b1ca3 Fix Candidataes typo (#6169) 2025-10-07 11:58:06 +00:00
Dana Jansens 2ee2b2f1e3 Move the FacetAccessType special case out of name lookup, and generalize it (#6163)
The `AppendLookupScopesForConstant` function had a special case for
`facet as type` which was overly broad (applying to all callers to the
function when only one caller needs it), and was confusingly overly
specific (applying to `facet as type` but not to `facet` constants).

We clarify all of this by moving it out to member access, and applying
it only to the case of looking into the type of `base_id`. In that case
we are doing member lookup into the facet itself, but since it's
symbolic we don't know the type to look into. And we don't defer the
lookup with a symbolic instruction, so we do the lookup into the facet's
type instead.

We add a helper function in member access, `ExtractFacetTypeForFacet` to
encapsulate this slightly-odd operation. It's odd because it ends up
getting *the type of the type* when the `base_id` has a facet as its
type.

The helper is now built on top of GetCanonicalFacetOrTypeValue() instead
of explicitly looking for FacetAccessType, which makes it work more
generally for any type instructions that represent a facet, including
SymbolicBindingType in the future.

While here document and improve clarity throughout the
`PerformActionHelper` for member access.
2025-10-06 19:06:26 +00:00
Dana Jansens fe020ee08b Make FacetAccessType evaluate to SymbolicBindingType for type-of a BindSymbolicName (#6115)
The SymbolicBindingType refers to the type value that will be
substituted in for the BindSymbolicName, but holds onto the EntityNameId
from the BindSymbolicName instead of (or in addition to, for now) the
instruction.

The EntityNameId will be used to look in the ScopeStack to find the
witnesses either from the BindSymbolicName instruction, or other
instructions that specify `impls` constraints against the EntityName.

This will allow us to have the `T` in `I(T)` resolve to a `.Self`
reference in the type so that we get type equality with the binding's
type: `T:! I(.Self)`.
2025-10-06 18:56:43 +00:00
Calvin bd4d5805dd Replace addr with ref in design docs (#6141)
Updates the documentation under `docs/design/` to use `ref` instead of
`addr` after their removal in #5434. Care was taken to manually clean up
edge cases and, in a couple cases, surrounding text (see
3d72c49bb75c0f40ca7e8114b6a1369b941e1697). After this change, there are
no matches for `addr(?!ess)` in `docs/design/`.

Closes #6032
2025-10-06 18:44:24 +00:00
Boaz Brickner b1c0854948 Add blank lines to group case with the above offset increment in InstNamer::GetScopeIdOffset() (#6165)
This would hopefully help prevent bugs like the one fixed in #6151.
See refactoring discussion in #6159.
2025-10-06 18:20:54 +00:00
Boaz Brickner 5f561282eb Properly set the name for C++ overload set instructions in SemIR (#6156)
This is a followup of #5891.
Part of #5915.
2025-10-06 07:36:28 +00:00
Dana Jansens b99bc00632 Deduce arguments against the canonical facet value (#6158)
When deducing an argument against a type that is `<facet value> as type`
we don't care about the `as type` part of that expression. We want to
find an argument that can convert to the `FacetType` of the facet value
for the generic binding that is the `<facet value>`.

This was done after-the-fact in the Deduce switch, but we move this
canonicalization step to be more explicit and done up front at the start
of the Deduce loop. This:
- Avoids a trip through the Deduce loop for a `FacetAccessType`
parameter, just to deduce through it in the switch, which avoids convert
and creation of extraneous constant values.
- Uses the `GetCanonicalFacetOrTypeValue()` function so that when we add
`SymbolicBindingType` handling to that function it will apply to Deduce
as well correctly, instead of needing to handle both in the switch.
2025-10-03 17:05:19 +00:00
Dana Jansens e3b4482893 Make the GetCanonicalFacetOrTypeValue operation more crisp (#6157)
Previously it performed two kinds of operations, with a boolean
parameter to control whether it would unwrap FacetValue or not. This
made the function hard to explain as "canonicalization".

Now the contract of GetCanonicalFacetOrTypeValue is as follows:
1. For a facet value expression, it returns the canonical value of the
facet value.
2. For a `<facet value> as type` it returns the canonical value of the
`<facet value>`.
3. For other type expressions, it returns the canonical value of the
type.

1 and 2 together collapse together two representations of a facet value
(as a FacetType or as a TypeType) into a single canonical value, which
is important for constant comparison of facet values where the `as type`
is not meant to change the result. This is the case in impl lookups and
`.Self` comparisons.

The step of unwrapping `FacetValue` is only useful in the constant
evaluation of `LookupImplWitness` and is used to collapse *symbolic*
queries on `FacetValue(T)` and on `T` down to a single canonical value,
since they produce the same result later when `T` is replaced with a
facet value or type that can provide a concrete witness. This is now
extensively documented in the constant evaluation of
`LookupImplWitness`.

This change came out of a request/discussion in #6115 (see comment
https://github.com/carbon-language/carbon-lang/pull/6115#discussion_r2383696576).
2025-10-03 15:21:07 +00:00
Jon Ross-Perkins 81c2b3be1a Handle some more errors in interfaces without crashing. (#6155)
This fixes and tests two crashes related to what I was observing [on
#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1422723976483831848).

The approach to Cpp imports taken in #6086 is problematic because it
returns before the work stack is completed, and doesn't store the
resulting constants. This fixes the approach taken in that PR.
2025-10-03 14:31:45 +00:00
David BlaikieandRichard Smith 12fa65e53c Check for use of InstIds from the wrong SemIR::File (#5997)
Use the `CheckIRId` as a unique identifier for the scope of an `InstId`
- if an `InstId` is created within the scope of one `CheckIRId` it must
not be used in the scope of a different `CheckIRId`.

This is achieved without extra storage, but with false negatives for
large inputs.

When an `InstId` is created, the original index of the `Inst` is XORed
with a tag derived from the `CheckIRId` to produce the final `InstId`.
When the `InstId` is used, the expected tag is XORed with the `InstId`
to get back to the original index - if the tags don't match, the
resulting index will be corrupted, likely too large - resulting in an
out of bounds index CHECK-failure.

(the tag value is derived as such:
* take the CheckIRId
* left shift one bit (padding zero)
* left shift another bit (padding 1 - used to signify that the resulting
`InstId` has a tag combined into it)
* reverse the bits

In this way, the tag is unlikely to overlap with the index for small
test cases - making it possible to separate out the `CheckIRId` from the
index in these cases to provide more meaningful debugging/CHECK
messages, and more informative `SemIR` textual dumping that can now
include the `CheckIRId` along with the `Inst`'s index in the name of an
`inst`)

The test churn here is improved printing as tagged `InstId`s can now,
with best effort (more likely for small test cases where the `CheckIRId`
and the `Inst` index aren't at risk of overlapping from the high and low
bits), render the `CheckIRId` as part of the inst's name. Going from
`instNN` to `irMM.instNN`.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-10-02 23:07:36 +00:00
Boaz Brickner ce6bf91a83 Avoid extra work when thunk_required is already true in IsCppThunkRequired() (#6150)
Also set `thunk_required` in a more consistent way, to avoid bugs like
the one fixed in #6152.

Part #6148.
2025-10-02 19:11:31 +00:00
Dana Jansens 0c761a9a78 Find the builtin TypeCanAggregateDestroy in the FacetType for facet values (#6119)
When doing impl lookup with a constraint facet type including the
builtin `TypeCanAggregateDestroy`, we look at the type to see if it
satisfies it. However if the type is a facet value, we need to look at
the FacetType to see if the eventual concrete type is going to satisfy
it.

Note that we can do this check up front in the `LookupImplWitness()`
function without creating a symbolic instruction to be modified by
future specifics with a more precise type for the facet value, because
the result of `TypeCanAggregateDestroy` does not actually provide a
witness, so we don't need the final specific type.

This was noticed by removing the "shortcut" in convert for converting a
`FacetAccessType(<symbolic binding>)` to `typeof(<symbolic binding>)`.
By removing the shortcut, we go into impl lookup when checking `impl`
decls containing `TypeCanAggregateDestroy` via deduce.
2025-10-02 18:57:37 +00:00
Boaz Brickner 57c0fde145 Fix C++ thunk triggering for functions with default args which return a simple type (#6152)
Before this change, we wrongly ignore the decision to generate a thunk
for a function with default args by overriding this decision with the
fact the return type by itself doesn't require a thunk.
This causes not generating a thunk which leads to crashing in lowering.
Add tests that show that now thunk is generated in `check` and it no
longer crashes in `lower`.

Follow up of #6108.
2025-10-02 15:16:28 +00:00
Boaz Brickner 16999a79cc Fix a crash caused by a bug introduced in C++ overloads support in GetScopeIdOffset() (#6151)
After this change, we correctly increment the offset by the next switch
case type.
Before this change, we accidentally incremented the offset by
`functions()` size instead of `cpp_overload_sets()` size and vice versa.
Also sorted the switch cases according to the order of the enum, for
consistency. This might help prevent a future similar incident.

This fix prevents crashing in the newly introduced test
`multiple_too_few_args_calls`.

This also has the side effect of showing `null name` for
`cpp_overload_set_type` and `cpp_overload_set_value`, instead of having
an arbitrary name.
Examples that demonstrate the old name is arbitrary can easily be seen
in tests like `cpp_namespace.carbon` and `decayed_param.carbon`, but
careful review would show that all old names are arbitrary, though often
luckily almost make sense.

We might want to have a proper name for these, but it's beyond the scope
of this crash fixing change.
See #6156.

Part of #5915.
2025-10-02 14:34:34 +00:00
Boaz Brickner a16102b249 Add tests for returning a C++ reference type, rvalue and const reference (#6149)
Part of #6148.
2025-10-02 08:49:10 +00:00
Jon Ross-Perkins 31d88633e3 Add some autoassigner notes (#6154) 2025-10-01 20:35:14 +00:00
Geoff RomerandRichard Smith c713279a3d Keep design documents current (#5606)
Require language design proposals to either update the design documents
to
reflect the proposed changes, or add "TODO" comments to mark where those
changes
will be needed, with links back to the proposal. This is intended to
ensure that
the design documentation accurately informs readers about the current
language
design, without excessively burdening the proposal process.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-10-01 20:12:05 +00:00
Jon Ross-PerkinsandDana Jansens f27ccbf76e Add CODEOWNERS for review assignment (#6153)
This disables the autoassign action so that the codeowners approach can
be tested without interference.

Trying this out because it might be a path for vacation handling. See
[GitHub
docs](https://docs.github.com/en/organizations/organizing-members-into-teams/managing-code-review-settings-for-your-team)
and
[#infra](https://discord.com/channels/655572317891461132/707150492370862090/1422985757311635620)

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-01 17:50:53 +00:00
Ivana Ivanovska a24598f069 Lower CppOverloadSetValue (#6101)
Following up on comments from
[#5891](https://github.com/carbon-language/carbon-lang/pull/5891) ([
1](https://github.com/carbon-language/carbon-lang/pull/5891#discussion_r2317244981),
[2](https://github.com/carbon-language/carbon-lang/pull/5891#discussion_r2317266756)).

Lowering `CppOverloadSetValue` as an empty struct value, using
`context.GetLiteralAsValue()`. Also changed its constant kind to
`InstConstantKind::Always`.

Part of https://github.com/carbon-language/carbon-lang/issues/5915
2025-10-01 16:25:05 +00:00
Jon Ross-Perkins 4a6376cf59 Rename/restructure Destroy logic to better reflect #6124 (#6144)
This also does a little restructuring in the same direction, following
#6124.

Leads want `Destroy` to work similarly now for all types. As a
consequence, there doesn't seem to be as much benefit to splitting off
aggregate destruction. In this PR, the `type.destroy` function can now
be expected to destroy anything that's destructible; that means it'll be
usable for the `final fn` once that support is available.

Similarly, this gets rid of the impls other than the single blanket
impl, now using `type.can_destroy`. Since they all need to use the same
function, there's no benefit to splitting approaches. Also, now it can
just be a `final impl` since there should be no need for people to
create specializations -- if this blanket impl applies, it means the
`final fn` is the same.

This also slips in `partial` support since there's no reason to have it
diverge anymore. Also `abstract`, which I'm not sure is broadly testable
since most cases it'd come up, the `abstract` keyword is explicitly
detected/rejected.

Note though that this doesn't make any really big changes. It's just
realigning on the leads decision. I'm going this way to try to reduce
name-related churn for other changes.
2025-09-30 20:43:36 +00:00
Hitesh JoshiandHitesh Joshi 0166d8837c Update Documentation to use new expression terminology (#5890)
# Changes

## Terminology Updates
This PR updates documentation to align with the expression phase
terminology changes introduced in
[#2964](https://github.com/carbon-language/carbon-lang/pull/2964):

* **"symbolic value" → "symbolic constant"**: Updated all remaining
instances using find-and-replace

## Scope of Changes
* Focused on documentation that predates the July 2023 terminology
change
* Used git blame history to identify instances likely using the old
"constant" definition
* Manually reviewed each "constant" usage to distinguish between:
- New definition (unchanged): the broader category including symbolic
constants

Closes
[#5599](https://github.com/carbon-language/carbon-lang/issues/5599)

---------

Co-authored-by: Hitesh Joshi <hitesh@mitsu.care>
2025-09-30 20:15:55 +00:00
Jon Ross-Perkins 47081be67a Reduce test sensitivity to small import loc changes (#6145)
Locations are similarly fragile, because adding a comment changes them.
This has made me pause when making prelude changes in #6144, so dropping
them for those cases.

Instruction ids aren't actually that interesting outside debugging, and
can be churny when doing other structural changes. I've seen this in
particular when doing singleton changes, which bump every instruction
id.

Note there are still other ways fragility from locations can crop up.
This shouldn't be considered a complete fix, but hopefully a small
improvement.
2025-09-30 17:20:14 +00:00
Dana Jansens 54b994ceac Simplify member access in facet values (#6146)
Given `fn f(T:! I, x: T)`, we have a facet type `I`, a facet value `T`
and a value `x` of type `FacetAccessType(T)`.

Previously we explicitly handled the case of member access on `x.F`
where the type is a `FacetAccessType` by looking through it at the facet
value, and then at its facet type. This is already something that impl
lookup does for us, so we can remove this special case.

We also previously had a complex branch handling the case `T.F` on a
facet value, because `PerformImplLookup()` in member access is expecting
a `TypeId`, not a facet value. However, the first thing that branch does
is convert the facet value to a type expression, forming a
`FacetAccessType`.

Unfortuntely, when combined, if we had `x.F` we would convert it from a
value of type `FacetAccessType` to a facet value, and then convert that
to a type as a `FacetAccessType` again. We see this extra
`FacetAccessType` disappear from the SemIR after this change.

In this change, we remove both the inlined replacement of
`PerformImplLookup()` and the explicit handling of `FacetAccessType`. We
drive all member access lookups on the `base_id`'s type through a single
`PerformImplLookup()` call. If the `base_id` is a facet value, to get
the TypeId to look into, we convert the facet value to a
`FacetAccessType`, reducing the complex special cases down to a single
line.
2025-09-30 16:27:31 +00:00
Chandler CarruthandDana Jansens 35fb000536 Use a thread pool when building runtimes (#6133)
This parallelizes the compilations and dramatically reduces the time to
build runtimes.

As part of this, teach the driver infrastructure to have an option to
control the use of threads and to build the relevant thread pool and
thread it into the various APIs.

However, it requires our `ClangRunner` to become thread-safe and to
invoke Clang in a way that is thread-safe. This is somewhat challenging
as the code in `clang_main` is distinctly _not_ thread-safe.

To address this, the relevant logic of `clang_main`, especially the CC1
execution, is extracted into our runner and cleaned up to be much more
appropriate in a multithreaded context. Much of this code should
eventually be factored back into Clang, but that will be a follow-up
patch to upstream.

Last but not least, this rearranges the `ClangRunner` API to make a bit
more sense out of the different options for building runtimes, and have
a clean model for which things need to be passed in at which points.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-09-30 12:54:51 +00:00
Dana Jansens a6bb11f1cf Rearrange convert: construct FacetAccessType from a facet value before impl lookup instead of after (#6113)
This makes convert more consistent, it always makes a FacetAccessType
for a facet value, rather than only doing so after lookup returns. The
intention for this is that FacetAccessType will evaluate to
SymbolicBindingType in the future, so this will expose that constant
value to impl lookup instead of the original facet value, which will
avoid impl lookup having to deal with `.Self` or `BindSymbolicName`
specifically.
2025-09-29 22:49:06 +00:00
Boaz Brickner 5abd214d9d Set the location for the candidate set when looking up C++ operators (#6138)
This adds location information and prevents crashes in some cases of
template instantiation in operator lookup.

Removed `InCppOperatorLookup` note as it is no longer necessary.

Part of #5995.
2025-09-29 22:45:22 +00:00
Jon Ross-Perkins e1b87ac2e1 Change IndexWith to use a standard binary operator setup (#6127)
This is closer to [the
design](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/expressions/indexing.md?plain=1#L55-L64),
just lacking `ref`, but does remove a lot of special-casing done for the
lookup.

The `ErrorInst` changes in `Build*Operator` are to align with what was
being done for `IndexWith`; don't do an interface lookup if the relevant
operand is an error. Otherwise, that becomes visible because some files
have an error operand and don't provide the interface.
2025-09-29 18:17:48 +00:00
Jon Ross-Perkins 49ba8cf3e1 Switch class to use a blanket impl for Destroy (#6125)
Right now, the class destroy impl is incorrectly generated (first
discussed [in
Discord](https://discord.com/channels/655572317891461132/941071822756143115/1418614787449032826)).
If we want it to be correct, deferred definition logic would need to be
added, and the declaration would need to be moved inside the `class`
scope (along with whatever generic logic that needs).

This instead switches to a blanket impl, to avoid creating latent bugs
with generating the `impl` and function body in the wrong scope. This
approach uses the same blanket impl as aggregate destruction that was
added by #6098.

The intent here is to allow progress on other parts of `Destroy`. For
example, under this model the implementation of the function body could
be done as part of lowering the specific.
2025-09-29 16:05:06 +00:00
Boaz Brickner 5705b94da8 Add PerformCallToCppFunction() which calls simplified version of PerformCppOverloadResolution() before calling PerformCallToFunction() (#6122)
Instead of calling `PerformCppOverloadResolution()` and use the complex
return value to call `PerformCallToFunction()`, we call
`PerformCallToCppFunction()` which will call both
`PerformCppOverloadResolution()` and `PerformCallToFunction()`.

Followup of #6112.
Part of #5995.
2025-09-29 14:26:23 +00:00
Richard SmithandDana Jansens 3b6d202730 Implement support for mixed-access overload sets. (#6137)
This turns out to be quite important, as several important standard
library types (such as `std::string`) have mixed-access overload sets
for their constructors as an implementation detail. The overall approach
here is:

- Use the most permissive access to determine the access of the overload
set itself. This affects whether name lookup finds the member name at
all.
- After overload resolution, re-check the access of the selected member,
if it's protected or private.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-09-26 23:18:16 +00:00
dependabot[bot] 83ba714165 Bump tar-fs from 2.1.3 to 2.1.4 in /utils/vscode in the npm_and_yarn group across 1 directory (#6139)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [tar-fs](https://github.com/mafintosh/tar-fs).

Updates `tar-fs` from 2.1.3 to 2.1.4
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/mafintosh/tar-fs/commit/f421a235565b6a6d305bdf87e999ebdfae9dd1cc"><code>f421a23</code></a>
2.1.4</li>
<li><a
href="https://github.com/mafintosh/tar-fs/commit/c412fa130e216d4c01392f6fb62c8725c1a4ac8b"><code>c412fa1</code></a>
refactor to same pattern as v3</li>
<li>See full diff in <a
href="https://github.com/mafintosh/tar-fs/compare/v2.1.3...v2.1.4">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=tar-fs&package-manager=npm_and_yarn&previous-version=2.1.3&new-version=2.1.4)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-26 19:58:55 +00:00
Jon Ross-Perkins 705c95d6e0 Drop fn destroy support (#6136)
`fn destroy` is being removed per decision on #6124. It seems like the
relevant decision will result in no more keyword-based function names,
so this is removing all related support.
2025-09-25 21:56:48 +00:00
Boaz Brickner 5b34054341 Update hello_world example comment following adding support for C++ member operators (#6134)
Part of #5995.
2025-09-25 20:31:51 +00:00
Richard SmithandJon Ross-Perkins 949ec17da2 Improve interop for classes with multiple inheritance. (#6130)
If there's a unique "preferred" base class, then treat that as "the"
base class for Carbon's purposes. In particular:

* If there's exactly one polymorphic base class, that's our preferred
base class.
* If there's exactly one non-empty base class, that's our perferred base
class.
* (Degenerate case) If there's exactly one base class, that's our
preferred base class.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-09-25 20:25:48 +00:00
David Blaikie f194acbf96 Implement system header lookup for interop import (#6128)
Using the toolchain-tasks suggested syntax of:
```
import Cpp header "<system_header.h>";
```
2025-09-25 15:49:06 +00:00
Boaz Brickner e3293a4f1f Improve C++ operator tests by covering unary operator for incomplete and unsupported types (#6135)
Also make sure to test the operator call in `incomplete operand C++
type` test, and not fail before the it.

Part of #5995.
2025-09-25 15:31:30 +00:00
Boaz Brickner 3bb0d3e0b1 When looking up C++ operators, make sure all operands are complete (#6132)
This diagnoses instead of crashing in some cases:
* When one of the operands is an incomplete Carbon type.
* When one of the operands is a C++ class that can't be completed due to
lack of Carbon supported.
The new tests cover these cases.

Part of #5995.
2025-09-25 14:15:02 +00:00
Chandler CarruthandGeoff Romer fd70196c67 Introduce a runtimes caching and management layer (#6002)
This layer allows runtimes to be built on-demand but cached in a
consistent and re-usable location on the system. It handles careful
filesystem operations to ensure consistency even in the face of multiple
versions and build configurations.

This addresses a number of TODOs from the initial runtimes building
on-demand, and sets the stage to scale up to more runtimes.

This doesn't switch on-demand runtimes to be on by default, I wanted to
wait and make that change as a separate step.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-09-25 12:30:50 +00:00
Chandler Carruth 42d03ac390 Another attempt to fix ClangD-tidy (#6131)
This restores the original approach in #6046 as it appears
`--notool_deps` isn't sufficient in some situations. It still isn't
clear to me why it seemed to work initially, but I can easily reproduce
the issue now even with that flag.

I've tried to address the feedback in the original PR on the Python
code.
2025-09-25 11:13:16 +00:00
Richard Smith d85781acbf Fix handling of deleted and templated constructors. (#6129)
Don't ignore deleted constructors in overload resolution. If one is the
best match, we want an error rather than picking something else. Don't
crash if we find a constructor template or other weird thing; use
`getConstructorInfo` to map it into a constructor and skip it if it
isn't one, like Clang does.
2025-09-25 04:19:18 +00:00
Jon Ross-Perkins 1fba60ca8c Core.Char -> char in a couple spots (#6126) 2025-09-24 23:34:51 +00:00
David Blaikie 7bfd26b06e Disallow using "request changes" as it's proven problematic (#6121)
I wasn't sure exactly in what way it was problematic, so I was a bit
vague in the justification (though justifications aren't generally
needed/provided here anyway - so I'm not sure it'd be net helpful to add
one anyway).
2025-09-24 21:26:07 +00:00
Boaz Brickner 88dac35ae8 Add support for C++ member operators (#6112)
Call `Sema::AddMemberOperatorCandidates()` to properly add candidates.
For C++ member operator calls, use the first arg as self.

C++ Interop Demo:

```c++
// my_number.h

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  int value() const { return value_; }
  auto operator++() -> MyNumber;

 private:
  int value_;
};
```

```c++
// my_number.cpp

#include "my_number.h"

auto MyNumber::operator++() -> MyNumber {
  ++value_;
  return *this;;
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn Run() -> i32 {
  var num: Cpp.MyNumber = Cpp.MyNumber.MyNumber(14);
  Core.Print(num.value());
  ++num;
  Core.Print(num.value());
  return 0;
}
```

```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
14
15
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
2025-09-24 10:11:09 +00:00
Richard SmithandJon Ross-Perkins 1e7b7e53ae C++ interop: support for default arguments. (#6108)
The general strategy here is to force use of a thunk when we want to use
default arguments, and have Clang generate uses of the default arguments
on its side of the thunk.

To support this, change the key type used in `clang_decls` from being
just a `Decl*` to being a pair of `Decl*` and number of parameters in
the case of function decls. Import distinct `SemIR::Function`s for each
number of parameters that's used, and corresponding distinct thunks.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-09-24 01:07:59 +00:00
Dana JansensandRichard Smith 82679e6689 Make BindSymbolicName the canonical form of a FacetValue wrapping the BindSymbolicName (#6107)
If a `BindSymbolicName` is converted to `type` and then to its exact
`FacetType`, we get a `FacetValue` wrapping the `BindSymbolicName` but
providing no different information: it has the same witnesses and
`FacetType` as the original `BindSymbolicName`. Yet it is a different
constant value, creating multiple canonical forms with the same meaning.
Now we make that `FacetValue` with the same `FacetType` as the
`BindSymbolicName` it wraps evaluate back to the `BindSymbolicName`,
making it the unique canonical form.

This makes the "shortcut" in convert for avoiding impl lookup when
converting from `FacetAccessType` to `FacetType` in this exact scenario
work the same as doing the full impl lookup.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-09-23 22:11:11 +00:00
Dana Jansens 737c329aba Save a trip through the deduce work loop with the non-canonical value in DeduceImplArguments() (#6120)
`DeduceImplArguments()` works with the argument as a constant value, but
starts with the non-canonical `impl.self_id`. As these are both derived
from `impl.self_id` it just means an extra trip through the work loop to
try again with the canonical `impl.self_id` as the param. Save that work
and give canonical instructions for both param and arg in
`DeduceImplArguments()`.
2025-09-23 21:00:54 +00:00
Jon Ross-Perkins 8004c2d5f6 CalleeFunction -> Callee name adjustments (#6117) 2025-09-23 17:51:31 +00:00
Ivana Ivanovska 6ca443afc7 Refactor ImportNameFromCpp in cpp/import.cpp (#6100)
Cleaned up `ImportNameFromCpp`, extracting smaller functions out of it.
Also added a documentation for `ClangLookup`. No changes in
functionality.

Part of #5915
2025-09-23 12:09:28 +00:00
Jon Ross-Perkins 0f7df4ed7e Switch CalleeFunction to a variant (#6104)
Trying to make it easier to see what's intended to be present/correct on
`CalleeFunction` in its various modes.
2025-09-22 22:56:38 +00:00
Boaz Brickner a73e259620 Add Check::Context::clang_sema() method and use it (#6110)
This replaces `sem_ir().clang_ast_unit()->getSema()`.
2025-09-22 19:11:06 +00:00
Boaz Brickner 87efd4cb0b Change C++ interop operators tests to use references for parameters of operators that should mutate them (#6111)
Returning by reference is still not supported and marked with a TODO.

C++ Interop Demo (compare to #6020):

```c++
// my_number.h

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  auto value() const -> int { return value_; }
  auto set_value(int value) -> void { value_ = value; }

 private:
  int value_;
};

auto operator++(MyNumber& operand) -> MyNumber;
auto operator--(MyNumber& operand) -> MyNumber;
```

```c++
// my_number.cpp

#include "my_number.h"

auto operator++(MyNumber& operand) -> MyNumber {
  operand.set_value(operand.value() + 1);
  return operand;
}

auto operator--(MyNumber& operand) -> MyNumber {
  operand.set_value(operand.value() - 1);
  return operand;
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn Run() -> i32 {
  var num: Cpp.MyNumber = Cpp.MyNumber.MyNumber(14);
  Core.Print(num.value());
  ++num;
  Core.Print(num.value());
  --num;
  Core.Print(num.value());
  return 0;
}
```

```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
14
15
14
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
2025-09-22 18:26:20 +00:00
Jon Ross-Perkins 6070db0b8a Fix handling of large int types in interop (#6102)
This fixes a crash on `i8388608`.
2025-09-22 17:50:42 +00:00
Jon Ross-Perkins 70cde77f0e Update TypeIterator to use CARBON_KIND_SWITCH (#6105)
Also clean up unnecessary `SemIR::` use in these files.
2025-09-22 15:56:08 +00:00
Jon Ross-Perkins ef1e47cd07 Remove redundant SemIR:: uses in SemIR (#6106)
Also cleaned up some in #6105, which is what got me looking for more.
2025-09-22 15:55:46 +00:00
Boaz Brickner 412d911578 Use context.x() instead of context.sema_ir().x() in check/cpp/ when possible (#6109)
Avoid using `const Context&`. We always work with a cmutable `Context&`
(https://github.com/carbon-language/carbon-lang/pull/6094#discussion_r2359199247).
2025-09-22 10:15:31 +00:00
Richard SmithandJon Ross-Perkins 925250f8f9 Improve diagnostics for overload resolution failure. (#6091)
Include notes listing the candidates and explaining why they didn't
work. Rather than duplicating the (substantial) logic for this, use the
Clang machinery to generate these diagnostics.

In order to support this, add a mechanism to map `SemIR::LocId`s to
`clang::SourceLocation`s. This works by creating source buffers in Clang
that refer into the Carbon source file so that `SourceLocation`s can
point into them.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-09-19 20:22:47 +00:00
Boaz Brickner ef488f00fa Overload resolution for C++ operators (#6092)
Multiple overloads for the same operator are now resolved using overload
resolution.
This change doesn't try to solve all issues with operator lookup.

Moved the operator lookup logic from `import` to `operators` and changed
it to take the args into account.
Use `Sema::LookupOverloadedBinOp()` (with ADL) when looking up operator
functions to create an overload set.

Verified all demos in #6017, #6020 and #6024 still work.

C++ Interop Demo:

```c++
// my_number.h

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  auto value() const -> int { return value_; }

 private:
  int value_;
};

class NotMyNumber {};

auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator+(NotMyNumber lhs, NotMyNumber rhs) -> NotMyNumber;
```

```c++
// my_number.cpp

#include "my_number.h"

auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() + rhs.value());
}

auto operator+(NotMyNumber lhs, NotMyNumber /*rhs*/) -> NotMyNumber {
  return lhs;
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn Run() -> i32 {
  // Arithmetic
  var num1: Cpp.MyNumber = Cpp.MyNumber.MyNumber(14);
  var num2: Cpp.MyNumber = Cpp.MyNumber.MyNumber(5);
  Core.Print(num1.value());
  Core.Print(num2.value());
  Core.Print((num1 + num2).value());

  return 0;
}
```

**After this change:**

```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
14
5
19
```

**Before this change**

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
main.carbon:14:15: error: semantics TODO: `Unsupported: Lookup succeeded but couldn't find a single result; LookupResultKind: 3`
  Core.Print((num1 + num2).value());
              ^~~~~~~~~~~
main.carbon:14:15: note: in `Cpp` operator `AddWith` lookup
  Core.Print((num1 + num2).value());
              ^~~~~~~~~~~
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
2025-09-19 16:42:46 +00:00
Boaz Brickner 05c9fd768e Add Check::Context::clang_decls() methods (#6094)
Use them instead of explicitly going through `sem_ir()`.
2025-09-19 13:20:01 +00:00
Boaz Brickner 8cbf289c91 Remove unnecessary llvm::formatv() call in TODO(). (#6099) 2025-09-19 09:14:41 +00:00
Jon Ross-Perkins 9704dc670e Change the Destroy blanket impls to be more specific (#6098)
The main direction of this change is the edits to `destroy.carbon`
(matching in both prelude and min_prelude).

Previously there was a no-op blanket impl for `Destroy`, which hid all
missing implementations of `Destroy`. This does a few things:

- Sets up builtin aggregate destruction for struct and tuple types as
before, but also adds C++ class types and array types to the same
handling. (all as a TODO for actual implementation)
- Also maybe-unformed destruction, for now at least. (there's a chance I
may try a different approach on this, but the impl lookup wasn't working
as I'd hope in order to write it in code)
- Adds handlers for simple things that are easy to do in code: `type`,
`bool`, pointers. (because these are no-op destruction)
- Redirect `const T` destruction to `T` destruction.

This leaves as future issues:

- `partial T` destruction. (this can't be done similar to `const`
because it only works for non-`final` class types; I think `class`
definitions should just generate what's needed)
- Destruction of other prelude-provided types. (will probably come up as
we implement class destruction, that the adapted builtin type doesn't
implement `Destroy` -- but may end up special-casing that in a way that
moots it)

This moves the `&` operator from `facet_types.carbon` to
`convert.carbon` because more things need to handle type and now that
we're getting separate copy and destroy interfaces. It should be
low-cost (an interface and builtin) so hopefully this is the right
balance for complexity and re-use.

A few tests are also edited in order to focus them more on what they
intend to test, and avoid a `Destroy` dependency.
2025-09-18 22:10:50 +00:00
Boaz Brickner 868c4b768c C++ interop: Don't crash when looking up names inside an incomplete C++ class/struct/union (#6096)
Only do the lookup when the class is complete.

Before this change we crash in `Sema::LookupQualifiedName()` on
`Declaration context must already be complete!`.
2025-09-18 22:03:42 +00:00
dependabot[bot] d137cbe1f1 Bump rexml from 3.3.9 to 3.4.2 in /website in the bundler group across 1 directory (#6088)
Bumps the bundler group with 1 update in the /website directory:
[rexml](https://github.com/ruby/rexml).

Updates `rexml` from 3.3.9 to 3.4.2
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/ruby/rexml/releases">rexml's
releases</a>.</em></p>
<blockquote>
<h2>REXML 3.4.2 - 2025-08-26</h2>
<h3>Improvement</h3>
<ul>
<li>
<p>Improved performance.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/244">GH-244</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/245">GH-245</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/246">GH-246</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/249">GH-249</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/256">GH-256</a></li>
<li>Patch by NAITOH Jun</li>
</ul>
</li>
<li>
<p>Raise appropriate exception when failing to match start tag in
DOCTYPE</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/247">GH-247</a></li>
<li>Patch by NAITOH Jun</li>
</ul>
</li>
<li>
<p>Deprecate accepting array as an element in XPath.match, first and
each</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/252">GH-252</a></li>
<li>Patch by tomoya ishida</li>
</ul>
</li>
<li>
<p>Don't call needless encoding_updated</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/259">GH-259</a></li>
<li>Patch by Sutou Kouhei</li>
</ul>
</li>
<li>
<p>Reuse XPath::match</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/263">GH-263</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Cache redundant calls for doctype</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/264">GH-264</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Use Safe Navigation (&amp;.) from Ruby 2.3</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/265">GH-265</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Remove redundant return statements</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/266">GH-266</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Added XML declaration check &amp; Source#skip_spaces method</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/282">GH-282</a></li>
<li>Patch by NAITOH Jun</li>
<li>Reported by Sofi Aberegg</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>Fix docs typo
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/248">GH-248</a></li>
<li>Patch by James Coleman</li>
</ul>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ruby/rexml/blob/master/NEWS.md">rexml's
changelog</a>.</em></p>
<blockquote>
<h2>3.4.2 - 2025-08-26 {#version-3-4-2}</h2>
<h3>Improvement</h3>
<ul>
<li>
<p>Improved performance.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/244">GH-244</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/245">GH-245</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/246">GH-246</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/249">GH-249</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/256">GH-256</a></li>
<li>Patch by NAITOH Jun</li>
</ul>
</li>
<li>
<p>Raise appropriate exception when failing to match start tag in
DOCTYPE</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/247">GH-247</a></li>
<li>Patch by NAITOH Jun</li>
</ul>
</li>
<li>
<p>Deprecate accepting array as an element in XPath.match, first and
each</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/252">GH-252</a></li>
<li>Patch by tomoya ishida</li>
</ul>
</li>
<li>
<p>Don't call needless encoding_updated</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/259">GH-259</a></li>
<li>Patch by Sutou Kouhei</li>
</ul>
</li>
<li>
<p>Reuse XPath::match</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/263">GH-263</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Cache redundant calls for doctype</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/264">GH-264</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Use Safe Navigation (&amp;.) from Ruby 2.3</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/265">GH-265</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Remove redundant return statements</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/266">GH-266</a></li>
<li>Patch by pboling</li>
</ul>
</li>
<li>
<p>Added XML declaration check &amp; Source#skip_spaces method</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/282">GH-282</a></li>
<li>Patch by NAITOH Jun</li>
<li>Reported by Sofi Aberegg</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>Fix docs typo
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/248">GH-248</a></li>
<li>Patch by James Coleman</li>
</ul>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ruby/rexml/commit/f36916fe1c66b8cdc1fe482263115625e084d8fe"><code>f36916f</code></a>
Add 3.4.2 entry (<a
href="https://redirect.github.com/ruby/rexml/issues/284">#284</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/5859bdeac792687eaf93d8e8f0b7e3c1e2ed5c23"><code>5859bde</code></a>
Added XML declaration check &amp; <code>Source#skip_spaces</code> method
(<a
href="https://redirect.github.com/ruby/rexml/issues/282">#282</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/1d876e3bf658b7b4ec7c3372867521695e8eb023"><code>1d876e3</code></a>
Bump actions/checkout from 4 to 5 (<a
href="https://redirect.github.com/ruby/rexml/issues/283">#283</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/c87bda8bb8773da7e5a0faf9f16ff165eb052a35"><code>c87bda8</code></a>
Remove ostruct from dev deps (<a
href="https://redirect.github.com/ruby/rexml/issues/281">#281</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/c60ae027a3c20f359fdf76fa41ae64d22313f482"><code>c60ae02</code></a>
Remove bundler from dev deps (<a
href="https://redirect.github.com/ruby/rexml/issues/277">#277</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/9b084d78708638cedff54743edc0907c4bd6574a"><code>9b084d7</code></a>
Fix &amp; Deprecate REXML::Text#text_indent (<a
href="https://redirect.github.com/ruby/rexml/issues/275">#275</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/04a589a61bf4e366abee8764ee74b03f4aecc4aa"><code>04a589a</code></a>
Fix a bug that XPath can't be used for no document element (<a
href="https://redirect.github.com/ruby/rexml/issues/268">#268</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/66232eaf680d0937ae59bea285cdb8e4d3d88a93"><code>66232ea</code></a>
Remove redundant return statements (<a
href="https://redirect.github.com/ruby/rexml/issues/266">#266</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/63f3e9772595a64b036953f0ab026d2ea5560a3b"><code>63f3e97</code></a>
Use Safe Navigation (&amp;.) from Ruby 2.3 (<a
href="https://redirect.github.com/ruby/rexml/issues/265">#265</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/d427fc5914fcc17d7247c5ff9099ee38639d6702"><code>d427fc5</code></a>
Avoid redundant calls for doctype (<a
href="https://redirect.github.com/ruby/rexml/issues/264">#264</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/ruby/rexml/compare/v3.3.9...v3.4.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=rexml&package-manager=bundler&previous-version=3.3.9&new-version=3.4.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-18 16:33:00 +00:00
Dana Jansens b1b79c1bac Set deduce_through to false for FacetType, since we don't deduce through it (#6087)
We decided on 2025-04-02 not to do deduction through facet types,
because types can implement a generic interface multiple times with
different arguments. See:
https://docs.google.com/document/d/1Iut5f2TQBrtBNIduF4vJYOKfw7MbS8xH_J01_Q4e6Rk/edit?pli=1&resourcekey=0-mc_vh5UzrzXfU4kO-3tOjA&tab=t.0#heading=h.95phmuvxog9n

Then we no longer need the case handling `FacetTypeId` in deduce.cpp. We
move the comment over to the definition of the `FacetType::Kind`.

The deduce case was for `FacetTypeId`, not `FacetType`, but `FacetType`
is the only instruction which holds such an Id.
2025-09-18 13:29:53 +00:00
Boaz Brickner 26cb28196d Fix typo and update comment on why std::cout not working now. (#6095) 2025-09-18 13:06:38 +00:00
Boaz Brickner 50a0f908c6 Mark Check::Context::insts() as const and use it in more use cases (#6093) 2025-09-18 13:04:18 +00:00
Boaz Brickner 3f6b26c6f2 Fix the import C++ namespace indirectly test to make it expected to fail (#6076)
Imported namespace do not implicitly import its content, so lookup
inside them is expected to fail.
2025-09-18 07:21:00 +00:00
Dana Jansens aa0095c29f Remove TODO in GetConstantValue for FacetTypeId (#6089)
The FacetTypeId comes from a CanonicalValueStore, so the value is
hashed, and if it's the same, the same id will be returned from Add().
2025-09-17 23:37:29 +00:00
David BlaikieandDana Jansens bff0e5978b Rudimentary virtual function call interop support (#6050)
This is Itanium-specific for now (explicitly downcasting to the itanium
vtable handling code in Clang) - though it doesn't look like it'd be a
big stretch to either have conditional/two codepaths down Itanium and
MSVC in Carbon, or maybe add a virtual function in clang to avoid
needing to conditional+downcast in Carbon.

Here's a working example:
`dynamic_type.h`:
```
#ifndef TEST_H
#define TEST_H

struct A {
  virtual auto virt0() -> int;
  virtual auto virt1() -> int;
};

auto GetVal() -> A* _Nonnull;

#endif
```
`test.carbon`:
```
library "test";

import Cpp library "dynamic_type.h";
import Core library "io";

fn Run() {
  var a: Cpp.A* = Cpp.GetVal();
  Core.Print(a->virt0());
  Core.Print(a->virt1());
}
```
`dynamic_type.cpp`:
```
#include "dynamic_type.h"

auto A::virt0() -> int {
  return 0;
}

auto A::virt1() -> int {
  return 1;
}

struct B: A {
  auto virt0() -> int override {
    return 7;
  }
  auto virt1() -> int override {
    return 42;
  }
};

auto GetVal() -> A* _Nonnull {
  static B b;
  return &b;
}
```
```
$ ./bazel-bin/toolchain/carbon compile test.carbon
$ clang++-tot -g dynamic_type.cpp test.o --output=a.out
$ ./a.out
7
42
```
(linking with `carbon link` failed because we aren't linking to the C++
runtime yet, it seems, so: `ld.lld: error: undefined symbol: vtable for
__cxxabiv1::__class_type_info`)

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-09-17 23:30:13 +00:00
Boaz Brickner cac3578b86 Avoid crashing when importing a C++ struct indirectly (#6086)
Return an error constant id instead and output a TODO.

Part of #6060.
2025-09-17 17:27:52 +00:00
Boaz Brickner 02ea39f2a4 Avoid crashing when importing a C++ function indirectly (#6085)
Return an error instruction instead and output a `TODO`.

Part of #6060.
2025-09-17 12:45:30 +00:00
Boaz Brickner f29515fe4e Move C++ interop related check code files to a cpp dir (#6065)
Context:
https://github.com/carbon-language/carbon-lang/pull/5891#pullrequestreview-3178216893
2025-09-17 09:31:36 +00:00
Richard Smith 1e47f29963 Add reference support to C++ interop. (#6082)
For now this works as follows:

* `T&&` is mapped to a by-value `param: T` parameter.
* `T&` is mapped to an `addr param: T*` parameter.

In either case, we will generate a thunk, which will internally pass the
parameter as a pointer.
2025-09-17 02:03:22 +00:00
Burak EmirandBurak Emir 4edd2ced62 docs/design: object-safe has been named to dyn-compatible (#6081)
Just a small fix to docs/design.

Co-authored-by: Burak Emir <bqe@google.com>
2025-09-17 01:54:08 +00:00
Richard Smith 65a7e50037 Instantiate C++ templates at end of file. (#6084)
Mark C++ functions as used when overload resolution selects them, and
trigger Clang's end-of-TU processing at the end of the Carbon
compilation to perform instantiation and other pending cleanup steps.
2025-09-17 01:06:47 +00:00
Richard Smith 6086d6eef2 Make str copyable. (#6083) 2025-09-17 01:04:24 +00:00
730935691a Support for mapping str to std::string_view in interop. (#6079)
We already did the opposite direction; this enables use of `str` in
overload resolution.

Fixes #6062

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-09-16 23:40:33 +00:00
Richard Smith 9d84391f11 Support for passing pointers to function templates. (#6080)
When a function template takes a parameter of deduced type, and we
deduce that type to a pointer type because we passed a Carbon pointer as
the argument, don't complain that the deduced type is not nullable. We
still know that it can't be null, because we deduced it from a
non-nullable type.
2025-09-16 23:39:07 +00:00
Richard Smith b054e3d2b0 Overload resolution support for more kinds of candidate. (#6071)
* Add support for template candidates by calling the suitable
`AddCandidate` function for them.
* Add support for overloading on `*this` qualifiers by calling
`AddMethodCandidate` when appropriate.
* Make mapping from Carbon arguments to Clang arguments a little more
faithful by mapping the Carbon expression category into the Clang value
kind.
2025-09-16 21:57:32 +00:00
Richard Smith bac828d244 Add support for char keyword per #5903. (#6078)
Make inst namer and stringify print `Core.Char` and `Core.String` as
`char` and `str` respectively. Plus a few cleanups.
2025-09-16 20:45:01 +00:00
Jon Ross-Perkins 59c4cbcaf1 Treat type modifiers as distinct type structure (#6073)
This came up because `const T` needs destructor support... This change
makes `impl T as Destroy` and `impl const T as Destroy` distinct type
structures. Right now there's no impl lookup fallback (see
[#6068](https://github.com/carbon-language/carbon-lang/issues/6068)); so
when trying to destroy `const T`, there's no way to have an `impl` for
it to find.

In discussion, `MaybeUnformed` and `partial` have similar challenges, so
I'm covering them together.

In type_structure.h, I'm switching to an enum because it felt like an
easier way to be adding more types. I can switch back if preferred,
though then might take a closer look at the `operator==` because that's
kind of verbose.
2025-09-16 20:44:39 +00:00
Boaz Brickner dfe9ffd369 Rename check/import_cpp.* to check/cpp_import.* to group C++ interop logic in check (#6074)
See #6065 for context.
2025-09-16 17:22:03 +00:00
Boaz Brickner c24975d3a5 Add a test for importing a C++ namespace indirectly (#6075)
Part of #6060.
2025-09-16 14:25:31 +00:00
Boaz Brickner 9b35640a31 C++ interop: Add Cpp.<builtin_type> (#6047)
Based on proposal #5448.

Defining all `Cpp.<builtin_type>` names.
Still unsupported types on LP64: `long long`, `unsigned long long` and
`long double`.
Still unsupported types on LLP64: `long`, `unsigned long` and `long
double`.

C++ Interop Demo (on LP64):

```c++
// half.h

auto Half(long x) -> float;
auto PrintLong(long x) -> void;
auto PrintFloat(float x) -> void;
```

```c++
// half.cpp

#include <cstdio>

auto Half(long x) -> float {
  return static_cast<float>(x) / 2;
}

auto PrintLong(long x) -> void {
  printf("%ld\n", x);
}

auto PrintFloat(float x) -> void {
  printf("%f\n", x);
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "half.h";

fn Run() -> i32 {
  let x: Cpp.long = 5;
  Cpp.PrintLong(x);
  let y: Cpp.float = Cpp.Half(x);
  Cpp.PrintFloat(y);
  return 0;
}
```

```shell
$ clang -c half.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link half.o main.o --output=demo
$ ./demo
5
2.500000
```

Part of #5263.
2025-09-16 09:29:10 +00:00
Richard Smith 170237b9e0 Fix handling of enums in overload resolution. (#6072)
When mapping Carbon types to C++ types, check first for the Carbon type
being imported from C++ before checking whether it's an adapter for a
builtin. Enums imported from C++ will be both, and it's important we map
them back to the enum type rather than to their underlying (integer)
type.

Fixes #6061
2025-09-16 00:35:13 +00:00
Richard Smith b44ba47cf3 Don't treat dependent types as having a copy value representation. (#6055)
Add `Dependent` value and initializing representations for types whose
representations are unknown because they are dependent. When generating
SemIR in such cases, use a worst-case initializing representation that
both provides a destination address and also propagates a potential
result value.

Use this to fix incorrect lowering and lowering crashes for specific
functions involving generic types that don't use a copy value
representation.

In lowering, be careful to distinguish between whether the initializing
representation for the generic return type uses a return slot (which
affects whether the SemIR declaration and call have one) and whether the
initializing representation for the specific return type uses a return
slot (which affects whether the LLVM IR declaration and call have one).
2025-09-15 23:59:00 +00:00
Richard Smith ca40e9d693 Support making method calls to C++ overload sets. (#6069)
Fixes #6059
2025-09-15 23:41:15 +00:00
Richard Smith 0cafb8f0e4 Store the CppOverloadSetId on CalleeFunction. (#6067) 2025-09-15 21:58:55 +00:00
Richard Smith ccca7f3bab Minor comment and naming cleanup. (#6070) 2025-09-15 21:58:43 +00:00
Dana Jansens 95b5cce9b4 Add tests that show .X and .Self.X are treated the same on the RHS of a rewrite constraint (#6056) 2025-09-15 18:11:05 +00:00
Jon Ross-PerkinsandDana Jansens 5e3bb523f8 Add builtin functions for destroy, with special requirements in facet types (#6035)
This is in support of a goal of changing the blanket `destroy` impl to
use (roughly):

```
private fn CanAggregateDestroy() -> type = "type.can_aggregate_destroy";

// Handles aggregate type destruction.
impl forall [AggregateDestroyT:! CanAggregateDestroy()] AggregateDestroyT as Destroy {
  fn Op[addr self: Self*]() = "type.aggregate_destroy";
}
```

That isn't done here because there's still other issues that migrating
raises. What this *does* do is add the builtin functions, and in
particular, support to `FacetTypeInfo` to make `CanAggregateDestroy`
work.

The "special requirement" approach in `FacetTypeInfo` allows us to
support restricting a blanket impl under the current approach of impls.
Maybe we'll find a cleaner approach that can work in the future, but
this fits into the current model by propagating similar to other
requirements. I'm using an enum mask because we have a number of similar
things to add (e.g. copy, move) but I'm not sure we need a full vector.

A few alternatives considered were:

- Supporting syntax more like `where .Self impls
TypeCanAggregateDestroy(.Self, SupportedInterface,
UnsupportedInterface)`. I think it'd be a little cleaner, but requires
better compile-time evaluation in order to assess the type of the call.
Right now it's expected to be a `FacetType` too early to make this work,
and I was concerned about pouring too much more time down this route.
- Providing an actual interface, in particular doing name lookup back
into `Core.` for an interface. This would've added name lookup overhead,
and the question of whether an `impl` exists.
- Generating an interface. This avoids the name lookup, but would still
raise the question of whether an `impl` should also be generated. Work
I've previously done generating interfaces for class destruction also
feels complex to both write and understand (an unfortunate issue).
- Still modeling as an `ImplsConstraint`, for example by defining a
special `InterfaceId::CanAggregateDestroy = -2` similar to what we do on
other ids. I was hesitant because of how this expands the number of
modes of `InterfaceId`, and things for consuming code to watch out for,
for what feels like a relatively niche set of use-cases that are only
interface-like.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-09-15 17:03:43 +00:00
Chandler CarruthandJon Ross-Perkins 3ec0bcb4fd Improve building of generated sources for ClangD (#6046)
We have grown more generation rules, so try to use a regex instead of
listing all of them.

Also, manually add the runfiles C++ library that isn't "generated", but
is symlinked into the source tree only when built.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-09-15 16:43:02 +00:00
Ivana Ivanovska 12ddfb9c7c [Carbon/C++ interop] Add support for C++ overloaded functions (#5891)
As proposed in [Carbon: C++ interop for overloaded functions and
function
templates](https://docs.google.com/document/d/1KUxumZtNe3mY3TsjW2s_ZADOlAaFlrtsLKHVILtqIaM/edit?tab=t.0),
Clang is used to perform the overload resolution using C++ rules, when
an overloaded C++ set is called from Carbon. Once a function is
selected, it's converted into a Carbon function and called using the
Carbon rules including argument conversions.

A single non-templated function is treated the same way as an overload
set and the same rules apply for its call.
Template functions are not supported yet.

Demo:

a) Non-templated function calls:

```c++
// --- overloads.h

auto foo(int a, short b) -> void;
auto foo(double a) -> void;
auto foo(int a) -> void;
```

```c++
// overloads.cpp

#include "overloads.h"
#include <cstdio>

auto foo(int a, short b) -> void {
  printf("hello from foo_int_short(%d, %d) \n", a, b);
}
auto foo(double a) -> void { printf("hello from foo_double(%f) \n", a); }
auto foo(int a) -> void { printf("hello from foo_int(%d) \n", a); }
```
```c++
library "Main";

import Cpp library "overloads.h";

fn Run() -> i32 {
  Cpp.foo(1.1 as f64);
  return 0;
}
```
```
$ clang -c overloads.cpp 
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link overloads.o main.o --output=demo
$ ./demo
hello from foo_double(1.100000) 
```

b) Constructors:
```c++
// --- constructor_overloads.h
class C {
 public:
  C();
  C(int a, int b);
};
```

```c++
// constructor_overloads.cpp
#include "constructor_overloads.h"
#include <cstdio>

C::C() { printf("hello from C() \n"); }
C::C(int a, int b) { printf("hello from C(%d, %d) \n", a, b); }
```
```c++
library "Main";

import Cpp library "constructor_overloads.h";

fn Run() -> i32 {
  let c1: Cpp.C = Cpp.C.C();
  let c2: Cpp.C = Cpp.C.C(1, 2);
  return 0;
}
```

```
$ clang -c constructor_overloads.cpp 
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link constructor_overloads.o main.o \--output=demo
$ ./demo
hello from C() 
hello from C(1, 2) 
```


Follow-ups:

- `Cpp.foo({})` - proper handling of struct literals as call args.
- Fix access for overloaded sets.
- Fix tests:
- Method calls: `error: missing object argument in method call
[MissingObjectInMethodCall]` in tests.
    - Fix `toolchain/check/testdata/interop/cpp/import.carbon` test.
    - Fix `enums` support.
    - Fix `str` -> `std::string_view` mapping.


Part of #5915
2025-09-15 12:29:49 +00:00
Richard Smith 20ac6b9270 Remove logging prints from advent example. (#6057)
Make this example just print the answer like the other tests do. This
makes automated testing of these examples easier.
2025-09-13 01:23:35 +00:00
Elliott KaltandRichard Smith f4bd6e42f9 Replace impl fn with override fn (#6008)
This proposal renames the syntax used to mark an overriding definition
of a virtual method from `impl fn` to `override fn` to avoid ambiguity:
besides indicating an overriding virtual function, it can be parsed as
an "impl" declaration when the construct following "impl" begins with a
lambda introduced by "fn".

Closes #5711

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-09-12 23:27:02 +00:00
Jon Ross-PerkinsandRichard Smith 973d721916 Some more edits to EnumBase and EnumMaskBase (#6054)
Adds a unit test, and some smaller edits:

- Remove the `=` when defining names, in order to change `}` placement
by clang-format on uses.
- context:
https://github.com/carbon-language/carbon-lang/pull/6053#discussion_r2343423178
- I believe with `EnumBase` that keeping the `=` had been a deliberate
choice, so this PR is intended to confirm that removing it is okay.
- Delete `EnumMaskBase::name`
- context:
https://github.com/carbon-language/carbon-lang/pull/6053#discussion_r2344233707
- We can't just do nothing because `EnumBase::name` uses indexing that's
incompatible with `EnumMaskBase`.
- Some small comment cleanups.
- Tests don't need to be in the `Carbon` namespace anymore, macros work
fine in other namespaces, but it's still the right namespace.
- Documentation on `EnumBase::name` seems to be referring to a prior
structure, wherein we had a macro defining the function instead of the
`Names` array.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-09-12 22:59:37 +00:00
Jon Ross-Perkins 1d19fa3954 Disable clang-tidy action in favor of clangd-tidy (#6037)
Generally seems to be working as intended: clang-tidy has variance from
a few minutes to an hour; clang-tidy hovers around 10 minutes. In this
case, the long tail of slow execution is more visible, partly because
tests will often take close to 10 minutes, if not more.

Branch enforcement should already be switched.
2025-09-12 20:10:14 +00:00
Jon Ross-Perkins 6cc5d7ed2a Add an EnumMaskBase type (#6053)
This is a bit of an experiment to see if there's a reasonable way to
write a shared enum type, rather than writing per-case wrappers for
things like `HasTypeQualifiers` or the printing. I think it's a bit
borderline complexity right now, but I'm not sure I can reduce it much
further.

This changes from things like `Internal::EnumClassName##RawEnum` to
`Internal::EnumClassName##Data::RawEnum` so that the enum entries can
have back references to bit shifts without needing to know the
containing type name. Because I'm trying to reduce duplication between
mask and non-mask enums, I did this to non-mask enums too.

This was motivated by #6035 adding another enum mask (which will grow
more entries, and is intended to switch if this is accepted), but I'm
not using that PR as a base here because I didn't want the merge
dependency.
2025-09-12 18:04:10 +00:00
Boaz Brickner 508a88e2a9 C++ inteop: Set type source info for a generated C++ thunk function (#6049)
This prevents a null pointer access crash when generating a thunk with
an automatically deduced trivial return type.
In this case, Clang calls `Sema::DeduceFunctionTypeFromReturnExpr()`
which calls `Sema::getReturnTypeLoc()`, which requires this information.

Part of #5514.
2025-09-12 07:11:36 +00:00
Richard Smith d60900cbeb Remove special case for returning value expressions by copy (#6052)
When returning a value from a function whose return type has a by-copy
initializing representation, perform initialization like we do when the
return type has an in-place initializing representation. This makes our
SemIR representation more uniform, as the return expression will now
always be an initializing expression rather than a value expression, but
more importantly it means that attempts to return a non-copyable type by
value now fail, even if the type has a by-copy initializing
representation.

This catches a bunch of places where we were returning a value of an
unconstrained template parameter `T:! type`, which we were incorrectly
allowing because we didn't notice it was not copyable. Unfortunately
this then requires quite a few test updates.

Like #6034, this exposes a lowering issue where lowering crashes when
attempting to lower a specific copy operation for certain types; a
couple more tests are temporarily disabled here. An upcoming PR
dependent on this one will fix the issue and re-enable those tests.
2025-09-12 00:13:33 +00:00
Dana Jansens 896ef4da0e Include the Name when dumping an instruction with a name (#6051)
If the first argument is an EntityNameId, then dump the name from within
it. In particular this affects dumping BindName and BindSymbolicName.

```
(lldb) dump context non_canonical_query_self_inst_id
inst96: {kind: BindSymbolicName, arg0: entity_name4, arg1: inst<none>, type: type(symbolic_constant35)}
  - name: `T`
  - type: type(symbolic_constant35): I(.Self) where .Self.(I(.Self).X) = (); {kind: FacetType, arg0: facet_type4, type: type(TypeType)}
  - value: symbolic_constant36
  - loc: LocId(<none>)
```
2025-09-11 18:50:35 +00:00
Boaz Brickner 34805543a1 Sort functions in import_cpp.cpp per import_cpp.h (#6048)
Context:
https://github.com/carbon-language/carbon-lang/pull/5891#discussion_r2247678242
2025-09-11 12:58:26 +00:00
Chandler Carruth 4776f3230b Disable the modernize headers clang-tidy check (#6045)
Our style guide suggests using `<stdint.h>` and not the `std::`
qualifiers, and this is consistent with other headers like `<time.h>`.
The `clang-tidy` check enforces the reverse pattern, so disable it to
allow us to continue following our style pattern.
2025-09-11 07:52:50 +00:00
Richard SmithandGeoff Romer 1ec8ac7ef9 Add Copy interface and use it for making copies. (#6034)
Instead of hardcoding which types are copyable, add a `Core.Copy`
interface to perform copying. Move almost all the current copy support
to that interface. Some remaining pieces are still using builtin logic
after this PR:

* For tuples and structs, builtin logic is used to perform elementwise
copies. This also supports copying *adapters of* tuples and structs,
which seems like it may not be desirable, especially for non-extending
adapters. A `Copy` impl is provided for tuples of at most 2 elements, so
that `Core.Copy` constraints are satisfied, but we can't implement this
generally until we have variadics support, and don't yet have a
mechanism to generalize this to structs.
* For `enum` types imported from C++, builtin logic is used to perform a
copy. This is temporary until we have a mechanism to identify these
types from an impl in the prelude.

One lowering test in `toolchain/lower/testdata/class/generic.carbon` is
disabled for now, as it causes a crash in the lowering code due to an
ABI mismatch between the call signature in the lowered declaration of a
specific function and the call that is generated in the specific callee.
Fixing this is a little involved, and will be done in a separate PR.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-09-10 23:55:55 +00:00
Dana Jansens 91722ae21a Stop round tripping through an InstId to get the ConstantId of a TypeId (#6044)
TypeId and ConstantId are easily interchangeable, and there's no need to
go through InstId, which is more complicated.
2025-09-10 22:16:29 +00:00
Richard Smith e8cd229e74 When performing an impl lookup, only import impls for related interfaces. (#6040)
This avoids impl lookups involving, say, `Core.Int` pulling in all ~65
impls in "prelude/types/int", which resulted in a lot of unnecessary
importing work, followed by a lot of unnecessary inst namer and inst
formatter work.

Before:
```
Ran 1335 tests in 6186 ms wall time, 146818 ms across threads
  Slowest tests:
  - toolchain/check/testdata/interop/cpp/function/arithmetic_types_bridged.carbon: 5611 ms, 5532 ms in Run
  - toolchain/check/testdata/interop/cpp/function/operators.carbon: 2034 ms, 1981 ms in Run
  - toolchain/check/testdata/primitives/import_symbolic.carbon: 1796 ms, 1786 ms in Run
  - toolchain/lower/testdata/operators/arithmetic.carbon: 1729 ms, 1728 ms in Run
  - toolchain/lower/testdata/function/generic/call_recursive_sccs_deep.carbon: 1700 ms, 1697 ms in Run
[==========] 1335 tests from 1 test suite ran. (682 ms total)
```

After:
```
Ran 1335 tests in 2419 ms wall time, 109587 ms across threads
  Slowest tests:
  - toolchain/check/testdata/interop/cpp/function/arithmetic_types_bridged.carbon: 1748 ms, 1665 ms in Run
  - toolchain/check/testdata/interop/cpp/function/operators.carbon: 1106 ms, 1057 ms in Run
  - toolchain/lower/testdata/function/generic/call_recursive_diamond.carbon: 1044 ms, 1041 ms in Run
  - toolchain/lower/testdata/function/generic/call_recursive_sccs_deep.carbon: 1015 ms, 1012 ms in Run
  - toolchain/lower/testdata/operators/arithmetic.carbon: 998 ms, 997 ms in Run
[==========] 1335 tests from 1 test suite ran. (652 ms total)
```

That's still slower than it should be, but a large improvement
nonetheless.

Fixes #6029
2025-09-10 21:40:27 +00:00
Chandler CarruthandDana Jansens 1c6e859a50 Many improvements to the filesystem library (#6000)
This is a collection of improvements to the filesystem library motivated
by using it to build a runtimes cache. It adds several core features:

- Advisory file locking
- Renaming of entries
- Testing for things being open
- File timestamp querying and updating

It also makes several more minor improvements such as improving the
names of functions and making them work in a more predictable fashion.
For example, the functions to read and write an entire file to/from
strings now actually handle the entire file rather than potentially
composing with other reads or writes, and adding the word `File` to
their name makes that more clear. Similarly, directory reading is more
robust in the face of repeatedly reading the same directory, and several
convenience functions were added to handle common patterns of reading
directories.

There is also a small fix to `ostream` uncovered by the tests added
here.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-09-10 20:21:51 +00:00
Jon Ross-Perkins e45d304340 Remove unused EnumBase macros (#6043)
These were used by explorer code.
2025-09-10 19:13:16 +00:00
Jon Ross-Perkins b0d93c2393 Use enumerated values in formatter (#6042)
Noticed this was essentially just fetching then discarding the values,
which felt odd to me. I was considering adding an `ids()` function, but
this would leave only 3 spots that'd use it, and the absence seems like
it'll nudge code towards using the value of `enumerate()` when
reasonable.
2025-09-10 18:40:48 +00:00
Jon Ross-Perkins 0da91115cd Run clangd-tidy for the merge queue (#6041)
Necessary for switching off clang-tidy, just forgot about this
(temporarily switched back enforcement).
2025-09-10 17:59:11 +00:00
Dana Jansens ed43fd2c1c Give the BindSymbolicName for .Self in a binding pattern a FacetType type (#6036)
If it's just `TypeType` then the `BindSymbolicName` appears directly in
type positions, but if it is replaced with another facet value, then we
would need to insert a `FacetAccessType` around it. By giving it a
`FacetType` type, like other `BindSymbolicName`s we make it consistent
and avoid having to introduce extra instructions.
2025-09-10 17:57:08 +00:00
Boaz Brickner d6fbe3c663 C++ interop: Support importing operators defined in namespaces (#6024)
C++ Interop Demo:

```c++
// my_number.h

namespace MyNamespace {

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  auto value() const -> int { return value_; }

 private:
  int value_;
};

auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber;

}  // namespace MyNamespace
```

```c++
// my_number.cpp

#include "my_number.h"

namespace MyNamespace {

auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() + rhs.value());
}

}  // namespace MyNamespace
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn Run() -> i32 {
  let n1: Cpp.MyNamespace.MyNumber = Cpp.MyNamespace.MyNumber.MyNumber(5);
  Core.Print(n1.value());
  let n2: Cpp.MyNamespace.MyNumber = Cpp.MyNamespace.MyNumber.MyNumber(7);
  Core.Print(n2.value());
  let n3: Cpp.MyNamespace.MyNumber = n1 + n2;
  Core.Print(n3.value());
  return 0;
}
```

Before this change:
```
$ bazel-bin/toolchain/carbon compile main.carbon
main.carbon:13:38: error: cannot access member of interface `Core.AddWith(Cpp.MyNamespace.MyNumber)` in type `Cpp.MyNamespace.MyNumber` that does not implement that interface
  let n3: Cpp.MyNamespace.MyNumber = n1 + n2;
                                     ^~~~~~~
```

With this change:

```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
5
7
12
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
2025-09-10 14:03:09 +00:00
Jon Ross-Perkins 3f799bd987 Use explicit(false) for implicit construction (#6039)
Echoing what was added in #5608, updating existing uses. Unfortunately
there's divergent behavior for operators versus constructors, so keeping
the nolint on those.
2025-09-10 13:47:59 +00:00
Jon Ross-Perkins b74fdf52de Use typename on templates for consistency. (#6038)
They're essentially equivalent, we just typically write `typename`; even
in the examples here, most have other templates in the same file that
use `typename`.
2025-09-10 13:44:36 +00:00
Jon Ross-Perkins 0518fdebbc Fix potential fingerprint conflict in constraints (#6033)
This uses each vector's size as a barrier between lists, to eliminate
the possibility of incidental collisions between entries of different
lists. This is the same as is done inside `AddBlock`.
2025-09-09 21:44:03 +00:00
Boaz Brickner 56adfa20ce C++ interop: Add a test for calling an operator on an inner class (#6030)
This currently works and I'd like to keep it that way when adding
operators in namespace support.

Part of #5995.
2025-09-09 13:06:55 +00:00
Dana Jansens 1dbf000905 Avoid python stack traces when hitting ^C in autoupdate (#6004)
Currently hitting ^C prints out two stack traces, requiring scrolling up
though multiple screens of scrollback to get back to the autoupdate
results. This primarily shows up when hitting ^C while it's symbolizing
a C++ stack trace.
2025-09-08 21:17:36 +00:00
Dana Jansens b92e23962a Use a FixedSizeValueStore<CheckIRId> in Lower::Context (#6021)
Now that the total number of IRs is available from SemIR::File, we can
use FixedSizeValueStore to store/look up values mapped from a CheckIRId
instead of a Map, which is demonstrably faster (unsurprisingly, since
it's just a vector index). See #6019.

This replaces a Map with FixedSizeValueStore in Lower::Context for use
in `GetFileContext()`. This function is used in some places that can
become hot, such as `HandleInst()` and `GetType()`. In our current
lowering tests, there's no measurable performance change from this PR,
but based on #6019 we can expect to see one as the amount of
instructions being lowered increases. Using a FixedSizeValueStore when
possible is a better approach than a map, generally.
2025-09-08 17:33:54 +00:00
Dana Jansens 64139e5d65 Stop using Map for the cache in InstFingerprinter (#6019)
This takes the debug runtime of
`toolchain/check/testdata/interop/cpp/function/arithmetic_types_bridged.carbon`
from 4.7s down to about 4s (so 15% faster overall).

There's still lots of room to improve this test which seems to be
hitting lots of pathological behaviour, but InstNamer is 30% of the
runtime, with fingerprinting's `InstFingerprinter::GetOrCompute`
consuming 10% of cycles. We reduce its impact by using a vector of
vectors instead of a Map for the cache of fingerprints. After this
change InstNamer drops below 24% of the runtime.

Also move the instruction name when giving it to `AllocateName` since it
receives std::string by value, though this doesn't show up in the
profile for the test.
2025-09-08 16:15:10 +00:00
Boaz Brickner 471b394c6d C++ interop: Support unary operators (#6020)
Newly supported: `-`.
Partially supported due to lack of reference support: `++` (prefix),
`--` (prefix).
Not supported due to lack of Carbon support to call them correctly: `+`,
`++` (postfix), `--` (postfix), `~`, `!`, `&`, `*`, `->`.

Also (for consistency):
* Add the operator declarations to unsupported binary operators tests.
* Logical operators and the unary `operator&` (address of) are expected
to be called by explicitly calling `operatorX`.

C++ Interop Demo:

```c++
// my_number.h

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  auto value() const -> int { return value_; }

 private:
  int value_;
};

auto operator++(MyNumber operand) -> MyNumber;
auto operator--(MyNumber operand) -> MyNumber;
auto operator-(MyNumber operand) -> MyNumber;
```

```c++
// my_number.cpp

#include "my_number.h"

auto operator++(MyNumber operand) -> MyNumber {
  return MyNumber(operand.value() + 1);
}

auto operator--(MyNumber operand) -> MyNumber {
  return MyNumber(operand.value() - 1);
}

auto operator-(MyNumber operand) -> MyNumber {
  return MyNumber(-operand.value());
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn Run() -> i32 {
  var num: Cpp.MyNumber = Cpp.MyNumber.MyNumber(14);
  Core.Print(num.value());
  ++num;
  Core.Print(num.value());
  --num;
  Core.Print(num.value());
  num = -num;
  Core.Print(num.value());
  return 0;
}
```

```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
14
14
14
-14
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
2025-09-08 15:39:08 +00:00
Chandler Carruth 049abc638d Update LLVM to pick up new compiler-rt build rules (#6023)
This removes the need for a patch and improves on the quality of the
rules significantly. A follow-up PR will use this to apply a number of
fixes to how we build the runtimes.
2025-09-08 14:51:23 +00:00
Boaz Brickner b88b53e7e3 C++ interop: Add support for importing globals (#6005)
This supports importing globals in the global scope and within
namespaces, and support for class static data members.

C++ Interop Demo:

```c++
// my_global.h

extern int my_global;
void inc_my_global();
```

```c++
// my_global.cpp

#include "my_global.h"

int my_global = 5;

void inc_my_global() {
  ++my_global;
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_global.h";

fn Run() -> i32 {
  Core.Print(Cpp.my_global);
  Cpp.inc_my_global();
  Core.Print(Cpp.my_global);
  return 0;
}
```

```shell
$ clang -c my_global.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_global.o main.o --output=demo
$ ./demo
5
6
```

Part of #6006.
2025-09-08 08:34:55 +00:00
Boaz Brickner 321891cd8e Hello world C++ interop example (#5991)
Based on #5920.
Added commented out better examples and clarified what is missing to
support them.
Added `tags` support to `carbon_binary` (based on #5967) to set the
`BUILD` rule to manual until we can find `cstdio` in macos.

```shell
$ bazel run examples/interop/cpp:hello_world
...
Hello world!
```
2025-09-08 07:44:29 +00:00
Chandler Carruth 0691d4827c Update LLVM (#6022)
Notably, this updates past a major AST refactoring and tries to apply
those changes across the toolchain.
2025-09-06 08:36:10 +00:00
Boaz Brickner ee42b2db93 C++ interop: Support more binary operators (#6017)
Already supported: `+`.
Newly supported: `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, `>>`, `==`,
`!=`, `<`, `>`, `<=`, `>=`.
Partially supported due to lack of reference support: `+=`, `-=`, `*=`,
`/=`, `%=`, `&=`, `|=`, `^=`.
Not supported due to lack of reference support: `<<=`, `>>=`.
Not supported (I think Carbon doesn't want overloading these): `&&`,
`||`.

C++ Interop Demo:

```c++
// my_number.h

class MyNumber {
 public:
  explicit MyNumber(int value) : value_(value) {}
  auto value() const -> int { return value_; }
  void set_value(int value) { value_ = value; }

 private:
  int value_;
};

// Arithmetic
auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator-(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator*(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator/(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator%(MyNumber lhs, MyNumber rhs) -> MyNumber;

// Bitwise
auto operator&(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator|(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator^(MyNumber lhs, MyNumber rhs) -> MyNumber;
auto operator<<(MyNumber lhs, int shift) -> MyNumber;
auto operator>>(MyNumber lhs, int shift) -> MyNumber;

// Compound Arithmetic
auto operator+=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;
auto operator-=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;
auto operator*=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;
auto operator/=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;
auto operator%=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;

// Compound Bitwise
auto operator&=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;
auto operator|=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;
auto operator^=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull;

// Relational
auto operator==(MyNumber lhs, MyNumber rhs) -> bool;
auto operator!=(MyNumber lhs, MyNumber rhs) -> bool;
auto operator<(MyNumber lhs, MyNumber rhs) -> bool;
auto operator>(MyNumber lhs, MyNumber rhs) -> bool;
auto operator<=(MyNumber lhs, MyNumber rhs) -> bool;
auto operator>=(MyNumber lhs, MyNumber rhs) -> bool;
```

```c++
// my_number.cpp

#include "my_number.h"

// Arithmetic
auto operator+(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() + rhs.value());
}
auto operator-(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() - rhs.value());
}
auto operator*(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() * rhs.value());
}
auto operator/(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() / rhs.value());
}
auto operator%(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() % rhs.value());
}

// Bitwise
auto operator&(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() & rhs.value());
}
auto operator|(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() | rhs.value());
}
auto operator^(MyNumber lhs, MyNumber rhs) -> MyNumber {
  return MyNumber(lhs.value() ^ rhs.value());
}
auto operator<<(MyNumber lhs, int shift) -> MyNumber {
  return MyNumber(lhs.value() << shift);
}
auto operator>>(MyNumber lhs, int shift) -> MyNumber {
  return MyNumber(lhs.value() >> shift);
}

// Compound Arithmetic
auto operator+=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs + rhs);
}
auto operator-=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs - rhs);
}
auto operator*=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs * rhs);
}
auto operator/=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs / rhs);
}
auto operator%=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs % rhs);
}

// Compound Bitwise
auto operator&=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs & rhs);
}
auto operator|=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs | rhs);
}
auto operator^=(MyNumber* _Nonnull lhs, MyNumber rhs) -> MyNumber* _Nonnull {
  return &(*lhs = *lhs ^ rhs);
}

// Relational
auto operator==(MyNumber lhs, MyNumber rhs) -> bool {
  return lhs.value() == rhs.value();
}
auto operator!=(MyNumber lhs, MyNumber rhs) -> bool {
  return lhs.value() != rhs.value();
}
auto operator<(MyNumber lhs, MyNumber rhs) -> bool {
  return lhs.value() < rhs.value();
}
auto operator>(MyNumber lhs, MyNumber rhs) -> bool {
  return lhs.value() > rhs.value();
}
auto operator<=(MyNumber lhs, MyNumber rhs) -> bool {
  return lhs.value() <= rhs.value();
}
auto operator>=(MyNumber lhs, MyNumber rhs) -> bool {
  return lhs.value() >= rhs.value();
}
```

```carbon
// main.carbon

library "Main";

import Core library "io";
import Cpp library "my_number.h";

fn PrintBool(b: bool) {
  if (b) {
    Core.Print(1);
  } else {
    Core.Print(0);
  }
}

fn Run() -> i32 {
  // Arithmetic
  var num1: Cpp.MyNumber = Cpp.MyNumber.MyNumber(14);
  var num2: Cpp.MyNumber = Cpp.MyNumber.MyNumber(5);
  Core.Print(num1.value());
  Core.Print(num2.value());
  Core.Print((num1 + num2).value());
  Core.Print((num1 - num2).value());
  Core.Print((num1 * num2).value());
  Core.Print((num1 / num2).value());
  Core.Print((num1 % num2).value());

  // Bitwise
  var bits1: Cpp.MyNumber = Cpp.MyNumber.MyNumber(12);
  var bits2: Cpp.MyNumber = Cpp.MyNumber.MyNumber(10);
  Core.Print(bits1.value());
  Core.Print(bits2.value());
  Core.Print((bits1 & bits2).value());
  Core.Print((bits1 | bits2).value());
  Core.Print((bits1 ^ bits2).value());
  Core.Print((bits1 << 2).value());
  Core.Print((bits1 >> 1).value());

  // Compound Arithmetic
  var c: Cpp.MyNumber = Cpp.MyNumber.MyNumber(100);
  Core.Print(c.value());
  &c += Cpp.MyNumber.MyNumber(10);
  Core.Print(c.value());
  &c -= Cpp.MyNumber.MyNumber(20);
  Core.Print(c.value());
  &c *= Cpp.MyNumber.MyNumber(2);
  Core.Print(c.value());
  &c /= Cpp.MyNumber.MyNumber(6);
  Core.Print(c.value());
  &c %= Cpp.MyNumber.MyNumber(9);
  Core.Print(c.value());

  // Compound Bitwise
  &c |= Cpp.MyNumber.MyNumber(12);
  Core.Print(c.value());
  &c &= Cpp.MyNumber.MyNumber(7);
  Core.Print(c.value());
  &c ^= Cpp.MyNumber.MyNumber(10);
  Core.Print(c.value());

  // Relational
  var rel1: Cpp.MyNumber = Cpp.MyNumber.MyNumber(20);
  var rel2: Cpp.MyNumber = Cpp.MyNumber.MyNumber(30);
  var rel3: Cpp.MyNumber = Cpp.MyNumber.MyNumber(20);
  Core.Print(rel1.value());
  Core.Print(rel2.value());
  Core.Print(rel3.value());
  PrintBool(rel1 == rel3);
  PrintBool(rel1 != rel2);
  PrintBool(rel1 < rel2);
  PrintBool(rel2 > rel1);
  PrintBool(rel1 <= rel3);
  PrintBool(rel1 >= rel2);

  return 0;
}
```

```shell
$ clang -c my_number.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link my_number.o main.o --output=demo
$ ./demo
14
5
19
9
70
2
4
12
10
8
14
6
48
6
100
110
90
180
30
3
15
7
13
20
30
20
1
1
1
1
1
0
```

Part of https://github.com/carbon-language/carbon-lang/issues/5995.
2025-09-05 13:03:10 +00:00
Richard Smith db0a00d713 Fix double-destruction of temporaries. (#6010)
Attach the cleanup to the `Temporary` instruction instead of to the
`TemporaryStorage` instruction. We create `TemporaryStorage`
instructions speculatively when creating an initializing expression, and
may overwrite those instructions with other instructions if it turns out
that a temporary is not required. Instead, wait until we finalize the
temporary and create a `Temporary` instruction to register the cleanup.
2025-09-04 19:19:59 +00:00
Richard Smith f943f31e41 Allow a value of type MaybeUnformed(T) to convert to T with unsafe as (#6014)
We already allowed this for reference expressions; this extends the
support to also cover value expressions. This requires a little more
work because the value representation of `T` and `MaybeUnformed(T)`
don't necessarily match in general.
2025-09-04 19:10:28 +00:00
Richard Smith 51cb078da4 Support lowering of functions with variable binding parameters. (#6012)
Fix a crash when attempting to lower a function with a variable binding
as a parameter. This is a narrowly-targeted fix, and not the right
longer-term approach; more complex patterns as function parameters will
still fail and likely crash.
2025-09-04 15:02:37 +00:00
Jon Ross-Perkins 74a8d51d78 Add test name to all file_test errors (#6011)
Common case is going to be like:

```
Running tests with 64 thread(s)

Autoupdate can't discard non-CHECK lines inside conflicts:

......................!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!..!!!!!!!!!!!!!!!!!!!!.
```

->

```
Running tests with 64 thread(s)

toolchain/check/testdata/as/unsafe_as.carbon: Autoupdate can't discard non-CHECK lines inside conflicts:

......................!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!..!!!!!!!!!!!!!!!!!!!!.
```

(i.e., the conflict line was blank)

One error had the test name, I'm dropping it here, meaning:

```
................................................................................
Missing AUTOUPDATE/NOAUTOUPDATE setting: toolchain/codegen/testdata/assembly/basic.carbon
................................................................................
```

->

```
................................................................................
toolchain/codegen/testdata/assembly/basic.carbon: Missing AUTOUPDATE/NOAUTOUPDATE setting
................................................................................
```

For single-threaded runs, at the top there's already:

```
  } else if (single_threaded) {
    std::unique_lock<std::mutex> lock(output_mutex);
    llvm::errs() << "\nTEST: " << test.test_name << ' ';
  }
```
2025-09-04 14:54:47 +00:00
Dana JansensandJon Ross-Perkins 70f104aa40 Always import canonical instructions except for exceptional Decl cases (#6009)
There are a few instructions that import in multiple phases, which
receive the `const_id` and use it to construct multiple constants until
building the final constant value. These include
`AssociatedConstantDecl`, `FunctionDecl`, and `InterfaceDecl`.

Other instructions just construct a constant value in a single attempt,
once all their dependencies are imported. For these instruction types,
avoid importing the non-canonical instruction. Always get the canonical
constant instruction and import that.

Since the constant value of an instruction can have a very different
structure than its non-canonical value, this ensures import has a
consistent structure to work with, by only working with canonical values
as much as possible.

The `VtableDecl` and `VtablePtr` were set up to pass along `const_id`
but do not actually require multiple phases, so they have been changed
to stop passing along the unused (and always empty) `const_id`.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-09-03 22:36:27 +00:00
Richard Smith cb5e2e1597 Improve support for qualification conversions. (#5999)
* Treat `MaybeUnformed` and `partial` as qualifiers, like `const`.
* Allow pointer conversions to add qualifiers.
* Allow unsafe pointer conversions to remove qualifiers.
* Allow conversions on non-reference expressions to drop `const`.
* Allow unsafe conversions on any expression to drop `const`.
* Allow unsafe conversions on non-initializing expressions to drop
  `partial`. For initializing expressions, we should initialize the
  vptr when dropping `partial`; this is not yet supported so we reject.
* Allow conversions on reference expressions to add `MaybeUnformed`.
* Allow unsafe conversions on reference expressions to drop
  `MaybeUnformed`. For non-reference expressions, additional work is
  required, because the value / initializing representation may not
  match between `T` and `MaybeUnformed(T)`, so those are rejected for
  now.
2025-09-03 21:00:12 +00:00
Richard Smithandjosh11b 10fab24451 Add example showing basic interop with C++ RE2 library (#5967)
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-09-03 20:41:48 +00:00
Boaz Brickner 870c5380a0 C++ interop: Support importing binary operator+ (#5996)
Triggered by calling a binary operator with LHS being an imported C++
class type.

Not supported (yet):
* Multiple overloads.
* Other operators.

C++ Interop Demo:

```c++
// hello_world.h

class C {
 public:
  C(int x) : x_(x) {}
  auto x() const -> int { return x_; }

 private:
  int x_ = 0; 
};

auto operator+ (C c1, C c2) -> C;
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

auto operator+ (C c1, C c2) -> C {
  printf("Adding %d with %d\n", c1.x(), c2.x());
  return C(c1.x() + c2.x());
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  let c1 : Cpp.C = Cpp.C.C(7);
  let c2 : Cpp.C = Cpp.C.C(8);
  let c3 : Cpp.C = c1 + c2;
  let c4 : Cpp.C = c3 + c2;
  return 0;
}

```

```shell
$ clang -c hello_world.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link hello_world.o main.o --output=demo
$ ./demo
Adding 7 with 8
Adding 15 with 8
```

Part of #5995.
2025-09-03 12:01:20 +00:00
Elliott Kalt 58de34e534 Decouple associated constants from let (#5973)
Decouples associated constants from being special cased in let handlers.
Enforces associated constant grammar restrictions in parsing instead of
checking.

Closes #5411
2025-09-02 23:15:26 +00:00
Richard Smith 0e6dd7e701 Add MaybeUnformed(T) type. (#5989)
This type has the same object representation as `T`, but always uses a
pointer type as its value representation. No other semantics are
provided for it yet.
2025-09-02 20:50:49 +00:00
Richard SmithandDana Jansens 4483d1e5a7 Recover better from invalid C++ classes. (#5992)
When importing a class definition, don't ask for the class layout if the
definition is invalid. Avoids an assertion failure in Clang.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-09-02 19:32:35 +00:00
Dana Jansens 00d0eb85e2 Remove redundant if condition after #5971 (#6003)
PR #5971 added this same condition as an early-out earlier in the
PerformBuiltinConversion function.
2025-09-02 19:28:54 +00:00
Boaz Brickner b5d86fdb6f Properly dump SemIR for inline C++ imports (#6001)
Dumping SemIR crashed on inline C++ imports and this outputs `import Cpp
inline` instead.
Followup of #5904.
2025-08-29 21:36:10 +00:00
Boaz Brickner 8adb3570ac C++ Interop: Add support for char (#5988)
Added tests for different character types.
`char` is currently not in primitives prelude, so had to use full
prelude.

C++ Interop Demo:

```carbon
// main.carbon

library "Main";

import Cpp inline '''
auto output_char(char c) -> void {
  printf("%c", c);
}
''';

fn Run() -> i32 {
  let msg: array(Core.Char, 13) =
      ('H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n');
  for (c: Core.Char in msg) {
    Cpp.output_char(c);
  }
  return 0;
}
```

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o --output=demo
$ ./demo
Hello world!
```

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2025-08-29 01:11:24 +00:00
Richard Smith 50e5476ee3 Add support for unsafe as operator to the toolchain. (#5993)
Following the direction of #5913, add support for parsing an `unsafe as`
operator. For now, we allow one additional conversion using `unsafe as`
beyond the conversions supported by `as`: we permit pointer conversions
that remove qualifiers, such as `const T*` -> `T*`.
2025-08-28 23:00:53 +00:00
David Blaikie 1d0f30df3a Fix a use of an imported InstId used where a local InstId is required (#5998)
Found by WIP validation for this type of issue ongoing in #5997

I'm not entirely sure how the one test update falls out of this change -
but it is from the same test that I originally reduced the problem from,
which is reassuring.

The reduced test case I investigated the issue with was this:
`a.carbon`:
```
library "lib";
interface I1(Other:! type) {
   let Result:! type;
}
```
`b.carbon`:
```
import library "lib";
class T1 { }
impl T1 as I1(Self) where .Result = Self { }
```
The SemIR dump diff looked like this:
```
89c89
<   %Main.import_ref.b6f = import_ref Main//lib, inst28 [no loc], unloaded
---
>   %Main.import_ref.b6f = import_ref Main//lib, inst27 [no loc], unloaded
96c96
<   %Main.import_ref.f7b: @I1.%I1.type (%I1.type.e87) = import_ref Main//lib, inst28 [no loc], loaded [symbolic = @I1.%Self (constants.%Self.c47)]
---
>   %Main.import_ref.f7b: @I1.%I1.type (%I1.type.e87) = import_ref Main//lib, inst27 [no loc], loaded [symbolic = @I1.%Self (constants.%Self.c47)]
```
Which is a difference, but given the `inst28`/`inst27` don't appear
anywhere else than these two lines, it doesn't give a terribly
meaningful diff/story about what changed - but perhaps it's
sufficient...

Not sure if this test ^ is sufficiently more interesting than the diff
update already in this patch. If so, happy to add the above as a new
test case.

Open to ideas.
2025-08-28 20:02:26 +00:00
pascal754 9cfbe9eac9 Fix a typo in README.md (#5994) 2025-08-28 16:25:53 +00:00
Richard SmithandChandler Carruth bd90fe1d9b Interop: map C++ std::string_view into Carbon str when importing. (#5985)
We assume these types have the same representation. For now, that will
only be the case for libc++ on 64-bit targets, because libc++ puts the
size field first, and `Core.String` always uses a 64-bit size field even
on 32-bit targets.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-08-27 01:02:39 +00:00
Richard Smith 82ba1a43a1 Support for importing C++ enum types. (#5978)
We import C++ enum types as Carbon class types as adapters for the
corresponding builtin integer type, and we import enumerator constants
as integer constants of that class type.

No operators are supported on such values for now; eventually once we
start asking Clang to implement operators on C++-owned types, these
types should be handled in the same way. However, they can be converted
to the corresponding integer type with `as` via adapter conversion, and
integer builtin functions can operate on them.
2025-08-26 23:11:35 +00:00
Boaz Brickner 6ba900ab97 Update comment to not be specific for signed integers (#5987)
Following the change in #5980.
2025-08-26 21:49:31 +00:00
Richard Smith 742017c475 Widen integer loads and stores to a multiple of 8 bits. (#5986)
This makes Carbon's loads and stores ABI-compatible with Clang's for
`bool` and `_BitInt(N)`.
2025-08-26 21:49:24 +00:00
Richard Smith 3533668186 Support for building thunks for C++ constructors. (#5977) 2025-08-26 21:49:11 +00:00
Richard Smith d37f1ae6b5 Add return value support to C++ thunks. (#5976)
Based on #5948. A couple of tricky parts:

* When generating the C++ side of the thunk, we are given a pointer to
the location to emplace the return value. The only mechanism C++
provides to perform this emplacement is using placement `operator new`,
which requires a library function in the `<new>` header. We handle this
by declaring that library function ourselves, and rely on Clang not
actually needing a definition for it (which the standard library owns).

* On the Carbon side of the thunk, we want to form an initializing
expression as the result of the call. We don't have a way of expressing
in SemIR that an initializing expression performs its initialization by
storing through a pointer, so this PR adds a new initializing
instruction, `InPlaceInit`, to model an initialization that's performed
opaquely in-place.
2025-08-26 02:23:38 +00:00
Richard Smith 1331ade57f Attempt to complete the source type in a conversion. (#5984)
This is necessary if the source type is an adapter, as we would not
otherwise be able to determine what type it adapts and hence could be
converted to.
2025-08-26 00:33:12 +00:00
Richard Smith 8c9080801c Support for building thunks for C++ methods. (#5972)
Also tweak how we import C++ methods to properly handle C++23's explicit
object parameters.
2025-08-25 22:33:51 +00:00
Richard Smith ddafbc9331 Use direct passing for 32- and 64-bit unsigned integers. (#5980)
Previously we only avoided creating a thunk for signed integers. But the
same logic also applies to the unsigned 32-bit and 64-bit types.
2025-08-25 21:49:03 +00:00
Chandler Carruth 74016d47f9 Rework the IsSuccess matcher to be fully polymorphic (#5981)
Previously, this matcher mostly worked, but the `DescribeTo` functions
wouldn't compile when another polymorphic matcher was nested to match
the value.

The updated code uses the same polymorphic matcher design as used by
`Not` and others in Google Test itself.

I've added a test that uses `VariantWith` to nest matchers more deeply
with `IsSuccess`. This test doesn't compile prior to this change.
2025-08-25 16:28:11 +00:00
d49cb3ecfb Start building Clang runtimes on-demand (#5338)
This is the first step to having Clang's runtime libraries fully
available for the Carbon toolchain. This PR focuses on the lowest level
runtimes, the CRT files and the builtins library.

The goal is to intercept Clang runs where it needs these
target-dependent pieces to be available, and build them on demand using
our Clang-running infrastructure. This avoids most of the subprocess
overhead, but there is still some due to missing features in Clang.

This requires exporting the sources for these runtimes from the Bazel
build, and installing them in our target-independent resource directory.
We then build a simplified "build" of these sources within the
`ClangRunner` itself to produce the specific artifacts and layout
expected by Clang.

It also required fixing our use of Clang on macOS to have a default
system root in order to successfully compile or link.

It also required cleaning up how the `ClangRunner` used target
information more generally -- instead of taking the target as
a constructor parameter, it manages its target internally and relies on
the Clang target-specifying command line flags.

I looked at whether we could split this into another layer separate from
the `ClangRunner`, but that proved frustratingly difficult to manage.
While we support building these on-demand as part of a detected link,
that doesn't seem feasible as we don't have the necessary separation
between compilation runs of Clang and link runs of Clang. However,
I have tried to factor the internals to provide as clear of separation
as I could across these.

I have also created a stand-alone subcommand to directly build the
runtimes which allows for easy testing. It also supports building them
into a specific directory, and that directory can in turn be passed to
a Clang invocation. This is designed to work both at the API level with
`ClangRunner` and at the subcommand level.

Currently, the only part of the commandline that is detected and
forwarded to the runtimes build is the target. Eventually, the plan is
to expand this so that we can build a maximally tailored set of runtimes
for a given compilation.

The other big TODO here is to actually implement caching storage of
these runtimes so they aren't built on every execution. Right now, this
uses a somewhat hack-y build of a temporary directory, but this isn't
expected to be suitable long-term. Building these runtimes on *every*
link makes those commands take approximately 15 seconds with an ASan
build like our default development build, and just over 2 seconds in an
optimized build. Because of this, I've kept all of this disabled by
default for now. The goal is that once caching and some other
improvements land, we can enable this by default.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-22 03:05:21 +00:00
Richard Smith 816d4589cd Make use of new ArrayRef::consume_* functions. (#5975)
Minor code simplifications.
2025-08-21 21:41:53 +00:00
Chandler Carruth 046fbbcb29 Tweak the name for the function that diagnoses when fuzzing external libraries (#5974)
The old function name caused some confusion during the review of #5338,
sending this to see if it provides a less surprising function name and
boolean result. Happy to try other names / approaches as well.
2025-08-21 19:36:44 +00:00
223d0397c0 Updating Carbon's safety strategy (#5914)
Carbon is accelerating and adjusting its safety strategy, specifically
to flesh out its memory safety strategy and reflect simplifying
developments in the safety space.

This proposal replaces the previous directional safety strategy with a
new concrete and updated framework for the safety design. It includes a
specific framework for memory safety, simplified build modes, specific
"safety modes", and terminology.

This proposal also provides a _directional_ suggestion for temporal and
data-race safety specifically.

In addition to fully building out the above directional component, there
are several other aspects of our safety design that will follow in
subsequent proposals. The hope is to establish the initial framework
here.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Mike Forster <michael@forster.pro>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-20 23:31:30 +00:00
Richard Smithandjosh11b 30b8a93fde Support conversion from T* to const T*. (#5971)
Also support conversion from Derived* to const Base*.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-08-20 23:27:03 +00:00
Richard Smith ad84e71acd Avoid non-UTF8-encoded test files. (#5965)
Add a content keyword to file_test, `[[@0xAB]]`, that expands to the
code unit 0xAB, and use that instead of putting raw malformed code units
in test files.

Instead of printing the raw input bytes in snippets in diagnostics,
replace non-printable characters with <AB> in the output, being careful
to still compute the location of the caret and underscore properly.
2025-08-20 21:07:58 +00:00
Richard Smith 2352e93bb5 Remove now-unused StringType instruction. (#5964) 2025-08-20 18:30:11 +00:00
Richard Smith b72c11e94a Support importing nested types from C++. (#5955)
Fix the algorithm for importing declarations in dependency order to
properly walk the dependency graph. Add the parent declaration of a
declaration to the dependency set so that we have a parent declaration
context to import a declaration into.

Fixes a crash when attempting to import a class whose parent is not
imported.
2025-08-20 07:39:12 +00:00
Chandler Carruth 3c9b87ab54 Add some more operations to the filesystem library (#5968)
Specifically this adds `WriteStream` to get an LLVM-style
`raw_fd_ostream` for an open file, and `Rename` corresponding to
`rename` and `renameat` Unix-like system calls.

Some basic testing for both is added as well.

This was split out of work to switch the runtimes building to use the
new filesystem library.
2025-08-20 02:54:22 +00:00
Richard Smith 41ed82e033 Add basic support for strings to core, check, and lower. (#5963)
Add a `Core.String` class to the prelude representing a string view, and
rename the `String` keyword to `str` and make it evaluate to
`Core.String`.

`Core.String` is represented as a pair of a pointer to a character
(actually, to the first character of a string, but we don't have a way
of modeling that yet) and a size (which should be pointer-width, but is
currently always a `u64` as we don't have a `usize` equivalent yet).
`Core.String` values are generated directly by the toolchain for string
literal expressions.

This follows the direction established at the recent summit, but the
design implemented here has not been through the proposal process yet.
2025-08-20 00:18:50 +00:00
Jon Ross-Perkins 8d08e774fc Add a feature to explicitly include a file's SemIR (#5961)
Trying to figure out an easy way to debug semir in the prelude, #5703
removed an option to set `--exclude-dump-file-prefix` to empty. But,
this is probably an improvement over that flow... With this change, it's
possible to add `//@dump-sem-ir-file` to a specific prelude file, and
its full IR will be printed. Additionally, it becomes an option with the
default `--dump-sem-ir-ranges=only` to add `//@dump-sem-ir-file` and get
the full file's IR.
2025-08-15 18:53:43 +00:00
David BlaikieandRichard Smith 3f9fc633fe Add a vtableDecl inst and use that in classes instead of VtablePtr (#5945)
This addresses/avoids the duplicate import of vtables.

I went through a few iterations/etc along the way and left them in the
commit
history for the PR in case any of them are useful to illustrate how I
got here,
or worth revisiting.

Essentially I ended up with a circularity in importing - importing the
class
imported the vtable_decl which imported the virtual functions - and then
pending
specifics of the virtual functions needed the self specific of the
enclosing
class which wasn't ready yet.

Adding ImportRef to the vtable_decl to break the cycle caused me trouble
when
naming the vtable_decl instructions - so I tried making the functions in
the
vtable unloaded ImportRefs instead. That worked, but meant that
importing a
class still was doing O(number of vtable entries) even if the vtable
wasn't
used.

So I revisited the lazy vtable_decl - figured out how to make the naming
work
(when building the vtable_ptr, even though the vtable_decl doesn't have
to be
loaded for the vtable_ptr, I force it to be loaded anyway, to load the
vtable so
it's usable by lowering, etc). And then I could go back to the old
non-lazy
loaded vtable entries (using some loaded ImportRefs in the cases where
we needed
them/had already adopted them).

Then thinking about the VtablePtr instruction, went back/forth on
exactly what
it needed - went from VtablePtr's member being a VtableDecl InstId, to a
ClassId, then back to a VtableId as it was before this patch.

Naming the instructions has one oddity, that the VtableDecl and
VtablePtr
instructions seem to need to add the pending name for the VtableId -
despite not
using the VtableId in their own name - should the inst namer be doing
this work
for parameters of instructions rather than requiring the inst to do it
deliberately? (or am I holding it wrong in some way?)

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-15 18:36:54 +00:00
Richard Smith 7727c62880 Enforce a couple of char literal restrictions from #1964: (#5960)
* `\x` escapes are not permitted in character literals
* ASCII control characters (U+0000 .. U+001F) are not permitted in
character literals unless specified with escape sequences.
2025-08-15 00:45:16 +00:00
Richard Smith ae54873441 Change tests in check/testdata/builtins/char to be tests for the builtin char functions. (#5956)
Follow the pattern used by other tests in check/testdata/builtins.
2025-08-14 20:58:09 +00:00
Chandler Carruth 0a679504a5 Update LLVM again to 2025-08-09 (#5958)
This lets us pick up another API update to creating lifetimes, as well
as the consequent test updates.
2025-08-14 19:19:27 +00:00
Dana Jansens 9feb493680 Add instructions for including CARBON_VLOG output when running a file_test (#5959) 2025-08-14 18:12:54 +00:00
Richard Smith b851e8c423 Add support for f16, f64, f128. (#5952)
Generalize the f64 support to support other sizes. Also provide interop
support for `float`, `_Float16`, and `__float128`.

Also lay some groundwork for non-standard floating-point types, though
we don't have any syntax to name them yet.
2025-08-14 01:14:40 +00:00
Jon Ross-Perkins cfe5599144 Support imports of more literal values (#5954)
I noticed while trying to set up an associated constant in the prelude
that we weren't supporting bool value imports; this goes through and
addresses support for simple builtin types.

Array initialization fails on declaration, which seems like a bug but
I'm only documenting it here.

Also fix missing export of `Core.FloatLiteral`

I checked and this doesn't seem to affect #5952, which is doing more
float changes.
2025-08-13 23:36:40 +00:00
Richard SmithandJon Ross-Perkins b2b0b4a73f Improve recovery from bad type imports. (#5953)
The main change here is that a bad type appearing somewhere within a
field or base class of a class shouldn't cause an import of that class
to fail. Instead, only that field or base class becomes inaccessible
from Carbon.

Also improve the way that type importing errors are diagnosed. While we
lose the precision of a diagnostic saying why a type is not supported,
we gain a useful source location for where the type was mentioned in C++
code.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-08-13 22:07:54 +00:00
Dana Jansens 2140a57294 Remove todo in facet_type.cpp after exploration (#5950)
We looked at it in
https://github.com/carbon-language/carbon-lang/pull/5947 and decided not
to proceed with it.
2025-08-13 16:01:31 +00:00
Chandler Carruth 52972ea83d Update LLVM to head on 2025-08-01 (#5951)
This pulls in updated LLVM IR features in our thunk test, and needs us
to adapt the dependency tests, but otherwise seems to work easily.
2025-08-13 01:12:40 +00:00
Richard Smith 629f77eb61 Switch to representing FloatLiteralType as a RealId. (#5944)
Don't convert to f64 until we know that's the type that we actually
want. Also reimplement the conversion from RealId to FloatId to perform
an exact conversion with a real check for overflow, rather than
performing an approximate conversion via the host `double` type.

Unfortunately, LLVM doesn't expose its integer mantissa and exponent to
APFloat conversion, so we convert the RealId back to a string for now.

The LLVM conversion also detects overflow only if the literal would
round to having an out-of-range exponent, not if the literal is outside
the range of values of the type as the Carbon design expects. It's not
clear to me which rule we actually want here, so for simplicitly I'm
using the LLVM rule for now.

In preparation for adding other floating-point types beyond f64.
2025-08-12 22:08:07 +00:00
Chandler Carruth 969abfe814 Follow-up fixes to filesystem code (#5949)
Tidies up extraneous move, unnecessary function style type cast, and
simplifies the temporary directory string construction. These were
noticed during another PR review.

Also corrects support for older glibc versions, including the
GNU-specific quirks of `strerror_r`. Restricts the fancier formatting
with the name of the error number to when a recent glibc is available.

Lastly, filters the benchmarks in the benchmark test down to smaller
ones to avoid test timeout flakiness.
2025-08-12 21:51:44 +00:00
Richard Smith 28103b8f2e Convert LegacyFloatType into FloatLiteralType. (#5939)
* Rename the type.
* Change lowering to lower FloatLiteralType values as the placeholder
  `{}` value we use for literals instead of as an LLVM f64.
* Change eval to convert the type as part of a floating point
  conversion, so that lowering can lower converted constants properly.

For now we still represent a value of FloatLiteralType as a
double-precision APFloat. (That will need to change so that we can
losslessly convert literals to f80 / f128 values, and so that we can
convert literals to f32 values without double-rounding.)
2025-08-12 18:55:38 +00:00
Dana JansensandJon Ross-Perkins 4b0e2b03b6 Add the .Self name for the type expression of a compile time binding (#5937)
We add a virtual node (`CompileTimeBindingPatternStart`) as the first
child of `CompileTimeBindingPattern` which holds the identifier
underneath it, so that it is checked just before the type expression of
the `CompileTimeBindingPattern`. When we reach this virtual node during
check, we add `.Self` as a name in the current scope, and when we reach
`CompileTimeBindingPattern` we remove it from scope, which ensures it's
present during only the checking of the type expression for the compile
time pattern.

At the moment the `.Self` has a different type (it's a `TypeType`) than
other `.Self` in the facet type (which are a single `FacetType`), but
the intention is to immediately substitute it out of the facet type
entirely, replacing it with a reference to the compile time binding (a
`BindSymbolicName`) itself. A TODO has been added for this.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-08-12 16:27:07 +00:00
Chandler Carruth 2e509e9103 Port //toolchain/install to new filesystem library (#5905)
This removes a bunch of manual filesystem helpers and complexity that
are directly provided by the new library.

It also moves all of the install paths detection to use
`std::filesystem::path` instead of the LLVM path library. The goal is to
consolidate all our logic onto a single stack, and the standard one
seems the best for that purpose. This does give up some of the
optimizations of this code to avoid memory allocation, but in practice
that likely isn't a critical issue. And with the new filesystem library
we can likely do more to avoid that by using directory-object-relative
filesystem access. However, that will have to wait for moving more parts
of the toolchain over to use this set of filesystem abstractions. There
is a related TODO left in the manifest handling code.
2025-08-12 02:20:22 +00:00
Chandler CarruthandDana Jansens 42d29764c0 Introduce a custom filesystem library (#5888)
The standard filesystem API lacks significant functionality, ranging
from correct and secure creation of directories and files within them by
using `openat` and avoiding [TOCTOU] issues, to support for filesystem
locking.

[TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use

The LLVM filesystem library has more functionality, but uses an API that
is increasingly diverging from the standard, and also fails to defend
against TOCTOU.

This library is designed to carefully model the Unix or POSIX filesystem
concepts of `openat` to avoid TOCTOU. However, it also tries to limit
itself to an API subset that LLVM's filesystem library has also
implemneted and so we have a strong reason to expect to be possible to
port to Windows reasonably.

This PR included several benchmarks that show that this implementation
is also faster for the majority of operations than the C++ standard
library. The only places where there is a consistent regression is in
recursively creating directories, and this is directly connected to the
approach of using `openat` as the basis. Even there, while the wall time
regresses, the cycles and instructions are significantly improved.

There are a number of operations not yet included here, I've focused on
a core set of opening, closing, creating, and removing, and then adding
those that I saw the current toolchain code using actively. I'll plan to
expand the operations as needed going forward.

A follow-up PR that I'll finish polishing and send next ports
`//toolchain/install` to consistently use this library and
`std::filesystem::path` to both exercise the library and showcase its
use. I'll be working systematically across the toolchain to converge all
the code, extending this library as needed.

For reference, benchmark results on my macOS laptop:
https://gist.github.com/chandlerc/29d1f4d465a835b8be5174a48dad2e8f

Benchmark results on a Asahi Linux M1 Mac Mini:
https://gist.github.com/chandlerc/c42d43dd6b9b91746ab314b2afa152f7

Benchmark results on a Linux server with weirdly slow FS operations:
https://gist.github.com/chandlerc/48301a7383eb3972d53351b7e35e0561

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-08-12 01:38:31 +00:00
Jon Ross-Perkins b410ebd088 Fix destruction of generic types (#5943)
The self access is important; for the test `generic_class.carbon` being
added to `toolchain/check/testdata/class/destroy_calls.carbon`, it was
using `%T.as.Destroy` instead of `%D.as.Destroy`, indicating the default
blank impl was being used instead of the type-specific version. That
test is trying to focus on the issue, but the delta is visible in a
couple other files in this PR, for example
`toolchain/check/testdata/class/generic/init.carbon`.

I'm separately working on getting rid of the default impl, which is how
I noticed this.
2025-08-12 00:10:43 +00:00
694c00c7eb Make Core.Float a class. Add missing builtins for float support. (#5932)
Add missing builtins for float compound assignment, for building a
FloatType, and for converting a float literal to FloatType. Switch
`Core.Float` to being a class and add impls for the various
floating-point operators.

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-08-11 21:01:34 +00:00
Richard Smith f616817b71 Improve autoupdate diagnostic CHECK line positioning. (#5942)
When an error diagnostic has an unattached location, for example because
the diagnostic points into a file that's in the prelude, use the next
attached location to position the error diagnostic's CHECK line. In
particular, if the error is followed by a note, use the position of the
note to determine where to place the error.

This exposes a general mechanism to do final fixups of the CHECK lines
to individual file_test binaries, which the toolchain's binary uses to
special-case error / warning CHECK lines.
2025-08-11 19:30:57 +00:00
David Blaikie efbc9f7c9c Create LoadedImportRefs for vtable entries with import insts instead of local insts (#5931)
With help from Richard Smith debugging/identifying this.

Hmm - looks like maybe the Self type import ref may have the same
problem? (or at least it seems to have the same quirk in the semir dump,
where the inst id is mentioned in the `import_ref` insts, but is not
defined elsewhere, has no name, and says `[no loc]`. I'll look into that
separately. (hmm, maybe this is just an unloaded ImportRef, actually)
2025-08-11 19:29:59 +00:00
Boaz Brickner 5b328da0aa Avoid creating a vector of bools to mark which C++ thunk parameter types were modified (#5941)
Instead, check which types were modified.
This simplifies the logic and could make it easier to add return value
support.

Part of #5514.
2025-08-11 15:01:51 +00:00
Boaz Brickner fd3eb136af Use llvm::zip() to iterate over callee_function_params, thunk_function_params and callee_arg_ids (#5940) 2025-08-11 14:57:42 +00:00
2232 changed files with 243456 additions and 122226 deletions
+83
View File
@@ -0,0 +1,83 @@
---
name: Bazel usage
description:
Instructions for using Bazel or Bazelisk to build, test, and debug in the
Carbon repository.
---
# Bazel usage
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
This skill documents how best to use Bazel when building, testing, or
manipulating the Carbon repository's Bazel in any way.
## Bazel wrappers
Carbon uses Bazel for its build system. To ensure consistent versions, the
project uses Bazelisk.
> [!IMPORTANT] Always use `bazelisk` whenever you want to run Bazel. Never run
> `bazel` directly in the Carbon project. Anything you want to do with `bazel`
> can be done with the `bazelisk` command instead.
- **Bazelisk**: Try to use `bazelisk` in your existing `$PATH` if available.
- **`run_bazelisk.py`**: If `bazelisk` isn't available, use
`./scripts/run_bazelisk.py` to run bazelisk without it being installed.
## Essential commands
### Building
- **Build all**: `bazelisk build //...`
- **Build toolchain**: `bazelisk build //toolchain/...`
- **Build specific target**: `bazelisk build //toolchain:carbon`
### Testing
- **Test all**: `bazelisk test //...:all`
- **Test toolchain**: `bazelisk test //toolchain/...`
- **Test examples**: `bazelisk test //examples/...`
> [!TIP] Running all of the tests can be slow, so try to narrowly test the
> immediately relevant parts of the project first, and only expand coverage as
> necessary to be confident in the changes.
> [!TIP] For specialized instructions on testing and developing the Carbon
> toolchain, consult these skills:
>
> - [Toolchain tests](/.agents/skills/toolchain_tests/SKILL.md): For
> authoring, structuring, and running `file_test` tests.
> - [Toolchain development](/.agents/skills/toolchain_development/SKILL.md):
> For architecture, essential commands, and debugging the toolchain.
### Running binaries built by Bazel
> [!IMPORTANT] Always manually run binaries built by Bazel using the
> `bazelisk run` command. Never run the binary directly from `bazel-bin/`.
You can run the Carbon driver or command line directly via Bazel:
- `bazelisk run //toolchain -- compile --phase=parse toolchain/parse/testdata/basics/empty.carbon`
## Advanced configurations
### AddressSanitizer (ASan)
To enable ASan for local testing:
- Pass `--config=asan`: `bazelisk test --config=asan //...`
## Common pitfalls and troubleshooting
### `bazel clean`
Changes to packages installed on your system (like changing LLVM versions or
installing `libc++`) may not be noticed by Bazel.
- Run `bazelisk clean` to force cached state to be rebuilt when environment
changes occur.
+45
View File
@@ -0,0 +1,45 @@
---
name: Code style
description:
Instructions for code formatting and style guidelines in the Carbon
toolchain.
---
# Code style
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
## License
- **Licenses**: All Carbon files outside of `third_party/` should have a
license following
[CONTRIBUTING license instructions](/CONTRIBUTING.md#license).
## Formatting
- **Bazel**: Use `pre-commit run buildifier --files <file.bzl>` to format
Bazel files.
- **C++**: Use `pre-commit run clang-format --files <file.cpp>` to format C++
files.
- **Carbon**: The toolchain's `format` command doesn't work well right now.
Instead, try to format Carbon code based on other Carbon files and the C++
style.
- **Markdown**: Use `pre-commit run prettier --files <file.md>` to format
markdown files.
- **Python**: Use `pre-commit run black --files <file.py>` to format Python
files.
## Style Guides
- **C++ style**: Follow the
[Carbon C++ Project Style Guide](/docs/project/cpp_style_guide.md).
- **Markdown style**: Follow the
[Google developer documentation style guide](https://developers.google.com/style).
- **Python style**: Follow the [PEP 8](https://peps.python.org/pep-0008/)
style guide.
- Wrap code and comments to 80 columns.
- Run `pre-commit run flake8 --files <file.py>` to check Python style.
+171
View File
@@ -0,0 +1,171 @@
---
name: GitHub CLI usage
description:
Instructions for using the `gh` command to query and inspect GitHub state
safely.
---
# GitHub CLI usage
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
This skill provides instructions for using the GitHub CLI (`gh`) to query,
inspect, and search GitHub state (issues, pull requests, repositories) for the
Carbon project.
## Safety First: Read-Only Usage
> [!IMPORTANT] AI assistants MUST NOT use the `gh` tool to modify any GitHub
> project state. Do NOT run commands that create, edit, delete, label, comment
> on, or merge issues, pull requests, releases, or any other resources.
### Allowed Verbs
- `list`
- `view`
- `search`
- `status`
- `api` (Only with `GET` requests)
### Prohibited Verbs
- `create`
- `edit`
- `delete`
- `merge`
- `reopen`
- `close`
- `comment`
- `label`
## Repository Configuration
The `gh` tool interacts with a default repository when run within a local check
out. For this project, the default repository is expected to be
`carbon-language/carbon-lang`.
### Verifying Default Repository
To verify the current default repository configuration:
```bash
gh repo view
```
The output should indicate the repository is `carbon-language/carbon-lang`.
### Correcting Misconfigurations
If the default repository is misconfigured (for example, pointing to a personal
fork or a different repository), the human operator must correct it.
> [!IMPORTANT] AI Assistants MUST NOT attempt to mutate `gh` configuration or
> run commands that change the default repository (such as
> `gh repository set-default`).
Instruct the human operator to run the following command to select the correct
default repository:
```bash
gh repo set-default
```
The operator will be prompted to select the correct repository (e.g.,
`carbon-language/carbon-lang`) from the available remotes.
## Common Query Commands
### Issues
- **List issues**: `gh issue list`
- **View specific issue**: `gh issue view <number>`
- **Search issues**: `gh issue search "<query>"`
- Example: `gh issue search "crash" --state open`
### Pull Requests
- **List PRs**: `gh pr list`
- **View specific PR**: `gh pr view <number>`
- **View PR diff**: `gh pr diff <number>`
- **Check PR status**: `gh pr status`
### Search
- **Search code**: `gh search code "<query>"`
- **Search repositories**: `gh search repos "<query>"`
## Advanced Usage: GitHub API
For queries that are not supported by standard `gh` commands, you can use the
`gh api` command to query the GitHub REST or GraphQL APIs.
### REST API
Query the REST API using paths relative to the API root.
- **List contributors**:
```bash
gh api repos/carbon-language/carbon-lang/contributors
```
- **List issue comments**:
```bash
gh api repos/carbon-language/carbon-lang/issues/<issue_number>/comments
```
### GraphQL API
For complex queries, use GraphQL to fetch exactly the data needed.
- **Get repository information**:
```bash
gh api graphql -f query='
query {
repository(owner: "carbon-language", name: "carbon-lang") {
description
stargazerCount
}
}
'
```
### Pagination
Use the `--paginate` flag to automatically fetch all pages of results.
```bash
gh api --paginate repos/carbon-language/carbon-lang/issues
```
### Filtering and Formatting
Use `--json` to request JSON output, and `--jq` or `--template` to filter or
format the results.
- **List PR titles and authors**:
```bash
gh pr list --json title,author --jq '.[] | "\(.title) by \(.author.login)"'
```
- **Format with Go templates**:
```bash
gh issue list --template '{{range .}}{{.number}} - {{.title}}{{"\n"}}{{end}}'
```
## Documentation References
- **GitHub CLI Manual**:
[cli.github.com/manual](https://cli.github.com/manual/)
- **GitHub REST API Documentation**:
[docs.github.com/en/rest](https://docs.github.com/en/rest)
- **GitHub GraphQL API Documentation**:
[docs.github.com/en/graphql](https://docs.github.com/en/graphql)
+95
View File
@@ -0,0 +1,95 @@
---
name: Accessing GitHub issues
description:
Instructions for safely viewing and accessing GitHub issues by way of
command line.
---
# Accessing GitHub issues
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
This skill provides instructions for AI assistants on how to access and view
GitHub issues. Agents should strongly prefer using the command line `gh` tool to
access and view the contents of issues rather than viewing their contents by way
of a web browser.
## Safety First
> [!IMPORTANT] AI assistants MUST NOT modify any GitHub issue state. Only use
> read-only access commands like `view` or `list`. Do NOT comment, edit, create,
> close, or delete issues.
## Accessing Issues
Agents must use this skill to access issues regardless of how they are mentioned
(for example, by URL or by issue number).
### Basic View
To view an issue in the current default repository (expected to be Carbon):
```bash
gh issue view <issue_number>
```
### Including Full Context (All Comments)
To ensure the view includes the entire context of the issue, always include the
`--comments` flag to dump all comments:
```bash
gh issue view <issue_number> --comments
```
> [!TIP] If the issue is extremely large and comments are truncated, or you need
> to process comments programmatically, use the JSON output with `jq`:
>
> ```bash
> gh issue view <issue_number> --json comments --jq '.comments[].body'
> ```
### Accessing Issues in Other Repositories
To view an issue in another repository (for example, LLVM), use the `-R` or
`--repo` flag to specify the repository:
```bash
gh issue view <issue_number> -R <owner>/<repo> --comments
```
Examples:
- **LLVM Issue**:
```bash
gh issue view 5678 -R llvm/llvm-project --comments
```
- **Carbon Issue (Explicit)**:
```bash
gh issue view 1234 -R carbon-language/carbon-lang --comments
```
## Mentions via URL
If an issue is mentioned via URL, parse the URL to extract the repository owner,
repository name, and issue number.
- **URL pattern**: `https://github.com/<owner>/<repo>/issues/<number>`
- **Extraction**:
- Host: `github.com`
- Owner: `<owner>`
- Repo: `<repo>`
- Number: `<number>`
Run the command specifying the repository:
```bash
gh issue view <number> -R <owner>/<repo> --comments
```
@@ -0,0 +1,203 @@
---
name: Summarize testdata changes
description:
Instructions for summarizing changes to Carbon testdata files
(`toolchain/*/testdata`).
---
# Summarize testdata changes
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
This skill provides instructions for creating a comprehensive report summarizing
changes to Carbon testdata files (`toolchain/*/testdata`) and associating them
with related code changes.
## Goals
Produce a report that:
1. Summarizes code changes outside of testdata.
2. Groups similar testdata changes together, listing all affected files for
each group. **Every change to testdata must be represented by at least one
group. This includes changes to CHECK lines.**
3. Provides detailed breakdowns of test input changes and diagnostic output
changes in the corresponding group. **Every single change to inputs or to
STDERR checks must be explicitly mentioned in the group, with either an
inline diff or a link to the file.**
## Process
### 1. Identify Changes
Use your VCS (Git or Jujutsu) or query Github to identify changes. For large
changes, it is recommended to use the included helper script to extract test
input changes.
#### For Git Users:
- **Summarize code changes**: `git diff --stat -- ':!toolchain/*/testdata'`
- To see content of non-testdata changes:
`git diff -- ':!toolchain/*/testdata'`
- **Identify testdata changes**: `git diff --name-only 'toolchain/*/testdata'`
#### For Jujutsu (jj) Users:
- **Summarize code changes**:
`jj --no-pager diff --stat '~toolchain/*/testdata'`
- Note: Quoting the fileset `'~toolchain/*/testdata'` is critical if it
contains wildcards.
- To see content of non-testdata changes, use `--git` to get standard
unified diff format: `jj --no-pager diff --git '~toolchain/*/testdata'`
- **Identify testdata changes**:
`jj --no-pager diff --name-only 'toolchain/*/testdata'`
#### For Github Pull Requests:
- **Summarize code changes**: `gh pr diff`
- **Identify testdata changes**:
`gh pr diff --name-only | grep '^toolchain/.*/testdata'`
#### Handling Specific Revisions:
If you are summarizing changes in a specific revision (for example, `@-`) or
pull request (for example, #1234), add `-r <rev>` or `<pr_number>` to the
commands:
- `git diff <rev>^ <rev> ...` (or use `git show <rev>`)
- `jj --no-pager diff -r <rev> ...`
- `gh pr diff <pr_number>`
### 2. Extract Test Input Changes (Recommended)
To easily identify changes, use the included Python helper script to extract all
text additions and removals from the diff, categorized by Input, STDERR, and
STDOUT changes. This script reads a unified diff from stdin.
```bash
# For Git:
git diff -- 'toolchain/*/testdata' | python3 .agents/skills/summarize_testdata_changes/scripts/parse_diff.py
# For Jujutsu (jj):
jj diff --git 'toolchain/*/testdata' | python3 .agents/skills/summarize_testdata_changes/scripts/parse_diff.py
# For a specific revision with jj:
jj diff -r @- --git 'toolchain/*/testdata' | python3 .agents/skills/summarize_testdata_changes/scripts/parse_diff.py
# For a specific PR with Github:
gh pr diff 1234 | python3 .agents/skills/summarize_testdata_changes/scripts/parse_diff.py
```
### 3. Identify Patterns and Produce a List of Groups
- Read the diff and produce a list of groups of changes that share a common
theme or cause (for example, "Updated expected output for integer literals",
"Added tests for new keyword").
- **CRITICAL**: _Every single change_ in the testdata diff must be represented
by at least one group. Do not ignore changes to `CHECK` lines.
- If it's not clear what group a change belongs to, create a new group for
it.
- For each group:
- Provide a brief description of the group.
- (Optional) Briefly note if the group appears to be an intended or
unintended consequence of the code changes.
- Divide the groups into sections:
- Test Changes: Changes to test inputs (lines not prefixed with
`// CHECK`), along with diagnostic output changes where relevant
- Diagnostic Changes: Changes to diagnostic output (lines prefixed with
`// CHECK:STDERR`) with no corresponding changes to test inputs
- [Output Type] Changes: Changes to STDOUT (lines prefixed with `// CHECK:STDOUT`)
- Create one section for each relevant kind of test. For example,
parser tests should typically be in a "Parse Tree Changes" section,
check tests should typically be in a "SemIR Changes" section, and
lower tests should typically be in an "LLVM IR Changes" section.
### 4. Improve Grouping
- Read the list of groups and check to see if any of them should be combined
or split apart. If needed, do so.
### 5. Assign Changes to Groups
- Read the diff again, and then for _each_ change in the diff:
- Add the change to the appropriate group (or, rarely, groups).
- **CRITICAL**: _Every single change_ in the testdata diff must be
represented by at least one group. Do not ignore changes to `CHECK`
lines.
- If the change affects _test inputs_ (lines not prefixed with `// CHECK`)
or _diagnostic output_ (lines prefixed with `// CHECK:STDERR`):
- List the file within the group. Don't just give one or a few
examples. Include every file.
- Provide an inline diff if the change is small.
- Provide a link to the file if the change is large.
- Otherwise, if the change only affects _STDOUT_ (lines prefixed with
`// CHECK:STDOUT`):
- Ensure the group contains a representative example that matches the
current change.
- The representative example should be an inline diff of the change.
- **CRITICAL**: _Every single change_ to test inputs and diagnostic
outputs in the files being summarized must be explicitly listed in at
least one group. Do not skip changes, even if they are similar to
changes you've already seen, and do not just give examples.
### 6. Validation
As a final validation step:
- Read through the testdata diff again.
- Ensure that every change in the diff is reflected by at least one group in
the report.
## Report Template
Use the following template for the generated report:
```markdown
# `testdata` Change Summary
## Code Changes
[One paragraph summarizing changes outside of testdata.]
## Test Changes
### [Group Name]
[Description of the group.]
[Change 1: diff context OR link]
[Change 2: diff context OR link]
...
## Diagnostic Changes
### [Group Name]
[Description of the group.]
[Change 1: diff context OR link]
[Change 2: diff context OR link]
...
## [Output Type] Changes
### [File Path]
[Description of the group.]
[Example diff context]
Changes of this kind were found in [Number] files. Examples: [List of files]
...
```
Skip sections that would be empty.
@@ -0,0 +1,65 @@
__copyright__ = """
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""
import sys
from collections import defaultdict
from typing import TextIO, Dict, List
def parse_diff(stream: TextIO) -> None:
current_file: str = ""
file_changes: Dict[str, Dict[str, List[str]]] = defaultdict(
lambda: {"input": [], "stderr": [], "stdout": []}
)
for line in stream:
if line.startswith("diff --git"):
parts = line.split()
if len(parts) >= 4:
current_file = (
parts[3][2:] if parts[3].startswith("b/") else parts[3]
)
elif line.startswith("+") or line.startswith("-"):
if not line.startswith("+++") and not line.startswith("---"):
stripped = line[1:].strip()
if stripped.startswith("// CHECK:STDERR"):
file_changes[current_file]["stderr"].append(
line.rstrip("\n")
)
elif stripped.startswith("// CHECK:STDOUT"):
file_changes[current_file]["stdout"].append(
line.rstrip("\n")
)
elif stripped.startswith("// CHECK"):
file_changes[current_file]["stdout"].append(
line.rstrip("\n")
)
else:
file_changes[current_file]["input"].append(
line.rstrip("\n")
)
for f, c in file_changes.items():
if not c["input"] and not c["stderr"] and not c["stdout"]:
continue
print(f"File: {f}")
if c["input"]:
print(" --- Input Changes ---")
for change in c["input"]:
print(f" {change}")
if c["stderr"]:
print(" --- STDERR Changes ---")
for change in c["stderr"]:
print(f" {change}")
if c["stdout"]:
print(" --- STDOUT Changes ---")
for change in c["stdout"]:
print(f" {change}")
print("-" * 40)
if __name__ == "__main__":
parse_diff(sys.stdin)
+34
View File
@@ -0,0 +1,34 @@
---
name: Tool usage
description:
Instructions for AI assistants on what tools to use in the carbon-lang
project.
---
# Tool usage
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
## Bazelisk and Bazel
We use `bazelisk` for build and test.
**IMPORTANT**: AI assistants use `bazelisk` instead of `bazel`.
## Pre-commit
Running `pre-commit` is mandatory. To run it on all files:
```bash
pre-commit run -a
```
To validate a specific list of files:
```bash
pre-commit run --files <files>
```
@@ -0,0 +1,115 @@
---
name: Toolchain development
description:
Instructions for checking, building, debugging, and understanding the Carbon
toolchain.
---
# Toolchain development
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
## Toolchain structure
- Under [`toolchain/`](/toolchain/):
- [`base/`](/toolchain/base/): Base infrastructure and common utilities.
- [`check/`](/toolchain/check/): Semantic analysis (SemIR generation).
- [`lex/`](/toolchain/lex/): Lexing (Source -> Tokens).
- [`lower/`](/toolchain/lower/): Lowering to LLVM IR.
- [`parse/`](/toolchain/parse/): Parsing (Token -> Parse Tree).
- [`sem_ir/`](/toolchain/sem_ir/): Semantic Intermediate Representation
(SemIR) definitions.
## Toolchain architecture
- **Documentation**: Refer to [`toolchain/docs`](/toolchain/docs) for detailed
architecture design and patterns.
- Refer to [Toolchain Idioms](/toolchain/docs/idioms.md) for a
comprehensive list of patterns (for example, `ValueStore`, formatting
`.def` files, struct reflection) used throughout the implementation.
- **Phases**: Lex -> Parse -> Check -> Lower.
- **Definitions**: Many kinds (tokens, parse nodes, SemIR instructions) are
defined in `.def` files and expanded by way of macros.
- **Handlers**:
- Parser: `Handle<StateName>` in `parse/handle_*.cpp`.
- Checker: `HandleParseNode` in `check/handle_*.cpp`.
- Lowering: `HandleInst` in `lower/handle_*.cpp`.
- **Iteration**: Prefer iterative algorithms over recursive ones to prevent
stack exhaustion on complex codebases.
### Essential commands
- **Test everything**: `bazelisk test //...`
- **Test specific target**: `bazelisk test //toolchain/testing:file_test`
- **Test specific file**:
`bazelisk test //toolchain/testing:file_test --test_arg=--file_tests=<path_to_carbon_file>`
- **Build toolchain**: `bazelisk build //toolchain/...`
### Updating test data
Carbon tests often use `file_test` (for example,
`//toolchain/testing/file_test`). For detailed guidelines on authoring tests,
including file splits, naming conventions (`fail_`, `todo_`), and generating
minimal output with SemIR dumps, please refer to the **Toolchain tests** skill.
If you change compiler behavior, you likely need to update expected test
outputs. **Do not manually edit thousands of lines of expected output.** Use the
script:
```bash
./toolchain/autoupdate_testdata.py
# Or for a specific file:
./toolchain/autoupdate_testdata.py toolchain/check/testdata/my_test.carbon
```
## Debugging and diagnostics
- **Printing to stderr**: Use `llvm::errs() << "debug info\n";`.
- Avoid `std::cout` (it may interfere with tool output).
- **SemIR Stringification**:
- SemIR objects often have a `Print` method or `operator<<`.
- `inst.Print(llvm::errs())`
- **Debugging Crashes**:
- Bazel sandboxing can hide artifacts. Use `--sandbox_debug` if needed,
but often running the binary directly from `bazel-bin/` is easier for
debugging.
## Error handling
- **No exceptions**: Do not use C++ exceptions.
- **`ErrorOr<T>`**: Return `ErrorOr<T>` for fallible operations.
- Check with `if (auto result = Function(); result) { Use(*result); }`
- **`llvm::Expected<T>`**: Similar to `ErrorOr`, used when interfacing with
LLVM.
### Casting (LLVM style)
- Use `llvm::cast<T>(obj)` (checked, asserts on failure).
- Use `llvm::dyn_cast<T>(obj)` (returns null on failure).
- Use `llvm::isa<T>(obj)` (boolean check).
- **Avoid** `dynamic_cast` and standard RTTI.
### Data structures
- Prefer APIs in `common/` and `toolchain/base/` over LLVM ADTs. For example,
use `Map` instead of `llvm::DenseMap`.
- If no Carbon API exists, prefer LLVM ADTs over standard library ones (for
example `llvm::SmallVector`, `llvm::StringRef`).
- `StringRef` is a view; be careful with lifetimes.
## Common pitfalls
1. **Legacy `explorer` references**: The `explorer` prototype has been moved.
Ignore references to it in proposals or old docs; focus on `toolchain`.
2. **Manually updating test files**: Always check if `autoupdate_testdata.py`
can do it for you.
3. **Using `std::string` unnecessarily**: Prefer `llvm::StringRef` for
arguments.
4. **Header includes**: Use specific include orders (often enforced by
`clang-format`).
5. **Parse node order**: Semantics processes parse nodes in post-order; ensure
your parser transitions support this.
+136
View File
@@ -0,0 +1,136 @@
---
name: Toolchain tests
description:
Instructions for authoring, structuring, and running toolchain tests using
the file_test infrastructure.
---
# Toolchain tests
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
## Introduction
This skill provides guidelines and patterns for creating and updating tests for
the Carbon toolchain, especially file tests in `toolchain/*/testdata/` (for
example, `toolchain/check/testdata/`).
Toolchain tests evaluate Carbon source files through Lexing, Parsing, Checking,
and optionally Lowering. Output (for example SemIR dumps, Clang errors) is
captured and validated using inline CHECK records.
## Structure and Authoring
### File Layout and Headers
Test files must start with the standard Carbon license, followed by
configuration comments. Separate sections with blank comment lines (`//`).
```carbon
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/...
//
// AUTOUPDATE
```
- `// AUTOUPDATE` is mandatory for files using CHECK markers.
- `// TIP:` lines are automatically generated by the autoupdater. You do not
need to hand-write them. It is harmless to add them, but the script will
handle it.
### Minimized Preludes
When writing tests entirely unrelated to the Core package, specify a minimal
prelude file using `// INCLUDE-FILE`. Usually, include
`toolchain/testing/testdata/min_prelude/` scripts, such as `int.carbon` or
`primitives.carbon`. This significantly speeds up execution and minimizes STDOUT
noise.
### Split Tests and `[[@TEST_NAME]]`
A single physical file can test multiple scenarios using split constraints:
```carbon
// --- passing_case.carbon
library "[[@TEST_NAME]]";
// ...
// --- fail_bad_case.carbon
library "[[@TEST_NAME]]";
// ...
```
- Use `library "[[@TEST_NAME]]";` in each split when necessary to prevent name
conflicts or redefining the default library.
- Exactly `[[@TEST_NAME]]` (including the brackets) should be used. The test
infrastructure automatically replaces it with the split's filename minus
`todo_` and `fail_` prefixes.
- **Do not put code that is expected to pass and code that is expected to fail
into the same split.** Validation relies on non-failing splits producing
absolutely no errors and failing splits producing the correct compiler
errors independently.
### File Prefixing: `fail_` and `todo_`
Expected failures must be differentiated from unexpected failures (and from
bugs). Include prefixes to name individual split files or the main test:
- `fail_...`: The test should and does produce compiler errors.
- `todo_fail_...`: The test should produce errors but currently does not.
- `fail_todo_...`: The test does produce errors or crashes, but it shouldn't
(or produces the wrong errors or otherwise misbehaves with errors).
- `todo_...`: The test has some incorrect behavior, but doesn't produce errors
currently, and shouldn't.
**Main File Naming**: The main test file (and any split-files) must have a
`fail_` prefix if they have an associated error. **Exception**: The main file
may omit `fail_` if it contains a least one split that has a `fail_` prefix.
Both the `fail_` and `todo_` prefixes are stripped from filename properties like
`[[@TEST_NAME]]`.
### Test Code Comments
- **No agent thinking:** Do not include comments describing your reasoning or
"train of thought" (for example, "Wait, but...") inside the test files. Any
comments left in tests should be concise and describe what the test _itself_
is validating for human readers.
## SemIR Dumps and Minimizing Output
Limit STDOUT checks to the logic under test. Always use `//@dump-sem-ir-begin`
and `//@dump-sem-ir-end` around the specific declarations/blocks where SemIR
output is desired. Only use these markers and **not**
`--dump-sem-ir-ranges=if-present` or similar extra args—new tests use
`//@dump-sem-ir...` to naturally filter output to the highlighted segments based
on the default behavior.
```carbon
//@dump-sem-ir-begin
fn F(x:? form(ref i32));
//@dump-sem-ir-end
```
## Creating/Updating the Output
AI tools should **never** hand-write or manually touch `// CHECK:STDOUT:` or
`// CHECK:STDERR:` comments.
Write your Carbon test code, headers, and `// AUTOUPDATE` then run the test
updater:
```bash
./toolchain/autoupdate_testdata.py toolchain/PATH/TO/YOUR/TEST.carbon
```
Review the updated test outputs (for example, by way of `git diff`). Ensure
logic paths are correctly tested rather than producing massive boilerplate
blocks.
+2 -2
View File
@@ -8,5 +8,5 @@ bazel-carbon-lang
# See github_tools/MODULE.bazel.
github_tools
# Used as part of repo patching.
third_party/boost_unordered
# Example Bazel project.
examples/bazel
+16 -8
View File
@@ -2,12 +2,15 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# Ensure all builds have Carbon's workspace status attached. We have carefully
# factored the stamping done by this to avoid excessive build performance impact
# and so enable stamping with it by default. CI and systems especially dependent
# on caching should explicitly use `--nostamp`.
# Setup stamping with Carbon's workspace status attached but disable it by
# default.
#
# Note that while we have minimized the impact of stamping on build caching, it
# still has a meaningful impact, especially during development. So we disable
# stamping by default and builds that need to include the workspace status
# should explicitly enable it with `--stamp`.
common --workspace_status_command=./scripts/workspace_status.py
common --stamp
common --nostamp
# Provide aliases for configuring the release and pre-release version being
# built. For documentation of these flags, see //bazel/version/BUILD.
@@ -82,12 +85,12 @@ common --define=absl=1
# Enable TCMalloc on Linux in optimized builds.
common --custom_malloc=//bazel/malloc:tcmalloc_if_linux_opt
# Configuration for enabling Address Sanitizer. Note that this is enabled by
# default for fastbuild. The config is provided to enable ASan even in
# optimized or other build configurations. Note that ASan and TCMalloc are
# Configuration for enabling Address Sanitizer. Note that ASan and TCMalloc are
# incompatible so this explicitly forces the system malloc.
common:asan --features=asan
common:asan --custom_malloc=@bazel_tools//tools/cpp:malloc
# Also double the test timeouts for ASan to improve their consistency.
test:asan --test_timeout=120,600,1800,-1
# Configuration for enabling LibFuzzer (along with ASan).
common:fuzzer --features=fuzzer
@@ -118,6 +121,11 @@ common:linux --define=pfm=1
# Disables `actions.declare_symlink`. Done for cross-environment support.
common --allow_unresolved_symlinks=false
# Removes the leading `/proc/self/cwd/` from file paths in the debug info. Some
# tools like VS Code don't understand `/proc/self/cwd` in places like terminal
# stack dumps, but do understand paths relative to the workspace root.
common --copt=-fdebug-prefix-map=/proc/self/cwd=
# Allow users to override any of the flags desired by importing a user-specific
# RC file here if present.
try-import %workspace%/user.bazelrc
+1 -1
View File
@@ -1 +1 @@
8.3.1
8.5.1
+12 -1
View File
@@ -11,13 +11,24 @@ DerivePointerAlignment: 'false'
ExperimentalAutoDetectBinPacking: 'false'
FixNamespaceComments: 'true'
InsertBraces: 'true'
InsertTrailingCommas: None
PointerAlignment: Left
# We abuse control macros for formatting other kinds of macros.
SpaceBeforeParens: ControlStatementsExceptControlMacros
IfMacros:
[
'CARBON_DEFINE_RAW_ENUM_CLASS',
'CARBON_DEFINE_RAW_ENUM_CLASS_NO_NAMES',
'CARBON_DEFINE_ENUM_CLASS_NAMES',
'CARBON_DEFINE_RAW_ENUM_MASK',
'CARBON_DEFINE_ENUM_MASK_NAMES',
'CARBON_KIND_SWITCH',
]
StatementMacros: ['ABSTRACT']
QualifierAlignment: Custom
QualifierOrder:
[inline, static, friend, constexpr, const, volatile, restrict, type]
Macros:
# These macros can contain variable declarations, so clang-format needs to
# "see through" them in order to format them correctly.
- CARBON_ASSIGN_OR_RETURN(x)=x
- CARBON_KIND(x)=x
+10
View File
@@ -22,6 +22,7 @@ Checks:
- '-misc-const-correctness'
- '-misc-include-cleaner'
- '-misc-use-anonymous-namespace'
- '-modernize-deprecated-headers'
- '-modernize-return-braced-init-list'
- '-modernize-use-default-member-init'
- '-modernize-use-integer-sign-comparison'
@@ -142,3 +143,12 @@ CheckOptions:
# Don't require writing a return type on lambdas.
- key: modernize-use-trailing-return-type.TransformLambdas
value: none
# Use lines rather than statements to measure function size, because
# for readability purposes we care about the code as written, before
# preprocessing.
- key: readability-function-size.StatementThreshold
value: none
- key: readability-function-size.LineThreshold
# Chose 800 to match the default for StatementThreshold.
value: 800
+9
View File
@@ -19,3 +19,12 @@ Diagnostics:
Suppress:
# The `#error` requiring a macro definition.
- pp_hash_error
---
# Suppress diagnostics for template source files.
If:
PathMatch: .*\.tpl\.h
Diagnostics:
Suppress:
- undeclared_var_use
+3
View File
@@ -2,6 +2,8 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
AggregateT
ArchType
atleast
circularly
compiletime
@@ -14,6 +16,7 @@ forin
groupt
indext
inout
isELF
parameteras
pullrequest
rightt
@@ -12,12 +12,12 @@ runs:
using: composite
steps:
# Setup Python and related tools.
- uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
# Match the min version listed in docs/project/contribution_tools.md
# or the oldest version available on the OS.
python-version:
${{ inputs.matrix_runner == 'macos-14' && '3.11' || '3.9' }}
${{ inputs.matrix_runner == 'macos-14' && '3.11' || '3.10' }}
- uses: ./.github/actions/build-setup-macos
if: startsWith(inputs.matrix_runner, 'macos')
@@ -70,6 +70,13 @@ runs:
build --remote_cache=https://storage.googleapis.com/carbon-builds-github-v${CACHE_VERSION}
build --remote_download_outputs=minimal
# Allow passing targets that are incompatible so that our explicit
# target lists work more like //... wild card patterns in CI. In CI,
# we're using explicit target lists to prune to a minimal set of
# dependencies, and so skipping incompatible targets is the expected
# behavior.
build --skip_incompatible_explicit_targets
# We import a special key into every action in order to key the Bazel
# remote cache in a way that avoids collisions between different
# runners. Anything that might change the system external to Bazel but
+1 -1
View File
@@ -28,7 +28,7 @@ runs:
# minimum supported LLVM version.
- name: Cache Homebrew
id: cache-homebrew-macos
uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
with:
# Cover all the critical parts of Homebrew here. Homebrew on Arm macOS
# uses its own prefix making this easy to cover, but we need a few
@@ -27,7 +27,7 @@ runs:
# reliability.
- name: Cache LLVM and Clang installation
id: cache-llvm-ubuntu
uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
with:
path: ~/llvm
key: LLVM-19.1.7-Cache-ubuntu-${{ runner.arch }}
+1
View File
@@ -18,6 +18,7 @@ the "Harden Runner" steps are
Most jobs only have a few endpoints, but due to tools which do downloads, a few
have significantly more. These are:
- clangd_tidy.yaml (Bazel)
- pre_commit.yaml (Bazel, pre-commit)
- nightly_release.yaml (Bazel)
- tests.yaml (Bazel)
-63
View File
@@ -1,63 +0,0 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: 'Auto assign PRs'
on:
pull_request_target:
types: [opened, ready_for_review]
permissions:
pull-requests: write # For gh to edit assignees.
jobs:
assign_reviewer:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
with:
disable-sudo: true
egress-policy: block
# prettier-ignore
allowed-endpoints: >
api.github.com:443
- id: filter
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
with:
filters: |
leads:
- '*.md'
- 'LICENSE'
- 'docs/project/principles/*'
- 'docs/project/evolution.md'
- 'docs/project/goals.md'
- 'docs/project/roadmap.md'
- 'proposals/*.md'
toolchain:
- 'toolchain/**'
- id: assign-leads
if: steps.filter.outputs.leads == 'true'
uses: hkusu/review-assign-action@5bee595fdb9765d4a0bd35724b6302fa15569158 # v1.4.0
with:
reviewers: KateGregory, chandlerc, zygoloid
max-num-of-reviewers: 1
- id: assign-toolchain
if: steps.filter.outputs.toolchain == 'true'
uses: hkusu/review-assign-action@5bee595fdb9765d4a0bd35724b6302fa15569158 # v1.4.0
with:
reviewers:
chandlerc, danakj, dwblaikie, geoffromer, jonmeow, josh11b, zygoloid
max-num-of-reviewers: 1
- id: assign-fallback
if: |
steps.filter.outputs.leads != 'true' &&
steps.filter.outputs.toolchain != 'true'
uses: hkusu/review-assign-action@5bee595fdb9765d4a0bd35724b6302fa15569158 # v1.4.0
with:
reviewers: chandlerc, danakj, jonmeow, josh11b, zygoloid
max-num-of-reviewers: 1
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
+33
View File
@@ -0,0 +1,33 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: Check Dependent Label
on:
pull_request_target:
types: [opened, synchronize, labeled, unlabeled]
# This workflow runs as `pull_request_target` so that the check can't be
# disabled or bypassed by a the PR, but it doesn't need any permissions.
permissions: {}
jobs:
check_label:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
# prettier-ignore
allowed-endpoints: >
api.github.com:443
- name: Check for 'dependent' label
run: |
if [[ "${{ contains(github.event.pull_request.labels.*.name, 'dependent') }}" == "true" ]]; then
echo "PR has 'dependent' label. Blocking merge."
exit 1
fi
echo "PR does not have 'dependent' label."
-80
View File
@@ -1,80 +0,0 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: 'Clang Tidy'
on:
push:
branches: [trunk, action-test]
pull_request:
merge_group:
permissions:
contents: read # For actions/checkout.
pull-requests: read # For dorny/paths-filter to read pull requests.
# Cancel previous workflows on the PR when there are multiple fast commits.
# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#concurrency
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
clang-tidy:
runs-on: ubuntu-22.04
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
with:
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.dl.sourceforge.net:443
api.github.com:443
bcr.bazel.build:443
downloads.sourceforge.net:443
github.com:443
mirrors.kernel.org:443
nodejs.org:443
oauth2.googleapis.com:443
objects.githubusercontent.com:443
pypi.org:443
releases.bazel.build:443
sourceforge.net:443
storage.googleapis.com:443
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- id: test-setup
uses: ./.github/actions/test-setup
with:
matrix_runner: 'ubuntu-22.04'
base_sha:
${{ github.event_name == 'pull_request' &&
github.event.pull_request.base.sha ||
github.event.merge_group.base_sha }}
remote_cache_key: ${{ secrets.CARBON_BUILDS_GITHUB }}
targets_file: ${{ runner.temp }}/targets
use_direct_targets: true
# Run in the clang-tidy config. This is done as part of tests so that we
# aren't duplicating bazel/llvm setup.
#
# The `-k` flag is used to print all clang-tidy errors.
- name: clang-tidy
if: steps.test-setup.outputs.has_code == 'true'
env:
TARGETS_FILE: ${{ runner.temp }}/targets
run: |
./scripts/run_bazel.py \
--attempts=5 \
build --config=clang-tidy -k \
--target_pattern_file=$TARGETS_FILE
# See "Disk space before build" in `test-setup`.
- name: Disk space after build
if: steps.test-setup.outputs.has_code == 'true'
run: df -h
+14 -6
View File
@@ -8,8 +8,7 @@ on:
push:
branches: [trunk, action-test]
pull_request:
# TODO: Don't run in merge_group until we're ready to replace clang-tidy.
# merge_group:
merge_group:
permissions:
contents: read # For actions/checkout.
@@ -27,27 +26,36 @@ jobs:
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.dl.sourceforge.net:443
*.blob.storage.azure.net:443
*.githubapp.com:443
*.sourceforge.net:443
api.github.com:443
api.ipify.org:443
bcr.bazel.build:443
downloads.sourceforge.net:443
files.pythonhosted.org:443
github.com:443
go.dev:443
mirror.bazel.build:443
mirrors.kernel.org:443
nodejs.org:443
oauth2.googleapis.com:443
objects.githubusercontent.com:443
pypi.org:443
registry.npmjs.org:443
release-assets.githubusercontent.com:443
releases.bazel.build:443
sourceforge.net:443
storage.googleapis.com:443
uploads.github.com:443
www.googleapis.com:443
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- id: filter
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
+3 -3
View File
@@ -22,16 +22,16 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
- name: Checkout
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Prebuild actions
run: ./website/prebuild.py
- name: Setup Ruby
uses: ruby/setup-ruby@a6e6f86333f0a2523ece813039b8b4be04560854 # v1.190.0
uses: ruby/setup-ruby@6ca151fd1bfcfd6fe0c4eb6837eb0584d0134a0c # v1.290.0
with:
# Runs 'bundle install' and caches installed gems automatically.
bundler-cache: true
+5 -5
View File
@@ -29,18 +29,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
- name: Checkout
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Prebuild actions
run: ./website/prebuild.py
- name: Setup Pages
uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5.0.0
- name: Setup Ruby
uses: ruby/setup-ruby@a6e6f86333f0a2523ece813039b8b4be04560854 # v1.190.0
uses: ruby/setup-ruby@6ca151fd1bfcfd6fe0c4eb6837eb0584d0134a0c # v1.290.0
with:
# Runs 'bundle install' and caches installed gems automatically.
bundler-cache: true
@@ -57,7 +57,7 @@ jobs:
- name: Upload artifact
# Automatically uploads an artifact from the './_site' directory by
# default.
uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3.0.1
uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4.0.0
deploy:
environment:
@@ -67,7 +67,7 @@ jobs:
needs: build
steps:
- name: Harden Runner
uses: step-security/harden-runner@5c7944e73c4c2a096b17a9cb74d65b6c2bbafbde # v2.9.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
+17 -6
View File
@@ -37,26 +37,37 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.dl.sourceforge.net:443
*.blob.storage.azure.net:443
*.githubapp.com:443
*.sourceforge.net:443
api.github.com:443
api.ipify.org:443
bcr.bazel.build:443
downloads.sourceforge.net:443
files.pythonhosted.org:443
github.com:443
go.dev:443
mirror.bazel.build:443
mirrors.kernel.org:443
nodejs.org:443
oauth2.googleapis.com:443
objects.githubusercontent.com:443
pypi.org:443
registry.npmjs.org:443
release-assets.githubusercontent.com:443
releases.bazel.build:443
sourceforge.net:443
storage.googleapis.com:443
uploads.github.com:443
www.googleapis.com:443
- name: Checkout branch
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up remote cache access
env:
@@ -79,10 +90,10 @@ jobs:
run: |
./scripts/run_bazel.py \
--attempts=5 --jobs-on-last-attempt=4 \
test -c opt --remote_download_toplevel \
test -c opt --stamp --remote_download_toplevel \
--pre_release=nightly --nightly_date=${{ env.nightly_date }} \
//toolchain \
//toolchain/install:carbon_toolchain_tar_gz_rule \
//toolchain/install:carbon_toolchain_tar_gz \
//toolchain/install:carbon_toolchain_tar_gz_test
- name: Extract the release version
+14 -7
View File
@@ -18,30 +18,37 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo-and-containers: true
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.dl.sourceforge.net:443
*.blob.storage.azure.net:443
*.githubapp.com:443
*.sourceforge.net:443
api.github.com:443
api.ipify.org:443
bcr.bazel.build:443
downloads.sourceforge.net:443
files.pythonhosted.org:443
github.com:443
go.dev:443
mirror.bazel.build:443
mirrors.kernel.org:443
nodejs.org:443
oauth2.googleapis.com:443
objects.githubusercontent.com:443
pypi.org:443
registry.npmjs.org:443
release-assets.githubusercontent.com:443
releases.bazel.build:443
storage.googleapis.com:443
sourceforge.net:443
uploads.github.com:443
www.googleapis.com:443
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
# Ensure LLVM is set up consistently.
- uses: ./.github/actions/build-setup-common
@@ -63,7 +70,7 @@ jobs:
mkdir -p pre-commit-output
git diff > pre-commit-output/diff
cp $GITHUB_EVENT_PATH pre-commit-output/event
- uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
if: failure()
with:
name: pre-commit output
@@ -28,12 +28,11 @@ jobs:
# Only generate suggestions if pre-commit for a PR failed.
if: |
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.event == 'pull_request' &&
github.actor != 'jonmeow'
github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
@@ -48,10 +47,10 @@ jobs:
with:
reviewdog_version: latest
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Download pre-commit output
uses: actions/download-artifact@c850b930e6ba138125429b7e5c93fc707a7f8427 # v4.1.4
uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0
with:
name: pre-commit output
github-token: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
+2 -2
View File
@@ -25,13 +25,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
# Checkout our main repository.
- name: Checkout the main repository
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
# Run the sync script.
- name: Sync to other repositories
+36 -9
View File
@@ -22,36 +22,62 @@ concurrency:
jobs:
test:
name:
Testing ${{ matrix.config.name != 'Default' && format('({0})',
matrix.config.name) || '' }} (${{ matrix.runner }})
strategy:
matrix:
# Test a recent version of each supported OS.
runner: ['ubuntu-22.04', 'macos-14']
build_mode: [fastbuild, opt]
# Create a synthetic matrix dimension with the event name for filtering.
event: ['${{ github.event_name }}']
config:
- name: 'Default'
flags: ''
- name: 'Opt'
flags: '-c opt'
- name: 'ASan'
flags: '--config=asan'
exclude:
- runner: 'macos-14'
config: { name: 'ASan', flags: '--config=asan' }
- event: 'pull_request'
config: { name: 'ASan', flags: '--config=asan' }
- event: 'merge_group'
config: { name: 'ASan', flags: '--config=asan' }
runs-on: ${{ matrix.runner }}
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.dl.sourceforge.net:443
*.blob.storage.azure.net:443
*.githubapp.com:443
*.sourceforge.net:443
api.github.com:443
api.ipify.org:443
bcr.bazel.build:443
downloads.sourceforge.net:443
files.pythonhosted.org:443
github.com:443
go.dev:443
mirror.bazel.build:443
mirrors.kernel.org:443
nodejs.org:443
oauth2.googleapis.com:443
objects.githubusercontent.com:443
pypi.org:443
registry.npmjs.org:443
release-assets.githubusercontent.com:443
releases.bazel.build:443
sourceforge.net:443
storage.googleapis.com:443
uploads.github.com:443
www.googleapis.com:443
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- id: test-setup
uses: ./.github/actions/test-setup
@@ -65,7 +91,7 @@ jobs:
targets_file: ${{ runner.temp }}/targets
# Build and run just the tests impacted by the PR or merge group.
- name: Test (${{ matrix.build_mode }})
- name: Test (${{ matrix.config.name }})
if: steps.test-setup.outputs.has_code == 'true'
shell: bash
env:
@@ -76,10 +102,11 @@ jobs:
run: |
# Decrease the jobs sharply if we see repeated failures to try to
# work around transient network errors even if it makes things
# slower.
# slower. Note that we allow passing targets that are incompatible and
# skip thim as-if we were using `//...` style wild card patterns.
./scripts/run_bazel.py \
--attempts=5 --jobs-on-last-attempt=4 \
test -c ${{ matrix.build_mode }} \
test ${{ matrix.config.flags }} \
--target_pattern_file=$TARGETS_FILE
# See "Disk space before build" in `test-setup`.
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@17d0e2bd7d51742c71671bd19fa12bdc9d40a3d6 # v2.8.1
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
+6
View File
@@ -9,6 +9,11 @@
/github_tools/bazel-*
/github_tools/MODULE.bazel.lock
# We also have example Bazel projects that shouldn't have their implementation
# details committed.
/examples/**/bazel-*
/examples/**/MODULE.bazel.lock
# Directories created by python.
**/__pycache__/
@@ -34,6 +39,7 @@
# vim temporary files
.*.sw[a-p]
.swp
# generated by utils/tree_sitter/helix.sh
/.helix/
+12 -5
View File
@@ -12,7 +12,7 @@ default_language_version:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: cef0300fd0fc4d2a87a85fa2093c6b283ea36f4b # frozen: v5.0.0
rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
@@ -33,6 +33,11 @@ repos:
rev: efaea7c61c774c0b1a9805fd999e754a2d19dbd1 # frozen: v1.2.5
hooks:
- id: check-google-doc-style
exclude: |
(?x)^(
.*\.agents/.*|
.*AGENTS.md
)$
- id: markdown-toc
- repo: local
hooks:
@@ -45,7 +50,7 @@ repos:
# Formatters should be run late so that they can re-format any prior changes.
- repo: https://github.com/psf/black
rev: 8a737e727ac5ab2f1d4cf5876720ed276dc8dc4b # frozen: 25.1.0
rev: 35ea67920b7f6ac8e09be1c47278752b1e827f76 # frozen: 26.3.0
hooks:
- id: black
- repo: local
@@ -90,7 +95,7 @@ repos:
types_or: [c++, def]
language: python
args: ['-i']
additional_dependencies: ['clang-format==20.1.8']
additional_dependencies: ['clang-format==21.1.8']
- repo: local
hooks:
@@ -134,7 +139,7 @@ repos:
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: '850d8bf806620ef89a99381c5cf5ea2c1ea826dd' # frozen: v1.17.0
rev: 'a66e98df7b4aeeb3724184b332785976d062b92e' # frozen: v1.19.1
hooks:
- id: mypy
# Use setup.cfg to match the command line.
@@ -148,16 +153,18 @@ repos:
# Exclusions are:
# - p#### scripts because they're not tested or maintained.
# - lit.cfg.py because it has multiple copies, breaking mypy.
# - `bazel_test_runner.py` which depends on Bazel-specific imports.
# - Unit tests because they sometimes violate typing, such as by
# assigning a mock to a function.
exclude: |
(?x)^(
proposals/(?!scripts/).*|
.*/lit\.cfg\.py|
examples/bazel_test_runner\.py|
.*_test\.py
)$
- repo: https://github.com/codespell-project/codespell
rev: 63c8f8312b7559622c0d82815639671ae42132ac # frozen: v2.4.1
rev: 2ccb47ff45ad361a21071a7eedda4c37e6ae8c5a # frozen: v2.4.2
hooks:
- id: codespell
args: ['-I', '.codespell_ignore', '--uri-ignore-words-list', '*']
+2
View File
@@ -10,6 +10,7 @@
"debuggerRoot": "${workspaceFolder}",
"initCommands": [
"command script import external/+llvm_project+llvm-project/llvm/utils/lldbDataFormatters.py",
"command script import scripts/lldbinit.py",
"settings append target.source-map \".\" \"${workspaceFolder}\"",
"settings append target.source-map \"/proc/self/cwd\" \"${workspaceFolder}\"",
"settings set escape-non-printables false",
@@ -33,6 +34,7 @@
"debuggerRoot": "${workspaceFolder}",
"initCommands": [
"command script import external/+llvm_project+llvm-project/llvm/utils/lldbDataFormatters.py",
"command script import scripts/lldbinit.py",
"settings append target.source-map \".\" \"${workspaceFolder}\"",
"settings append target.source-map \"/proc/self/cwd\" \"${workspaceFolder}\"",
"settings set escape-non-printables false",
+58
View File
@@ -0,0 +1,58 @@
# Gemini & AI assistant guide for Carbon
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
This document provides high-density technical context for AI assistants (and
humans!) contributing to the Carbon Language project. If you are an AI
assistant, **read this first** to avoid common pitfalls.
## Table of contents
- [General instructions](#general-instructions)
- [Project structure](#project-structure)
- [Bazel usage](#bazel-usage)
- [Toolchain development](#toolchain-development)
## General instructions
- **Communication**: Be concise, professional, and technical. Use GitHub-style
markdown.
- **Verification**: Always run relevant tests.
- **Tool usage**: Use web search for any research outside the immediate
codebase or KIs.
## Project structure
- **[`common/`](common/)**: Common C++ utilities used across the project.
- **[`core/`](core/)**: The Carbon standard library (Core).
- **[`docs/`](docs/)**: Project documentation, design, and style guides.
- **[`examples/`](examples/)**: Example Carbon programs and code snippets.
- **[`proposals/`](proposals/)**: Evolution proposals.
- **[`testing/`](testing/)**: Testing utilities and infrastructure.
- **[`toolchain/`](toolchain/)**: The C++ implementation of the compiler
(Toolchain).
## Tool usage
See the "Tool usage" skill for instructions on what tools to use in the
carbon-lang project.
## Bazel usage
> [!IMPORTANT] Always use `bazelisk` instead of `bazel` for all commands in the
> Carbon project. Refer to the
> [Bazel usage skill](/.agents/skills/bazel/SKILL.md) for detailed instructions.
## Code style
See the "Code style" skill for instructions on formatting, style guides, and
code conventions to follow.
## Toolchain development
See the "Toolchain Development" skill for instructions on architecture,
building, testing, debugging, C++ patterns, and common pitfalls.
+43
View File
@@ -2,8 +2,51 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
load("@bazel_skylib//rules:common_settings.bzl", "bool_flag", "bool_setting", "int_flag")
filegroup(
name = "clang_tidy_config",
srcs = [".clang-tidy"],
visibility = ["//visibility:public"],
)
# `bazel run //:generate_compile_commands` to produce `compile_commands.json`.
alias(
name = "generate_compile_commands",
actual = "@wolfd_bazel_compile_commands//:generate_compile_commands",
)
bool_setting(
name = "runtimes_build",
build_setting_default = False,
visibility = ["//visibility:public"],
)
int_flag(
name = "bootstrap_stage",
build_setting_default = 0,
visibility = ["//visibility:public"],
)
# A setting that causes bootstrapping to occur using the `exec` config rather
# than the target config.
#
# The exec config is the more technically correct way of doing bootstrapping
# than the target config. For example it allows bootstrapping with a target that
# isn't compatible with the current execution host. However, in development
# builds, it is likely to force building the entire toolchain twice -- once in
# the target config for running test, and a second time in the exec config for
# the bootstrap. As a consequence, this is disabled by default.
#
# TODO: Add documentation for using the bootstrap flags once stabilized.
bool_flag(
name = "bootstrap_exec_config",
build_setting_default = False,
visibility = ["//visibility:public"],
)
config_setting(
name = "bootstrap_with_exec_config",
flag_values = {"//:bootstrap_exec_config": "True"},
visibility = ["//visibility:public"],
)
+24
View File
@@ -0,0 +1,24 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# This file is only used for PR autoassignment. Branch protections don't enforce
# it.
#
# Syntax:
# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners#codeowners-syntax
# Toolchain reviewers are used as a fallback.
* @carbon-language/toolchain-reviewers
# Key project documents should be reviewed by leads.
/*.md @carbon-language/leads
/LICENSE @carbon-language/leads
/docs/project/evolution.md @carbon-language/leads
/docs/project/goals.md @carbon-language/leads
/docs/project/principles/* @carbon-language/leads
/docs/project/roadmap.md @carbon-language/leads
/proposals/*.md @carbon-language/leads
# Toolchain code.
/toolchain @carbon-language/toolchain-reviewers
+50 -15
View File
@@ -33,6 +33,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
- [Style](#style)
- [Google Docs and Markdown](#google-docs-and-markdown)
- [Other files](#other-files)
- [Testing](#testing)
- [License](#license)
- [Google Docs](#google-docs)
- [Markdown](#markdown)
@@ -98,7 +99,7 @@ early, before even writing a proposal, and the process explains how to do that.
Helping with
[pull requests](https://github.com/carbon-language/carbon-lang/pulls) review is
a good way to provide feedback, while getting a acquainted with the code base.
a good way to provide feedback, while getting acquainted with the code base.
#### Implement Carbon's design
@@ -231,22 +232,49 @@ as well as helpful tooling that will ease the contribution process. For example,
#### Using AI-based contribution tools
If you are using an AI assistant to help you contribute, or if you are an AI
assistant yourself, please consult [AGENTS.md](/AGENTS.md) for high-density
technical context and tips.
All submissions to Carbon need to follow our
[Contributor License Agreement (CLA)](#contributor-license-agreements-clas), in
which contributors agree that their contribution is an original work of
authorship. This doesn’t prohibit the use of coding assistance tools, but what’s
submitted does need to be a contributor’s original creation.
[Contributor License Agreement (CLA)](#contributor-license-agreements-clas),
which covers any original work of authorship included in the submission. This
doesn't prohibit the use of coding assistance tools, including tool-, AI-, or
machine-generated code, as long as these submissions abide by the CLA's
requirements.
All contributions, regardless of what tools are used, are also still subject to
normal code review and our
[guidelines and standards](#contribution-guidelines-and-standards) below.
All contributions, regardless of what tools are used, are also still the
responsibility of the operator of these tools and subject to normal code review
and our [guidelines and standards](#contribution-guidelines-and-standards)
below. We also emphasize two additional requirements for contributors operating
or using AI-based tools:
Additionally, we want contributions to Carbon to also be viable as contributions
to LLVM so that we can move things between these projects where relevant. We
selected our license in part for this reason, and the same should be true for
the use of AI-based coding tools. Any contributions to Carbon should also abide
by the guidance in the
[LLVM Developer Policy around AI generated code](https://llvm.org/docs/DeveloperPolicy.html#ai-generated-contributions).
1. **Contributions should not become extractive of the project and community**:
the value added should outweigh the overhead of landing the contribution. The
overhead of landing contributions ranges from code review, to discussions,
distractions from the current project priorities, or growing maintenance
burden without growing maintainers.
2. **Each PR should be transparent about the tooling used** in proportion to how
much of the PR was produced by the tool and whether the tool is a standard
one for the project. For example, formatting with the standard tools is
reasonable to assume without further comment. But if a PR is largely derived
from running a specific Python script, regular expression, or AI-based tool
over the codebase, we ask that its commit message is transparent about this
and include a description of how the tool was used to formulate the change.
For PRs largely derived from AI-based tooling, we suggest following the
pattern established by the Fedora Project to mark commits with
`Assisted-by: ...`.
Our policies and practices here are inspired by and aim to be roughly compatible
with several other open source projects:
- [Fedora Project's policy](https://docs.fedoraproject.org/en-US/council/policy/ai-contribution-policy/)
- [LLVM Developer Policy around AI generated code](https://llvm.org/docs/DeveloperPolicy.html#ai-generated-contributions)
As the open source community evolves and learns how best to integrate these
tools into project and development workflows, we expect to reflect that with
updates and improvements here.
### Contribution guidelines and standards
@@ -281,7 +309,6 @@ follow the Carbon documentation and coding styles.
request.
- For code:
- New features should have a documented design that has been approved
through the [evolution process](docs/project/evolution.md). This
includes modifications to preexisting designs.
@@ -400,6 +427,14 @@ Other style points to be aware of are:
If you're not sure what style to use, please ask on Discord or GitHub.
## Testing
Most development in the Carbon project is on the [toolchain](toolchain/). The
toolchain contains some unit tests, but the majority of testing is done through
`file_test` tests, which test the output of the different phases of the
toolchain. The toolchain docs include instructions for
[building and running tests](toolchain/docs/adding_features.md#tests-and-debugging).
## License
A license is required at the top of all documents and files.
+73 -68
View File
@@ -19,50 +19,40 @@ of:
- Running `bazel mod deps` provides a canonical update to
`MODULE.bazel.lock`; create a PR with those changes in order to include
the host platform.
For updates, run `scripts/query_module_versions.py` to list the latest package
versions.
"""
module(name = "carbon")
http_archive = use_repo_rule(
"@bazel_tools//tools/build_defs/repo:http.bzl",
"http_archive",
)
bazel_dep(name = "abseil-cpp", version = "20260107.1")
bazel_dep(name = "bazel_skylib", version = "1.9.0")
bazel_dep(name = "boost.unordered", version = "1.90.0.bcr.1")
bazel_dep(name = "google_benchmark", version = "1.9.5")
bazel_dep(name = "googletest", version = "1.17.0.bcr.2")
bazel_dep(name = "libpfm", version = "4.13.0")
bazel_dep(name = "re2", version = "2025-11-05.bcr.1")
bazel_dep(name = "rules_cc", version = "0.2.17")
bazel_dep(name = "rules_pkg", version = "1.2.0")
bazel_dep(name = "rules_shell", version = "0.6.1")
bazel_dep(name = "tcmalloc", version = "0.0.0-20250927-12f2552")
bazel_dep(name = "tree-sitter-bazel", version = "0.26.5")
bazel_dep(name = "abseil-cpp", version = "20250512.1")
bazel_dep(name = "bazel_skylib", version = "1.8.1")
bazel_dep(name = "google_benchmark", version = "1.9.4")
bazel_dep(name = "googletest", version = "1.17.0")
bazel_dep(name = "re2", version = "2024-07-02.bcr.1")
bazel_dep(name = "rules_cc", version = "0.1.4")
bazel_dep(name = "rules_pkg", version = "1.1.0")
bazel_dep(name = "rules_shell", version = "0.5.0")
bazel_dep(name = "tcmalloc", version = "0.0.0-20250331-43fcf6e")
bazel_dep(name = "tree-sitter-bazel", version = "0.24.4")
# The registry only has an old version. We use that here to avoid a miss but
# override it with a newer version.
bazel_dep(name = "libpfm", version = "4.11.0")
libpfm_version = "4.13.0"
# The official site is https://perfmon2.sourceforge.net/, but SourceForge makes
# it difficult to download from bazel. On GitHub action runners,
# https://git.code.sf.net/p/perfmon2/libpfm4 seems to be blocked. As a
# consequence, use a mirror.
archive_override(
module_name = "libpfm",
integrity = "sha256-sGBx1+UoQCplBCc+pwA1Tr/PS2L/4jnLZHH82wSuPz0=",
patch_strip = 1,
patches = ["@//bazel/libpfm:0001-Introduce-a-simple-native-Bazel-build.patch"],
strip_prefix = "libpfm4-{0}".format(libpfm_version),
urls = ["https://github.com/wcohen/libpfm4/archive/v{0}.tar.gz".format(libpfm_version)],
bazel_dep(name = "wolfd_bazel_compile_commands", version = "0.5.2", dev_dependency = True)
git_override(
module_name = "wolfd_bazel_compile_commands",
# This is https://github.com/wolfd/bazel-compile-commands/pull/3 which is
# needed to correctly select target configurations in our compile commands.
commit = "7c673ac868cd237f262bb37a7819b1a279566a66",
remote = "https://github.com/chandlerc/bazel-compile-commands.git",
)
bazel_dep(name = "bazel_clang_tidy", dev_dependency = True)
git_override(
module_name = "bazel_clang_tidy",
# HEAD as of 2025-01-09.
commit = "db677011c7363509a288a9fb3bf0a50830bbf791",
# HEAD as of 2026-01-28.
commit = "c4d35e0d0b838309358e57a2efed831780f85cd0",
remote = "https://github.com/erenon/bazel_clang_tidy.git",
)
@@ -74,51 +64,37 @@ use_repo(bazel_cc_toolchain, "bazel_cc_toolchain")
register_toolchains("@bazel_cc_toolchain//:all")
bazel_dep(name = "hedron_compile_commands", dev_dependency = True)
git_override(
module_name = "hedron_compile_commands",
# HEAD as of 2025-01-09.
commit = "4f28899228fb3ad0126897876f147ca15026151e",
remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git",
)
boost_unordered_version = "1.85.0"
http_archive(
name = "boost_unordered",
build_file = "@//:third_party/boost_unordered/BUILD.bazel",
integrity = "sha256-2dQ4IQH/xFiK1iWCkrMYLeR8zsSQqGchKOdTuf1u0zI=",
strip_prefix = "boost_unordered-{0}".format(boost_unordered_version),
urls = ["https://github.com/MikePopoloski/boost_unordered/archive/v{0}.tar.gz".format(boost_unordered_version)],
)
register_toolchains("//toolchain/install:all")
# Required for llvm-project.
bazel_dep(name = "platforms", version = "1.0.0")
bazel_dep(name = "zlib", version = "1.3.1.bcr.6", repo_name = "llvm_zlib")
bazel_dep(name = "zstd", version = "1.5.7", repo_name = "llvm_zstd")
bazel_dep(name = "protobuf", version = "34.0.bcr.1", repo_name = "com_google_protobuf")
bazel_dep(name = "zlib-ng", version = "2.0.7", repo_name = "llvm_zlib")
bazel_dep(name = "zstd", version = "1.5.7.bcr.1", repo_name = "llvm_zstd")
###############################################################################
# llvm-project
###############################################################################
# We pin to specific upstream commits and try to track top-of-tree reasonably
# closely rather than pinning to a specific release.
# HEAD as of 2025-05-28.
llvm_project_version = "7b074fc9362a4a6a5f172dd8936a22fb25eff96b"
# Load a repository for the raw llvm-project, pre-overlay.
http_archive(
name = "llvm-raw",
bazel_dep(name = "llvm-raw")
git_override(
module_name = "llvm-raw",
build_file_content = "# empty",
patch_args = ["-p1"],
# We pin to specific upstream commits and try to track top-of-tree
# reasonably closely rather than pinning to a specific release.
# HEAD as of 2026-04-01.
commit = "b71eacea7687f68c11299e3bda5654fbbaa1e20e",
patch_cmds = ["echo \"module(name='llvm-raw')\" > MODULE.bazel"],
patch_strip = 1,
patches = [
"@carbon//bazel/llvm_project:0001_Patch_for_mallinfo2_when_using_Bazel_build_system.patch",
"@carbon//bazel/llvm_project:0002_Added_Bazel_build_for_compiler_rt_fuzzer.patch",
"@carbon//bazel/llvm_project:0003_Comment_out_unloaded_proto_library_dependencies.patch",
"//bazel/llvm_project:0001_Patch_for_mallinfo2_when_using_Bazel_build_system.patch",
"//bazel/llvm_project:0002_Added_Bazel_build_for_compiler_rt_fuzzer.patch",
"//bazel/llvm_project:0004_Introduce_basic_sources_exporting_for_libunwind.patch",
"//bazel/llvm_project:0005_Introduce_basic_sources_exporting_for_libcxx_and_libcxxabi.patch",
"//bazel/llvm_project:0009_Introduce_starlark_exporting_compiler-rt_build_information.patch",
],
sha256 = "07f80f32e81ac5dc19c5e49830f6d4a2e6208adb7d875ac3d1e8d043a602d9e4",
strip_prefix = "llvm-project-{0}".format(llvm_project_version),
urls = ["https://github.com/llvm/llvm-project/archive/{0}.tar.gz".format(llvm_project_version)],
remote = "https://github.com/llvm/llvm-project.git",
)
# Apply the overlay to produce llvm-project.
@@ -132,10 +108,39 @@ use_repo(llvm_project, "llvm-project")
# Python
###############################################################################
bazel_dep(name = "rules_python", version = "1.5.1")
bazel_dep(name = "rules_python", version = "1.9.0")
python = use_extension("@rules_python//python/extensions:python.bzl", "python")
python.toolchain(
python_version = "3.11",
)
use_repo(python, "python_versions")
###############################################################################
# Bazel integration testing
###############################################################################
bazel_dep(
name = "rules_bazel_integration_test",
version = "0.37.1",
dev_dependency = True,
)
# We test against our current Bazel version, the latest release, and the latest
# release candidate.
bazel_binaries = use_extension(
"@rules_bazel_integration_test//:extensions.bzl",
"bazel_binaries",
dev_dependency = True,
)
bazel_binaries.download(version_file = "//:.bazelversion")
bazel_binaries.download(version = "latest")
bazel_binaries.download(version = "last_rc")
use_repo(
bazel_binaries,
"bazel_binaries",
"bazel_binaries_bazelisk",
"build_bazel_bazel_.bazelversion",
"build_bazel_bazel_last_rc",
"build_bazel_bazel_latest",
)
+641 -271
View File
File diff suppressed because it is too large Load Diff
+34 -17
View File
@@ -169,6 +169,9 @@ If you're already a C++ developer, Carbon should have a gentle learning curve.
It is built out of a consistent set of language constructs that should feel
familiar and be easy to read and understand.
The Carbon code here is hypothetical and meant to show the look and feel of the
language.
C++ code like this:
<a href="docs/images/snippets.md#c">
@@ -244,27 +247,28 @@ and with a smooth evolutionary path.
Safety, and especially
[memory safety](https://en.wikipedia.org/wiki/Memory_safety), remains a key
challenge for C++ and something a successor language needs to address. Our
initial priority and focus is on immediately addressing important, low-hanging
fruit in the safety space:
challenge for C++ and something a successor language needs to address.
We plan to support a two step migration process:
1. Highly automated, minimal supervision migration from C++ to a dialect of
Carbon designed for C++ interop and migration.
2. Incremental refactoring of the Carbon code to adopt memory-safe designs,
patterns, and APIs.
We also want to address important, low-hanging fruit in the safety space
immediately when migrating into Carbon:
- Tracking uninitialized states better, increased enforcement of
initialization, and systematically providing hardening against
initialization bugs when desired.
- Designing fundamental APIs and idioms to support dynamic bounds checks in
debug and hardened builds.
- Having a default debug build mode that is both cheaper and more
comprehensive than existing C++ build modes even when combined with
initialization, and hardening against initialization bugs when needed.
- Designing fundamental APIs and idioms to support dynamic bounds checking.
- Switching from undefined behavior to erroneous behavior wherever possible,
and marking the remaining undefined behavior with visible `unsafe` syntax.
- Having a default debug build mode that has less runtime overhead while being
more comprehensive than existing C++ debug build modes combined with
[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer).
Once we can migrate code into Carbon, we will have a simplified language with
room in the design space to add any necessary annotations or features, and
infrastructure like [generics](#generics) to support safer design patterns.
Longer term, we will build on this to introduce **a safe Carbon subset**. This
will be a large and complex undertaking, and won't be in the 0.1 design.
Meanwhile, we are closely watching and learning from efforts to add memory safe
semantics onto C++ such as Rust-inspired
[lifetime annotations](https://discourse.llvm.org/t/rfc-lifetime-annotations-for-c/61377).
For more details, see our [safety design](/docs/design/safety).
## Getting started
@@ -361,6 +365,19 @@ Learn more about the Carbon project:
Carbon focused talks from the community:
### 2026
- Benchmarking and optimizing the Carbon compiler, NDC {Toronto} (May 5-8)
- Carbon: graduating from the experiment, NDC {Toronto} (May 5-8)
### 2025
- Carbon: from C++ to Memory Safety, REBASE - ICFP/SPLASH
([slides](https://chandlerc.blog/slides/2025-rebase-carbon))
- Memory safety everywhere with both Carbon and Rust, RustConf
([video](https://youtu.be/FYLuom6gg_s),
[slides](https://chandlerc.blog/slides/2025-rustconf-memory-safety-everywhere))
### 2024
- Generic implementation strategies in Carbon and Clang, LLVM Developers'
-1
View File
@@ -27,7 +27,6 @@ If you haven't received a response, a couple steps to take are (in order):
1. Contact individuals directly:
- [Chandler Carruth](mailto:chandlerc@gmail.com)
- [Richard Smith](mailto:richard@metafoo.co.uk)
- [Jon Ross-Perkins](mailto:jperkins@google.com)
2. Reach out on
[#infra](https://discord.com/channels/655572317891461132/707150492370862090)
on Discord ([invite](https://discord.gg/ZjVdShJDAs))
+107 -16
View File
@@ -4,22 +4,59 @@
"""Provides rules for building Carbon files using the toolchain."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
load("@rules_cc//cc/common:cc_info.bzl", "CcInfo")
def _carbon_binary_impl(ctx):
toolchain_driver = ctx.executable.internal_exec_toolchain_driver
toolchain_data = ctx.files.internal_exec_toolchain_data
prebuilt_runtimes = ctx.files.internal_exec_prebuilt_runtimes
# If the exec driver isn't provided, that means we're trying to use a target
# config toolchain, likely to avoid build overhead of two configs.
if toolchain_driver == None:
toolchain_driver = ctx.executable.internal_target_toolchain_driver
toolchain_data = ctx.files.internal_target_toolchain_data
prebuilt_runtimes = ctx.files.internal_target_prebuilt_runtimes
# The extra link flags needed.
link_flags = []
# Pass any C++ flags from our dependencies onto Carbon.
dep_flags = []
dep_hdrs = []
dep_link_inputs = []
for dep in ctx.attr.deps:
if CcInfo in dep:
cc_info = dep[CcInfo]
# TODO: We should reuse the feature-based flag generation in
# bazel/cc_toolchains here.
dep_flags += ["--clang-arg=-D{0}".format(define) for define in cc_info.compilation_context.defines.to_list()]
dep_flags += ["--clang-arg=-I{0}".format(path) for path in cc_info.compilation_context.includes.to_list()]
dep_flags += ["--clang-arg=-iquote{0}".format(path) for path in cc_info.compilation_context.quote_includes.to_list()]
dep_flags += ["--clang-arg=-isystem{0}".format(path) for path in cc_info.compilation_context.system_includes.to_list()]
dep_hdrs.append(cc_info.compilation_context.headers)
for link_input in cc_info.linking_context.linker_inputs.to_list():
link_flags += link_input.user_link_flags
dep_link_inputs += link_input.additional_inputs
for lib in link_input.libraries:
dep_link_inputs += [dep for dep in [lib.dynamic_library, lib.static_library] if dep]
dep_link_inputs += lib.objects
if DefaultInfo in dep:
dep_link_inputs += dep[DefaultInfo].files.to_list()
# Add the dependencies' link flags and inputs to the link flags.
link_flags += [dep.path for dep in dep_link_inputs]
# Build object files for the prelude and for the binary itself.
# TODO: Eventually the prelude should be build as a separate `carbon_library`.
srcs_and_flags = [
(ctx.files.prelude_srcs, ["--no-prelude-import"]),
(ctx.files.srcs, []),
(ctx.files.srcs, dep_flags),
]
objs = []
for (srcs, extra_flags) in srcs_and_flags:
for src in srcs:
@@ -32,7 +69,7 @@ def _carbon_binary_impl(ctx):
# TODO: This is a hack; replace with something better once the toolchain
# supports doing so.
#
# TODO: Switch to the `prefix_root` based rule similar to linking when
# TODO: Switch to the `prefix` based rule similar to linking when
# the prelude moves there.
out = ctx.actions.declare_file("_objs/{0}/{1}o".format(
ctx.label.name,
@@ -42,21 +79,50 @@ def _carbon_binary_impl(ctx):
srcs_reordered = [s for s in srcs if s != src] + [src]
ctx.actions.run(
outputs = [out],
inputs = srcs_reordered,
inputs = depset(direct = srcs_reordered, transitive = dep_hdrs),
executable = toolchain_driver,
tools = depset(toolchain_data),
arguments = ["compile", "--output=" + out.path] + [s.path for s in srcs_reordered] + extra_flags,
arguments = ["compile", "--output=" + out.path, "--output-last-input-only"] +
[s.path for s in srcs_reordered] + extra_flags + ctx.attr.flags,
mnemonic = "CarbonCompile",
progress_message = "Compiling " + src.short_path,
)
# Add the Carbon object files to the link flags.
link_flags += [o.path for o in objs]
bin = ctx.actions.declare_file(ctx.label.name)
# Get all link options from the toolchain and dependencies using standard pattern.
cc_toolchain = ctx.attr._cc_toolchain[cc_common.CcToolchainInfo]
feature_configuration = cc_common.configure_features(
ctx = ctx,
cc_toolchain = cc_toolchain,
requested_features = ctx.features,
unsupported_features = ctx.disabled_features,
)
variables = cc_common.create_link_variables(
feature_configuration = feature_configuration,
cc_toolchain = cc_toolchain,
is_using_linker = True,
user_link_flags = link_flags + [
# TODO: Remove once the sanitizer runtimes are available.
"-fno-sanitize=all",
],
output_file = bin.path,
)
full_link_flags = cc_common.get_memory_inefficient_command_line(
feature_configuration = feature_configuration,
action_name = ACTION_NAMES.cpp_link_executable,
variables = variables,
)
ctx.actions.run(
outputs = [bin],
inputs = objs,
inputs = objs + dep_link_inputs,
executable = toolchain_driver,
tools = depset(toolchain_data),
arguments = ["link", "--output=" + bin.path] + [o.path for o in objs],
tools = depset(toolchain_data + prebuilt_runtimes),
arguments = full_link_flags,
mnemonic = "CarbonLink",
progress_message = "Linking " + bin.short_path,
)
@@ -65,11 +131,17 @@ def _carbon_binary_impl(ctx):
_carbon_binary_internal = rule(
implementation = _carbon_binary_impl,
attrs = {
# The exec config toolchain driver and data. These will be `None` when
# using the target config and populated when using the exec config. We
# have to use duplicate attributes here and below to have different
# `cfg` settings, as that isn't `select`-able, and we'll use `select`s
# when populating these.
"deps": attr.label_list(allow_files = True, providers = [[CcInfo]]),
"flags": attr.string_list(),
# The exec config toolchain attributes. These will be `None` when using
# the target config and populated when using the exec config. We have to
# use duplicate attributes here and below to have different `cfg`
# settings, as that isn't `select`-able, and we'll use `select`s when
# populating these.
"internal_exec_prebuilt_runtimes": attr.label(
cfg = "exec",
),
"internal_exec_toolchain_data": attr.label(
cfg = "exec",
),
@@ -79,11 +151,14 @@ _carbon_binary_internal = rule(
cfg = "exec",
),
# The target config toolchain driver and data. These will be 'None' when
# The target config toolchain attributes. These will be 'None' when
# using the exec config and populated when using the target config. We
# have to use duplicate attributes here and below to have different
# `cfg` settings, as that isn't `select`-able, and we'll use `select`s
# when populating these.
"internal_target_prebuilt_runtimes": attr.label(
cfg = "target",
),
"internal_target_toolchain_data": attr.label(
cfg = "target",
),
@@ -94,21 +169,29 @@ _carbon_binary_internal = rule(
),
"prelude_srcs": attr.label_list(allow_files = [".carbon"]),
"srcs": attr.label_list(allow_files = [".carbon"]),
"_cc_toolchain": attr.label(default = "//toolchain/install:carbon_stage1_cc_toolchain"),
},
executable = True,
fragments = ["cpp"],
)
def carbon_binary(name, srcs):
def carbon_binary(name, srcs, deps = [], flags = [], tags = []):
"""Compiles a Carbon binary.
Args:
name: The name of the build target.
srcs: List of Carbon source files to compile.
deps: List of dependencies.
flags: Extra flags to pass to the Carbon compile command.
tags: Tags to apply to the rule.
"""
_carbon_binary_internal(
name = name,
srcs = srcs,
prelude_srcs = ["//core:prelude_files"],
deps = deps,
flags = flags,
tags = tags,
# We synthesize two sets of attributes from mirrored `select`s here
# because we want to select on an internal property of these attributes
@@ -116,18 +199,26 @@ def carbon_binary(name, srcs):
# `select` which one we use.
internal_exec_toolchain_driver = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": None,
"//conditions:default": "//toolchain/install:prefix_root/bin/carbon",
"//conditions:default": "//toolchain/install:carbon-busybox",
}),
internal_exec_toolchain_data = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": None,
"//conditions:default": "//toolchain/install:install_data",
}),
internal_exec_prebuilt_runtimes = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": None,
"//conditions:default": "//toolchain/install:built_runtimes",
}),
internal_target_toolchain_driver = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:prefix_root/bin/carbon",
"//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:carbon-busybox",
"//conditions:default": None,
}),
internal_target_toolchain_data = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:install_data",
"//conditions:default": None,
}),
internal_target_prebuilt_runtimes = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:built_runtimes",
"//conditions:default": None,
}),
)
+47
View File
@@ -3,9 +3,13 @@
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
load("@bazel_skylib//lib:selects.bzl", "selects")
load("@rules_python//python:defs.bzl", "py_library", "py_test")
load(":carbon_cc_toolchain_config.bzl", "gen_cc_toolchain_paths_with_stage")
package(default_visibility = ["//visibility:public"])
exports_files(["carbon_cc_toolchain_config.bzl"])
# For use by defs.bzl.
# Matches when asan is enabled on a macOS platform.
selects.config_setting_group(
@@ -46,3 +50,46 @@ config_setting(
name = "fastbuild",
values = {"compilation_mode": "fastbuild"},
)
filegroup(
name = "installed_cc_toolchain_starlark",
srcs = [
"cc_toolchain_actions.bzl",
"cc_toolchain_base_features.bzl",
"cc_toolchain_config_features.bzl",
"cc_toolchain_cpp_features.bzl",
"cc_toolchain_debugging.bzl",
"cc_toolchain_features.bzl",
"cc_toolchain_linking.bzl",
"cc_toolchain_modules.bzl",
"cc_toolchain_optimization.bzl",
"cc_toolchain_sanitizer_features.bzl",
"cc_toolchain_tools.bzl",
# TODO: Remove this once we can remove the use of it from Carbon
# toolchain rules.
"cc_toolchain_carbon_project_features.bzl",
],
)
gen_cc_toolchain_paths_with_stage(
name = "gen_cc_tools_paths",
stage = 0,
)
# Test that the default toolchain's Make variables expand correctly.
py_test(
name = "cc_tools_test",
srcs = ["cc_tools_test.py"],
args = ["$(location :gen_cc_tools_paths)"],
data = [":gen_cc_tools_paths"],
deps = [":cc_tools_test_lib"],
)
# Library containing the test logic, used by tests in other packages.
py_library(
name = "cc_tools_test_lib",
srcs = ["cc_tools_test.py"],
visibility = ["//visibility:public"],
deps = ["@bazel_tools//tools/python/runfiles"],
)
@@ -0,0 +1,547 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Starlark cc_toolchain configuration rules for using the Carbon toolchain"""
load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"action_config",
"flag_group",
"flag_set",
"tool",
)
load(
"@rules_cc//cc:defs.bzl",
"CcToolchainConfigInfo",
"cc_toolchain",
)
load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
load("//toolchain/runtimes:carbon_runtimes.bzl", "carbon_runtimes_build")
load(
"carbon_clang_variables.bzl",
"clang_include_dirs",
"clang_resource_dir",
"clang_sysroot",
)
load(
"cc_toolchain_actions.bzl",
"all_c_compile_actions",
"all_cpp_compile_actions",
"all_link_actions",
)
load("cc_toolchain_carbon_project_features.bzl", "carbon_project_features")
load("cc_toolchain_features.bzl", "clang_cc_toolchain_features")
load(
":cc_toolchain_tools.bzl",
"llvm_tool_paths",
)
def _make_action_configs(tools, runtimes_path = None):
runtimes_flag = "--no-build-runtimes"
if runtimes_path:
runtimes_flag = "--prebuilt-runtimes={0}".format(runtimes_path)
return [
action_config(
action_name = name,
enabled = True,
tools = [tools.clang],
)
for name in all_c_compile_actions
] + [
action_config(
action_name = name,
enabled = True,
tools = [tools.clangpp],
)
for name in all_cpp_compile_actions
] + [
action_config(
action_name = name,
enabled = True,
tools = [tools.carbon_busybox],
flag_sets = [flag_set(flag_groups = [flag_group(flags = [
runtimes_flag,
"link",
# We want to allow Bazel to intermingle linked object files and
# Clang-spelled link flags. The first `--` starts the list of
# initial object files by ending flags to the `link` subcommand,
# and the second `--` switches to Clang-spelled flags.
"--",
"--",
])])],
)
for name in all_link_actions
] + [
action_config(
action_name = name,
enabled = True,
tools = [tools.llvm_ar],
)
for name in [ACTION_NAMES.cpp_link_static_library]
] + [
action_config(
action_name = name,
enabled = True,
tools = [tools.llvm_strip],
)
for name in [ACTION_NAMES.strip]
]
def _compute_clang_system_include_dirs():
system_include_dirs_start_index = None
for index, dir in enumerate(clang_include_dirs):
# Skip over the include search directories until we find the resource
# directory. The system include directories are everything after that.
if dir.startswith(clang_resource_dir):
system_include_dirs_start_index = index + 1
break
if not system_include_dirs_start_index:
fail("Could not find the resource directory in the clang include " +
"directories: {}".format(clang_include_dirs))
return clang_include_dirs[system_include_dirs_start_index:]
def _carbon_cc_toolchain_config_impl(ctx):
llvm_bindir = "llvm/bin"
clang_bindir = llvm_bindir
tools = struct(
carbon_busybox = tool(path = "carbon-busybox"),
clang = tool(path = clang_bindir + "/clang"),
clangpp = tool(path = clang_bindir + "/clang++"),
llvm_ar = tool(path = llvm_bindir + "/llvm-ar"),
llvm_strip = tool(path = llvm_bindir + "/llvm-strip"),
)
if ctx.attr.bins:
carbon_busybox = None
clang = None
clangpp = None
llvm_ar = None
llvm_strip = None
for f in ctx.files.bins:
if f.basename == "carbon-busybox":
carbon_busybox = f
elif f.basename == "clang":
clang = f
elif f.basename == "clang++":
clangpp = f
elif f.basename == "llvm-ar":
llvm_ar = f
elif f.basename == "llvm-strip":
llvm_strip = f
if not all([carbon_busybox, clang, clangpp, llvm_ar, llvm_strip]):
fail("Missing required tool in bins: {0}".format(ctx.attr.bins))
llvm_bindir = llvm_ar.dirname
clang_bindir = clang.dirname
tools = struct(
carbon_busybox = tool(tool = carbon_busybox),
clang = tool(tool = clang),
clangpp = tool(tool = clangpp),
llvm_ar = tool(tool = llvm_ar),
llvm_strip = tool(tool = llvm_strip),
)
# Only use a sysroot if a non-trivial one is set in Carbon's config.
builtin_sysroot = None
sysroot_include_search = []
if clang_sysroot != "None" and clang_sysroot != "/":
builtin_sysroot = clang_sysroot
sysroot_include_search = ["%sysroot%/usr/include"]
runtimes_path = None
if ctx.attr.runtimes:
for f in ctx.files.runtimes:
if f.basename == "runtimes_root":
runtimes_path = f.dirname
break
if not runtimes_path:
fail("Unable to compute the runtimes path for: {0}".format(
ctx.attr.runtimes,
))
identifier = "{0}_toolchain_{1}_{2}".format(
ctx.attr.identifier_prefix,
ctx.attr.target_cpu,
ctx.attr.target_os,
)
return cc_common.create_cc_toolchain_config_info(
ctx = ctx,
features = clang_cc_toolchain_features(
target_os = ctx.attr.target_os,
target_cpu = ctx.attr.target_cpu,
# TODO: This should be configured externally rather than here so
# that the install Carbon toolchain doesn't automatically include
# Carbon-project-specific flags. However, that is especially awkward
# to do until we fully migrate to a rules-based toolchain, and the
# project-specific flags are largely harmless at the moment. We also
# omit a meaningful cache key as when using the Carbon toolchain we
# don't need it as it is a hermetic part of Bazel.
project_features = carbon_project_features(cache_key = ""),
),
action_configs = _make_action_configs(tools, runtimes_path),
cxx_builtin_include_directories = [
"runtimes/libunwind/include",
"runtimes/libcxx/include",
"runtimes/libcxxabi/include",
"{}/include".format(clang_resource_dir),
"runtimes/clang_resource_dir/include",
] + _compute_clang_system_include_dirs() + sysroot_include_search,
builtin_sysroot = builtin_sysroot,
# This configuration only supports local non-cross builds so derive
# everything from the target CPU selected.
toolchain_identifier = identifier,
# This is used to expose a "flag" that `config_setting` rules can use to
# determine if the compiler is Clang.
compiler = "clang",
# Pass in our tool paths to expose Make variables like $(NM) and
# $(OBJCOPY).
tool_paths = llvm_tool_paths(llvm_bindir, clang_bindir),
)
carbon_cc_toolchain_config = rule(
implementation = _carbon_cc_toolchain_config_impl,
attrs = {
"bins": attr.label(mandatory = False),
"identifier_prefix": attr.string(mandatory = True),
"runtimes": attr.label(mandatory = False),
"target_cpu": attr.string(mandatory = True),
"target_os": attr.string(mandatory = True),
},
provides = [CcToolchainConfigInfo],
)
def _transition_with_stage_impl(_, attr):
return {
"//:bootstrap_stage": attr.stage,
"//:runtimes_build": attr.enable_runtimes_build,
}
_transition_with_stage = transition(
inputs = [],
outputs = [
"//:bootstrap_stage",
"//:runtimes_build",
],
implementation = _transition_with_stage_impl,
)
def _filegroup_with_stage_impl(ctx):
return [DefaultInfo(files = depset(ctx.files.srcs))]
filegroup_with_stage = rule(
implementation = _filegroup_with_stage_impl,
attrs = {
# Whether to enable runtimes building for the sources of this filegroup.
"enable_runtimes_build": attr.bool(default = False),
# Mark that our dependencies are built through a transition.
"srcs": attr.label_list(mandatory = True, cfg = _transition_with_stage),
# The bootstrap stage that the sources of this filegroup should be built
# with.
"stage": attr.int(mandatory = True),
# Enable transitions in this rule.
"_allowlist_function_transition": attr.label(
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
),
},
doc = """
A filegroup whose sources are built using a specific toolchain stage, and
which provides an interface to build those sources with or without enabling
runtimes building.
""",
)
def _exec_filegroup_impl(ctx):
return [DefaultInfo(files = depset(ctx.files.srcs))]
_exec_filegroup = rule(
implementation = _exec_filegroup_impl,
attrs = {
"srcs": attr.label_list(cfg = "exec"),
},
)
def filegroup_with_stage_and_exec(name, srcs, stage, tags = []):
"""Wraps `filegroup_with_stage` with a conditional `exec` config transition.
When `//:bootstrap_exec_config` is disabled, this works exactly like
`filegroup_with_stage`. But when it is _enabled_, it also adds an `exec`
config transition. This allows bootstrapping for a target that is not exec
compatible with the host, and in general makes bootstrapping more robust at
the expense of a likely duplicate build of the entire toolchain.
"""
filegroup_with_stage(
name = name + "_stage_only",
srcs = srcs,
stage = stage,
tags = tags,
)
_exec_filegroup(
name = name + "_with_exec",
srcs = [":" + name + "_stage_only"],
tags = tags,
)
native.alias(
name = name,
actual = select({
"//:bootstrap_with_exec_config": ":" + name + "_with_exec",
"//conditions:default": ":" + name + "_stage_only",
}),
tags = tags,
)
def _gen_cc_toolchain_paths_impl(ctx):
cc_toolchain = find_cpp_toolchain(ctx)
expanded_vars = [
ctx.expand_make_variables("vars", v, {})
for v in ctx.attr.vars
]
out = ctx.actions.declare_file(ctx.attr.name + ".txt")
ctx.actions.write(out, "\n".join(expanded_vars) + "\n")
# Include all toolchain files in runfiles.
runfiles = ctx.runfiles(files = [out]).merge(
ctx.runfiles(transitive_files = cc_toolchain.all_files),
)
return [DefaultInfo(files = depset([out]), runfiles = runfiles)]
gen_cc_toolchain_paths_with_stage = rule(
implementation = _gen_cc_toolchain_paths_impl,
attrs = {
"enable_runtimes_build": attr.bool(default = False),
"stage": attr.int(mandatory = True),
"vars": attr.string_list(
default = ["$(CC)", "$(AR)", "$(NM)", "$(OBJCOPY)", "$(STRIP)"],
),
"_allowlist_function_transition": attr.label(
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
),
"_cc_toolchain": attr.label(
default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
),
},
toolchains = ["@bazel_tools//tools/cpp:toolchain_type"],
cfg = _transition_with_stage,
)
def carbon_cc_toolchain_suite(
name,
all_hdrs,
base_files,
clang_hdrs,
platforms,
runtimes_cfg,
build_stage = 1,
base_stage = 0,
tags = []):
"""Create a Carbon `cc_toolchain` for the current target platform.
This provides the final toolchain for Carbon, but also all of the
infrastructure for supporting on-demand built runtimes in this toolchain.
There is also support for bootstrapping, where one `build_stage` toolchain
builds on top of another `base_stage`.
Args:
name:
The name of the toolchain suite to produce, used as the base of the
names of each component of the toolchain suite.
all_hdrs: A list of header files to include in the toolchain.
base_files: A list of files to include in the toolchain.
build_stage: The stage to use for the build files.
base_stage: The stage to use for the base files.
clang_hdrs: A list of header files to include in the toolchain.
platforms: An array of (os, cpu) pairs to support in the toolchain.
runtimes_cfg: The runtimes configuration to use in the toolchain.
tags: Tags to apply to the toolchain.
"""
# First, declare file groups that are explicitly built using the base stage,
# and not in the runtimes build. These allow us to form the inputs to both
# the runtimes toolchain and the main toolchain of this stage that are built
# entirely by the base stage toolchain.
filegroup_with_stage_and_exec(
name = "{}_clang_hdrs".format(name),
srcs = clang_hdrs,
stage = base_stage,
tags = tags,
)
filegroup_with_stage_and_exec(
name = "{}_base_files".format(name),
srcs = base_files,
stage = base_stage,
tags = tags,
)
filegroup_with_stage_and_exec(
name = "{}_runtimes_compile_files".format(name),
srcs = [
":{}_base_files".format(name),
":{}_clang_hdrs".format(name),
],
stage = base_stage,
tags = tags,
)
filegroup_with_stage_and_exec(
name = "{}_compile_files".format(name),
srcs = [":{}_base_files".format(name)] + all_hdrs,
stage = base_stage,
tags = tags,
)
# Now build a configuration and toolchain that is configured to work
# _without_ runtimes, and be used to _build_ the runtimes on-demand.
carbon_cc_toolchain_config(
name = "{}_runtimes_toolchain_config".format(name),
identifier_prefix = "{}_runtimes".format(name),
target_cpu = select({
# Note that we need to select on both OS and CPU so that we end up
# spelling the CPU in the correct OS-specific ways.
":is_{}_{}".format(os, cpu): cpu
for os, cpus in platforms.items()
for cpu in cpus
}),
target_os = select({
"@platforms//os:{}".format(os): os
for os in platforms.keys()
}),
bins = ":{}_base_files".format(name),
tags = tags,
)
cc_toolchain(
name = "{}_runtimes_cc_toolchain".format(name),
all_files = ":{}_runtimes_compile_files".format(name),
ar_files = ":{}_base_files".format(name),
as_files = ":{}_runtimes_compile_files".format(name),
compiler_files = ":{}_runtimes_compile_files".format(name),
dwp_files = ":{}_base_files".format(name),
linker_files = ":{}_base_files".format(name),
objcopy_files = ":{}_base_files".format(name),
strip_files = ":{}_base_files".format(name),
toolchain_config = ":{}_runtimes_toolchain_config".format(name),
toolchain_identifier = select({
":is_{}_{}".format(os, cpu): "{}_{}_{}_runtimes_toolchain".format(name, os, cpu)
for os, cpus in platforms.items()
for cpu in cpus
}),
tags = tags,
)
native.toolchain(
name = "{}_runtimes_toolchain".format(name),
target_settings = [
":is_bootstrap_stage_{}".format(build_stage),
":is_runtimes_build",
],
use_target_platform_constraints = True,
toolchain = ":{}_runtimes_cc_toolchain".format(name),
toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
tags = tags,
)
# Now that we have a toolchain for building runtimes, actually do the build
# here using the runtimes config provided to us. This is important to do
# here because we need each runtimes build for a particular bootstrapping
# stage of the toolchain to be distinct.
carbon_runtimes_build(
name = "{}_runtimes_build".format(name),
config = runtimes_cfg,
clang_hdrs = [":{}_clang_hdrs".format(name)],
tags = tags,
)
# Wrap the built runtimes for this stage in a filegroup that ensures they
# are built at this stage, but with the runtimes build enabled. This will
# select the runtimes build toolchain above that doesn't yet provide any
# runtimes, avoiding a cycle when the main toolchain below depends on these
# runtimes.
filegroup_with_stage(
name = "{}_runtimes".format(name),
enable_runtimes_build = True,
srcs = ["{}_runtimes_build".format(name)],
stage = build_stage,
tags = tags,
)
# Now we can build the main toolchain configuration, filegroups including
# the on-demand built runtimes, and the final tolochain itself.
carbon_cc_toolchain_config(
name = "{}_toolchain_config".format(name),
identifier_prefix = name,
target_cpu = select({
# Note that we need to select on both OS and CPU so that we end up
# spelling the CPU in the correct OS-specific ways.
":is_{}_{}".format(os, cpu): cpu
for os, cpus in platforms.items()
for cpu in cpus
}),
target_os = select({
"@platforms//os:{}".format(os): os
for os in platforms.keys()
}),
runtimes = ":{}_runtimes".format(name),
bins = ":{}_base_files".format(name),
tags = tags,
)
native.filegroup(
name = "{}_linker_files".format(name),
srcs = [
":{}_base_files".format(name),
":{}_runtimes".format(name),
],
tags = tags,
)
native.filegroup(
name = "{}_all_files".format(name),
srcs = [
":{}_compile_files".format(name),
":{}_linker_files".format(name),
],
tags = tags,
)
cc_toolchain(
name = "{}_cc_toolchain".format(name),
all_files = ":{}_all_files".format(name),
ar_files = ":" + name + "_base_files",
as_files = ":" + name + "_compile_files",
compiler_files = ":" + name + "_compile_files",
dwp_files = ":" + name + "_linker_files",
linker_files = ":" + name + "_linker_files",
objcopy_files = ":" + name + "_base_files",
strip_files = ":" + name + "_base_files",
toolchain_config = ":" + name + "_toolchain_config",
toolchain_identifier = select({
":is_{}_{}".format(os, cpu): "{}_{}_{}_toolchain".format(name, os, cpu)
for os, cpus in platforms.items()
for cpu in cpus
}),
tags = tags,
)
native.toolchain(
name = name + "_toolchain",
target_settings = [":is_bootstrap_stage_{}".format(build_stage), ":not_runtimes_build"],
use_target_platform_constraints = True,
toolchain = ":" + name + "_cc_toolchain",
toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
tags = tags,
)
@@ -0,0 +1,20 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""A Starlark file exporting detected Carbon toolchain configuration variables.
This file gets processed by a repository rule, substituting the `VARIABLE`s with
values, for example using an invocation of `carbon config`.
"""
load(
"@bazel_cc_toolchain//:clang_detected_variables.bzl",
_clang_include_dirs = "clang_include_dirs",
_clang_resource_dir = "clang_resource_dir",
_sysroot_dir = "sysroot_dir",
)
clang_include_dirs = _clang_include_dirs
clang_resource_dir = _clang_resource_dir
clang_sysroot = _sysroot_dir
@@ -0,0 +1,47 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Useful sets of actions for defining `cc_toolchain_config` features."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
all_c_compile_actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
]
all_cpp_compile_actions = [
ACTION_NAMES.cpp_compile,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
]
all_compile_actions = all_c_compile_actions + all_cpp_compile_actions
preprocessor_compile_actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
]
codegen_compile_actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.cpp_module_codegen,
]
all_link_actions = [
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_nodeps_dynamic_library,
]
@@ -0,0 +1,134 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Definitions used for the base features of a `cc_toolchain_config`."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
)
load(
":cc_toolchain_actions.bzl",
"all_compile_actions",
"all_link_actions",
)
# Declare features that are used by Bazel to model specific build modes.
dbg_feature = feature(name = "dbg")
fastbuild_feature = feature(name = "fastbuild")
host_feature = feature(name = "host")
opt_feature = feature(name = "opt")
# Declare features that control enabling and disabling Bazel logic.
no_legacy_features_feature = feature(name = "no_legacy_features")
supports_pic_feature = feature(name = "supports_pic", enabled = True)
supports_dynamic_linker_feature = feature(
name = "supports_dynamic_linker",
enabled = True,
requires = [feature_set(["linux_target"])],
)
supports_start_end_lib_feature = feature(
name = "supports_start_end_lib",
enabled = True,
requires = [feature_set(["linux_target"])],
)
user_flags_feature = feature(
name = "user_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions,
flag_groups = [flag_group(
expand_if_available = "user_compile_flags",
flags = ["%{user_compile_flags}"],
iterate_over = "user_compile_flags",
)],
),
flag_set(
actions = all_link_actions,
flag_groups = [flag_group(
expand_if_available = "user_link_flags",
flags = ["%{user_link_flags}"],
iterate_over = "user_link_flags",
)],
),
],
)
# TODO: It's not clear this is the right location for these flags, and it is a
# little awkward.
output_flags_feature = feature(
name = "output_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions,
flag_groups = [
# For compile actions we have a single source and so put it at
# the end next to the output.
flag_group(
expand_if_available = "source_file",
flags = ["%{source_file}"],
),
flag_group(
expand_if_available = "output_file",
flags = ["-o", "%{output_file}"],
),
],
),
flag_set(
actions = all_link_actions,
flag_groups = [flag_group(
expand_if_available = "output_execpath",
flags = ["-o", "%{output_execpath}"],
)],
),
],
)
strip_feature = feature(
name = "strip_flags",
enabled = True,
flag_sets = [flag_set(
actions = [ACTION_NAMES.strip],
flag_groups = [
flag_group(
flags = ["-S"],
),
flag_group(
flags = ["-p"],
),
flag_group(
expand_if_available = "output_file",
flags = ["-o", "%{output_file}"],
),
flag_group(
iterate_over = "stripopts",
flags = ["%{stripopts}"],
),
flag_group(
expand_if_available = "input_file",
flags = ["%{input_file}"],
),
],
)],
)
base_features = [
dbg_feature,
fastbuild_feature,
host_feature,
no_legacy_features_feature,
opt_feature,
strip_feature,
supports_pic_feature,
supports_dynamic_linker_feature,
supports_start_end_lib_feature,
]
@@ -0,0 +1,83 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Defines `cc_toolchain_config` features specific to the Carbon project."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
"with_feature_set",
)
load(
":cc_toolchain_actions.bzl",
"all_compile_actions",
"preprocessor_compile_actions",
)
# An enabled feature that requires the `fastbuild` compilation. This is used
# to toggle general features on by default, while allowing them to be
# directly enabled and disabled more generally as desired.
carbon_project_fastbuild_feature = feature(
name = "enable_in_fastbuild",
enabled = True,
requires = [feature_set(["fastbuild"])],
implies = [
"minimal_optimization_flags",
"minimal_debug_info_flags",
"preserve_call_stacks",
],
)
def carbon_project_features(cache_key):
return [carbon_project_fastbuild_feature, feature(
name = "project_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions,
flag_groups = [flag_group(flags = [
# Don't warn on external code as we can't
# necessarily patch it easily. Note that these have
# to be initial directories in the `#include` line.
"--system-header-prefix=absl/",
"--system-header-prefix=benchmark/",
"--system-header-prefix=boost/",
"--system-header-prefix=clang-tools-extra/",
"--system-header-prefix=clang/",
"--system-header-prefix=gmock/",
"--system-header-prefix=gtest/",
"--system-header-prefix=libfuzzer/",
"--system-header-prefix=llvm/",
"--system-header-prefix=re2/",
"--system-header-prefix=tools/cpp/",
"--system-header-prefix=tree_sitter/",
])],
),
flag_set(
actions = preprocessor_compile_actions,
flag_groups = [flag_group(flags = [
# Pass a cache key as a `-D` flag to avoid unintended Bazel
# cache hits when the underlying toolchain changes.
# TODO: We should consider replacing this by causing changes
# to the installed toolchain to more reliably end up as part
# of the action digest.
"-DBAZEL_COMPILE_CACHE_KEY=\"%s\"" % cache_key,
])],
),
flag_set(
actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
],
flag_groups = [flag_group(flags = ["-DHAVE_MALLCTL"])],
with_features = [with_feature_set(["freebsd_target"])],
),
],
)]
@@ -0,0 +1,54 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Configuration features for other features in a `cc_toolchain_config`.
These features are designed to be used by other features in a
`cc_toolchain_config` that need to configure their behavior in some way. This
can be configuration based on either the target or host of the build, and along
multiple dimensions of each.
"""
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
)
os_names = [
"freebsd",
"linux",
"macos",
"windows",
]
def target_os_features(target_os):
if target_os not in os_names:
fail("Unsupported target OS: %s" % target_os)
return [
feature(name = os_name + "_target", enabled = os_name == target_os)
for os_name in os_names
]
cpu_names = [
"aarch64",
"x86_64",
]
# Also support canonicalizing different spellings of CPUs to one of the above
# names.
cpu_canonical_name_map = {
"aarch64": "aarch64",
"arm64": "aarch64",
"x86_64": "x86_64",
}
def target_cpu_features(target_cpu):
if target_cpu not in cpu_canonical_name_map:
fail("Unsupported target CPU: %s" % target_cpu)
target_cpu = cpu_canonical_name_map[target_cpu]
return [
feature(name = cpu_name + "_target", enabled = cpu_name == target_cpu)
for cpu_name in cpu_names
]
@@ -0,0 +1,306 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Definitions of general C++ `cc_toolchain_config` features."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"with_feature_set",
)
load(
":cc_toolchain_actions.bzl",
"all_compile_actions",
"all_cpp_compile_actions",
"all_link_actions",
"codegen_compile_actions",
"preprocessor_compile_actions",
)
clang_feature = feature(
name = "clang",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions + all_link_actions,
flag_groups = [
flag_group(flags = [
"-no-canonical-prefixes",
"-fcolor-diagnostics",
]),
flag_group(
expand_if_available = "sysroot",
flags = ["--sysroot=%{sysroot}"],
),
],
),
flag_set(
actions = all_compile_actions,
flag_groups = [
flag_group(flags = [
# Compile actions shouldn't link anything.
"-c",
]),
# Flags controlling the production of specific outputs from
# compile actions.
flag_group(
expand_if_available = "output_assembly_file",
flags = ["-S"],
),
flag_group(
expand_if_available = "output_preprocess_file",
flags = ["-E"],
),
flag_group(
expand_if_available = "dependency_file",
flags = ["-MD", "-MF", "%{dependency_file}"],
),
flag_group(
expand_if_available = "output_file",
flags = ["-frandom-seed=%{output_file}"],
),
],
),
flag_set(
# Flags specific to compiling C++ sources.
actions = all_cpp_compile_actions,
flag_groups = [flag_group(flags = [
"-std=c++20",
])],
),
flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(flags = [
"-ffunction-sections",
"-fdata-sections",
])],
),
flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(
expand_if_available = "pic",
flags = ["-fPIC"],
)],
),
flag_set(
actions = preprocessor_compile_actions,
flag_groups = [
flag_group(flags = [
# Disable a warning and override builtin macros to
# ensure a hermetic build.
"-Wno-builtin-macro-redefined",
"-D__DATE__=\"redacted\"",
"-D__TIMESTAMP__=\"redacted\"",
"-D__TIME__=\"redacted\"",
]),
flag_group(
flags = ["-D%{preprocessor_defines}"],
iterate_over = "preprocessor_defines",
),
flag_group(
expand_if_available = "includes",
flags = ["-include", "%{includes}"],
iterate_over = "includes",
),
flag_group(
flags = ["-iquote", "%{quote_include_paths}"],
iterate_over = "quote_include_paths",
),
flag_group(
flags = ["-I%{include_paths}"],
iterate_over = "include_paths",
),
flag_group(
flags = ["-isystem", "%{system_include_paths}"],
iterate_over = "system_include_paths",
),
],
),
flag_set(
actions = [
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_nodeps_dynamic_library,
],
flag_groups = [flag_group(flags = ["-shared"])],
),
flag_set(
actions = all_link_actions,
flag_groups = [
flag_group(
expand_if_available = "strip_debug_symbols",
flags = ["-Wl,-S"],
),
flag_group(
expand_if_available = "library_search_directories",
flags = ["-L%{library_search_directories}"],
iterate_over = "library_search_directories",
),
flag_group(
expand_if_available =
"runtime_library_search_directories",
iterate_over = "runtime_library_search_directories",
flags = [
"-Wl,-rpath,$ORIGIN/%{runtime_library_search_directories}",
],
),
],
),
flag_set(
actions = all_link_actions,
flag_groups = [
flag_group(
flags = [
"-fuse-ld=lld",
# Force the C++ standard library and runtime libraries
# to be statically linked. This works even with libc++
# and libunwind despite the names, provided libc++ is
# built with the CMake option:
# - `-DCMAKE_POSITION_INDEPENDENT_CODE=ON`
"-static-libstdc++",
"-static-libgcc",
# Link with Clang's runtime library. This is always
# linked statically.
"-rtlib=compiler-rt",
# Link with pthread.
"-lpthread",
],
),
],
with_features = [with_feature_set(["linux_target"])],
),
flag_set(
actions = [ACTION_NAMES.cpp_link_executable],
flag_groups = [flag_group(
expand_if_available = "force_pic",
flags = ["-pie"],
)],
with_features = [with_feature_set([
"linux_target",
"freebsd_target",
])],
),
flag_set(
actions = [ACTION_NAMES.cpp_link_executable],
flag_groups = [flag_group(
expand_if_available = "force_pic",
flags = ["-fpie"],
)],
with_features = [with_feature_set(["macos_target"])],
),
],
)
clang_warnings_feature = feature(
name = "clang_warnings",
enabled = True,
flag_sets = [flag_set(
actions = all_compile_actions,
flag_groups = [flag_group(flags = [
"-Werror",
"-Wall",
"-Wextra",
"-Wthread-safety",
"-Wself-assign",
"-Wimplicit-fallthrough",
"-Wctad-maybe-unsupported",
"-Wextra-semi",
"-Wmissing-prototypes",
"-Wzero-as-null-pointer-constant",
"-Wdelete-non-virtual-dtor",
# TODO: Regression that warns on anonymous unions; remove depending
# on fix.
"-Wno-missing-designated-field-initializers",
])],
)],
)
# Libc++ HARDENING_MODE has 4 possible values:
# https://libcxx.llvm.org/Hardening.html#notes-for-users
#
# Do not enable DEBUG hardening mode, even for -c dbg, because its performance
# impact on llvm-symbolizer is too severe -- this flag results in symbolization
# becoming quadratic in the number of debug symbols, in practice meaning it
# never completes.
_libcpp_debug_flags = [
"-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE",
]
_libcpp_release_flags = [
"-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST",
]
def libcxx_feature(llvm_bindir = None, clang_bindir = None):
"""Builds a libc++ feature.
Returns:
The feature for use with `cc_toolchain_config`.
Args:
llvm_bindir: Optional LLVM installation `bin` directory, causes the
feature to look for adjacent installed libraries.
clang_bindir: Optional Clang installation `bin` directory, causes the
feature to look for adjacent installed libraries if different from
`llvm_bindir`.
"""
# Explicitly add LLVM libs to the search path to preempt the
# detected GCC installation's library paths. Those might have a
# system installed libc++ and we want to find the one next to
# our Clang.
extra_link_flags = []
if llvm_bindir:
extra_link_flags.append("-L" + llvm_bindir + "/../lib")
if clang_bindir and clang_bindir != llvm_bindir:
extra_link_flags.append("-L" + clang_bindir + "/../lib")
return feature(
name = "libcxx",
enabled = True,
flag_sets = [
flag_set(
actions = all_cpp_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = [
"-stdlib=libc++",
])],
with_features = [
# libc++ is only used on non-Windows platforms.
with_feature_set(not_features = ["windows_target"]),
],
),
flag_set(
actions = all_cpp_compile_actions,
flag_groups = [flag_group(flags = _libcpp_debug_flags)],
with_features = [with_feature_set(not_features = ["opt"])],
),
flag_set(
actions = all_cpp_compile_actions,
flag_groups = [flag_group(flags = _libcpp_release_flags)],
with_features = [with_feature_set(features = ["opt"])],
),
flag_set(
actions = all_link_actions,
flag_groups = [flag_group(flags = [
"-unwindlib=libunwind",
])],
with_features = [
# libc++ is only used on non-Windows platforms.
with_feature_set(not_features = ["windows_target"]),
],
),
flag_set(
actions = all_link_actions,
flag_groups = [flag_group(flags = extra_link_flags + [
# Force linking the static libc++abi archive here. This
# *should* be linked automatically, but not every release of
# LLVM correctly sets the CMake flags to do so.
"-l:libc++abi.a",
])],
with_features = [with_feature_set(["linux_target"])],
),
],
)
@@ -0,0 +1,139 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Definitions of debugging related features used in a `cc_toolchain_config`."""
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
)
load(
":cc_toolchain_actions.bzl",
"all_link_actions",
"codegen_compile_actions",
)
# Handle different levels and forms of debug info emission with individual
# features so that they can be ordered and the defaults can override the
# minimal settings if both are enabled.
minimal_debug_info_flags = feature(
name = "minimal_debug_info_flags",
implies = ["debug_info_compression_flags"],
flag_sets = [flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(flags = ["-gmlt"])],
)],
)
debug_info_flags = feature(
name = "debug_info_flags",
implies = ["debug_info_compression_flags"],
flag_sets = [flag_set(
actions = codegen_compile_actions,
flag_groups = [
flag_group(flags = ["-g"]),
flag_group(
expand_if_available = "per_object_debug_info_file",
flags = ["-gsplit-dwarf"],
),
],
)],
)
debug_info_compression_flags = feature(
name = "debug_info_compression_flags",
flag_sets = [flag_set(
actions = codegen_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = ["-gz"])],
)],
)
# Define a set of mutually exclusive debugger flags.
debugger_flags = feature(name = "debugger_flags")
lldb_flags = feature(
# Use a convenient name for users to select if needed.
name = "lldb_flags",
# Default enable LLDB-optimized flags whenever debugging.
enabled = True,
requires = [feature_set(features = ["debug_info_flags"])],
provides = ["debugger_flags"],
flag_sets = [flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(flags = [
"-glldb",
"-gpubnames",
"-gsimple-template-names",
])],
)],
)
gdb_flags = feature(
# Use a convenient name for users to select if needed.
name = "gdb_flags",
requires = [feature_set(features = ["debug_info_flags"])],
provides = ["debugger_flags"],
flag_sets = [
flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(flags = [
"-ggdb",
"-ggnu-pubnames",
])],
),
flag_set(
actions = all_link_actions,
flag_groups = [flag_group(flags = ["-Wl,--gdb-index"])],
),
],
)
# This feature can be enabled in conjunction with any optimizations to
# ensure accurate call stacks and backtraces for profilers or errors.
preserve_call_stacks = feature(
name = "preserve_call_stacks",
flag_sets = [flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(flags = [
# Ensure good backtraces by preserving frame pointers and
# disabling tail call elimination.
"-fno-omit-frame-pointer",
"-mno-omit-leaf-frame-pointer",
"-fno-optimize-sibling-calls",
])],
)],
)
# Enable split debug info whenever debug info is requested.
enable_split_debug_info = feature(
name = "per_object_debug_info",
enabled = True,
# This has to be directly conditioned on requesting debug info at
# all, otherwise Bazel will look for an extra output file and not
# find one.
requires = [feature_set(features = ["debug_info_flags"])],
)
# Enable debug info whenever in the `dbg` build mode. We do this separately from
# the `debug_info_flags` feature itself as other things may want to enable that
# feature as well.
enable_debug_info_in_dbg = feature(
name = "enable_debug_info_in_dbg",
enabled = True,
requires = [feature_set(["dbg"])],
implies = ["debug_info_flags"],
)
# Note that the order of features is significant in this list and determines the
# relative order of flags from the features listed.
debugging_features = [
minimal_debug_info_flags,
debug_info_flags,
debug_info_compression_flags,
debugger_flags,
lldb_flags,
gdb_flags,
preserve_call_stacks,
enable_split_debug_info,
enable_debug_info_in_dbg,
]
@@ -0,0 +1,75 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Helpers to construct ordered sequences of `cc_toolchain` features."""
load(
":cc_toolchain_base_features.bzl",
"base_features",
"output_flags_feature",
"user_flags_feature",
)
load(
":cc_toolchain_config_features.bzl",
"target_cpu_features",
"target_os_features",
)
load(
":cc_toolchain_cpp_features.bzl",
"clang_feature",
"clang_warnings_feature",
)
load(":cc_toolchain_debugging.bzl", "debugging_features")
load(":cc_toolchain_linking.bzl", "linking_features")
load(":cc_toolchain_modules.bzl", "modules_features")
load(":cc_toolchain_optimization.bzl", "optimization_features")
load(":cc_toolchain_sanitizer_features.bzl", "sanitizer_features")
def clang_cc_toolchain_features(
target_os,
target_cpu,
project_features = [],
extra_cpp_features = []):
"""Builds a sequence of Clang-oriented `cc_toolchain_config` features.
Returns:
The list of features for calling `create_cc_toolchain_config_info`.
Args:
target_os: Used to select OS-specific features to include.
target_cpu: Used to select CPU-specific features to include.
project_features: Optional list of project-specific features to include.
extra_cpp_features: Optional list of extra C++ features to include, for
example `libcxx_feature` can be passed here to enable using libc++.
"""
# The order of the features determines the relative order of flags used.
features = []
features += target_os_features(target_os)
features += target_cpu_features(target_cpu)
features += base_features
features += [
# We always use Clang in the toolchain and enable all of its warnings.
clang_feature,
clang_warnings_feature,
]
# Enable any extra baseline C++ features here where others can override
# their flags if needed.
features += extra_cpp_features
features += sanitizer_features
features += optimization_features
features += modules_features
features += debugging_features
features += linking_features
# Lastly, we add project features and the user flags so they can override
# anything above, and the output flags last of all for ease of debugging.
features += project_features
features += [
user_flags_feature,
output_flags_feature,
]
return features
@@ -0,0 +1,288 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Definitions of linking related features used in a `cc_toolchain_config`."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"variable_with_value",
"with_feature_set",
)
load(
":cc_toolchain_actions.bzl",
"all_link_actions",
)
link_libraries_feature = feature(
name = "link_libraries",
enabled = True,
flag_sets = [
flag_set(
actions = all_link_actions,
flag_groups = [
flag_group(
expand_if_available = "linkstamp_paths",
flags = ["%{linkstamp_paths}"],
iterate_over = "linkstamp_paths",
),
flag_group(
expand_if_available = "libraries_to_link",
flag_groups = [
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file_group",
),
flags = ["-Wl,--start-lib"],
),
flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,-whole-archive"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file_group",
),
flags = ["%{libraries_to_link.object_files}"],
iterate_over = "libraries_to_link.object_files",
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file",
),
flags = ["%{libraries_to_link.name}"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "interface_library",
),
flags = ["%{libraries_to_link.name}"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "static_library",
),
flags = ["%{libraries_to_link.name}"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "dynamic_library",
),
flags = ["-l%{libraries_to_link.name}"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "versioned_dynamic_library",
),
flags = ["-l:%{libraries_to_link.name}"],
),
flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,-no-whole-archive"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file_group",
),
flags = ["-Wl,--end-lib"],
),
],
iterate_over = "libraries_to_link",
),
# Note that the params file comes at the end, after the
# libraries to link above.
flag_group(
expand_if_available = "linker_param_file",
flags = ["@%{linker_param_file}"],
),
],
with_features = [with_feature_set(not_features = ["macos_target"])],
),
flag_set(
actions = all_link_actions,
flag_groups = [
flag_group(
expand_if_available = "linkstamp_paths",
flags = ["%{linkstamp_paths}"],
iterate_over = "linkstamp_paths",
),
flag_group(
expand_if_available = "libraries_to_link",
flag_groups = [
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file_group",
),
flags = ["-Wl,--start-lib"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file_group",
),
flag_groups = [
flag_group(
expand_if_false = "libraries_to_link.is_whole_archive",
flags = ["%{libraries_to_link.object_files}"],
),
flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,-force_load,%{libraries_to_link.object_files}"],
),
],
iterate_over = "libraries_to_link.object_files",
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file",
),
flag_groups = [
flag_group(
expand_if_false = "libraries_to_link.is_whole_archive",
flags = ["%{libraries_to_link.name}"],
),
flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,-force_load,%{libraries_to_link.name}"],
),
],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "interface_library",
),
flag_groups = [
flag_group(
expand_if_false = "libraries_to_link.is_whole_archive",
flags = ["%{libraries_to_link.name}"],
),
flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,-force_load,%{libraries_to_link.name}"],
),
],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "static_library",
),
flag_groups = [
flag_group(
expand_if_false = "libraries_to_link.is_whole_archive",
flags = ["%{libraries_to_link.name}"],
),
flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flags = ["-Wl,-force_load,%{libraries_to_link.name}"],
),
],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "dynamic_library",
),
flags = ["-l%{libraries_to_link.name}"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "versioned_dynamic_library",
),
flags = ["-l:%{libraries_to_link.name}"],
),
flag_group(
expand_if_true = "libraries_to_link.is_whole_archive",
flag_groups = [
flag_group(
expand_if_false = "macos_flags",
flags = ["-Wl,-no-whole-archive"],
),
],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file_group",
),
flags = ["-Wl,--end-lib"],
),
],
iterate_over = "libraries_to_link",
),
# Note that the params file comes at the end, after the
# libraries to link above.
flag_group(
expand_if_available = "linker_param_file",
flags = ["@%{linker_param_file}"],
),
],
with_features = [with_feature_set(["macos_target"])],
),
],
)
# Archive actions have an entirely independent set of flags and don't
# interact with either compiler or link actions.
archiving_feature = feature(
name = "archiving",
enabled = True,
flag_sets = [flag_set(
actions = [ACTION_NAMES.cpp_link_static_library],
flag_groups = [
flag_group(flags = ["rcsD"]),
flag_group(
expand_if_available = "output_execpath",
flags = ["%{output_execpath}"],
),
flag_group(
expand_if_available = "libraries_to_link",
flag_groups = [
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file",
),
flags = ["%{libraries_to_link.name}"],
),
flag_group(
expand_if_equal = variable_with_value(
name = "libraries_to_link.type",
value = "object_file_group",
),
flags = ["%{libraries_to_link.object_files}"],
iterate_over = "libraries_to_link.object_files",
),
],
iterate_over = "libraries_to_link",
),
flag_group(
expand_if_available = "linker_param_file",
flags = ["@%{linker_param_file}"],
),
],
)],
)
# Note that the order of features is significant in this list and determines the
# relative order of flags from the features listed.
linking_features = [
link_libraries_feature,
archiving_feature,
]
@@ -0,0 +1,82 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Definitions of C++ and Clang header modules toolchain features."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
)
use_module_maps = feature(
name = "use_module_maps",
requires = [feature_set(features = ["module_maps"])],
flag_sets = [
flag_set(
actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
],
flag_groups = [
# These flag groups are separate so they do not expand to
# the cross product of the variables.
flag_group(flags = ["-fmodule-name=%{module_name}"]),
flag_group(
flags = ["-fmodule-map-file=%{module_map_file}"],
),
],
),
],
)
# Tell bazel we support module maps in general, so they will be generated
# for all c/c++ rules.
# Note: not all C++ rules support module maps; thus, do not imply this
# feature from other features - instead, require it.
module_maps = feature(
name = "module_maps",
enabled = True,
implies = [
# "module_map_home_cwd",
# "module_map_without_extern_module",
# "generate_submodules",
],
)
layering_check = feature(
name = "layering_check",
implies = ["use_module_maps"],
flag_sets = [flag_set(
actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
],
flag_groups = [
flag_group(flags = [
"-fmodules-strict-decluse",
"-Wprivate-header",
]),
flag_group(
iterate_over = "dependent_module_map_files",
flags = ["-fmodule-map-file=%{dependent_module_map_files}"],
),
],
)],
)
# Note that the order of features is significant in this list and determines the
# relative order of flags from the features listed.
modules_features = [
layering_check,
module_maps,
use_module_maps,
]
@@ -0,0 +1,71 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Definitions of optimization `cc_toolchain_config` features."""
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
"with_feature_set",
)
load(
":cc_toolchain_actions.bzl",
"all_compile_actions",
"all_link_actions",
"codegen_compile_actions",
)
# Handle different levels of optimization with individual features so that
# they can be ordered and the defaults can override the minimal settings if
# both are enabled.
minimal_optimization_flags = feature(
name = "minimal_optimization_flags",
flag_sets = [flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(flags = ["-Og"])],
)],
)
default_optimization_flags = feature(
name = "default_optimization_flags",
enabled = True,
requires = [feature_set(["opt"])],
flag_sets = [
flag_set(
actions = all_compile_actions,
flag_groups = [flag_group(flags = ["-DNDEBUG"])],
),
flag_set(
actions = codegen_compile_actions,
flag_groups = [flag_group(flags = ["-O3"])],
),
],
)
cpu_flags = feature(
name = "aarch64_cpu_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = ["-march=armv8.2-a"])],
with_features = [with_feature_set(["aarch64_target"])],
),
flag_set(
actions = all_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = ["-march=x86-64-v2"])],
with_features = [with_feature_set(["x86_64_target"])],
),
],
)
# Note that the order of features is significant in this list and determines the
# relative order of flags from the features listed.
optimization_features = [
minimal_optimization_flags,
default_optimization_flags,
cpu_flags,
]
@@ -0,0 +1,113 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Definitions of sanitizer-related `cc_toolchain_config` features."""
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
"with_feature_set",
)
load(
":cc_toolchain_actions.bzl",
"all_compile_actions",
"all_link_actions",
)
sanitizer_common_flags = feature(
name = "sanitizer_common_flags",
implies = ["minimal_debug_info_flags", "preserve_call_stacks"],
flag_sets = [flag_set(
actions = all_link_actions,
flag_groups = [flag_group(flags = ["-static-libsan"])],
with_features = [
with_feature_set(["linux_target"]),
with_feature_set(["freebsd_target"]),
],
)],
)
asan = feature(
name = "asan",
implies = ["sanitizer_common_flags"],
flag_sets = [flag_set(
actions = all_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = [
"-fsanitize=address,undefined,nullability",
"-fsanitize-address-use-after-scope",
# Outlining is almost always the right tradeoff for our
# sanitizer usage where we're more pressured on generated code
# size than runtime performance.
"-fsanitize-address-outline-instrumentation",
# We don't need the recovery behavior of UBSan as we expect
# builds to be clean. Not recovering is a bit cheaper.
"-fno-sanitize-recover=undefined,nullability",
# Don't embed the full path name for files. This limits the size
# and combined with line numbers is unlikely to result in many
# ambiguities.
"-fsanitize-undefined-strip-path-components=-1",
# Needed due to clang AST issues, such as in
# clang/AST/Redeclarable.h line 199.
"-fno-sanitize=vptr",
])],
)],
)
# A feature that further reduces the generated code size of our the ASan
# feature, but at the cost of lower quality diagnostics. This is enabled
# along with ASan in our fastbuild configuration, but can be disabled
# explicitly to get better error messages.
asan_min_size = feature(
name = "asan_min_size",
requires = [feature_set(["asan"])],
flag_sets = [flag_set(
actions = all_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = [
# Force two UBSan checks that have especially large code size
# cost to use the minimal branch to a trapping instruction model
# instead of the full diagnostic.
"-fsanitize-trap=alignment,null",
])],
)],
)
fuzzer = feature(
name = "fuzzer",
flag_sets = [flag_set(
actions = all_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = [
"-fsanitize=fuzzer-no-link",
])],
)],
)
sanitizer_workarounds = feature(
name = "sanitizer_workarounds",
enabled = True,
requires = [feature_set(["asan"])],
flag_sets = [flag_set(
actions = all_compile_actions + all_link_actions,
flag_groups = [flag_group(flags = [
# Likely due to being unable to use the static-linked and up-to-date
# sanitizer runtimes, we have to disable this sanitizer on macOS.
"-fno-sanitize=function",
])],
with_features = [with_feature_set(["macos_target"])],
)],
)
# Note that the order of features is significant in this list and determines the
# relative order of flags from the features listed.
sanitizer_features = [
sanitizer_common_flags,
asan,
asan_min_size,
fuzzer,
# Note that the workarounds must come last here to override earlier flags.
sanitizer_workarounds,
]
@@ -0,0 +1,81 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Macros to produce tool-related parts of a `cc_toolchain_config`.
These macros cover both the `actions_config` array and the `tool_paths` array.
They presume an LLVM and Clang toolchain's tools, but support both a single
installation and installations that split the LLVM tools and Clang tools apart.
"""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"action_config",
"tool",
"tool_path",
)
load(
":cc_toolchain_actions.bzl",
"all_c_compile_actions",
"all_cpp_compile_actions",
"all_link_actions",
)
def llvm_tool_paths(llvm_bindir, clang_bindir = None):
if not clang_bindir:
clang_bindir = llvm_bindir
return [
tool_path(name = "ar", path = llvm_bindir + "/llvm-ar"),
tool_path(name = "ld", path = clang_bindir + "/ld.lld"),
tool_path(name = "cpp", path = clang_bindir + "/clang-cpp"),
tool_path(name = "gcc", path = clang_bindir + "/clang++"),
tool_path(name = "dwp", path = llvm_bindir + "/llvm-dwp"),
tool_path(name = "gcov", path = llvm_bindir + "/llvm-cov"),
tool_path(name = "nm", path = llvm_bindir + "/llvm-nm"),
tool_path(name = "objcopy", path = llvm_bindir + "/llvm-objcopy"),
tool_path(name = "objdump", path = llvm_bindir + "/llvm-objdump"),
tool_path(name = "strip", path = llvm_bindir + "/llvm-strip"),
]
def llvm_action_configs(llvm_bindir, clang_bindir = None):
if not clang_bindir:
clang_bindir = llvm_bindir
return [
action_config(
action_name = name,
enabled = True,
tools = [tool(path = clang_bindir + "/clang")],
)
for name in all_c_compile_actions
] + [
action_config(
action_name = name,
enabled = True,
tools = [tool(path = clang_bindir + "/clang++")],
)
for name in all_cpp_compile_actions
] + [
action_config(
action_name = name,
enabled = True,
tools = [tool(path = clang_bindir + "/clang++")],
)
for name in all_link_actions
] + [
action_config(
action_name = name,
enabled = True,
tools = [tool(path = llvm_bindir + "/llvm-ar")],
)
for name in [ACTION_NAMES.cpp_link_static_library]
] + [
action_config(
action_name = name,
enabled = True,
tools = [tool(path = llvm_bindir + "/llvm-strip")],
)
for name in [ACTION_NAMES.strip]
]
+59
View File
@@ -0,0 +1,59 @@
"""Tests that the C++ toolchain tools can be executed.
This script reads a file containing paths to C++ tools (like clang++, llvm-ar)
and attempts to run each with `--version` to verify they are functional.
"""
__copyright__ = """
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""
import os
import subprocess
import sys
from bazel_tools.tools.python.runfiles import runfiles
def test_tools() -> None:
"""Reads paths from file and runs each tool with --version."""
if len(sys.argv) < 2:
print("Usage: cc_tools_test.py <paths_file>")
sys.exit(1)
paths_file = sys.argv[1]
print(f"Reading tools from: {paths_file}")
with open(paths_file, "r") as f:
tools = [line.strip() for line in f if line.strip()]
print(f"Testing tools: {tools}")
r = runfiles.Create()
repo_name = os.environ.get("TEST_WORKSPACE") or "_main"
for tool in tools:
if "bazel-out/" in tool:
_, _, rest = tool.partition("bazel-out/")
_, sep, after = rest.partition("bin/")
if sep:
tool = after
rlocation_path = os.path.join(repo_name, tool)
tool = r.Rlocation(rlocation_path)
print(f"Running {tool} --version")
try:
res = subprocess.run(
[tool, "--version"],
capture_output=True,
text=True,
check=True,
)
print(res.stdout)
except Exception as e:
print(f"Failed to run {tool}: {e}")
sys.exit(1)
if __name__ == "__main__":
test_tools()
File diff suppressed because it is too large Load Diff
+19 -1
View File
@@ -174,6 +174,8 @@ def _configure_clang_toolchain_impl(repository_ctx):
repository_ctx.attr._clang_cc_toolchain_config,
"cc_toolchain_config.bzl",
)
for file_label in repository_ctx.attr._clang_toolchain_files:
repository_ctx.symlink(file_label, file_label.name)
# Find a Clang C++ compiler, and where it lives. We need to walk symlinks
# here as the other LLVM tools may not be symlinked into the PATH even if
@@ -224,7 +226,7 @@ def _configure_clang_toolchain_impl(repository_ctx):
repository_ctx.attr._clang_detected_variables_template,
substitutions = {
"{CLANG_BINDIR}": str(clang.dirname),
"{CLANG_INCLUDE_DIRS_LIST}": str(
"{CLANG_INCLUDE_DIRS}": str(
[str(path) for path in include_dirs],
),
"{CLANG_RESOURCE_DIR}": resource_dir,
@@ -258,6 +260,22 @@ configure_clang_toolchain = repository_rule(
default = Label("//bazel/cc_toolchains:clang_toolchain.BUILD"),
allow_single_file = True,
),
"_clang_toolchain_files": attr.label_list(
default = [
Label("//bazel/cc_toolchains:cc_toolchain_actions.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_base_features.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_carbon_project_features.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_config_features.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_cpp_features.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_debugging.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_features.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_linking.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_modules.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_optimization.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_sanitizer_features.bzl"),
Label("//bazel/cc_toolchains:cc_toolchain_tools.bzl"),
],
),
},
environ = ["CC"],
)
@@ -14,5 +14,5 @@ clang_bindir = "{CLANG_BINDIR}"
clang_version = {CLANG_VERSION}
clang_version_for_cache = "{CLANG_VERSION_FOR_CACHE}"
clang_resource_dir = "{CLANG_RESOURCE_DIR}"
clang_include_dirs_list = {CLANG_INCLUDE_DIRS_LIST}
clang_include_dirs = {CLANG_INCLUDE_DIRS}
sysroot_dir = "{SYSROOT}"
+2 -2
View File
@@ -13,8 +13,8 @@ load("@rules_python//python:defs.bzl", "py_test")
filegroup(
name = "non_test_cc_rules",
data = [
"//toolchain/install:carbon_toolchain_tar_gz_rule",
"//toolchain/install:carbon_toolchain_tar_rule",
"//toolchain/install:carbon_toolchain_tar",
"//toolchain/install:carbon_toolchain_tar_gz",
],
tags = ["manual"],
)
+23 -5
View File
@@ -41,11 +41,25 @@ for dep in deps:
# Other packages in the LLVM project shouldn't be accidentally used
# in Carbon. We can expand the above list if use cases emerge.
if package not in (
"llvm",
"lld",
"clang",
"clang-tools-extra/clangd",
"libc",
"libcxx",
"libcxxabi",
"libunwind",
"lld",
"llvm",
# While this is in a `third_party` directory, its code is documented
# as part of LLVM and for use in compiler-rt.
"third-party/siphash",
) and (
package == "third-party"
and rule
not in (
# LLVM wrappers for zlib-ng and zstd, which are fine as linked.
"zlib",
"zstd",
)
):
sys.exit(
"ERROR: unexpected dependency into the LLVM project: %s" % dep
@@ -65,14 +79,18 @@ for dep in deps:
if repo == "" and not rule.startswith("third_party"):
continue
# LLVM code managed in the Carbon repository is still LLVM code and OK.
if repo == "" and rule.startswith("third_party/llvm:"):
continue
# Utility libraries provided by Bazel that are under a compatible license.
if repo in ("@@rules_cc+", "@@bazel_tools"):
continue
# These are stubs wrapping system libraries for LLVM. They aren't
# distributed and so should be fine.
# These libraries have compatible licenses and are linked in without copying
# source, so fine for our binaries.
if repo in (
"@@zlib+",
"@@zlib-ng+",
"@@zstd+",
):
continue
@@ -1,133 +0,0 @@
From 04fb28b5673d29a8c38519845c87f4c00c76e9cf Mon Sep 17 00:00:00 2001
From: Chandler Carruth <chandlerc@gmail.com>
Date: Sat, 13 Jan 2024 02:15:19 -0800
Subject: [PATCH] Introduce a simple native Bazel build.
---
BUILD.bazel | 84 +++++++++++++++++++++++++++++++++++++++++++++++++
MODULE.bazel | 10 ++++++
WORKSPACE.bazel | 5 +++
3 files changed, 99 insertions(+)
create mode 100644 BUILD.bazel
create mode 100644 MODULE.bazel
create mode 100644 WORKSPACE.bazel
diff --git a/BUILD.bazel b/BUILD.bazel
new file mode 100644
index 0000000..427c854
--- /dev/null
+++ b/BUILD.bazel
@@ -0,0 +1,84 @@
+# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+# Exceptions. See /LICENSE for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+load("@rules_cc//cc:defs.bzl", "cc_library")
+
+package(default_visibility = ["//visibility:public"])
+
+aarch64_srcs = [
+ "lib/pfmlib_arm_perf_event.c",
+ "lib/pfmlib_arm.c",
+ "lib/pfmlib_arm_armv8.c",
+ "lib/pfmlib_arm_armv9.c",
+ "lib/pfmlib_tx2_unc_perf_event.c",
+ "lib/pfmlib_kunpeng_unc_perf_event.c",
+ "lib/pfmlib_arm_priv.h",
+ "lib/events/arm_cortex_a57_events.h",
+ "lib/events/arm_cortex_a53_events.h",
+ "lib/events/arm_xgene_events.h",
+ "lib/events/arm_cavium_tx2_events.h",
+ "lib/events/arm_marvell_tx2_unc_events.h",
+ "lib/events/arm_fujitsu_a64fx_events.h",
+ "lib/events/arm_neoverse_n1_events.h",
+ "lib/events/arm_neoverse_n2_events.h",
+ "lib/events/arm_neoverse_v1_events.h",
+ "lib/events/arm_neoverse_v2_events.h",
+ "lib/events/arm_hisilicon_kunpeng_events.h",
+ "lib/events/arm_hisilicon_kunpeng_unc_events.h",
+]
+
+x86_64_srcs = [
+ "lib/pfmlib_amd64_priv.h",
+] + glob(
+ [
+ "lib/pfmlib_amd64*.c",
+ "lib/pfmlib_intel*.c",
+ "lib/pfmlib_intel*_priv.h",
+ "lib/events/amd64_events_*.h",
+ "lib/events/intel_*_events.h",
+ ],
+ exclude = [
+ # 32-bit CPUs
+ "lib/pfmlib_intel_coreduo.c",
+ "lib/pfmlib_intel_p6.c",
+ ],
+)
+
+cc_library(
+ name = "libpfm",
+ srcs = [
+ "lib/events/perf_events.h",
+ "lib/pfmlib_common.c",
+ "lib/pfmlib_perf_event.c",
+ "lib/pfmlib_perf_event_pmu.c",
+ "lib/pfmlib_perf_event_priv.h",
+ "lib/pfmlib_perf_event_raw.c",
+ "lib/pfmlib_priv.h",
+ ] + select({
+ "@platforms//cpu:aarch64": aarch64_srcs,
+ "@platforms//cpu:x86_64": x86_64_srcs,
+ }),
+ hdrs = glob(["include/perfmon/*.h"]),
+ copts = [
+ "-DHAS_OPENAT",
+ "-D_REENTRANT",
+ "-I.",
+ "-fvisibility=hidden",
+ ] + select({
+ "@platforms//cpu:x86_64": [
+ "-DCONFIG_PFMLIB_ARCH_X86",
+ "-DCONFIG_PFMLIB_ARCH_X86_64",
+ ],
+ "//conditions:default": [],
+ }),
+ strip_include_prefix = "include",
+ target_compatible_with = select({
+ # This library only makes sense on Linux, and we only include support
+ # for building on AArch64 and x86-64. Other CPUs can be added to this
+ # list if build support is added for them.
+ "@platforms//cpu:aarch64": ["@platforms//os:linux"],
+ "@platforms//cpu:x86_64": ["@platforms//os:linux"],
+ "//conditions:default": ["@platforms//:incompatible"],
+ }),
+)
diff --git a/MODULE.bazel b/MODULE.bazel
new file mode 100644
index 0000000..c901cbe
--- /dev/null
+++ b/MODULE.bazel
@@ -0,0 +1,10 @@
+# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+# Exceptions. See /LICENSE for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+"""Bazel modules."""
+
+module(name = "libpfm")
+
+bazel_dep(name = "rules_cc", version = "0.0.9")
+bazel_dep(name = "platforms", version = "0.0.8")
diff --git a/WORKSPACE.bazel b/WORKSPACE.bazel
new file mode 100644
index 0000000..9aad57c
--- /dev/null
+++ b/WORKSPACE.bazel
@@ -0,0 +1,5 @@
+# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+# Exceptions. See /LICENSE for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+# See `MODULE.bazel` for details.
--
2.43.0
-9
View File
@@ -1,9 +0,0 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
package(default_visibility = ["//visibility:public"])
exports_files(glob([
"*.patch",
]))
@@ -8,14 +8,13 @@ Subject: [PATCH] Add libfuzzer target to compiler-rt.
1 file changed, 17 insertions(+)
diff --git a/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel b/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
index 9bdd454e1e36..0f30c21f63dc 100644
index 90264449de76..115da4cb77f6 100644
--- a/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
@@ -50,3 +50,20 @@ cc_library(
":config",
@@ -57,6 +57,23 @@ cc_library(
],
)
+
+cc_library(
+ name = "FuzzerMain",
+ srcs = glob(
@@ -32,5 +31,9 @@ index 9bdd454e1e36..0f30c21f63dc 100644
+ ],
+ includes = ["lib/fuzzer"],
+)
+
cc_library(
name = "orc_rt_common_headers",
hdrs = [
--
2.42.0
2.42.0
@@ -1,69 +0,0 @@
From 01f35f954121def682097d8e697ac524b2c8acc6 Mon Sep 17 00:00:00 2001
From: jonmeow <jperkins@google.com>
Date: Mon, 3 Feb 2025 11:18:25 -0800
Subject: [PATCH] Comment out unloaded proto_library dependencies
---
.../llvm-project-overlay/clang/BUILD.bazel | 46 +++++++++----------
1 file changed, 23 insertions(+), 23 deletions(-)
diff --git a/utils/bazel/llvm-project-overlay/clang/BUILD.bazel b/utils/bazel/llvm-project-overlay/clang/BUILD.bazel
index e3b20e43dd22..8b26e322a0ed 100644
--- a/utils/bazel/llvm-project-overlay/clang/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/clang/BUILD.bazel
@@ -2603,29 +2603,29 @@ cc_library(
],
)
-proto_library(
- name = "cxx-proto",
- srcs = ["tools/clang-fuzzer/cxx_proto.proto"],
-)
-
-cc_proto_library(
- name = "cxx_cc_proto",
- deps = [":cxx-proto"],
-)
-
-cc_library(
- name = "proto-to-cxx-lib",
- srcs = ["tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.cpp"],
- hdrs = ["tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.h"],
- includes = ["tools/clang-fuzzer"],
- deps = [":cxx_cc_proto"],
-)
-
-cc_binary(
- name = "clang-proto-to-cxx",
- srcs = ["tools/clang-fuzzer/proto-to-cxx/proto_to_cxx_main.cpp"],
- deps = [":proto-to-cxx-lib"],
-)
+# proto_library(
+# name = "cxx-proto",
+# srcs = ["tools/clang-fuzzer/cxx_proto.proto"],
+# )
+#
+# cc_proto_library(
+# name = "cxx_cc_proto",
+# deps = [":cxx-proto"],
+# )
+#
+# cc_library(
+# name = "proto-to-cxx-lib",
+# srcs = ["tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.cpp"],
+# hdrs = ["tools/clang-fuzzer/proto-to-cxx/proto_to_cxx.h"],
+# includes = ["tools/clang-fuzzer"],
+# deps = [":cxx_cc_proto"],
+# )
+#
+# cc_binary(
+# name = "clang-proto-to-cxx",
+# srcs = ["tools/clang-fuzzer/proto-to-cxx/proto_to_cxx_main.cpp"],
+# deps = [":proto-to-cxx-lib"],
+# )
cc_library(
name = "clang-fuzzer-initialize",
--
2.48.1
@@ -0,0 +1,64 @@
Commit ID: 354e38c89f28e2cc284e655a9cde707f457dc02c
Change ID: sxspxmonsuvqzuvxvrvorlumwpwromsv
Author : Chandler Carruth <chandlerc@gmail.com> (2025-09-25 22:55:26)
Committer: Chandler Carruth <chandlerc@gmail.com> (2026-02-14 03:46:06)
Introduce basic sources exporting for libunwind
This exports the source files directly so that they can be used to build
this runtime library on demand.
diff --git a/utils/bazel/llvm-project-overlay/libunwind/BUILD.bazel b/utils/bazel/llvm-project-overlay/libunwind/BUILD.bazel
index c9fdc819c0..7d734c5a06 100644
--- a/utils/bazel/llvm-project-overlay/libunwind/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libunwind/BUILD.bazel
@@ -21,3 +21,19 @@
],
strip_include_prefix = "include",
)
+
+filegroup(
+ name = "libunwind_hdrs",
+ srcs = glob(["include/**/*.h"]),
+)
+
+filegroup(
+ name = "libunwind_srcs",
+ srcs = glob([
+ "src/*.cpp",
+ "src/*.hpp",
+ "src/*.c",
+ "src/*.h",
+ "src/*.S",
+ ]),
+)
diff --git a/utils/bazel/llvm-project-overlay/libunwind/libunwind_library.bzl b/utils/bazel/llvm-project-overlay/libunwind/libunwind_library.bzl
new file mode 100644
index 0000000000..25675d3070
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/libunwind/libunwind_library.bzl
@@ -0,0 +1,24 @@
+# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+"""Starlark variables and macros for building libunwind.
+
+Variables provide base line information for how to build libunwind source files.
+These can be used to generate non-Bazel builds of the library.
+
+Macros provide a convenient way to construct Bazel `cc_library` rules for
+libunwind.
+"""
+
+# TODO: Should libunwind use `-fvisibility-inlines-hidden` and
+# `-fvisibility=hidden`, similar to libc++?
+libunwind_copts = [
+ "-D_LIBUNWIND_IS_NATIVE_ONLY",
+ "-O3",
+ "-fPIC",
+ "-fno-exceptions",
+ "-fno-rtti",
+ "-funwind-tables",
+ "-nostdinc++",
+]
@@ -0,0 +1,236 @@
Commit ID: 1fd710ed69a0f47f454c386d39302ddb756a88b3
Change ID: mstnwoqruyypnoouksnyqssllrsozpos
Bookmarks: bz-libcxx* bz-libcxx@git
Author : Chandler Carruth <chandlerc@gmail.com> (2025-09-25 22:55:26)
Committer: Chandler Carruth <chandlerc@gmail.com> (2026-03-08 07:41:54)
Introduce basic sources exporting for libcxx and libcxxabi
This exports the source files directly so that they can be used to build
a libcxx runtime library on demand. It also differentiates between
normal sources and textual sources.
diff --git a/utils/bazel/llvm-project-overlay/libcxx/BUILD.bazel b/utils/bazel/llvm-project-overlay/libcxx/BUILD.bazel
new file mode 100644
index 0000000000..c8b517ab56
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/libcxx/BUILD.bazel
@@ -0,0 +1,139 @@
+# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+licenses(["notice"])
+
+package(
+ default_visibility = ["//visibility:public"],
+)
+
+exports_files([
+ "include/__config_site.in",
+ "include/module.modulemap.in",
+ "vendor/llvm/default_assertion_handler.in",
+])
+
+filegroup(
+ name = "libcxx_hdrs",
+ srcs = glob(
+ [
+ # Top level includes and those in `experimental` and `ext` sometimes
+ # have no extension.
+ "include/*",
+ "include/experimental/*",
+ "include/ext/*",
+
+ # Implementation detail headers all use `.h` extensions
+ "include/**/*.h",
+ ],
+ exclude = [
+ # Omit CMake and CMake-configured files that get caught by the
+ # extension-less patterns.
+ "**/*.in",
+ "**/CMakeLists.txt",
+
+ # Omit C++03 compatibility headers as current users don't need them.
+ "include/__cxx03/**",
+ ],
+ ),
+)
+
+LIBCXX_SRCS_PSTL_LIBDISPATCH = [
+ "src/pstl/libdispatch.cpp",
+]
+
+filegroup(
+ name = "libcxx_srcs_pstl_libdispatch",
+ srcs = LIBCXX_SRCS_PSTL_LIBDISPATCH,
+)
+
+LIBCXX_SRCS_SUPPORT_IBM_PATTERNS = [
+ "src/support/ibm/**/*.cpp",
+]
+
+filegroup(
+ name = "libcxx_srcs_support_ibm",
+ srcs = glob(LIBCXX_SRCS_SUPPORT_IBM_PATTERNS),
+)
+
+LIBCXX_SRCS_SUPPORT_WIN32_PATTERNS = [
+ "src/support/win32/**/*.cpp",
+]
+
+filegroup(
+ name = "libcxx_srcs_support_win32",
+ srcs = glob(LIBCXX_SRCS_SUPPORT_WIN32_PATTERNS),
+)
+
+LIBCXX_SRCS_TZDB = [
+ "src/experimental/chrono_exception.cpp",
+ "src/experimental/time_zone.cpp",
+ "src/experimental/tzdb.cpp",
+ "src/experimental/tzdb_list.cpp",
+]
+
+filegroup(
+ name = "libcxx_srcs_tzdb",
+ srcs = LIBCXX_SRCS_TZDB,
+)
+
+# Exclude platform-dependent patterns that are provided by per-target filegroups
+# above.
+LIBCXX_SRCS_TARGET_EXCLUDES = (
+ LIBCXX_SRCS_PSTL_LIBDISPATCH +
+ LIBCXX_SRCS_SUPPORT_IBM_PATTERNS +
+ LIBCXX_SRCS_SUPPORT_WIN32_PATTERNS +
+ LIBCXX_SRCS_TZDB
+)
+
+filegroup(
+ name = "libcxx_srcs_generic",
+ srcs = glob(
+ [
+ "src/**/*.cpp",
+ "src/**/*.h",
+ "src/**/*.ipp",
+ ],
+ exclude = [
+ # Build is for use with libc++abi and so don't need 'new.cpp'.
+ "src/new.cpp",
+
+ # Build is for compiler-rt platforms so we have its int128 support.
+ "src/filesystem/int128_builtins.cpp",
+ ] + LIBCXX_SRCS_TARGET_EXCLUDES,
+ ),
+)
+
+filegroup(
+ name = "libcxx_linux_srcs",
+ srcs = [
+ ":libcxx_srcs_generic",
+ ":libcxx_srcs_tzdb",
+ ],
+)
+
+filegroup(
+ name = "libcxx_macos_srcs",
+ srcs = [
+ ":libcxx_srcs_generic",
+ # TODO: Include libdispatch sources here to enable that pstl backend.
+ ],
+)
+
+filegroup(
+ name = "libcxx_win32_srcs",
+ srcs = [
+ ":libcxx_srcs_generic",
+ ":libcxx_srcs_support_win32",
+ ],
+)
+
+filegroup(
+ name = "libcxx_all_srcs",
+ srcs = [
+ ":libcxx_linux_srcs",
+ ":libcxx_macos_srcs",
+ ":libcxx_win32_srcs",
+ ],
+)
diff --git a/utils/bazel/llvm-project-overlay/libcxx/libcxx_library.bzl b/utils/bazel/llvm-project-overlay/libcxx/libcxx_library.bzl
new file mode 100644
index 0000000000..66f64f3610
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/libcxx/libcxx_library.bzl
@@ -0,0 +1,37 @@
+# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+"""Starlark variables and macros for building libc++ and libc++abi.
+
+Variables provide base line information for how to build libc++ and libc++abi
+source files. These can be used to generate non-Bazel builds of the library.
+
+TODO: Add macros that provide a convenient way to construct Bazel `cc_library`
+rules for libc++ and libc++abi.
+
+TODO: Add either sufficient usage in the macros, or add a how-to example here in
+the documentation so the use of these variables is more clear.
+"""
+
+_libcxx_base_copts = [
+ "-std=c++26",
+ "-O3",
+ "-fPIC",
+ "-fvisibility-inlines-hidden",
+ "-fvisibility=hidden",
+ "-nostdinc++",
+]
+
+_libcxx_defines = [
+ "-D_LIBCPP_BUILDING_LIBRARY",
+ "-D_LIBCPP_REMOVE_TRANSITIVE_INCLUDES",
+]
+
+_libcxxabi_defines = [
+ "-DLIBCXX_BUILDING_LIBCXXABI",
+]
+
+libcxx_copts = _libcxx_base_copts + _libcxx_defines
+libcxxabi_copts = _libcxx_base_copts + _libcxxabi_defines
+libcxx_and_abi_copts = _libcxx_base_copts + _libcxx_defines + _libcxxabi_defines
diff --git a/utils/bazel/llvm-project-overlay/libcxxabi/BUILD.bazel b/utils/bazel/llvm-project-overlay/libcxxabi/BUILD.bazel
new file mode 100644
index 0000000000..2db70b54e2
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/libcxxabi/BUILD.bazel
@@ -0,0 +1,30 @@
+# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+licenses(["notice"])
+
+package(
+ default_visibility = ["//visibility:public"],
+)
+
+filegroup(
+ name = "libcxxabi_hdrs",
+ srcs = glob(["include/*.h"]),
+)
+
+filegroup(
+ name = "libcxxabi_srcs",
+ srcs = glob([
+ "src/**/*.cpp",
+ "src/**/*.h",
+ ]),
+)
+
+filegroup(
+ name = "libcxxabi_textual_srcs",
+ srcs = glob([
+ "src/**/*.def",
+ "src/**/*.inc",
+ ]),
+)
@@ -0,0 +1,521 @@
Commit ID: d3b82534c2546a892a27856672ed95a7db97dba3
Change ID: zyxuvzwmzsnorloyuupuurxkppkoplnw
Author : Chandler Carruth <chandlerc@gmail.com> (2026-02-16 23:17:06)
Committer: Chandler Carruth <chandlerc@gmail.com> (2026-03-11 07:54:02)
Improve compiler-rt build structure and export compilation info
This first improves the structure of the compiler-rt BUILD.bazel, fixing
bugs and exposing more carefully arranged source files.
It also exposes compilation info for builtins and CRT files for use in
compiling these source files.
diff --git a/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel b/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
index 4ded226174..3b5b8fc787 100644
--- a/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
@@ -3,6 +3,7 @@
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
load("@rules_cc//cc:defs.bzl", "cc_library")
+load("compiler-rt.bzl", "make_filtered_builtins_srcs_groups")
package(
default_visibility = ["//visibility:public"],
@@ -160,9 +161,15 @@
srcs = BUILTINS_CRTEND_SRCS,
)
+BUILTINS_EMUTLS_SRCS = ["lib/builtins/emutls.c"]
+
+filegroup(
+ name = "builtins_emutls_srcs",
+ srcs = BUILTINS_EMUTLS_SRCS,
+)
+
BUILTINS_HOSTED_SRCS = [
"lib/builtins/clear_cache.c",
- "lib/builtins/emutls.c",
"lib/builtins/enable_execute_stack.c",
"lib/builtins/eprintf.c",
]
@@ -224,11 +231,11 @@
),
)
-BUILTNS_ATOMICS_SRCS = ["lib/builtins/atomic.c"]
+BUILTINS_ATOMICS_SRCS = ["lib/builtins/atomic.c"]
filegroup(
name = "builtins_atomics_srcs",
- srcs = BUILTNS_ATOMICS_SRCS + ["lib/builtins/assembly.h"],
+ srcs = BUILTINS_ATOMICS_SRCS + ["lib/builtins/assembly.h"],
)
BUILTINS_MACOS_ATOMIC_SRCS_PATTERNS = [
@@ -241,6 +248,28 @@
srcs = glob(BUILTINS_MACOS_ATOMIC_SRCS_PATTERNS),
)
+# Source files for portable components of the compiler builtins library.
+filegroup(
+ name = "builtins_generic_srcs",
+ srcs = ["lib/builtins/cpu_model/cpu_model.h"] + glob(
+ [
+ "lib/builtins/*.c",
+ "lib/builtins/*.cpp",
+ "lib/builtins/*.h",
+ "lib/builtins/*.inc",
+ ],
+ allow_empty = True,
+ exclude = (
+ BUILTINS_CRTBEGIN_SRCS +
+ BUILTINS_CRTEND_SRCS +
+ BUILTINS_TF_EXCLUDES +
+ BUILTINS_TF_SRCS_PATTERNS +
+ BUILTINS_ATOMICS_SRCS +
+ BUILTINS_MACOS_ATOMIC_SRCS_PATTERNS
+ ),
+ ),
+)
+
# Apple-platform specific SME source file.
filegroup(
name = "builtins_aarch64_apple_sme_srcs",
@@ -305,10 +334,13 @@
# Source files for the AArch64 architecture-specific builtins.
filegroup(
- name = "builtins_aarch64_srcs",
+ name = "builtins_unfiltered_aarch64_srcs",
srcs = [
"lib/builtins/cpu_model/aarch64.c",
"lib/builtins/cpu_model/aarch64.h",
+ ":builtins_bf16_srcs",
+ ":builtins_generic_srcs",
+ ":builtins_tf_srcs",
] + [
AARCH64_OUTLINE_ATOMICS_FMT.format(pat, size, model)
for (pat, size, model) in AARCH64_OUTLINE_ATOMICS
@@ -328,10 +360,20 @@
"lib/builtins/aarch64/lse.S",
# These files are provided by SME-specific file groups above.
"lib/builtins/aarch64/*sme*",
+ # This is only used with MinGW.
+ "lib/builtins/aarch64/chkstk.S",
+ # TODO: Remove this once we have a way of accessing `SipHash.h`.
+ "lib/builtins/aarch64/emupac.cpp",
],
),
)
+make_filtered_builtins_srcs_groups(
+ name = "builtins_aarch64_srcs",
+ srcs = [":builtins_unfiltered_aarch64_srcs"],
+ textual_name = "builtins_aarch64_textual_srcs",
+)
+
BUILTINS_ARM_VFP_SRCS_PATTERNS = [
"lib/builtins/arm/*vfp*.S",
"lib/builtins/arm/*vfp*.c",
@@ -348,9 +390,19 @@
),
)
+BUILTINS_ARM_IMPLICIT_IT_SRCS = [
+ "lib/builtins/arm/mulsf3.S",
+ "lib/builtins/arm/divsf3.S",
+]
+
+filegroup(
+ name = "builtins_arm_implicit_it_srcs",
+ srcs = BUILTINS_ARM_IMPLICIT_IT_SRCS,
+)
+
# Source files for the ARM architecture-specific builtins.
filegroup(
- name = "builtins_arm_srcs",
+ name = "builtins_arm_arch_srcs",
srcs = glob(
[
"lib/builtins/arm/*.S",
@@ -359,14 +411,52 @@
"lib/builtins/arm/*.h",
],
allow_empty = True,
- exclude = BUILTINS_ARM_VFP_SRCS_PATTERNS,
+ exclude = (BUILTINS_ARM_VFP_SRCS_PATTERNS +
+ BUILTINS_ARM_IMPLICIT_IT_SRCS) + [
+ # This is only used with MinGW.
+ "lib/builtins/arm/chkstk.S",
+ ],
),
)
-# Source files for the PPC architecture-specific builtins.
-filegroup(
- name = "builtins_ppc_srcs",
- srcs = glob(
+filegroup(
+ name = "builtins_unfiltered_armv7_srcs",
+ srcs = [
+ ":builtins_arm_arch_srcs",
+ ":builtins_arm_vfp_srcs",
+ ":builtins_bf16_srcs",
+ ":builtins_generic_srcs",
+ ],
+)
+
+make_filtered_builtins_srcs_groups(
+ name = "builtins_armv7_srcs",
+ srcs = [":builtins_unfiltered_armv7_srcs"],
+ textual_name = "builtins_armv7_textual_srcs",
+)
+
+filegroup(
+ name = "builtins_unfiltered_aarch32_srcs",
+ srcs = [
+ ":builtins_arm_arch_srcs",
+ ":builtins_arm_vfp_srcs",
+ ":builtins_bf16_srcs",
+ ":builtins_generic_srcs",
+ ],
+)
+
+make_filtered_builtins_srcs_groups(
+ name = "builtins_aarch32_srcs",
+ srcs = [":builtins_unfiltered_aarch32_srcs"],
+ textual_name = "builtins_aarch32_textual_srcs",
+)
+
+filegroup(
+ name = "builtins_unfiltered_ppc64_srcs",
+ srcs = [
+ ":builtins_generic_srcs",
+ ":builtins_tf_srcs",
+ ] + glob(
[
"lib/builtins/ppc/*.S",
"lib/builtins/ppc/*.c",
@@ -377,17 +467,64 @@
),
)
-# Source files for the RISC-V architecture-specific builtins.
-filegroup(
- name = "builtins_riscv_srcs",
- srcs = glob(
- [
- "lib/builtins/riscv/*.S",
- "lib/builtins/riscv/*.c",
- "lib/builtins/riscv/*.cpp",
- ],
- allow_empty = True,
- ),
+make_filtered_builtins_srcs_groups(
+ name = "builtins_ppc64_srcs",
+ srcs = [":builtins_unfiltered_ppc64_srcs"],
+ textual_name = "builtins_ppc64_textual_srcs",
+)
+
+filegroup(
+ name = "builtins_unfiltered_ppc32_srcs",
+ srcs = [":builtins_generic_srcs"],
+)
+
+make_filtered_builtins_srcs_groups(
+ name = "builtins_ppc32_srcs",
+ srcs = [":builtins_unfiltered_ppc32_srcs"],
+ textual_name = "builtins_ppc32_textual_srcs",
+)
+
+filegroup(
+ name = "builtins_unfiltered_riscv64_srcs",
+ srcs = [
+ ":builtins_generic_srcs",
+ ":builtins_tf_srcs",
+ ] + glob(
+ [
+ "lib/builtins/riscv/*.S",
+ "lib/builtins/riscv/*.c",
+ "lib/builtins/riscv/*.cpp",
+ "lib/builtins/riscv/*.h",
+ ],
+ allow_empty = True,
+ ),
+)
+
+make_filtered_builtins_srcs_groups(
+ name = "builtins_riscv64_srcs",
+ srcs = [":builtins_unfiltered_riscv64_srcs"],
+ textual_name = "builtins_riscv64_textual_srcs",
+)
+
+filegroup(
+ name = "builtins_unfiltered_riscv32_srcs",
+ srcs = [
+ ":builtins_generic_srcs",
+ ] + glob(
+ [
+ "lib/builtins/riscv/*.S",
+ "lib/builtins/riscv/*.c",
+ "lib/builtins/riscv/*.cpp",
+ "lib/builtins/riscv/*.h",
+ ],
+ allow_empty = True,
+ ),
+)
+
+make_filtered_builtins_srcs_groups(
+ name = "builtins_riscv32_srcs",
+ srcs = [":builtins_unfiltered_riscv32_srcs"],
+ textual_name = "builtins_riscv32_textual_srcs",
)
# Source files for the x86 architecture specific builtins (both 32-bit and
@@ -402,8 +539,14 @@
# Source files for the x86-64 architecture specific builtins.
filegroup(
- name = "builtins_x86_64_srcs",
- srcs = glob(
+ name = "builtins_unfiltered_x86_64_srcs",
+ srcs = [
+ ":builtins_bf16_srcs",
+ ":builtins_generic_srcs",
+ ":builtins_tf_srcs",
+ ":builtins_x86_arch_srcs",
+ ":builtins_x86_fp80_srcs",
+ ] + glob(
[
"lib/builtins/x86_64/*.S",
"lib/builtins/x86_64/*.c",
@@ -411,13 +554,29 @@
"lib/builtins/x86_64/*.h",
],
allow_empty = True,
+ exclude = [
+ # This is a Windows-specific routine.
+ # TODO: We should expose this as a Windows source at some point.
+ "lib/builtins/x86_64/chkstk.S",
+ ],
),
)
+make_filtered_builtins_srcs_groups(
+ name = "builtins_x86_64_srcs",
+ srcs = [":builtins_unfiltered_x86_64_srcs"],
+ textual_name = "builtins_x86_64_textual_srcs",
+)
+
# Source files for the 32-bit-specific x86 architecture specific builtins.
filegroup(
- name = "builtins_i386_srcs",
- srcs = glob(
+ name = "builtins_unfiltered_i386_srcs",
+ srcs = [
+ ":builtins_bf16_srcs",
+ ":builtins_generic_srcs",
+ ":builtins_x86_arch_srcs",
+ ":builtins_x86_fp80_srcs",
+ ] + glob(
[
"lib/builtins/i386/*.S",
"lib/builtins/i386/*.c",
@@ -429,28 +588,16 @@
# This file is used for both i386 and x86_64 and so included in the
# broader x86 sources.
"lib/builtins/i386/fp_mode.c",
+ # These are Windows-specific routines.
+ # TODO: We should expose these as Windows source at some point.
+ "lib/builtins/i386/chkstk.S",
+ "lib/builtins/i386/chkstk2.S",
],
),
)
-# Source files for portable components of the compiler builtins library.
-filegroup(
- name = "builtins_generic_srcs",
- srcs = ["lib/builtins/cpu_model/cpu_model.h"] + glob(
- [
- "lib/builtins/*.c",
- "lib/builtins/*.cpp",
- "lib/builtins/*.h",
- "lib/builtins/*.inc",
- ],
- allow_empty = True,
- exclude = (
- BUILTINS_CRTBEGIN_SRCS +
- BUILTINS_CRTEND_SRCS +
- BUILTINS_TF_EXCLUDES +
- BUILTINS_TF_SRCS_PATTERNS +
- BUILTNS_ATOMICS_SRCS +
- BUILTINS_MACOS_ATOMIC_SRCS_PATTERNS
- ),
- ),
+make_filtered_builtins_srcs_groups(
+ name = "builtins_i386_srcs",
+ srcs = [":builtins_unfiltered_i386_srcs"],
+ textual_name = "builtins_i386_textual_srcs",
)
diff --git a/utils/bazel/llvm-project-overlay/compiler-rt/compiler-rt.bzl b/utils/bazel/llvm-project-overlay/compiler-rt/compiler-rt.bzl
new file mode 100644
index 0000000000..e33ceb6a89
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/compiler-rt/compiler-rt.bzl
@@ -0,0 +1,153 @@
+# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+"""Starlark for building parts of compiler-rt.
+
+Variables provide baseline information for how to build various parts of
+compiler-rt. These can be used to generate non-Bazel builds of the library.
+
+Rules and macros support building the relevant filegroups of source files.
+
+TODO: Add macros that provide a convenient way to construct a Bazel target for
+the Clang resource directory with builtins and crt files.
+"""
+
+_common_copts = [
+ "-O3",
+ "-fPIC",
+ "-ffreestanding",
+ "-std=c11",
+]
+
+crt_copts = _common_copts + [
+ "-DCRT_HAS_INITFINI_ARRAY",
+ "-DEH_USE_FRAME_REGISTRY",
+ "-fno-lto",
+]
+
+builtins_copts = _common_copts + [
+ "-fno-builtin",
+ "-fomit-frame-pointer",
+ "-fvisibility=hidden",
+ "-Wno-missing-prototypes",
+ "-Wno-unused-parameter",
+]
+
+def _get_rel_path(path_str):
+ rel_path = path_str.rpartition("/lib/builtins/")[2]
+ if rel_path == path_str:
+ fail("Expected '/lib/builtins/' in path " + path_str)
+ return rel_path
+
+def _filtered_builtins_srcs_impl(ctx):
+ """Implementation of filter_builtins_srcs rule."""
+
+ # Build a map from generic file basename to list of overriding files.
+ overrides = {}
+ for f in ctx.files.srcs:
+ rel_path = _get_rel_path(f.short_path)
+ if "/" in rel_path:
+ base_file = rel_path.rpartition("/")[2]
+ if base_file.endswith(".S"):
+ base_file = base_file.removesuffix(".S") + ".c"
+ overrides[base_file] = True
+
+ filtered_files = []
+ for f in ctx.files.srcs:
+ rel_path = _get_rel_path(f.short_path)
+ if "/" not in rel_path:
+ # This is a generic file. Check if it's overridden.
+ if rel_path not in overrides:
+ filtered_files.append(f)
+ else:
+ # This is an arch-specific file, include it.
+ filtered_files.append(f)
+
+ # Remove any textual sources from this list.
+ filtered_files = [
+ f
+ for f in filtered_files
+ if f.extension not in ["inc", "def"]
+ ]
+
+ return [DefaultInfo(files = depset(filtered_files))]
+
+filtered_builtins_srcs = rule(
+ implementation = _filtered_builtins_srcs_impl,
+ attrs = {
+ "srcs": attr.label_list(
+ mandatory = True,
+ allow_files = True,
+ doc = "Input files.",
+ ),
+ },
+ doc = """Build a filtered filegroup of non-textual srcs for builtins.
+
+ Accepts a filegroup whose files are in lib/builtins/, and produces a target
+ behaving like a filegroup containing filtered files.
+
+ This removes any textual source files (`.inc` or `.def`) from the input.
+
+ It also replaces generic srcs that are overridden by architecture-specific
+ sources. For example, given a list of sources from filegroup of the form:
+
+ - `.../lib/builtins/file_0.c`
+ - `.../lib/builtins/file_1.c`
+ - `.../lib/builtins/file_2.c`
+ - `.../lib/builtins/arch/file_0.c`
+ - `.../lib/builtins/arch/file_1.S`
+
+ It removes any source-file at the top level of lib/builtins/ (e.g.
+ lib/builtins/file_0.c) that has a corresponding source-file in an arch
+ directory (e.g. lib/builtins/arch/file_0.c or lib/builtins/arch/file_1.S),
+ producing a list like:
+
+ - `.../lib/builtins/file_2.c`
+ - `.../lib/builtins/arch/file_0.c`
+ - `.../lib/builtins/arch/file_1.S`
+
+ This allows a target architecture to simply add a specialized file to the
+ list of sources with the architecture prefix and have the specialized
+ version override the generic version.
+ """,
+)
+
+def _filtered_builtins_textual_srcs_impl(ctx):
+ """Implementation of filter_builtins_textual_srcs rule."""
+
+ filtered_files = [
+ f
+ for f in ctx.files.srcs
+ if f.extension in ["inc", "def"]
+ ]
+
+ return [DefaultInfo(files = depset(filtered_files))]
+
+filtered_builtins_textual_srcs = rule(
+ implementation = _filtered_builtins_textual_srcs_impl,
+ attrs = {
+ "srcs": attr.label_list(
+ mandatory = True,
+ allow_files = True,
+ doc = "Input files.",
+ ),
+ },
+ doc = """Build a filegroup of the textual srcs for builtins.
+
+ Textual sources are those that can't be compiled directly and aren't
+ recognized as header files by Bazel. The extensions recognized here are
+ `.inc` and `.def`.
+ """,
+)
+
+def make_filtered_builtins_srcs_groups(name, textual_name, srcs):
+ """Macro to expand both the non-textual and textual filtered srcs groups."""
+ filtered_builtins_srcs(
+ name = name,
+ srcs = srcs,
+ )
+ filtered_builtins_textual_srcs(
+ name = textual_name,
+ srcs = srcs,
+ )
-4
View File
@@ -8,10 +8,6 @@ def _get_files(ctx):
files = []
for src in ctx.attr.srcs:
files.extend([f.path for f in src[DefaultInfo].files.to_list()])
files.extend([
f.path
for f in src[DefaultInfo].default_runfiles.files.to_list()
])
if ctx.attr.strip_package_dir:
# Files may or may not be prefixed with the bin directory, and then
+1 -1
View File
@@ -88,7 +88,7 @@ def main() -> None:
# Remove line endings.
line = line.rstrip("\r\n")
# Exactly matches our pattern
(key, value) = line.split(" ", 1)
key, value = line.split(" ", 1)
key = key.removeprefix("STABLE_")
if key in substitutions:
if args.verbose:
+1 -1
View File
@@ -134,7 +134,7 @@ expand_version_build_info_internal = rule(
def expand_version_build_info(name, **kwargs):
expand_version_build_info_internal(
name = name,
internal_stamp_flag_detect = select({
internal_stamp_flag_detect = False if kwargs.get("stamp") == 0 else select({
"//bazel/version:internal_stamp_flag_detect": True,
"//conditions:default": False,
}),
+106 -5
View File
@@ -32,6 +32,8 @@ cc_library(
name = "bazel_working_dir",
hdrs = ["bazel_working_dir.h"],
deps = [
":check",
":filesystem",
"@llvm-project//llvm:Support",
],
)
@@ -159,6 +161,27 @@ cc_test(
],
)
cc_library(
name = "enum_mask_base",
hdrs = ["enum_mask_base.h"],
deps = [
":enum_base",
"@llvm-project//llvm:Support",
],
)
cc_test(
name = "enum_mask_base_test",
size = "small",
srcs = ["enum_mask_base_test.cpp"],
deps = [
":enum_mask_base",
":raw_string_ostream",
"//testing/base:gtest_main",
"@googletest//:gtest",
],
)
cc_library(
name = "error",
hdrs = ["error.h"],
@@ -176,6 +199,7 @@ cc_library(
hdrs = ["error_test_helpers.h"],
deps = [
":error",
":ostream",
"@googletest//:gtest",
],
)
@@ -214,6 +238,61 @@ cc_test(
],
)
cc_library(
name = "filesystem",
srcs = ["filesystem.cpp"],
hdrs = ["filesystem.h"],
deps = [
":build_data",
":check",
":error",
":ostream",
":raw_string_ostream",
":template_string",
"@llvm-project//llvm:Support",
],
)
cc_test(
name = "filesystem_test",
size = "small",
srcs = ["filesystem_test.cpp"],
deps = [
":error_test_helpers",
":filesystem",
"//testing/base:gtest_main",
"@googletest//:gtest",
"@llvm-project//llvm:Support",
],
)
cc_binary(
name = "filesystem_benchmark",
testonly = 1,
srcs = ["filesystem_benchmark.cpp"],
deps = [
":check",
":filesystem",
"//testing/base:benchmark_main",
"@abseil-cpp//absl/hash",
"@abseil-cpp//absl/random",
"@google_benchmark//:benchmark",
"@llvm-project//llvm:Support",
],
)
sh_test(
name = "filesystem_benchmark_test",
size = "small",
srcs = [":filesystem_benchmark"],
args = [
"--benchmark_dry_run",
# Restrict the sizes to 4-digit ones or smaller to keep test times low.
# The `$$` is repeated for Bazel escaping of `$`.
"--benchmark_filter=^[^/]+(/[0-9]{1,4}(/[0-9]+)?)?/real_time$$",
],
)
cc_library(
name = "find",
hdrs = ["find.h"],
@@ -338,6 +417,28 @@ cc_library(
alwayslink = 1,
)
cc_library(
name = "latch",
srcs = ["latch.cpp"],
hdrs = ["latch.h"],
deps = [
":check",
"@llvm-project//llvm:Support",
],
)
cc_test(
name = "latch_test",
size = "small",
srcs = ["latch_test.cpp"],
deps = [
":latch",
"//testing/base:gtest_main",
"@googletest//:gtest",
"@llvm-project//llvm:Support",
],
)
cc_library(
name = "map",
hdrs = ["map.h"],
@@ -372,7 +473,7 @@ cc_binary(
"//testing/base:benchmark_main",
"@abseil-cpp//absl/container:flat_hash_map",
"@abseil-cpp//absl/random",
"@boost_unordered",
"@boost.unordered",
"@google_benchmark//:benchmark",
"@llvm-project//llvm:Support",
],
@@ -386,7 +487,7 @@ sh_test(
timeout = "moderate",
srcs = [":map_benchmark"],
args = [
"--benchmark_min_time=1x",
"--benchmark_dry_run",
# The `$$` is repeated for Bazel escaping of `$`.
"--benchmark_filter=^[^/]*/[1-9][0-9]{0,3}(/[0-9]+)?$$",
],
@@ -456,7 +557,7 @@ sh_test(
size = "small",
srcs = ["raw_hashtable_metadata_group_benchmark"],
args = [
"--benchmark_min_time=1x",
"--benchmark_dry_run",
],
)
@@ -476,7 +577,7 @@ cc_library(
"@abseil-cpp//absl/base:no_destructor",
"@abseil-cpp//absl/hash",
"@abseil-cpp//absl/random",
"@boost_unordered",
"@boost.unordered",
"@google_benchmark//:benchmark",
"@llvm-project//llvm:Support",
],
@@ -559,7 +660,7 @@ sh_test(
timeout = "moderate",
srcs = [":set_benchmark"],
args = [
"--benchmark_min_time=1x",
"--benchmark_dry_run",
# The `$$` is repeated for Bazel escaping of `$`.
"--benchmark_filter=^[^/]*/[1-9][0-9]{0,3}(/[0-9]+)?$$",
],
+1 -1
View File
@@ -82,7 +82,7 @@ class ArrayStack {
// Adds multiple values to the top array on the stack.
auto AppendToTop(llvm::ArrayRef<ValueT> values) -> void {
CARBON_CHECK(!array_offsets_.empty(),
"Must call PushArray before PushValues.");
"Must call PushArray before AppendToTop.");
llvm::append_range(values_, values);
}
+30 -10
View File
@@ -5,25 +5,45 @@
#ifndef CARBON_COMMON_BAZEL_WORKING_DIR_H_
#define CARBON_COMMON_BAZEL_WORKING_DIR_H_
#include "llvm/Support/FileSystem.h"
#include <stdlib.h>
#include <filesystem>
#include <system_error>
#include "common/check.h"
#include "common/filesystem.h"
namespace Carbon {
// Behave as if the working directory is where `bazel run` was invoked.
// This should only be used in development binaries, not release.
inline auto SetWorkingDirForBazel() -> bool {
// Change working directory to behave as if it is where `bazel run` was invoked.
//
// Accepts an optional `exe_path` argument that will be adjusted to continue to
// be valid after this adjustment.
//
// There is no reasonable recovery we can do if either we can't make the path
// absolute or we can't change directory. As a consequence, this aborts if
// either of those fail rather than propagating any error.
inline auto SetWorkingDirForBazelRun(std::filesystem::path exe_path = {})
-> std::filesystem::path {
char* build_working_dir = getenv("BUILD_WORKING_DIRECTORY");
if (build_working_dir == nullptr) {
return true;
return exe_path;
}
if (std::error_code err =
llvm::sys::fs::set_current_path(build_working_dir)) {
llvm::errs() << "Failed to set working directory: " << err.message();
return false;
// Adjust `exe_path` before changing directory.
if (!exe_path.empty()) {
std::error_code err;
exe_path = std::filesystem::absolute(exe_path, err);
CARBON_CHECK(!err, "Unable to make an absolute path for `{0}`: {1}",
exe_path, err.message());
}
return true;
auto chdir_result = Filesystem::Cwd().Chdir(build_working_dir);
CARBON_CHECK(chdir_result.ok(),
"Unable to change working directory to `{0}`: {1}",
build_working_dir, chdir_result.error());
return exe_path;
}
} // namespace Carbon
+1 -2
View File
@@ -85,8 +85,7 @@ template <TemplateString Kind, TemplateString File, int Line,
#ifdef NDEBUG
[[noreturn]]
#endif
[[gnu::cold, clang::noinline]] auto
CheckFail(Ts&&... values) -> void {
[[gnu::cold, clang::noinline]] auto CheckFail(Ts&&... values) -> void {
if constexpr (llvm::StringRef(FormatStr).empty()) {
// Skip the format string rendering if empty. Note that we don't skip it
// even if there are no values as we want to have consistent handling of
+10 -12
View File
@@ -358,10 +358,11 @@ auto MetaPrinter::PrintVersion(const Command& command) const -> void {
}
auto MetaPrinter::PrintSubcommands(const Command& command) const -> void {
PrintListOfAlternatives(*out_, llvm::ArrayRef(command.subcommands),
[](const std::unique_ptr<Command>& subcommand) {
return subcommand->info.name;
});
PrintListOfAlternatives<std::unique_ptr<Command>>(
*out_, command.subcommands,
[](const std::unique_ptr<Command>& subcommand) {
return subcommand->info.name;
});
}
auto MetaPrinter::PrintRawVersion(const Command& command,
@@ -929,8 +930,8 @@ auto Parser::ParseOneOfArgValue(const Arg& arg, llvm::StringRef value)
error << "` has an invalid value `";
llvm::printEscapedString(value, error);
error << "`; valid values are: ";
PrintListOfAlternatives(error, arg.value_strings,
[](llvm::StringRef x) { return x; });
PrintListOfAlternatives<llvm::StringRef>(
error, arg.value_strings, [](llvm::StringRef x) { return x; });
return Error(error.TakeStr());
}
return Success();
@@ -1218,8 +1219,7 @@ auto Parser::ParsePositionalSuffix(
// arguments.
bool empty_positional = false;
while (!unparsed_args.empty()) {
llvm::StringRef unparsed_arg = unparsed_args.front();
unparsed_args = unparsed_args.drop_front();
llvm::StringRef unparsed_arg = unparsed_args.consume_front();
if (unparsed_arg != "--") {
CARBON_RETURN_IF_ERROR(ParsePositionalArg(unparsed_arg));
@@ -1260,11 +1260,9 @@ auto Parser::Parse(llvm::ArrayRef<llvm::StringRef> unparsed_args)
PopulateMaps(*command_);
while (!unparsed_args.empty()) {
llvm::StringRef unparsed_arg = unparsed_args.front();
// Peak at the front for an exact `--` argument that switches to a
// positional suffix parsing without dropping this argument.
if (unparsed_arg == "--") {
if (unparsed_args.front() == "--") {
if (command_->positional_args.empty()) {
return Error(
"cannot meaningfully end option and subcommand arguments with a "
@@ -1284,7 +1282,7 @@ auto Parser::Parse(llvm::ArrayRef<llvm::StringRef> unparsed_args)
// Now that we're not switching parse modes, drop the current unparsed
// argument and parse it.
unparsed_args = unparsed_args.drop_front();
llvm::StringRef unparsed_arg = unparsed_args.consume_front();
if (unparsed_arg.starts_with("--")) {
// Note that the exact argument "--" has been handled above already.
+5 -7
View File
@@ -704,7 +704,7 @@ struct Arg {
// One-of information.
struct {
llvm::OwningArrayRef<llvm::StringRef> value_strings;
llvm::SmallVector<llvm::StringRef> value_strings;
ValueActionT value_action;
};
};
@@ -800,20 +800,18 @@ auto OneOfArgBuilder::OneOfImpl(const OneOfValueT<U> (&input_values)[N],
MatchT match,
std::index_sequence<Indices...> /*indices*/)
-> void {
std::array<llvm::StringRef, N> value_strings = {input_values[Indices].str...};
std::array<U, N> values = {input_values[Indices].value...};
// Directly copy the value strings into a heap-allocated array in the
// argument.
new (&arg()->value_strings)
llvm::OwningArrayRef<llvm::StringRef>(value_strings);
// Directly copy the value strings into a vector.
new (&arg()->value_strings) llvm::SmallVector<llvm::StringRef>(
std::initializer_list<llvm::StringRef>{input_values[Indices].str...});
// And build a type-erased action that maps a specific value string to a value
// by index.
new (&arg()->value_action) Arg::ValueActionT(
[values, match](const Arg& arg, llvm::StringRef value_string) -> bool {
for (auto [value, arg_value_string] :
llvm::zip(values, arg.value_strings)) {
llvm::zip_equal(values, arg.value_strings)) {
if (value_string == arg_value_string) {
match(value);
return true;
+28 -37
View File
@@ -5,6 +5,7 @@
#ifndef CARBON_COMMON_ENUM_BASE_H_
#define CARBON_COMMON_ENUM_BASE_H_
#include <compare>
#include <type_traits>
#include "common/ostream.h"
@@ -53,7 +54,7 @@ namespace Carbon::Internal {
//
// In `my_kind.cpp`:
// ```
// CARBON_DEFINE_ENUM_CLASS_NAMES(MyKind) = {
// CARBON_DEFINE_ENUM_CLASS_NAMES(MyKind) {
// #define CARBON_MY_KIND(Name) CARBON_ENUM_CLASS_NAME_STRING(Name)
// #include ".../my_kind.def"
// };
@@ -122,22 +123,26 @@ class EnumBase : public Printable<DerivedT> {
// function.
//
// NOLINTNEXTLINE(google-explicit-constructor)
constexpr operator RawEnumType() const { return value_; }
explicit(false) constexpr operator RawEnumType() const { return value_; }
// Conversion to bool is deleted to prevent direct use in an `if` condition
// instead of comparing with another value.
explicit operator bool() const = delete;
// Returns the name of this value.
//
// This method will be automatically defined using the static `names` string
// table in the base class, which is in turn will be populated for each
// derived type using the macro helpers in this file.
auto name() const -> llvm::StringRef { return Names[AsInt()]; }
// Prints this value using its name.
auto Print(llvm::raw_ostream& out) const -> void { out << name(); }
// Don't support comparison of enums by default.
friend auto operator<(DerivedT lhs, DerivedT rhs) -> bool = delete;
friend auto operator<=(DerivedT lhs, DerivedT rhs) -> bool = delete;
friend auto operator>(DerivedT lhs, DerivedT rhs) -> bool = delete;
friend auto operator>=(DerivedT lhs, DerivedT rhs) -> bool = delete;
friend auto operator<=>(DerivedT lhs, DerivedT rhs)
-> std::partial_ordering = delete;
protected:
// The default constructor is explicitly defaulted (and constexpr) as a
// protected constructor to allow derived classes to be constructed but not
@@ -165,42 +170,38 @@ class EnumBase : public Printable<DerivedT> {
}
private:
template <typename MaskDerivedT, typename MaskEnumT,
const llvm::StringLiteral MaskNames[]>
friend class EnumMaskBase;
RawEnumType value_;
};
} // namespace Carbon::Internal
// For use when multiple enums use the same list of names.
#define CARBON_DEFINE_RAW_ENUM_CLASS_NO_NAMES(EnumClassName, UnderlyingType) \
namespace Internal { \
enum class EnumClassName##RawEnum : UnderlyingType; \
} \
enum class Internal::EnumClassName##RawEnum : UnderlyingType
// Use this before defining a class that derives from `EnumBase` to begin the
// definition of the raw `enum class`. It should be followed by the body of that
// raw enum class.
#define CARBON_DEFINE_RAW_ENUM_CLASS(EnumClassName, UnderlyingType) \
namespace Internal { \
extern const llvm::StringLiteral EnumClassName##Names[]; \
struct EnumClassName##Data { \
static const llvm::StringLiteral Names[]; \
enum class RawEnum : UnderlyingType; \
}; \
} \
CARBON_DEFINE_RAW_ENUM_CLASS_NO_NAMES(EnumClassName, UnderlyingType)
enum class Internal::EnumClassName##Data::RawEnum : UnderlyingType
// In CARBON_DEFINE_RAW_ENUM_CLASS block, use this to generate each enumerator.
// In the `CARBON_DEFINE_RAW_ENUM_CLASS` block, use this to generate each
// enumerator.
#define CARBON_RAW_ENUM_ENUMERATOR(Name) Name,
// Use this to compute the `Internal::EnumBase` specialization for a Carbon enum
// class. It both computes the name of the raw enum and ensures all the
// namespaces are correct.
#define CARBON_ENUM_BASE(EnumClassName) \
CARBON_ENUM_BASE_CRTP(EnumClassName, EnumClassName, EnumClassName)
// This variant handles the case where the external name for the Carbon enum is
// not the same as the name by which we refer to it from this context.
#define CARBON_ENUM_BASE_CRTP(EnumClassName, LocalTypeNameForEnumClass, \
EnumClassNameForNames) \
::Carbon::Internal::EnumBase<LocalTypeNameForEnumClass, \
Internal::EnumClassName##RawEnum, \
Internal::EnumClassNameForNames##Names>
#define CARBON_ENUM_BASE(EnumClassName) \
::Carbon::Internal::EnumBase<EnumClassName, \
Internal::EnumClassName##Data::RawEnum, \
Internal::EnumClassName##Data::Names>
// Use this within the Carbon enum class body to generate named constant
// declarations for each value.
@@ -209,19 +210,9 @@ class EnumBase : public Printable<DerivedT> {
// Use this immediately after the Carbon enum class body to define each named
// constant.
#define CARBON_ENUM_CONSTANT_DEFINITION(EnumClassName, Name) \
constexpr EnumClassName EnumClassName::Name = \
inline constexpr EnumClassName EnumClassName::Name = \
EnumClassName::Make(RawEnumType::Name);
// Alternatively, use this within the Carbon enum class body to declare and
// define each named constant. Due to type completeness constraints, this will
// only work if the enum-like class is templated.
//
// This requires the template to have a member named `Base` that names the
// `EnumBase` base class.
#define CARBON_INLINE_ENUM_CONSTANT_DEFINITION(Name) \
static constexpr const typename Base::EnumType& Name = \
Base::Make(Base::RawEnumType::Name);
// Use this in the `.cpp` file for an enum class to start the definition of the
// constant names array for each enumerator. It is followed by the desired
// constant initializer.
@@ -229,7 +220,7 @@ class EnumBase : public Printable<DerivedT> {
// `clang-format` has a bug with spacing around `->` returns in macros. See
// https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
#define CARBON_DEFINE_ENUM_CLASS_NAMES(EnumClassName) \
constexpr llvm::StringLiteral Internal::EnumClassName##Names[]
constexpr llvm::StringLiteral Internal::EnumClassName##Data::Names[] =
// Use this within the names array initializer to generate a string for each
// name.
+2 -10
View File
@@ -30,7 +30,7 @@ class TestKind : public CARBON_ENUM_BASE(TestKind) {
CARBON_ENUM_CONSTANT_DEFINITION(TestKind, Name)
#include "common/enum_base_test.def"
CARBON_DEFINE_ENUM_CLASS_NAMES(TestKind) = {
CARBON_DEFINE_ENUM_CLASS_NAMES(TestKind) {
#define CARBON_ENUM_BASE_TEST_KIND(Name) CARBON_ENUM_CLASS_NAME_STRING(Name)
#include "common/enum_base_test.def"
};
@@ -79,23 +79,15 @@ TEST(EnumBaseTest, Switch) {
TEST(EnumBaseTest, Comparison) {
TestKind kind = TestKind::Beep;
// Make sure all the different comparisons work, and also to work with
// Make sure all the different comparisons work, and also work with
// GoogleTest expectations.
EXPECT_EQ(TestKind::Beep, kind);
EXPECT_NE(TestKind::Boop, kind);
EXPECT_LT(kind, TestKind::Boop);
EXPECT_GT(TestKind::Burr, kind);
EXPECT_LE(kind, TestKind::Beep);
EXPECT_GE(TestKind::Beep, kind);
// These should also all be constexpr.
constexpr TestKind Kind2 = TestKind::Beep;
static_assert(Kind2 == TestKind::Beep);
static_assert(Kind2 != TestKind::Boop);
static_assert(Kind2 < TestKind::Boop);
static_assert(!(Kind2 > TestKind::Burr));
static_assert(Kind2 <= TestKind::Beep);
static_assert(!(Kind2 >= TestKind::Burr));
}
TEST(EnumBaseTest, IntConversion) {
+151
View File
@@ -0,0 +1,151 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef CARBON_COMMON_ENUM_MASK_BASE_H_
#define CARBON_COMMON_ENUM_MASK_BASE_H_
#include <bit>
#include "common/enum_base.h"
#include "llvm/ADT/StringExtras.h"
namespace Carbon::Internal {
// CRTP-style base class similar to `EnumBase`, but supporting mask enums.
// Enumerator values are consecutive bit shifts (1 << 0, 1 << 1, 1 << 2, 1 << 3,
// ...).
//
// Users must be in the `Carbon` namespace and should look like the following.
//
// In `my_kind.h`:
// ```
// #define CARBON_MY_KIND(X) \
// X(Enumerator1) \
// X(Enumerator2) \
// X(Enumerator3) \
// ...
//
// CARBON_DEFINE_RAW_ENUM_MASK(MyKind, uint32_t) {
// CARBON_MY_KIND(CARBON_RAW_ENUM_MASK_ENUMERATOR)
// };
//
// class MyKind : public CARBON_ENUM_MASK_BASE(MyKind) {
// public:
// CARBON_MY_KIND(CARBON_ENUM_MASK_CONSTANT_DECL)
//
// // Plus, anything else you wish to include.
// };
//
// #define CARBON_MY_KIND_WITH_TYPE(X) \
// CARBON_ENUM_MASK_CONSTANT_DEFINITION(MyKind, X)
// CARBON_MY_KIND(CARBON_MY_KIND_WITH_TYPE)
// #undef CARBON_MY_KIND_WITH_TYPE
// ```
//
// In `my_kind.cpp`:
// ```
// CARBON_DEFINE_ENUM_MASK_NAMES(MyKind) {
// CARBON_MY_KIND(CARBON_ENUM_MASK_NAME_STRING)
// };
// ```
template <typename DerivedT, typename EnumT, const llvm::StringLiteral Names[]>
class EnumMaskBase : public EnumBase<DerivedT, EnumT, Names> {
public:
// Provide a standard `None`.
//
// This uses a `&` to trigger slightly different instantiation behaviors in
// Clang. For context on why this is needed, see http://wg21.link/CWG2800.
// NOLINTNEXTLINE(readability-identifier-naming)
static const DerivedT& None;
// Returns true if there's a non-empty set intersection.
constexpr auto HasAnyOf(DerivedT other) const -> bool {
return !(*this & other).empty();
}
// Adds entries to the mask.
auto Add(DerivedT other) -> void { *this = *this | other; }
// Removes entries from the mask.
auto Remove(DerivedT other) -> void { *this = *this & ~other; }
constexpr auto empty() const -> bool { return this->AsInt() == 0; }
constexpr auto operator|(DerivedT other) const -> DerivedT {
return DerivedT::FromInt(this->AsInt() | other.AsInt());
}
constexpr auto operator&(DerivedT other) const -> DerivedT {
return DerivedT::FromInt(this->AsInt() & other.AsInt());
}
constexpr auto operator~() const -> DerivedT {
return DerivedT::FromInt(~this->AsInt());
}
// Use `Print` for mask entries. This hides `EnumBase::name`; it's not
// compatible with `EnumMaskBase`.
auto name() const -> llvm::StringRef = delete;
// Prints this value as a `|`-separated list of mask entries, or `None`.
//
// This shadows EnumBase::Print.
auto Print(llvm::raw_ostream& out) const -> void {
int value = this->AsInt();
if (value == 0) {
out << "None";
return;
}
llvm::ListSeparator sep("|");
for (int bit = 0; value != 0; value >>= 1, ++bit) {
if (value & 1) {
out << sep << Names[bit];
}
}
}
};
template <typename DerivedT, typename EnumT, const llvm::StringLiteral Names[]>
constexpr const DerivedT& EnumMaskBase<DerivedT, EnumT, Names>::None =
DerivedT::FromInt(0);
} // namespace Carbon::Internal
// Use this before defining a class that derives from `EnumMaskBase` to begin
// the definition of the raw `enum class`. It should be followed by the body of
// that raw enum class.
#define CARBON_DEFINE_RAW_ENUM_MASK(EnumMaskName, UnderlyingType) \
namespace Internal { \
struct EnumMaskName##Data { \
static const llvm::StringLiteral Names[]; \
/* For bit shifts, track the initial counter value. This will increment on \
* each enum entry. */ \
static constexpr uint64_t BitShiftCounter = __COUNTER__ + 1; \
enum class RawEnum : UnderlyingType; \
}; \
} \
enum class Internal::EnumMaskName##Data::RawEnum : UnderlyingType
// In the `CARBON_DEFINE_RAW_ENUM_MASK` block, use this to generate each
// enumerator.
#define CARBON_RAW_ENUM_MASK_ENUMERATOR(Name) \
Name = 1 << (__COUNTER__ - BitShiftCounter),
// Use this to compute the `Internal::EnumMaskBase` specialization for a Carbon
// enum mask. It both computes the name of the raw enum and ensures all the
// namespaces are correct.
#define CARBON_ENUM_MASK_BASE(EnumMaskName) \
::Carbon::Internal::EnumMaskBase<EnumMaskName, \
Internal::EnumMaskName##Data::RawEnum, \
Internal::EnumMaskName##Data::Names>
// Constants and names are declared equivalently as to `EnumBase`.
#define CARBON_ENUM_MASK_CONSTANT_DECL(Name) CARBON_ENUM_CONSTANT_DECL(Name)
#define CARBON_ENUM_MASK_CONSTANT_DEFINITION(EnumMaskName, Name) \
CARBON_ENUM_CONSTANT_DEFINITION(EnumMaskName, Name)
#define CARBON_DEFINE_ENUM_MASK_NAMES(EnumMaskName) \
CARBON_DEFINE_ENUM_CLASS_NAMES(EnumMaskName)
#define CARBON_ENUM_MASK_NAME_STRING(Name) CARBON_ENUM_CLASS_NAME_STRING(Name)
#endif // CARBON_COMMON_ENUM_MASK_BASE_H_
+142
View File
@@ -0,0 +1,142 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "common/enum_mask_base.h"
#include <gtest/gtest.h>
#include "common/raw_string_ostream.h"
namespace Carbon {
namespace {
#define CARBON_TEST_KIND(X) \
X(Beep) \
X(Boop) \
X(Burr)
CARBON_DEFINE_RAW_ENUM_MASK(TestKind, uint8_t) {
CARBON_TEST_KIND(CARBON_RAW_ENUM_MASK_ENUMERATOR)
};
class TestKind : public CARBON_ENUM_MASK_BASE(TestKind) {
public:
CARBON_TEST_KIND(CARBON_ENUM_MASK_CONSTANT_DECL)
using EnumMaskBase::AsInt;
using EnumMaskBase::FromInt;
};
#define CARBON_TEST_KIND_WITH_TYPE(X) \
CARBON_ENUM_MASK_CONSTANT_DEFINITION(TestKind, X)
CARBON_TEST_KIND(CARBON_TEST_KIND_WITH_TYPE)
#undef CARBON_TEST_KIND_WITH_TYPE
CARBON_DEFINE_ENUM_MASK_NAMES(TestKind) {
CARBON_TEST_KIND(CARBON_ENUM_MASK_NAME_STRING)
};
static_assert(sizeof(TestKind) == sizeof(uint8_t),
"Class size doesn't match enum size!");
TEST(EnumMaskBaseTest, Printing) {
RawStringOstream stream;
TestKind kind = TestKind::Beep;
stream << kind;
EXPECT_EQ("Beep", stream.TakeStr());
kind = TestKind::Boop;
stream << kind;
EXPECT_EQ("Boop", stream.TakeStr());
stream << TestKind::Beep;
EXPECT_EQ("Beep", stream.TakeStr());
stream << (TestKind::Beep | TestKind::Burr);
EXPECT_EQ("Beep|Burr", stream.TakeStr());
}
// This just ensures it compiles, it's not validating what's printed.
TEST(EnumMaskBaseTest, PrintToGoogletest) {
EXPECT_TRUE(true) << TestKind::Beep;
}
TEST(EnumMaskBaseTest, Switch) {
TestKind kind = TestKind::Boop;
switch (kind) {
case TestKind::Beep: {
FAIL() << "Beep case selected!";
break;
}
case TestKind::Boop: {
EXPECT_EQ(kind, TestKind::Boop);
break;
}
case TestKind::Burr: {
FAIL() << "Burr case selected!";
break;
}
}
}
TEST(EnumMaskBaseTest, Equality) {
TestKind kind = TestKind::Beep;
// Make sure all the different comparisons work, and also work with
// GoogleTest expectations.
EXPECT_EQ(TestKind::Beep, kind);
EXPECT_NE(TestKind::Boop, kind);
// These should also all be constexpr.
constexpr TestKind Kind2 = TestKind::Beep;
static_assert(Kind2 == TestKind::Beep);
static_assert(Kind2 != TestKind::Boop);
}
TEST(EnumMaskBaseTest, AddRemove) {
TestKind kind = TestKind::Beep;
EXPECT_EQ(kind, TestKind::Beep);
kind.Add(TestKind::Beep);
EXPECT_EQ(kind, TestKind::Beep);
kind.Add(TestKind::Burr);
EXPECT_EQ(kind, TestKind::Beep | TestKind::Burr);
kind.Remove(TestKind::Beep);
EXPECT_EQ(kind, TestKind::Burr);
kind.Remove(TestKind::Beep);
EXPECT_EQ(kind, TestKind::Burr);
kind.Remove(TestKind::Burr);
EXPECT_EQ(kind, TestKind::None);
}
TEST(EnumMaskBaseTest, HasAnyOf) {
static_assert(TestKind::Beep.HasAnyOf(TestKind::Beep));
static_assert(TestKind::Beep.HasAnyOf(TestKind::Beep | TestKind::Burr));
static_assert(!TestKind::Beep.HasAnyOf(TestKind::Burr));
}
TEST(EnumMaskBaseTest, MaskOperations) {
TestKind kind =
TestKind::Beep | (TestKind::Burr & (TestKind::Burr | TestKind::Beep));
EXPECT_EQ(kind, TestKind::Beep | TestKind::Burr);
// These should also all be constexpr.
static_assert((TestKind::Beep & TestKind::Burr) == TestKind::None);
static_assert((TestKind::Beep | TestKind::Burr) != TestKind::None);
static_assert(TestKind::Beep == ~~TestKind::Beep);
}
TEST(EnumMaskBaseTest, IntConversion) {
EXPECT_EQ(1, TestKind::Beep.AsInt());
EXPECT_EQ(2, TestKind::Boop.AsInt());
EXPECT_EQ(4, TestKind::Burr.AsInt());
EXPECT_EQ(TestKind::Beep, TestKind::FromInt(1));
EXPECT_EQ(TestKind::Boop, TestKind::FromInt(2));
EXPECT_EQ(TestKind::Burr, TestKind::FromInt(4));
}
} // namespace
} // namespace Carbon
+7 -12
View File
@@ -104,8 +104,7 @@ class [[nodiscard]] ErrorOr {
// Constructs with an error; the error must not be Error::Success().
// Implicit for easy construction on returns.
// NOLINTNEXTLINE(google-explicit-constructor)
ErrorOr(ErrorT err) : val_(std::move(err)) {}
explicit(false) ErrorOr(ErrorT err) : val_(std::move(err)) {}
// Constructs from a custom error type derived from `ErrorBase` into an
// `ErrorOr` for `Error` to facilitate returning errors transparently.
@@ -113,8 +112,7 @@ class [[nodiscard]] ErrorOr {
requires(std::same_as<ErrorT, Error> &&
std::derived_from<OtherErrorT, ErrorBase<OtherErrorT>>)
// Implicit for easy construction on returns.
// NOLINTNEXTLINE(google-explicit-constructor)
ErrorOr(OtherErrorT other_err) : val_(other_err.ToError()) {}
explicit(false) ErrorOr(OtherErrorT other_err) : val_(other_err.ToError()) {}
// Constructs with any convertible error type, necessary for return statements
// that are already converting to the `ErrorOr` wrapper.
@@ -126,21 +124,18 @@ class [[nodiscard]] ErrorOr {
requires(std::constructible_from<ErrorT, OtherErrorT> &&
std::derived_from<OtherErrorT, ErrorBase<OtherErrorT>>)
// Implicit for easy construction on returns.
// NOLINTNEXTLINE(google-explicit-constructor)
ErrorOr(OtherErrorT other_err)
explicit(false) ErrorOr(OtherErrorT other_err)
: val_(std::in_place_type<ErrorT>, std::move(other_err)) {}
// Constructs with a reference.
// Implicit for easy construction on returns.
// NOLINTNEXTLINE(google-explicit-constructor)
ErrorOr(T ref)
explicit(false) ErrorOr(T ref)
requires std::is_reference_v<T>
: val_(std::ref(ref)) {}
// Constructs with a value.
// Implicit for easy construction on returns.
// NOLINTNEXTLINE(google-explicit-constructor)
ErrorOr(T val)
explicit(false) ErrorOr(T val)
requires(!std::is_reference_v<T>)
: val_(std::move(val)) {}
@@ -224,11 +219,11 @@ class ErrorBuilder {
}
// NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
operator Error() { return Error(out_->TakeStr()); }
explicit(false) operator Error() { return Error(out_->TakeStr()); }
template <typename T>
// NOLINTNEXTLINE(google-explicit-constructor): Implicit cast for returns.
operator ErrorOr<T>() {
explicit(false) operator ErrorOr<T>() {
return Error(out_->TakeStr());
}
+12
View File
@@ -19,6 +19,7 @@ using ::Carbon::Testing::IsError;
using ::Carbon::Testing::IsSuccess;
using ::testing::_;
using ::testing::Eq;
using ::testing::VariantWith;
TEST(ErrorTest, Error) {
Error err("test");
@@ -158,6 +159,17 @@ TYPED_TEST(ErrorOrTest, UnprintableValue) {
EXPECT_THAT(error, IsError(this->ErrorStr()));
}
// Note that this is more of a test of `IsSuccess` than `ErrorOr` itself.
TYPED_TEST(ErrorOrTest, NestedMatching) {
using TestErrorOr = ErrorOr<std::variant<int, float>, TypeParam>;
TestErrorOr i(42);
EXPECT_THAT(i, IsSuccess(VariantWith<int>(Eq(42))));
TestErrorOr f(0.42F);
EXPECT_THAT(f, IsSuccess(VariantWith<float>(Eq(0.42F))));
}
TYPED_TEST(ErrorOrTest, ReturnIfErrorNoError) {
using TestErrorOr = ErrorOr<Success, TypeParam>;
auto result = []() -> TestErrorOr {
+47 -16
View File
@@ -7,7 +7,10 @@
#include <gmock/gmock.h>
#include <concepts>
#include "common/error.h"
#include "common/ostream.h"
namespace Carbon::Testing {
@@ -48,43 +51,69 @@ class IsError {
::testing::Matcher<std::string> matcher_;
};
// Matches the value for a non-error state of `ErrorOr<T>`. For example:
// EXPECT_THAT(my_result, IsSuccess(Eq(3)));
template <typename InnerMatcher>
class IsSuccessMatcher {
// Implementation of a success matcher for a specific `T` and `ErrorT` in an
// `ErrorOr`. Supports a nested matcher for the `T` value.
template <typename T, typename ErrorT>
class IsSuccessMatcherImpl
: public ::testing::MatcherInterface<const ErrorOr<T, ErrorT>&> {
public:
// NOLINTNEXTLINE(readability-identifier-naming)
using is_gtest_matcher = void;
explicit IsSuccessMatcherImpl(const ::testing::Matcher<T>& matcher)
: matcher_(matcher) {}
explicit IsSuccessMatcher(InnerMatcher matcher)
: matcher_(std::move(matcher)) {}
template <typename T, typename ErrorT>
auto MatchAndExplain(const ErrorOr<T, ErrorT>& result,
::testing::MatchResultListener* listener) const -> bool {
::testing::MatchResultListener* listener) const
-> bool override {
if (result.ok()) {
return ::testing::Matcher<T>(matcher_).MatchAndExplain(*result, listener);
return matcher_.MatchAndExplain(*result, listener);
} else {
*listener << "is an error with `" << result.error() << "`";
return false;
}
}
auto DescribeTo(std::ostream* os) const -> void {
auto DescribeTo(std::ostream* os) const -> void override {
*os << "is a success and matches ";
matcher_.DescribeTo(os);
}
auto DescribeNegationTo(std::ostream* os) const -> void {
auto DescribeNegationTo(std::ostream* os) const -> void override {
*os << "is an error or does not match ";
matcher_.DescribeTo(os);
matcher_.DescribeNegationTo(os);
}
private:
::testing::Matcher<T> matcher_;
};
// Polymorphic match implementation for GoogleTest.
//
// To support matching arbitrary types that `InnerMatcher` can also match, this
// itself must match arbitrary types. This is accomplished by not being a
// matcher itself, but by being convertible into matchers for any particular
// `ErrorOr`.
template <typename InnerMatcher>
class IsSuccessMatcher {
public:
explicit IsSuccessMatcher(InnerMatcher matcher)
: matcher_(std::move(matcher)) {}
template <typename T, typename ErrorT>
explicit(false)
// NOLINTNEXTLINE(google-explicit-constructor): Required for matcher APIs.
operator ::testing::Matcher<const ErrorOr<T, ErrorT>&>() const {
return ::testing::Matcher<const ErrorOr<T, ErrorT>&>(
new IsSuccessMatcherImpl<T, ErrorT>(
::testing::SafeMatcherCast<T>(matcher_)));
}
private:
InnerMatcher matcher_;
};
// Wraps `IsSuccessMatcher` for the inner matcher deduction.
// Returns a matcher the value for a non-error state of `ErrorOr<T>`.
//
// For example:
// EXPECT_THAT(my_result, IsSuccess(Eq(3)));
template <typename InnerMatcher>
auto IsSuccess(InnerMatcher matcher) -> IsSuccessMatcher<InnerMatcher> {
return IsSuccessMatcher<InnerMatcher>(matcher);
@@ -96,6 +125,8 @@ namespace Carbon {
// Supports printing `ErrorOr<T>` to `std::ostream` in tests.
template <typename T, typename ErrorT>
requires(std::same_as<ErrorT, Error> ||
std::derived_from<ErrorT, ErrorBase<ErrorT>>)
auto operator<<(std::ostream& out, const ErrorOr<T, ErrorT>& error_or)
-> std::ostream& {
if (error_or.ok()) {
+3 -2
View File
@@ -13,8 +13,9 @@ namespace Carbon {
// `argv0` is required to be null-terminated.
//
// A simplistic approach -- if the provided string isn't already a valid path,
// we look it up in the PATH environment variable. Doesn't resolve any symlinks
// and if it fails, returns the main executable path.
// we look it up in the PATH environment variable. Doesn't resolve any symlinks.
// If it doesn't find a value based on `argv[0]`, returns the main executable
// path.
auto FindExecutablePath(const char* argv0) -> std::string;
} // namespace Carbon
+743
View File
@@ -0,0 +1,743 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "common/filesystem.h"
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <chrono>
#include "common/build_data.h"
#include "llvm/Support/MathExtras.h"
namespace Carbon::Filesystem {
// Render an error number from `errno` to the provided stream using the richest
// rendering available on the platform.
static auto PrintErrorNumber(llvm::raw_ostream& out, int errnum) -> void {
#if defined(_GNU_SOURCE) && \
(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 32))
// For sufficiently recent glibc versions, use GNU-specific routines to
// compute the error name and description.
llvm::StringRef name = strerrordesc_np(errnum);
llvm::StringRef desc = strerrorname_np(errnum);
out << llvm::formatv("{0}: {1}", name, desc);
#elif defined(__APPLE__) || defined(_GNU_SOURCE) || defined(_POSIX_SOURCE)
// Broadly portable fallback for Unix-like systems.
char buffer[4096];
#ifdef _GNU_SOURCE
const char* str = strerror_r(errnum, buffer, sizeof(buffer));
// The GNU version doesn't report a meta-error.
int meta_error = 0;
#else
int meta_error = strerror_r(errnum, buffer, sizeof(buffer));
const char* str = buffer;
#endif
if (meta_error == 0) {
out << llvm::formatv("errno {0}: {1}", errnum, llvm::StringRef(str));
} else {
out << llvm::formatv(
"error number {0}; encountered meta-error number {1} while rendering "
"an error message",
errnum, meta_error);
}
#else
#error TODO: Implement this for other platforms.
#endif
}
auto FdError::Print(llvm::raw_ostream& out) const -> void {
// The `format_` member is a `StringLiteral` that is null terminated, so
// `.data()` is safe here.
// NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage)
out << llvm::formatv(format_.data(), fd_) << " failed: ";
PrintErrorNumber(out, unix_errnum());
}
auto PathError::Print(llvm::raw_ostream& out) const -> void {
// The `format_` member is a `StringLiteral` that is null terminated, so
// `.data()` is safe here.
// NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage)
out << llvm::formatv(format_.data(), path_,
dir_fd_ == AT_FDCWD ? std::string("AT_FDCWD")
: std::to_string(dir_fd_))
<< " failed: ";
PrintErrorNumber(out, unix_errnum());
}
auto Internal::FileRefBase::ReadFileToString()
-> ErrorOr<std::string, FdError> {
std::string result;
// Read a buffer at a time until we reach the end. We use the pipe buffer
// length as our max buffer size as it is likely to be small but reasonable
// for the OS, and in the case of pipes the same chunking in which the data
// will arrive.
//
// TODO: Replace this with a smaller buffer and using `resize_and_overwrite`
// to read into the string in-place for larger strings. Unclear if that will
// be any faster, but it will be much more friendly to callers with
// constrained stack sizes and use less memory overall.
std::byte buffer[PIPE_BUF];
CARBON_RETURN_IF_ERROR(SeekFromBeginning(0));
for (;;) {
auto read_result = ReadToBuffer(buffer);
if (!read_result.ok()) {
return std::move(read_result).error();
}
if (read_result->empty()) {
// EOF
break;
}
result.append(reinterpret_cast<const char*>(read_result->data()),
read_result->size());
}
return result;
}
auto Internal::FileRefBase::WriteFileFromString(llvm::StringRef str)
-> ErrorOr<Success, FdError> {
CARBON_RETURN_IF_ERROR(SeekFromBeginning(0));
auto bytes = llvm::ArrayRef<std::byte>(
reinterpret_cast<const std::byte*>(str.data()), str.size());
while (!bytes.empty()) {
auto write_result = WriteFromBuffer(bytes);
if (!write_result.ok()) {
return std::move(write_result).error();
}
bytes = *write_result;
}
CARBON_RETURN_IF_ERROR(Truncate(str.size()));
return Success();
}
// A macOS specific sleep routine that builds on more standard utilities. This
// is technically a portable implementation so we always compile it but only use
// it on macOS where the more efficient direct use of `clock_nanosleep` isn't
// available.
[[maybe_unused]]
static auto SleepMacos(Duration sleep) -> void {
TimePoint stop = Clock::now() + sleep;
timespec sleep_ts = Internal::DurationToTimespec(sleep);
for (;;) {
timespec rem_sleep_ts = {};
int result = nanosleep(&sleep_ts, &rem_sleep_ts);
if (result == 0) {
return;
}
// Continue sleeping if we get interrupted by a resumable signal. For
// everything else report it.
if (errno != EINTR) {
int errnum = errno;
RawStringOstream error_os;
PrintErrorNumber(error_os, errnum);
CARBON_FATAL("Unexpected error while sleeping: {0}", error_os.TakeStr());
}
// Update to the remaining sleep time for the next attempt at sleeping.
sleep_ts = rem_sleep_ts;
// Also check if the clock has passed our stop time as a fallback to avoid
// too much clock skew.
if (Clock::now() > stop) {
return;
}
}
}
static auto Sleep(Duration sleep) -> void {
// For every platform but macOS we can sleep directly on an absolute time.
#if __APPLE__
// On Apple platforms, dispatch to a specialized routine.
SleepMacos(sleep);
#else
// We use `clock_gettime` instead of the filesystem `Clock` or some other
// `std::chrono` clock because we want to use the exact same clock that we'll
// use for sleeping below, and we'll need the time in a `timespec` for that
// call anyways. We do use a monotonic clock to try and avoid sleeps being
// interrupted by clock changes.
timespec ts = {};
int result = clock_gettime(CLOCK_MONOTONIC, &ts);
CARBON_CHECK(result == 0, "Error getting the time: {0}", strerror(errno));
// Now convert the timespec to a duration that we can safely do arithmetic on.
// Since the sleep interval is in nanoseconds it is tempting to directly do
// arithmetic here, but this has a subtle pitfall near the boundary between
// the nanosecond component and the second component.
//
// Note that our `Duration` uses `__int128` to avoid worrying about running
// out of precision to represent the final deadline.
Duration stop_time = std::chrono::seconds(ts.tv_sec);
stop_time += std::chrono::nanoseconds(ts.tv_nsec);
stop_time += sleep;
// Now convert back to timespec.
ts = Internal::DurationToTimespec(stop_time);
do {
result = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, nullptr);
// Continue sleeping if we get interrupted by a resumable signal. Because
// we're using a monotonic clock and an absolute deadline time we will
// eventually progress past that deadline.
} while (result != 0 && (errno == EINTR));
if (result != 0) {
int errnum = errno;
RawStringOstream error_os;
PrintErrorNumber(error_os, errnum);
CARBON_FATAL("Unexpected error while sleeping: {0}", error_os.TakeStr());
}
#endif
}
auto Internal::FileRefBase::TryLock(FileLock::Kind kind, Duration deadline,
Duration poll_interval)
-> ErrorOr<FileLock, FdError> {
CARBON_CHECK(poll_interval <= deadline);
if (deadline != Duration(0) && poll_interval == Duration(0)) {
// If the caller didn't provide a poll interval but did provide a deadline,
// pick a poll interval to roughly be 1/1000th of the deadline but at least
// 1 microsecond. We don't support polling faster than 1 microsecond given
// how expensive file locking is.
poll_interval =
std::max(Duration(std::chrono::microseconds(1)), deadline / 1000);
}
if (deadline != Duration(0)) {
CARBON_CHECK(
deadline >= std::chrono::microseconds(10),
"A deadline for a file lock shorter than 10 microseconds is not "
"supported, callers can implement their own polling logic.");
CARBON_CHECK(poll_interval >= std::chrono::microseconds(1),
"Polling for a file lock faster than every microsecond is not "
"supported, callers can implement their own polling logic.");
}
auto stop = Clock::now() + deadline;
for (;;) {
int result = flock(fd_, static_cast<int>(kind) | LOCK_NB);
if (result == 0) {
return FileLock(fd_);
}
// Return an error if this is something other than blocking for the lock to
// be available, or we didn't get a deadline for continuing to try and
// acquire the lock, or we've reached our deadline.
if (errno != EWOULDBLOCK || deadline == Duration(0) ||
Clock::now() >= stop) {
return FdError(errno, "File::TryLock on '{0}'", fd_);
}
// The caller requested attempting to wait up to a deadline to acquire the
// lock with a specific poll interval. Try to sleep for that poll interval
// before trying the lock again.
Sleep(poll_interval);
}
}
auto DirRef::AppendEntriesIf(
llvm::SmallVectorImpl<std::filesystem::path>& entries,
llvm::function_ref<auto(llvm::StringRef name)->bool> predicate)
-> ErrorOr<Success, FdError> {
CARBON_ASSIGN_OR_RETURN(Reader reader, Read());
for (const Entry& entry : reader) {
llvm::StringRef name = entry.name();
if (name == "." || name == "..") {
continue;
}
if (predicate && !predicate(name)) {
continue;
}
entries.push_back(name.str());
}
return Success();
}
auto DirRef::AppendEntriesIf(
llvm::SmallVectorImpl<std::filesystem::path>& dir_entries,
llvm::SmallVectorImpl<std::filesystem::path>& non_dir_entries,
llvm::function_ref<auto(llvm::StringRef name)->bool> predicate)
-> ErrorOr<Success, FdError> {
CARBON_ASSIGN_OR_RETURN(Reader reader, Read());
for (const Entry& entry : reader) {
llvm::StringRef name = entry.name();
if (name == "." || name == "..") {
continue;
}
if (predicate && !predicate(name)) {
continue;
}
std::filesystem::path name_path = name.str();
if (entry.is_known_dir()) {
dir_entries.push_back(std::move(name_path));
continue;
}
if (!entry.is_unknown_type()) {
non_dir_entries.push_back(std::move(name_path));
continue;
}
auto stat_result = Lstat(name_path);
if (!stat_result.ok()) {
return FdError(stat_result.error().unix_errnum(),
"Dir::AppendEntriesIf on '{0}' failed while stat-ing "
"entries to determine which are directories",
dfd_);
}
if (stat_result->is_dir()) {
dir_entries.push_back(std::move(name_path));
} else {
non_dir_entries.push_back(std::move(name_path));
}
}
return Success();
}
auto DirRef::OpenDir(const std::filesystem::path& path,
CreationOptions creation_options, ModeType creation_mode,
OpenFlags open_flags) -> ErrorOr<Dir, PathError> {
// If we potentially need to create a directory, we have to do that
// separately as no systems support `O_CREAT | O_DIRECTORY`, even though
// that would be (much) nicer.
if (creation_options == CreateNew) {
// If we are required to be the one that created the directory, disable
// following the last symlink when we open that directory. The last symlink
// is the only one that matters for security here because it is only valid
// to create the last component. It is that directory component that we want
// to ensure has not been replaced with a symlink by an adversarial
// concurrent process.
open_flags |= OpenFlags::NoFollow;
}
if (creation_options != OpenExisting) {
CARBON_CHECK(creation_options != CreateAlways,
"Invalid `creation_options` value of `CreateAlways`: there is "
"no support for truncating directories, and so they cannot be "
"created in an analogous way to files if they already exist.");
if (mkdirat(dfd_, path.c_str(), creation_mode) != 0) {
// Unless the error is just that the path already exists, and that is
// allowed for the requested creation flags, report any error here as part
// of opening just like we would if the error originated from `openat`
// with `O_CREAT`.
if (creation_options == CreateNew || errno != EEXIST) {
return PathError(errno,
"Calling `mkdirat` on '{0}' relative to '{1}' during "
"DirRef::OpenDir",
path, dfd_);
}
}
}
// Open this path as a directory. Note that this has to succeed, and when we
// created the directory we require the last component to not be a symlink in
// case it was _replaced_ with a symlink while running.
int result_fd =
openat(dfd_, path.c_str(), static_cast<int>(open_flags) | O_DIRECTORY);
if (result_fd == -1) {
// No need for `EINTR` handling here as if this is a FIFO it would be an
// error with `O_DIRECTORY`.
return PathError(
errno,
"Calling `openat` on '{0}' relative to '{1}' during DirRef::OpenDir",
path, dfd_);
}
Dir result(result_fd);
// If we were required to create the directory, we also need to verify that
// the opened file descriptor continues to have the same permissions and the
// correct owner as we couldn't do the creation atomically with the open. This
// defends against an adversarial removal of the created directory and
// creation of a new directory with the same name but either with wider
// permissions such as all-write, or with a different owner.
//
// We don't defend against replacement with a directory of the same name, same
// permissions, same owner, but different group. There is no good way to do
// this defense given the complexity of group assignment, and there appears to
// be no need. Achieving such a replacement without superuser power would
// require a parent directory with `setgid` bit, and a group that gives the
// attacker access -- but such a parent directory would make *any* creation
// vulnerable without any need for a replacement, so we can't defend against
// that here. The caller has ample tools to defend against this including
// taking care with the parent directory and restricting the group permission
// bits which we *do* verify.
if (creation_options == CreateNew) {
auto stat_result = result.Stat();
if (!stat_result.ok()) {
// Manually propagate this error so we can attach it back to the opened
// path and relative directory.
return PathError(stat_result.error().unix_errnum(),
"DirRef::Stat after opening '{0}' relative to '{1}'",
path, dfd_);
}
// Check that the owning UID is the current effective UID.
if (stat_result->unix_uid() != geteuid()) {
// Model this as `EPERM`, which is a bit awkward, but should be fine.
return PathError(EPERM,
"Unexpected UID change after creating '{0}' relative to "
"'{1}' during DirRef::OpenDir",
path, dfd_);
}
// Check that the permissions are a subset of the requested ones. They may
// have been masked down by `umask`, but if there are *new* permissions,
// that would be a security issue.
if ((stat_result->permissions() & creation_mode) !=
stat_result->permissions()) {
// Model this with `EPERM` and a custom message.
return PathError(EPERM,
"Unexpected permissions after creating '{0}' relative "
"to '{1}' during DirRef::OpenDir",
path, dfd_);
}
}
return result;
}
auto DirRef::ReadFileToString(const std::filesystem::path& path)
-> ErrorOr<std::string, PathError> {
CARBON_ASSIGN_OR_RETURN(ReadFile f, OpenReadOnly(path));
auto result = f.ReadFileToString();
if (result.ok()) {
return *std::move(result);
}
return PathError(result.error().unix_errnum(),
"Dir::ReadFileToString on '{0}' relative to '{1}'", path,
dfd_);
}
auto DirRef::WriteFileFromString(const std::filesystem::path& path,
llvm::StringRef content,
CreationOptions creation_options)
-> ErrorOr<Success, PathError> {
CARBON_ASSIGN_OR_RETURN(WriteFile f, OpenWriteOnly(path, creation_options));
auto write_result = f.WriteFileFromString(content);
// Immediately close the file as even if there was a write error we don't want
// to leave the file open.
auto close_result = std::move(f).Close();
// Now report the first error encountered or return success.
if (!write_result.ok()) {
return PathError(
write_result.error().unix_errnum(),
"Write error in Dir::WriteFileFromString on '{0}' relative to '{1}'",
path, dfd_);
}
if (!close_result.ok()) {
return PathError(
close_result.error().unix_errnum(),
"Close error in Dir::WriteFileFromString on '{0}' relative to '{1}'",
path, dfd_);
}
return Success();
}
auto DirRef::CreateDirectories(const std::filesystem::path& path,
ModeType creation_mode)
-> ErrorOr<Dir, PathError> {
// Avoid having to handle an empty path by immediately rejecting it as
// invalid.
if (path.empty()) {
return PathError(EINVAL,
"DirRef::CreateDirectories on '{0}' relative to '{1}'",
path, dfd_);
}
// Try directly opening the directory and use that if successful. This is an
// important hot path case of users essentially doing an "open-always" form of
// creating multiple steps of directories.
auto open_result = OpenDir(path, OpenExisting);
if (open_result.ok()) {
return std::move(*open_result);
} else if (!open_result.error().no_entity()) {
return std::move(open_result).error();
}
// Walk from the full path towards this directory (or the root) to find the
// first existing directory. This is faster than walking down as no file
// descriptors have to be allocated for any intervening directories, etc. We
// keep the path components that are missing as we pop them off for easy
// traversal back down.
std::optional<Dir> work_dir;
// Paths typically consist of relatively few components
// and so we can use a bit of stack and avoid allocating and moving the paths
// in common cases. We use `8` as an arbitrary but likely good for all of the
// hottest cases.
llvm::SmallVector<std::filesystem::path, 8> missing_components;
missing_components.push_back(path.filename());
for (std::filesystem::path parent_path = path.parent_path();
!parent_path.empty(); parent_path = parent_path.parent_path()) {
auto open_result = OpenDir(parent_path, OpenExisting);
if (open_result.ok()) {
work_dir = std::move(*open_result);
break;
}
missing_components.push_back(parent_path.filename());
}
CARBON_CHECK(!missing_components.empty());
// If we haven't yet opened an intermediate directory, start by creating one
// relative to this directory. We can't do this as part of the loop below as
// `this` and the newly opened directory have different types.
if (!work_dir) {
std::filesystem::path component = missing_components.pop_back_val();
CARBON_ASSIGN_OR_RETURN(
Dir component_dir,
OpenDir(component, CreationOptions::OpenAlways, creation_mode));
// Move this component into our temporary directory slot.
work_dir = std::move(component_dir);
}
// Now walk through the remaining components opening and creating each
// relative to the previous.
while (!missing_components.empty()) {
std::filesystem::path component = missing_components.pop_back_val();
CARBON_ASSIGN_OR_RETURN(
Dir component_dir,
work_dir->OpenDir(component, CreationOptions::OpenAlways,
creation_mode));
// Close the current temporary directory and move the new component
// directory object into its place.
work_dir = std::move(component_dir);
}
CARBON_CHECK(work_dir,
"Should always have created at least one directory for a "
"non-empty path!");
return std::move(work_dir).value();
}
auto DirRef::Rmtree(const std::filesystem::path& path)
-> ErrorOr<Success, PathError> {
struct DirAndIterator {
DirRef::Reader dir;
ssize_t dir_entry_start;
};
llvm::SmallVector<DirAndIterator> dir_stack;
llvm::SmallVector<std::filesystem::path> dir_entries;
llvm::SmallVector<std::filesystem::path> unknown_entries;
dir_entries.push_back(path);
for (;;) {
// When we bottom out, we're removing the initial tree path and doing so
// relative to `this` directory.
DirRef current = dir_stack.empty() ? *this : dir_stack.back().dir;
ssize_t dir_entry_start =
dir_stack.empty() ? 0 : dir_stack.back().dir_entry_start;
// If we've finished all the child directories of the current entry in the
// stack, pop it off and continue.
if (dir_entry_start == static_cast<ssize_t>(dir_entries.size())) {
dir_stack.pop_back();
continue;
}
CARBON_CHECK(dir_entry_start < static_cast<ssize_t>(dir_entries.size()));
// Take the last entry under the current directory and try removing it.
const std::filesystem::path& entry_path = dir_entries.back();
auto rmdir_result = current.Rmdir(entry_path);
if (rmdir_result.ok() || rmdir_result.error().no_entity()) {
// Removed here or elsewhere already, so pop the entry.
dir_entries.pop_back();
if (dir_entries.empty()) {
// The last entry is the input path with an empty stack, so we've
// finished at this point.
CARBON_CHECK(dir_stack.empty());
return Success();
}
continue;
}
// If we get any error other than not-empty, just return that.
if (!rmdir_result.error().not_empty()) {
return std::move(rmdir_result).error();
}
// Recurse into the subdirectory since it isn't empty, opening it, getting a
// reader, and pushing it onto our stack.
CARBON_ASSIGN_OR_RETURN(Dir subdir, current.OpenDir(entry_path));
auto read_result = std::move(subdir).TakeAndRead();
if (!read_result.ok()) {
return PathError(
read_result.error().unix_errnum(),
"Dir::Read on '{0}' relative to '{1}' during RmdirRecursively",
entry_path, current.dfd_);
}
dir_stack.push_back(
{*std::move(read_result), static_cast<ssize_t>(dir_entries.size())});
// Now read the directory entries. It would be nice to be able to directly
// remove the files and empty directories as we find them when reading, and
// the POSIX spec appears to require that to work, but testing shows at
// least some Linux environments don't work reliably in this case and will
// fail to visit some entries entirely. As a consequence, we walk the entire
// directory and collect the entries into data structures before beginning
// to remove them.
DirRef::Reader& subdir_reader = dir_stack.back().dir;
for (const auto& entry : subdir_reader) {
llvm::StringRef name = entry.name();
if (name == "." || name == "..") {
continue;
}
if (entry.is_known_dir()) {
dir_entries.push_back(name.str());
} else {
// We end up here for entries known to be regular files, other kinds of
// non-directory entries, or when the entry kind isn't known.
//
// Unless we *know* the entry is a directory, we put it into the unknown
// entries. For these, we unlink them first in case they are
// non-directory entries and use the failure of that to move any
// directories that end up here to the directory entries list.
unknown_entries.push_back(name.str());
}
}
// We can immediately try to unlink all the unknown entries, which will
// include any regular files, and use an error on directories that were
// unknown above to switch them to the `dir_entries` list.
while (!unknown_entries.empty()) {
std::filesystem::path name = unknown_entries.pop_back_val();
auto unlink_result = subdir_reader.Unlink(name);
if (unlink_result.ok() || unlink_result.error().no_entity()) {
continue;
} else if (!unlink_result.error().is_dir()) {
return std::move(unlink_result).error();
}
dir_entries.push_back(std::move(name));
}
// We'll handle the directory entries we've queued here in the next
// iteration, removing them or recursing as needed.
}
}
auto DirRef::ReadlinkSlow(const std::filesystem::path& path)
-> ErrorOr<std::string, PathError> {
constexpr ssize_t MinBufferSize =
#ifdef PATH_MAX
PATH_MAX
#else
1024
#endif
;
// Read directly into a string to avoid allocating two large buffers.
std::string large_buffer;
// Stat the symlink to get an initial guess at the size.
CARBON_ASSIGN_OR_RETURN(FileStatus status, Lstat(path));
// We try to use the size from the `lstat` unless it is empty, in which case
// we try to use our minimum buffer size which is `PATH_MAX` or a constant
// value. We have a fallback to dynamically discover an adequate buffer size
// below that will handle any inaccuracy.
ssize_t buffer_size = status.size();
if (buffer_size == 0) {
buffer_size = MinBufferSize;
}
large_buffer.resize(buffer_size);
ssize_t result =
readlinkat(dfd_, path.c_str(), large_buffer.data(), large_buffer.size());
if (result == -1) {
return PathError(errno, "Readlink on '{0}' relative to '{1}'", path, dfd_);
}
// Now the really bad fallback case: if there are racing writes to the
// symlink, the guessed size may not have been large enough. As a last-ditch
// effort, begin doubling (from the next power of two >= our min buffer size)
// the length until it fits. We cap this at 10 MiB to prevent egregious file
// system contents (or some bug somewhere) from exhausting memory.
constexpr ssize_t MaxBufferSize = 10 << 20;
while (result == static_cast<ssize_t>(large_buffer.size())) {
int64_t next_buffer_size = std::max<ssize_t>(
MinBufferSize, llvm::NextPowerOf2(large_buffer.size()));
if (next_buffer_size > MaxBufferSize) {
return PathError(ENOMEM, "Readlink on '{0}' relative to '{1}'", path,
dfd_);
}
large_buffer.resize(next_buffer_size);
result = readlinkat(dfd_, path.c_str(), large_buffer.data(),
large_buffer.size());
if (result == -1) {
return PathError(errno, "Readlink on '{0}' relative to '{1}'", path,
dfd_);
}
}
// Fix-up the size of the string and return it.
large_buffer.resize(result);
return large_buffer;
}
auto MakeTmpDir() -> ErrorOr<RemovingDir, Error> {
std::filesystem::path tmpdir_path = "/tmp";
// We use both `TEST_TMPDIR` and `TMPDIR`. The `TEST_TMPDIR` is set by Bazel
// and preferred to keep tests using the expected output tree rather than
// the system temporary directory.
for (const char* tmpdir_env_name : {"TEST_TMPDIR", "TMPDIR"}) {
const char* tmpdir_env_cstr = getenv(tmpdir_env_name);
if (tmpdir_env_cstr == nullptr) {
continue;
}
std::filesystem::path tmpdir_env = tmpdir_env_cstr;
tmpdir_path = std::move(tmpdir_env);
break;
}
std::filesystem::path target = BuildData::BuildTarget.str();
tmpdir_path /= target.filename();
return MakeTmpDirWithPrefix(std::move(tmpdir_path));
}
auto MakeTmpDirWithPrefix(std::filesystem::path prefix)
-> ErrorOr<RemovingDir, Error> {
std::filesystem::path tmpdir_path = std::move(prefix);
tmpdir_path += ".XXXXXX";
std::string tmpdir_path_buffer = tmpdir_path.native();
char* result = mkdtemp(tmpdir_path_buffer.data());
if (result == nullptr) {
RawStringOstream os;
os << llvm::formatv("Calling mkdtemp on '{0}' failed: ",
tmpdir_path.native());
PrintErrorNumber(os, errno);
return Error(os.TakeStr());
}
CARBON_CHECK(result == tmpdir_path_buffer.data(),
"`mkdtemp` used a modified path");
tmpdir_path = std::move(tmpdir_path_buffer);
// Because `mkdtemp` doesn't return an open directory atomically, open the
// created directory and perform safety checks similar to `OpenDir` when
// creating a new directory.
CARBON_ASSIGN_OR_RETURN(
Dir tmp, Cwd().OpenDir(tmpdir_path, OpenExisting, /*creation_mode=*/0,
OpenFlags::NoFollow));
// Make sure we try to remove the directory from here on out.
RemovingDir result_dir(std::move(tmp), tmpdir_path);
// It's a bit awkward to report `fstat` errors as `Error`s, but we
// don't have much choice. The stat failing here would be very weird.
CARBON_ASSIGN_OR_RETURN(FileStatus stat, result_dir.Stat());
// The permissions must be exactly 0700 for a temporary directory, and the UID
// should be ours.
if (stat.permissions() != 0700 && stat.unix_uid() != geteuid()) {
return Error(
llvm::formatv("Found incorrect permissions or UID on tmpdir '{0}'",
tmpdir_path.native())
.str());
}
return result_dir;
}
} // namespace Carbon::Filesystem
+1841
View File
File diff suppressed because it is too large Load Diff
+544
View File
@@ -0,0 +1,544 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <benchmark/benchmark.h>
#include <fstream>
#include <system_error>
#include "absl/random/random.h"
#include "common/filesystem.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/StringExtras.h"
namespace Carbon::Filesystem {
namespace {
// Alternative implementation strategies to allow comparing performance.
//
// WHen implementing benchmarks below, we try to make them templates on this
// enum and then switch in the body between different implementations. This
// allows us to share the framework of each benchmark but select different
// implementations for different instantiations. The different instantiations
// get these enumerators in their names in the output, so we keep them short.
enum BenchmarkComparables {
Carbon,
Std,
};
// Filler text.
constexpr llvm::StringLiteral Text =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim "
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea "
"commodo consequat. Duis aute irure dolor in reprehenderit in voluptate "
"velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint "
"occaecat cupidatat non proident, sunt in culpa qui officia deserunt "
"mollit anim id est laborum.";
// Gets the filler text repeated up to a specific length.
static auto GetText(int length) -> std::string {
std::string content;
content.reserve(length);
while (static_cast<int>(content.size()) < length) {
content += Text.substr(0, length - content.size());
}
CARBON_CHECK(static_cast<int>(content.size()) == length);
return content;
}
// We build a collection of file paths to use across different benchmarks in
// batches to avoid looking at the same file over and over again. We can even
// shuffle the file orders to further avoid hiding performance cost. If there
// are specific cases where we want to measure the cached / predicted speed, we
// can write those benchmarks against a specific file, but most often we instead
// look at the worst case scenario for wall-clock time and use cycle counters
// and instruction counters to measure aspects of the best case. The exact
// number here was chosen arbitrarily to not make running benchmarks excessively
// slow due to the large batches.
constexpr int NumFiles = 64;
// A common set of context used in benchmarks below. A separate context object
// works better than the benchmark fixture support in practice.
//
// This is a struct as there are no invariants or contracts enforced. This is
// just a container of commonly useful data and commonly useful helper
// functions.
struct BenchContext {
RemovingDir tmpdir;
absl::BitGen rng;
std::array<std::filesystem::path, NumFiles> file_paths;
std::array<std::filesystem::path, NumFiles> missing_paths;
BenchContext() : tmpdir(*MakeTmpDir()) {
for (int i : llvm::seq(NumFiles)) {
file_paths[i] = llvm::formatv("file_{0}", i).str();
auto result = tmpdir.WriteFileFromString(file_paths[i], Text);
CARBON_CHECK(result.ok(), "{0}", result.error());
missing_paths[i] = llvm::formatv("missing_{0}", i).str();
}
ShuffleFilePaths();
ShuffleMissingPaths();
}
auto ShuffleFilePaths() -> void {
std::shuffle(file_paths.begin(), file_paths.end(), rng);
}
auto ShuffleMissingPaths() -> void {
std::shuffle(missing_paths.begin(), missing_paths.end(), rng);
}
// Create a tree of files and directories starting from a `base` new directory
// in our tmp directory, and containing `entries` total entries with
// `entries_per_dir` in each directory. These will be a mixture of further
// subdirectories and files.
auto CreateTree(std::filesystem::path base, int entries, int entries_per_dir)
-> void {
CARBON_CHECK(entries >= 1);
CARBON_CHECK(entries_per_dir >= 1);
int num_subdirs = std::max<int>(entries_per_dir / 2, 1);
struct DirStackEntry {
Dir dir;
int num_entries;
int subdir_count;
};
llvm::SmallVector<DirStackEntry> dir_stack;
auto d = tmpdir.OpenDir(base, CreationOptions::CreateNew);
CARBON_CHECK(d.ok(), "{0}", d.error());
dir_stack.push_back({std::move(*d), entries, 0});
while (!dir_stack.empty()) {
auto& [dir, num_entries, subdir_count] = dir_stack.back();
// We want `num_entries` transitively in this directory, and
// `entries_per_dir` directly. Spread the remaining entries across
// `num_subdirs`.
int entries_per_subdir = ((num_entries - entries_per_dir) / num_subdirs);
CARBON_CHECK(entries_per_subdir < num_entries);
// While we'll still put entries in a subdirectory, and we still need more
// subdirectories in this directory, create another subdirectory, push it
// on the stack, and recurse to it by continuing.
if (entries_per_subdir >= entries_per_dir && subdir_count < num_subdirs) {
auto name = llvm::formatv("dir_{0}", subdir_count).str();
auto subdir = dir.OpenDir(name, CreationOptions::CreateNew);
CARBON_CHECK(subdir.ok(), "{0}", subdir.error());
++subdir_count;
// Note we have to continue after `push_back` as this will invalidate
// the current references.
dir_stack.push_back({std::move(*subdir), entries_per_subdir, 0});
continue;
}
// Otherwise, we're finished with subdirectories and just need to create
// direct files.
int num_files = entries_per_dir - subdir_count;
CARBON_CHECK(num_files >= 0);
for (int i = 0; i < num_files; ++i) {
auto name = llvm::formatv("file_{0}", i).str();
auto f = dir.OpenWriteOnly(name, CreationOptions::CreateNew);
CARBON_CHECK(f.ok(), "{0}", f.error());
auto close_result = std::move(*f).Close();
CARBON_CHECK(close_result.ok(), "{0}", close_result.error());
}
dir_stack.pop_back();
}
}
};
template <BenchmarkComparables Comp>
auto BM_Access(benchmark::State& state) -> void {
BenchContext context;
while (state.KeepRunningBatch(NumFiles)) {
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto result = context.tmpdir.Access(context.file_paths[i]);
CARBON_CHECK(result.ok(), "{0}", result.error());
} else if constexpr (Comp == Std) {
std::error_code ec;
bool exists = std::filesystem::exists(
context.tmpdir.path() / context.file_paths[i], ec);
CARBON_CHECK(!ec, "{0}", ec.message());
CARBON_CHECK(exists);
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_Access<Carbon>)->UseRealTime();
BENCHMARK(BM_Access<Std>)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_AccessMissing(benchmark::State& state) -> void {
BenchContext context;
while (state.KeepRunningBatch(NumFiles)) {
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto result = context.tmpdir.Access(context.missing_paths[i]);
CARBON_CHECK(result.error().no_entity());
} else if constexpr (Comp == Std) {
std::error_code ec;
auto exists = std::filesystem::exists(
context.tmpdir.path() / context.missing_paths[i], ec);
CARBON_CHECK(!ec, "{0}", ec.message());
CARBON_CHECK(!exists);
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_AccessMissing<Carbon>)->UseRealTime();
BENCHMARK(BM_AccessMissing<Std>)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_Stat(benchmark::State& state) -> void {
BenchContext context;
while (state.KeepRunningBatch(NumFiles)) {
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto status = context.tmpdir.Stat(context.file_paths[i]);
CARBON_CHECK(status.ok(), "{0}", status.error());
benchmark::DoNotOptimize(status->permissions());
} else if constexpr (Comp == Std) {
std::error_code ec;
auto status = std::filesystem::status(
context.tmpdir.path() / context.file_paths[i], ec);
CARBON_CHECK(!ec, "{0}", ec.message());
benchmark::DoNotOptimize(status.permissions());
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_Stat<Carbon>)->UseRealTime();
BENCHMARK(BM_Stat<Std>)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_StatMissing(benchmark::State& state) -> void {
BenchContext context;
while (state.KeepRunningBatch(NumFiles)) {
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto status = context.tmpdir.Stat(context.missing_paths[i]);
CARBON_CHECK(status.error().no_entity());
} else if constexpr (Comp == Std) {
std::error_code ec;
auto status = std::filesystem::status(
context.tmpdir.path() / context.missing_paths[i], ec);
CARBON_CHECK(ec.value() == ENOENT, "{0}", ec.message());
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_StatMissing<Carbon>)->UseRealTime();
BENCHMARK(BM_StatMissing<Std>)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_OpenMissing(benchmark::State& state) -> void {
BenchContext context;
while (state.KeepRunningBatch(NumFiles)) {
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto f = context.tmpdir.OpenReadOnly(context.missing_paths[i]);
CARBON_CHECK(f.error().no_entity());
} else if constexpr (Comp == Std) {
std::ifstream f(context.tmpdir.path() / context.missing_paths[i]);
CARBON_CHECK(!f.is_open());
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_OpenMissing<Carbon>)->UseRealTime();
BENCHMARK(BM_OpenMissing<Std>)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_OpenClose(benchmark::State& state) -> void {
BenchContext context;
while (state.KeepRunningBatch(NumFiles)) {
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto f = context.tmpdir.OpenReadOnly(context.file_paths[i]);
CARBON_CHECK(f.ok(), "{0}", f.error());
auto close_result = std::move(*f).Close();
CARBON_CHECK(close_result.ok(), "{0}", close_result.error());
} else if constexpr (Comp == Std) {
std::ifstream f(context.tmpdir.path() / context.file_paths[i]);
CARBON_CHECK(f.is_open());
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_OpenClose<Carbon>)->UseRealTime();
BENCHMARK(BM_OpenClose<Std>)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_CreateRemove(benchmark::State& state) -> void {
BenchContext context;
while (state.KeepRunningBatch(NumFiles)) {
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
// Create the file by opening it.
auto f = context.tmpdir.OpenWriteOnly(context.missing_paths[i],
CreationOptions::CreateNew);
CARBON_CHECK(f.ok(), "{0}", f.error());
// Close it right away.
auto close_result = std::move(*f).Close();
CARBON_CHECK(close_result.ok(), "{0}", close_result.error());
// Remove it.
auto remove_result = context.tmpdir.Unlink(context.missing_paths[i]);
CARBON_CHECK(remove_result.ok(), "{0}", remove_result.error());
} else if constexpr (Comp == Std) {
auto path = context.tmpdir.path() / context.missing_paths[i];
// Create the file by opening it.
std::ofstream f(path);
CARBON_CHECK(f.is_open());
// Close it right away.
f.close();
// Remove it.
std::error_code ec;
std::filesystem::remove(path, ec);
CARBON_CHECK(!ec, "{0}", ec.message());
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_CreateRemove<Carbon>)->UseRealTime();
BENCHMARK(BM_CreateRemove<Std>)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_Read(benchmark::State& state) -> void {
BenchContext context;
int length = state.range(0);
std::string content = GetText(length);
for (int i : llvm::seq(NumFiles)) {
auto result =
context.tmpdir.WriteFileFromString(context.file_paths[i], content);
CARBON_CHECK(result.ok(), "{0}", result.error());
}
while (state.KeepRunningBatch(NumFiles)) {
// Re-shuffle the order of the files for each batch to avoid exact cache
// hits.
state.PauseTiming();
context.ShuffleFilePaths();
state.ResumeTiming();
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto read_result =
context.tmpdir.ReadFileToString(context.file_paths[i]);
CARBON_CHECK(read_result.ok(), "{0}", read_result.error());
benchmark::DoNotOptimize(*read_result);
} else if constexpr (Comp == Std) {
std::ifstream f(context.tmpdir.path() / context.file_paths[i],
std::ios::binary);
CARBON_CHECK(f.is_open());
// This may be a somewhat surprising implementation, but benchmarking
// against several other ways of reading the file with `std::ifstream`
// all have the same or worse performance.
std::string read_content((std::istreambuf_iterator<char>(f)),
(std::istreambuf_iterator<char>()));
benchmark::DoNotOptimize(read_content);
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_Read<Carbon>)->Range(4, 1024LL * 1024)->UseRealTime();
BENCHMARK(BM_Read<Std>)->Range(4, 1024LL * 1024)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_Write(benchmark::State& state) -> void {
BenchContext context;
int length = state.range(0);
std::string content = GetText(length);
while (state.KeepRunningBatch(NumFiles)) {
// Re-shuffle the order of the files for each batch to avoid exact cache
// hits.
state.PauseTiming();
context.ShuffleFilePaths();
state.ResumeTiming();
for (int i : llvm::seq(NumFiles)) {
if constexpr (Comp == Carbon) {
auto write_result =
context.tmpdir.WriteFileFromString(context.file_paths[i], content);
CARBON_CHECK(write_result.ok(), "{0}", write_result.error());
} else if constexpr (Comp == Std) {
std::ofstream f(context.tmpdir.path() / context.file_paths[i],
std::ios::binary | std::ios::trunc);
CARBON_CHECK(f.is_open());
f.write(content.data(), content.length());
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_Write<Carbon>)->Range(4, 1024LL * 1024)->UseRealTime();
BENCHMARK(BM_Write<Std>)->Range(4, 1024LL * 1024)->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_Rmtree(benchmark::State& state) -> void {
BenchContext context;
int entries = state.range(0);
int depth = state.range(1);
// Configure our batch size based on the number of entries. Creating large
// numbers of entries in the filesystem can cause problems, and is also very
// slow. We don't need that much accuracy once the trees get large.
int batch_size = entries <= 1024 ? 10 : entries <= (32 * 1024) ? 5 : 1;
while (state.KeepRunningBatch(batch_size)) {
state.PauseTiming();
for (int i : llvm::seq(batch_size)) {
context.CreateTree(llvm::formatv("tree_{0}", i).str(), entries, depth);
}
state.ResumeTiming();
for (int i : llvm::seq(batch_size)) {
std::string tree = llvm::formatv("tree_{0}", i).str();
if constexpr (Comp == Carbon) {
auto rmdir_result = context.tmpdir.Rmtree(tree);
CARBON_CHECK(rmdir_result.ok(), "{0}", rmdir_result.error());
} else if constexpr (Comp == Std) {
std::error_code ec;
std::filesystem::remove_all(context.tmpdir.path() / tree, ec);
CARBON_CHECK(!ec, "{0}", ec.message());
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
}
}
BENCHMARK(BM_Rmtree<Carbon>)
->Ranges({{1, 256}, {1, 32}})
->Ranges({{2 * 1024, 256 * 1024}, {512, 1024}})
->Unit(benchmark::kMicrosecond)
->UseRealTime();
BENCHMARK(BM_Rmtree<Std>)
->Ranges({{1, 256}, {1, 32}})
->Ranges({{2 * 1024, 256 * 1024}, {512, 1024}})
->Unit(benchmark::kMicrosecond)
->UseRealTime();
template <BenchmarkComparables Comp>
auto BM_CreateDirectories(benchmark::State& state) -> void {
BenchContext context;
int depth = state.range(0);
int existing_depth = state.range(1);
CARBON_CHECK(existing_depth <= depth);
CARBON_CHECK(depth > 0);
// Use a batch size of 10 to get avoid completely swamping the measurements
// with overhead from creating existing directories and cleaning up.
constexpr int BatchSize = 10;
// Pre-build both the paths and the existing paths. Note that we use
// relatively short paths here, which if anything makes the benefits of the
// Carbon library smaller.
llvm::SmallVector<std::string> paths;
llvm::SmallVector<std::string> existing_paths;
for (int i : llvm::seq(BatchSize)) {
RawStringOstream path;
llvm::ListSeparator sep("/");
for (int j = 0; j < existing_depth; ++j) {
path << sep << "exists_" << (j == 0 ? i : j);
}
existing_paths.push_back(path.TakeStr());
path << existing_paths.back();
for (int k = existing_depth; k < depth; ++k) {
path << sep << "dir_" << (k == 0 ? i : k);
}
paths.push_back(path.TakeStr());
}
while (state.KeepRunningBatch(BatchSize)) {
state.PauseTiming();
for (int i : llvm::seq(BatchSize)) {
if (existing_depth > 0) {
auto result = context.tmpdir.CreateDirectories(existing_paths[i]);
CARBON_CHECK(result.ok(), "{0}", result.error());
}
}
state.ResumeTiming();
for (int i : llvm::seq(BatchSize)) {
if constexpr (Comp == Carbon) {
auto result = context.tmpdir.CreateDirectories(paths[i]);
CARBON_CHECK(result.ok(), "Failed to create '{0}': {1}", paths[i],
result.error());
// Create a file in the provided directory. This adds some baseline
// overhead but matches the realistic use case and ensures that there
// isn't some laziness that makes just creating a directory have an
// unusually low cost.
auto f = result->OpenWriteOnly("test", CreationOptions::CreateNew);
CARBON_CHECK(f.ok(), "{0}", f.error());
auto close_result = std::move(*f).Close();
CARBON_CHECK(close_result.ok(), "{0}", close_result.error());
} else if constexpr (Comp == Std) {
std::filesystem::path path = context.tmpdir.path() / paths[i];
std::error_code ec;
std::filesystem::create_directories(path, ec);
CARBON_CHECK(!ec, "{0}", ec.message());
// Create a file in the directory, similar to above. This has a (much)
// bigger effect though because the C++ APIs don't open the created
// directory, and so the creation cost of it can very much be hidden
// from the benchmark if we don't use it. This also lets us see the
// benefit of not needing to re-walk the path to create the file.
std::ofstream f(path / "test");
CARBON_CHECK(f.is_open());
f.close();
} else {
static_assert(false, "Invalid benchmark comparable");
}
}
state.PauseTiming();
for (int i : llvm::seq(BatchSize)) {
auto result = context.tmpdir.Rmtree(
llvm::formatv("{0}_{1}", existing_depth > 0 ? "exists" : "dir", i)
.str());
CARBON_CHECK(result.ok(), "{0}", result.error());
}
state.ResumeTiming();
}
}
static auto CreateDirectoriesBenchArgs(benchmark::Benchmark* b) {
// The first argument is the depth of directory to create. We mostly care
// about reasonably small depths here. It must be >= 1 for there to be
// something to benchmark. The second number is the depth of pre-existing
// directories which can vary from 0 to equal to the depth to benchmark the
// case of no new directory being needed.
for (int i = 1; i <= 8; i *= 2) {
b->Args({i, 0});
for (int j = 1; j <= i; j *= 2) {
b->Args({i, j});
}
}
}
BENCHMARK(BM_CreateDirectories<Carbon>)
->Apply(CreateDirectoriesBenchArgs)
->UseRealTime();
BENCHMARK(BM_CreateDirectories<Std>)
->Apply(CreateDirectoriesBenchArgs)
->UseRealTime();
} // namespace
} // namespace Carbon::Filesystem
+618
View File
@@ -0,0 +1,618 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "common/filesystem.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <concepts>
#include <string>
#include <thread>
#include <utility>
#include "common/error_test_helpers.h"
namespace Carbon::Filesystem {
namespace {
using ::testing::_;
using ::testing::Eq;
using ::testing::HasSubstr;
using Testing::IsError;
using Testing::IsSuccess;
using ::testing::UnorderedElementsAre;
class FilesystemTest : public ::testing::Test {
public:
explicit FilesystemTest() {
auto result = MakeTmpDir();
CARBON_CHECK(result.ok(), "{0}", result.error());
dir_ = std::move(*result);
}
~FilesystemTest() override {
auto result = std::move(dir_).Remove();
CARBON_CHECK(result.ok(), "{0}", result.error());
}
auto path() const -> const std::filesystem::path& { return dir_.path(); }
// The test's temp directory, deleted on destruction.
RemovingDir dir_;
};
TEST_F(FilesystemTest, CreateOpenCloseAndUnlink) {
auto unlink_result = dir_.Unlink("test");
ASSERT_FALSE(unlink_result.ok());
EXPECT_TRUE(unlink_result.error().no_entity());
#if defined(_GNU_SOURCE) && \
(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 32))
EXPECT_THAT(unlink_result, IsError(HasSubstr("ENOENT")));
#endif
EXPECT_THAT(unlink_result, IsError(HasSubstr("No such file")));
auto f = dir_.OpenWriteOnly("test", CreationOptions::CreateNew);
ASSERT_THAT(f, IsSuccess(_));
auto result = (*std::move(f)).Close();
EXPECT_THAT(result, IsSuccess(_));
f = dir_.OpenWriteOnly("test", CreationOptions::CreateNew);
ASSERT_FALSE(f.ok());
EXPECT_TRUE(f.error().already_exists());
#if defined(_GNU_SOURCE) && \
(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 32))
EXPECT_THAT(f, IsError(HasSubstr("EEXIST")));
#endif
EXPECT_THAT(f, IsError(HasSubstr("File exists")));
f = dir_.OpenWriteOnly("test");
ASSERT_THAT(f, IsSuccess(_));
result = std::move(*f).Close();
EXPECT_THAT(result, IsSuccess(_));
f = dir_.OpenWriteOnly("test");
ASSERT_THAT(f, IsSuccess(_));
result = std::move(*f).Close();
EXPECT_THAT(result, IsSuccess(_));
unlink_result = dir_.Unlink("test");
EXPECT_THAT(unlink_result, IsSuccess(_));
f = dir_.OpenWriteOnly("test");
EXPECT_FALSE(f.ok());
EXPECT_TRUE(f.error().no_entity());
#if defined(_GNU_SOURCE) && \
(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 32))
EXPECT_THAT(f, IsError(HasSubstr("ENOENT")));
#endif
EXPECT_THAT(f, IsError(HasSubstr("No such file")));
f = dir_.OpenWriteOnly("test", CreationOptions::OpenAlways);
ASSERT_THAT(f, IsSuccess(_));
result = std::move(*f).Close();
EXPECT_THAT(result, IsSuccess(_));
unlink_result = dir_.Unlink("test");
EXPECT_THAT(unlink_result, IsSuccess(_));
}
TEST_F(FilesystemTest, BasicWriteAndRead) {
std::string content_str = "0123456789";
{
auto f = dir_.OpenWriteOnly("test", CreationOptions::CreateNew);
ASSERT_THAT(f, IsSuccess(_));
auto write_result = f->WriteFileFromString(content_str);
EXPECT_THAT(write_result, IsSuccess(_));
(*std::move(f)).Close().Check();
}
{
auto f = dir_.OpenReadOnly("test");
ASSERT_THAT(f, IsSuccess(_));
auto read_result = f->ReadFileToString();
EXPECT_THAT(read_result, IsSuccess(Eq(content_str)));
}
auto unlink_result = dir_.Unlink("test");
EXPECT_THAT(unlink_result, IsSuccess(_));
}
TEST_F(FilesystemTest, SeekReadAndWrite) {
std::string content_str = "0123456789";
// First write some initial content.
{
auto f = dir_.OpenWriteOnly("test", CreationOptions::CreateNew);
ASSERT_THAT(f, IsSuccess(_));
auto write_result = f->WriteFileFromString(content_str);
EXPECT_THAT(write_result, IsSuccess(_));
(*std::move(f)).Close().Check();
}
// Now seek and read.
{
auto f = dir_.OpenReadOnly("test");
ASSERT_THAT(f, IsSuccess(_));
auto seek_result = f->Seek(3);
ASSERT_THAT(seek_result, IsSuccess(Eq(3)));
std::array<std::byte, 4> buffer;
auto read_result = f->ReadToBuffer(buffer);
ASSERT_THAT(read_result, IsSuccess(_));
EXPECT_THAT(std::string(reinterpret_cast<char*>(read_result->data()),
read_result->size()),
Eq(content_str.substr(3, read_result->size())));
// Now test that we can seek back to the beginning and read the full file.
auto read_file_result = f->ReadFileToString();
EXPECT_THAT(read_file_result, IsSuccess(Eq(content_str)));
}
// Now a mixture of reads, writes, an seeking.
{
auto f = dir_.OpenReadWrite("test");
ASSERT_THAT(f, IsSuccess(_));
auto seek_result = f->SeekFromEnd(-6);
ASSERT_THAT(seek_result, IsSuccess(Eq(content_str.size() - 6)));
std::string new_content_str = "abcdefg";
llvm::ArrayRef<std::byte> new_content_bytes(
reinterpret_cast<std::byte*>(new_content_str.data()),
new_content_str.size());
for (auto write_bytes = new_content_bytes.slice(0, 4);
!write_bytes.empty();) {
auto write_result = f->WriteFromBuffer(write_bytes);
ASSERT_THAT(write_result, IsSuccess(_));
write_bytes = *write_result;
}
std::array<std::byte, 4> buffer;
auto read_result = f->ReadToBuffer(buffer);
ASSERT_THAT(read_result, IsSuccess(_));
EXPECT_THAT(std::string(reinterpret_cast<char*>(read_result->data()),
read_result->size()),
Eq(content_str.substr(8, read_result->size())));
EXPECT_THAT(*f->ReadFileToString(), "0123abcd89");
// Now write the entire file, also changing its size, after a fresh seek.
seek_result = f->Seek(-6);
ASSERT_THAT(seek_result, IsSuccess(Eq(content_str.size() - 6)));
auto write_file_result = f->WriteFileFromString(new_content_str);
EXPECT_THAT(write_file_result, IsSuccess(_));
EXPECT_THAT(*f->ReadFileToString(), "abcdefg");
(*std::move(f)).Close().Check();
}
auto unlink_result = dir_.Unlink("test");
EXPECT_THAT(unlink_result, IsSuccess(_));
}
TEST_F(FilesystemTest, CreateAndRemoveDirecotries) {
auto d1 = Cwd().CreateDirectories(path() / "a" / "b" / "c" / "test1");
ASSERT_THAT(d1, IsSuccess(_));
auto d2 = Cwd().CreateDirectories(path() / "a" / "b" / "c" / "test2");
ASSERT_THAT(d2, IsSuccess(_));
auto d3 = Cwd().CreateDirectories(path() / "a" / "b" / "c" / "test3");
ASSERT_THAT(d3, IsSuccess(_));
// Get a directory object to use, this shouldn't cover much new.
auto d4 = Cwd().CreateDirectories(path());
EXPECT_THAT(d4, IsSuccess(_));
// Single, present, relative component.
auto d5 = d4->CreateDirectories("a");
EXPECT_THAT(d5, IsSuccess(_));
// Multiple, present, but relative components.
auto d6 = d5->CreateDirectories(std::filesystem::path("b") / "c");
EXPECT_THAT(d6, IsSuccess(_));
// Single new component.
auto d7 = d6->CreateDirectories("test4");
ASSERT_THAT(d7, IsSuccess(_));
// Two new relative components.
auto d8 = d6->CreateDirectories(std::filesystem::path("test5") / "d");
EXPECT_THAT(d8, IsSuccess(_));
// Mixed relative components.
auto d9 = d5->CreateDirectories(std::filesystem::path("b") / "test6");
EXPECT_THAT(d9, IsSuccess(_));
{
auto f1 = d1->OpenWriteOnly("file1", CreateNew);
ASSERT_THAT(f1, IsSuccess(_));
auto f2 = d2->OpenWriteOnly("file2", CreateNew);
ASSERT_THAT(f2, IsSuccess(_));
auto f3 = d3->OpenWriteOnly("file3", CreateNew);
ASSERT_THAT(f3, IsSuccess(_));
auto f4 = d7->OpenWriteOnly("file4", CreateNew);
ASSERT_THAT(f4, IsSuccess(_));
(*std::move(f1)).Close().Check();
(*std::move(f2)).Close().Check();
(*std::move(f3)).Close().Check();
(*std::move(f4)).Close().Check();
}
auto rm_result = Cwd().Rmtree(path() / "a");
ASSERT_THAT(rm_result, IsSuccess(_));
}
TEST_F(FilesystemTest, StatAndAccess) {
auto access_result = dir_.Access("test");
ASSERT_FALSE(access_result.ok());
EXPECT_TRUE(access_result.error().no_entity());
// Make sure the flags and bit-or-ing them works in the boring case.
access_result =
dir_.Access("test", AccessCheckFlags::Read | AccessCheckFlags::Write |
AccessCheckFlags::Execute);
ASSERT_FALSE(access_result.ok());
EXPECT_TRUE(access_result.error().no_entity());
auto stat_result = dir_.Stat("test");
ASSERT_FALSE(access_result.ok());
EXPECT_TRUE(access_result.error().no_entity());
// Create a file for testing, using very unusual and minimal permissions to
// help us test. Hopefully this isn't modified on the usual `umask` tests run
// under.
std::string content_str = "0123456789";
ModeType permissions = 0450;
auto f = dir_.OpenWriteOnly("test", CreationOptions::CreateNew, permissions);
ASSERT_THAT(f, IsSuccess(_));
auto write_result = f->WriteFileFromString(content_str);
EXPECT_THAT(write_result, IsSuccess(_));
access_result = dir_.Access("test");
EXPECT_THAT(access_result, IsSuccess(_));
access_result = dir_.Access("test", AccessCheckFlags::Read);
EXPECT_THAT(access_result, IsSuccess(_));
// Neither write nor execute permission should be present though.
access_result = dir_.Access("test", AccessCheckFlags::Write);
ASSERT_FALSE(access_result.ok());
EXPECT_TRUE(access_result.error().access_denied());
access_result =
dir_.Access("test", AccessCheckFlags::Read | AccessCheckFlags::Write |
AccessCheckFlags::Execute);
ASSERT_FALSE(access_result.ok());
EXPECT_TRUE(access_result.error().access_denied());
stat_result = dir_.Stat("test");
ASSERT_THAT(stat_result, IsSuccess(_));
EXPECT_TRUE(stat_result->is_file());
EXPECT_FALSE(stat_result->is_dir());
EXPECT_FALSE(stat_result->is_symlink());
EXPECT_THAT(stat_result->size(), Eq(content_str.size()));
EXPECT_THAT(stat_result->permissions(), Eq(permissions));
// Directory instead of file.
access_result =
dir_.Access(".", AccessCheckFlags::Read | AccessCheckFlags::Write |
AccessCheckFlags::Execute);
EXPECT_THAT(access_result, IsSuccess(_));
stat_result = dir_.Stat(".");
ASSERT_THAT(stat_result, IsSuccess(_));
EXPECT_FALSE(stat_result->is_file());
EXPECT_TRUE(stat_result->is_dir());
EXPECT_FALSE(stat_result->is_symlink());
// Can remove file but still stat through the file.
auto unlink_result = dir_.Unlink("test");
ASSERT_THAT(unlink_result, IsSuccess(_));
auto file_stat_result = f->Stat();
ASSERT_THAT(file_stat_result, IsSuccess(_));
EXPECT_TRUE(file_stat_result->is_file());
EXPECT_FALSE(file_stat_result->is_dir());
EXPECT_FALSE(file_stat_result->is_symlink());
EXPECT_THAT(file_stat_result->size(), Eq(content_str.size()));
EXPECT_THAT(file_stat_result->permissions(), Eq(permissions));
(*std::move(f)).Close().Check();
}
TEST_F(FilesystemTest, Symlinks) {
auto readlink_result = dir_.Readlink("test");
ASSERT_FALSE(readlink_result.ok());
EXPECT_TRUE(readlink_result.error().no_entity());
auto lstat_result = dir_.Lstat("test");
ASSERT_FALSE(lstat_result.ok());
EXPECT_TRUE(lstat_result.error().no_entity());
auto symlink_result = dir_.Symlink("test", "abc");
EXPECT_THAT(symlink_result, IsSuccess(_));
readlink_result = dir_.Readlink("test");
EXPECT_THAT(readlink_result, IsSuccess(Eq("abc")));
symlink_result = dir_.Symlink("test", "def");
ASSERT_FALSE(symlink_result.ok());
EXPECT_TRUE(symlink_result.error().already_exists());
lstat_result = dir_.Lstat("test");
ASSERT_THAT(lstat_result, IsSuccess(_));
EXPECT_FALSE(lstat_result->is_file());
EXPECT_FALSE(lstat_result->is_dir());
EXPECT_TRUE(lstat_result->is_symlink());
EXPECT_THAT(lstat_result->size(), Eq(strlen("abc")));
auto unlink_result = dir_.Unlink("test");
EXPECT_THAT(unlink_result, IsSuccess(_));
readlink_result = dir_.Readlink("test");
ASSERT_FALSE(readlink_result.ok());
EXPECT_TRUE(readlink_result.error().no_entity());
// Try a symlink with null bytes for fun. This demonstrates that the symlink
// syscall only uses the leading C-string.
symlink_result = dir_.Symlink("test", std::string("a\0b\0c", 5));
EXPECT_THAT(symlink_result, IsSuccess(_));
readlink_result = dir_.Readlink("test");
EXPECT_THAT(readlink_result, IsSuccess(Eq("a")));
}
TEST_F(FilesystemTest, Chdir) {
auto current_result = Cwd().OpenDir(".");
ASSERT_THAT(current_result, IsSuccess(_));
auto symlink_result = dir_.Symlink("test", "abc");
EXPECT_THAT(symlink_result, IsSuccess(_));
auto chdir_result = dir_.Chdir();
EXPECT_THAT(chdir_result, IsSuccess(_));
auto readlink_result = Cwd().Readlink("test");
EXPECT_THAT(readlink_result, IsSuccess(Eq("abc")));
auto chdir_path_result = dir_.Chdir("missing");
ASSERT_FALSE(chdir_path_result.ok());
EXPECT_TRUE(chdir_path_result.error().no_entity());
// Dangling symlink.
chdir_path_result = dir_.Chdir("test");
ASSERT_FALSE(chdir_path_result.ok());
EXPECT_TRUE(chdir_path_result.error().no_entity());
// Create a regular file and try to chdir to that.
auto f = dir_.OpenWriteOnly("test2", CreationOptions::CreateNew);
ASSERT_THAT(f, IsSuccess(_));
auto write_result = f->WriteFileFromString("test2");
EXPECT_THAT(write_result, IsSuccess(_));
chdir_path_result = dir_.Chdir("test2");
ASSERT_FALSE(chdir_path_result.ok());
EXPECT_TRUE(chdir_path_result.error().not_dir());
auto d2_result = Cwd().OpenDir("test_d2", CreationOptions::CreateNew);
ASSERT_THAT(d2_result, IsSuccess(_));
symlink_result = d2_result->Symlink("test2", "def");
EXPECT_THAT(symlink_result, IsSuccess(_));
chdir_path_result = dir_.Chdir("test_d2");
ASSERT_THAT(chdir_path_result, IsSuccess(_));
readlink_result = Cwd().Readlink("test2");
EXPECT_THAT(readlink_result, IsSuccess(Eq("def")));
readlink_result = Cwd().Readlink("../test");
EXPECT_THAT(readlink_result, IsSuccess(Eq("abc")));
chdir_result = current_result->Chdir();
ASSERT_THAT(chdir_result, IsSuccess(_));
readlink_result = Cwd().Readlink("test");
ASSERT_FALSE(readlink_result.ok());
EXPECT_TRUE(readlink_result.error().no_entity());
(*std::move(f)).Close().Check();
}
TEST_F(FilesystemTest, WriteStream) {
std::string content_str = "0123456789";
auto write = dir_.OpenWriteOnly("test", CreationOptions::CreateNew);
ASSERT_THAT(write, IsSuccess(_));
{
llvm::raw_fd_ostream os = write->WriteStream();
os << content_str;
EXPECT_FALSE(os.has_error()) << os.error();
}
(*std::move(write)).Close().Check();
EXPECT_THAT(dir_.ReadFileToString("test"), IsSuccess(Eq(content_str)));
}
TEST_F(FilesystemTest, Rename) {
// Rename a file within a directory.
ASSERT_THAT(dir_.WriteFileFromString("file1", "content1"), IsSuccess(_));
EXPECT_THAT(dir_.Rename("file1", dir_, "file2"), IsSuccess(_));
EXPECT_THAT(dir_.ReadFileToString("file2"), IsSuccess(Eq("content1")));
auto read_missing = dir_.ReadFileToString("file1");
EXPECT_FALSE(read_missing.ok());
EXPECT_TRUE(read_missing.error().no_entity());
// Rename a file between two directories.
auto d1 = *dir_.CreateDirectories("subdir1");
EXPECT_THAT(dir_.Rename("file2", d1, "file1"), IsSuccess(_));
EXPECT_THAT(d1.ReadFileToString("file1"), IsSuccess(Eq("content1")));
auto d2 = *dir_.CreateDirectories("subdir2");
EXPECT_THAT(d1.Rename("file1", d2, "file1"), IsSuccess(_));
EXPECT_THAT(d2.ReadFileToString("file1"), IsSuccess(Eq("content1")));
// Close the first directory.
d1 = Filesystem::Dir();
EXPECT_THAT(dir_.Rmdir("subdir1"), IsSuccess(_))
<< "Directory should have bene empty!";
// Rename directories.
ASSERT_THAT(dir_.ReadFileToString(std::filesystem::path("subdir2") / "file1"),
IsSuccess(Eq("content1")));
EXPECT_THAT(dir_.Rename("subdir2", dir_, "subdir1"), IsSuccess(_));
EXPECT_THAT(dir_.ReadFileToString(std::filesystem::path("subdir1") / "file1"),
IsSuccess(Eq("content1")));
// The open directory `d2` should survive the rename and point at the same
// directory.
EXPECT_THAT(d2.ReadFileToString("file1"), IsSuccess(Eq("content1")));
EXPECT_THAT(d2.WriteFileFromString("file2", "content2"), IsSuccess(_));
EXPECT_THAT(dir_.ReadFileToString(std::filesystem::path("subdir1") / "file2"),
IsSuccess(Eq("content2")));
// Rename over an existing file.
EXPECT_THAT(d2.Rename("file2", d2, "file1"), IsSuccess(_));
EXPECT_THAT(d2.ReadFileToString("file1"), IsSuccess(Eq("content2")));
// Test error calls as well.
auto result = dir_.Rename("missing1", dir_, "missing2");
EXPECT_TRUE(result.error().no_entity()) << result.error();
result = d2.Rename("file1", dir_,
std::filesystem::path("missing_subdir") / "file2");
EXPECT_TRUE(result.error().no_entity()) << result.error();
// Note that `d2` was renamed `subdir1` above, which is why this creates
// infinite subdirectories.
result = dir_.Rename("subdir1", d2, "infinite_subdirs");
EXPECT_THAT(result.error().unix_errnum(), EINVAL) << result.error();
}
TEST_F(FilesystemTest, TryLock) {
auto file = dir_.OpenReadWrite("test_file", CreateNew);
ASSERT_THAT(file, IsSuccess(_));
// Acquire an exclusive lock.
auto lock = file->TryLock(FileLock::Exclusive);
ASSERT_THAT(lock, IsSuccess(_));
EXPECT_TRUE(lock->is_locked());
// Try to acquire a second lock from a different file object.
auto file2 = dir_.OpenReadOnly("test_file");
ASSERT_THAT(file2, IsSuccess(_));
auto lock2 = file2->TryLock(FileLock::Exclusive);
ASSERT_THAT(lock2, IsError(_));
EXPECT_TRUE(lock2.error().would_block());
// A shared lock should also fail.
auto lock3 = file2->TryLock(FileLock::Shared);
ASSERT_THAT(lock3, IsError(_));
EXPECT_TRUE(lock3.error().would_block());
// Release the first lock.
*lock = {};
EXPECT_FALSE(lock->is_locked());
// Now we can acquire an exclusive lock.
lock2 = file2->TryLock(FileLock::Exclusive);
ASSERT_THAT(lock2, IsSuccess(_));
EXPECT_TRUE(lock2->is_locked());
*lock2 = {};
// Test shared locks.
auto shared_lock1 = file->TryLock(FileLock::Shared);
ASSERT_THAT(shared_lock1, IsSuccess(_));
EXPECT_TRUE(shared_lock1->is_locked());
auto shared_lock2 = file2->TryLock(FileLock::Shared);
ASSERT_THAT(shared_lock2, IsSuccess(_));
EXPECT_TRUE(shared_lock2->is_locked());
// An exclusive lock should fail.
auto file3 = dir_.OpenReadOnly("test_file");
ASSERT_THAT(file3, IsSuccess(_));
auto exclusive_lock = file3->TryLock(FileLock::Exclusive);
ASSERT_THAT(exclusive_lock, IsError(_));
EXPECT_TRUE(exclusive_lock.error().would_block());
// Release locks and close files.
*shared_lock1 = {};
*shared_lock2 = {};
ASSERT_THAT((*std::move(file)).Close(), IsSuccess(_));
ASSERT_THAT((*std::move(file2)).Close(), IsSuccess(_));
ASSERT_THAT((*std::move(file3)).Close(), IsSuccess(_));
}
TEST_F(FilesystemTest, ReadAndAppendEntries) {
// Test with an empty directory.
{
auto entries = dir_.ReadEntries();
ASSERT_THAT(entries, IsSuccess(_));
EXPECT_TRUE(entries->empty());
}
{
llvm::SmallVector<std::filesystem::path> entries;
EXPECT_THAT(dir_.AppendEntriesIf(entries), IsSuccess(_));
EXPECT_TRUE(entries.empty());
}
// Create some files and directories.
ASSERT_THAT(dir_.WriteFileFromString("file1", ""), IsSuccess(_));
ASSERT_THAT(dir_.WriteFileFromString("file2", ""), IsSuccess(_));
ASSERT_THAT(dir_.WriteFileFromString(".hidden", ""), IsSuccess(_));
ASSERT_THAT(dir_.CreateDirectories("subdir1"), IsSuccess(_));
ASSERT_THAT(dir_.CreateDirectories("subdir2"), IsSuccess(_));
// Test ReadEntries.
{
auto entries = dir_.ReadEntries();
ASSERT_THAT(entries, IsSuccess(_));
EXPECT_THAT(*entries, UnorderedElementsAre(".hidden", "file1", "file2",
"subdir1", "subdir2"));
}
// Test AppendEntriesIf with no predicate.
{
llvm::SmallVector<std::filesystem::path> entries;
EXPECT_THAT(dir_.AppendEntriesIf(entries), IsSuccess(_));
EXPECT_THAT(entries, UnorderedElementsAre(".hidden", "file1", "file2",
"subdir1", "subdir2"));
}
// Test AppendEntriesIf with a predicate.
{
llvm::SmallVector<std::filesystem::path> entries;
auto result = dir_.AppendEntriesIf(
entries, [](llvm::StringRef name) { return name.starts_with("file"); });
EXPECT_THAT(result, IsSuccess(_));
EXPECT_THAT(entries, UnorderedElementsAre("file1", "file2"));
}
// Test AppendEntriesIf with directory splitting and a predicate.
{
llvm::SmallVector<std::filesystem::path> dir_entries;
llvm::SmallVector<std::filesystem::path> non_dir_entries;
auto result = dir_.AppendEntriesIf(
dir_entries, non_dir_entries,
[](llvm::StringRef name) { return !name.starts_with("."); });
EXPECT_THAT(result, IsSuccess(_));
EXPECT_THAT(dir_entries, UnorderedElementsAre("subdir1", "subdir2"));
EXPECT_THAT(non_dir_entries, UnorderedElementsAre("file1", "file2"));
}
}
TEST_F(FilesystemTest, MtimeAndUpdateTimes) {
// Test UpdateTimes on a path that doesn't exist.
auto update_missing = dir_.UpdateTimes("test_file");
ASSERT_THAT(update_missing, IsError(_));
EXPECT_TRUE(update_missing.error().no_entity());
// Create a file and get its initial modification time.
ASSERT_THAT(dir_.WriteFileFromString("test_file", "content"), IsSuccess(_));
auto stat = dir_.Stat("test_file");
ASSERT_THAT(stat, IsSuccess(_));
auto time1 = stat->mtime();
// Repeated stats have stable time.
stat = dir_.Stat("test_file");
ASSERT_THAT(stat, IsSuccess(_));
EXPECT_THAT(stat->mtime(), Eq(time1));
// Update the timestamp to a specific time in the past.
auto past_time = time1 - std::chrono::seconds(120);
ASSERT_THAT(dir_.UpdateTimes("test_file", past_time), IsSuccess(_));
stat = dir_.Stat("test_file");
ASSERT_THAT(stat, IsSuccess(_));
EXPECT_THAT(stat->mtime(), Eq(past_time));
// Now test updating times on an open file. Should still be at `past_time`.
auto file = *dir_.OpenReadWrite("test_file");
auto file_stat = file.Stat();
ASSERT_THAT(file_stat, IsSuccess(_));
EXPECT_THAT(file_stat->mtime(), Eq(past_time));
// Update the times through the file and verify those updates arrived.
ASSERT_THAT(file.UpdateTimes(time1), IsSuccess(_));
file_stat = file.Stat();
ASSERT_THAT(file_stat, IsSuccess(_));
EXPECT_THAT(file_stat->mtime(), Eq(time1));
ASSERT_THAT(std::move(file).Close(), IsSuccess(_));
}
} // namespace
} // namespace Carbon::Filesystem
+1 -1
View File
@@ -450,7 +450,7 @@ class Hasher {
// both more often and have a larger impact relative to the number of keys
// than the rare cases where some combinations of pointer seeds and pointer
// keys create minor quality issues with the constant we use.
static constexpr uint64_t MulConstant = 0x7924'f9e0'de1e'8cf5U;
static constexpr uint64_t MulConstant = 0x79d5'f9e0'de1e'8cf5U;
private:
uint64_t buffer;
+37 -7
View File
@@ -18,17 +18,18 @@ namespace Carbon {
//
// This provides a hashtable-specific extension point to implement equality
// comparison within a hashtable key context. By default, it will use
// `operator==` on the LHS and RHS operands. However, types can provide a
// dedicated customization point by implementing a free function that can be
// found by ADL for your type called `CarbonHashtableEq` with the following
// signature:
// `operator==` on the LHS and RHS operands if they are of the identical type.
// However, types can provide a dedicated customization point by implementing a
// free function that can be found by ADL for your type called
// `CarbonHashtableEq` with the following signature:
//
// ```cpp
// auto CarbonHashtableEq(const YourType& lhs, const YourType& rhs) -> bool;
// ```
//
// Any such overload will be able to override the default we provide for types
// that can compare with `==`.
// that can compare with `==`. This overload may only compare two objects equal
// if the hash of those two objects are identical.
//
// This library also provides any customization points for LLVM or standard
// library types either lacking `operator==` or where that operator is not
@@ -161,8 +162,37 @@ inline auto CarbonHashtableEq(const llvm::APFloat& lhs,
return lhs.bitwiseIsEqual(rhs);
}
template <typename LeftT, typename RightT>
inline auto CarbonHashtableEq(const LeftT& lhs, const RightT& rhs) -> bool
inline auto CarbonHashtableEq(llvm::StringRef lhs, const std::string& rhs)
-> bool {
return lhs == rhs;
}
template <typename T>
inline auto CarbonHashtableEq(llvm::MutableArrayRef<T> lhs,
llvm::ArrayRef<T> rhs) -> bool {
return lhs == rhs;
}
template <typename LHS, typename RHS>
inline auto CarbonHashtableEq(const LHS& lhs, const RHS& rhs) -> bool
requires(requires {
{ CarbonHashtableEq(rhs, lhs) } -> std::convertible_to<bool>;
})
{
return CarbonHashtableEq(rhs, lhs);
}
// Provides symmetric equality so the `CarbonHashtableEq` operands aren't
// ordered.
//
// If this template proves problematic in any way, we can revisit it - the
// `CarbonHashtableEq` functions don't really need to be symmetric, since they
// generally represent an implicit conversion which is often only one-way (eg:
// MutableArrayRef converts to ArrayRef, but not the other way around) - but
// documenting/describing that asymmetry felt a little awkward too - so maybe
// this template is an OK solution for now.
template <typename T>
inline auto CarbonHashtableEq(const T& lhs, const T& rhs) -> bool
requires(requires {
{ lhs == rhs } -> std::convertible_to<bool>;
})
+60
View File
@@ -0,0 +1,60 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "common/latch.h"
#include "common/check.h"
namespace Carbon {
auto Latch::Inc() -> void {
// The increment must be _atomic_ but is _relaxed_.
//
// Increments and decrements can happen concurrently on separate threads, so
// we need to prevent tearing and for there to be a total ordering of stores
// to this atomic.
//
// However we provide no _synchronization_ of the increment with any other
// operations. Instead, the caller must provide some extrinsic happens-before
// between its call to `Inc` and its later call to `Dec`. When that call to
// `Dec` synchronizes-with another call to `Dec`, all relaxed stores are
// covered by the resulting inter-thread happens-before relationship.
count_.fetch_add(1, std::memory_order_relaxed);
}
auto Latch::Dec() -> bool {
// The decrement is both an _acquire_ and _release_ operation.
//
// All threads which decrement to a non-zero value need to synchronize-with
// the thread which decrements to a zero value. This means the decrements to
// non-zero values need to have _release_ semantics that are _acquired_ by the
// decrement to zero. Since there is a single decrement operation, it must be
// both _acquire_ and _release_.
//
// Note that this technically provides a stronger guarantee than the contract
// of `Dec` requires -- *all* decrements synchronize with all decrements whose
// value they observe, we only need that to be true of the decrement arriving
// at zero. This could in theory be modeled by conditional fences, but those
// have their own problems and we don't need to model the more precise
// semantics for efficiency.
auto previous = count_.fetch_sub(1, std::memory_order_acq_rel);
CARBON_CHECK(previous > 0);
if (previous == 1) {
// Ensure that our closure is fully destroyed here, releasing any
// resources, locks, or other synchronization primitives.
auto on_zero = std::exchange(on_zero_, [] {});
std::move(on_zero)();
return true;
}
return false;
}
auto Latch::Init(llvm::unique_function<auto()->void> on_zero) -> Handle {
CARBON_CHECK(count_ == 0);
on_zero_ = std::move(on_zero);
return Handle(this);
}
} // namespace Carbon

Some files were not shown because too many files have changed in this diff Show More