Compare commits

...
Author SHA1 Message Date
Chandler Carruth 08a11ff3ef Avoid passing -unwindlib on macOS where it isn't needed (#7825)
Removes some warnings from our links on macs when the flag is ignored.
2026-09-24 13:51:02 +00:00
Christopher Di Bella f7cd39428e Add Destroy.SubobjectDestroy as a temporary replacement for Destroy.Op (#7773)
This change partially implements [PR #7362], which revises how objects
are destroyed. It is a partial implementation for two reasons:

1. This change moves `Destroy.Op`'s current behaviour into
`Destroy.SubobjectDestroy`, but it doesn't add support for objects with
non-trivial destruction.
2. `Destroy.SubobjectDestroy` is a workaround for `require impls
SubobjectDestroy`. We aren't able to use the latter until the dependents
add their requirements' implementations to their own witness tables.

[PR #7362]: https://github.com/carbon-language/carbon-lang/pulls/7362
2026-09-24 00:06:28 +00:00
Richard Smith 03939a9223 Add language server support for SemIR in testdata. (#7803)
Add hover cards and jump to declaration / definition / reference for the
formatted SemIR that appears in check tests. This is done by adding a
heuristic "parser" for SemIR to the language server. The
cross-references are strictly best-effort, since this is just a tool for
Carbon developers, not a user-facing facility.

A couple of other changes made along the way:

* file_test tests with an AUTOUPDATE-SPLIT no longer look for CHECK:
lines outside that split. This was motivated by the tests for this new
facility including CHECK: lines as part of the test input.
* An agent skill for working on the language server, tracking some
things that cost Claude time when working on this.

Assisted-by: Claude via Antigravity
2026-09-23 23:44:32 +00:00
Chandler Carruth 652e0ce7d0 Fix the jj_push.sh script to work on macOS (#7820)
It had a few subtle GNU extensions in it that didn't work on macOS.
There are simple portable alternatives so it was easy to adapt.

Assisted-by: Antigravity with Gemini
2026-09-23 22:47:02 +00:00
Dana Jansens c832d7c11c Skill file for reviewing filetest output changes (#7815)
When an LLM tool is used to prototype a change, one of the major tasks
it must undertake is validating filetest output changes. This skill
helps to ground that validation in some best practices and explain what
sorts of changes should or should not be expected, and how to judge
STDOUT vs STDERR changes.

Assisted-by: Opus 5
2026-09-23 19:18:59 +00:00
Dana Jansens 15e3eeaca9 Only look in facet types for name scopes when they have constraints (#7819)
This falls back to diagnosing that values of type `type` can not be used
for name lookup more consistently.
2026-09-23 17:50:34 +00:00
Richard Smith efbe1d2489 Add default fns and final fns to the eval block for a generic impl (#7817)
When a generic impl uses a default or final fn, it picks the specific
function value out of the interface to put in the witness table.
However, because this is done by modifying an existing instruction
block, the generics machinery has no hook to convert the function
constant into an attached constant, and because it was found in a
specific for a different generic, the constant inst will be unattached.
Fix this by manually mapping to an attached constant inst in the current
generic when building the witness table.
2026-09-23 01:19:28 +00:00
Lucile Rose Nihlen 53b7cfbaba Add basic caller-side support for default values in check (#7800)
Modifies the arity check to include a lower-bound for arguments.
Adds logic to pattern matching to supply default arguments for
missing parameters.
2026-09-22 22:07:35 +00:00
Dana Jansens 795729bb4a Fix git path globs in summarize testdata changes SKILL (#7818)
When there's a wildcard in a path, git treats the path as matching
exactly, unless the path also ends in a wildcard. So
`toolchain/*/testdata` only matches the testdata directory names,
whereas `toolchain/*/testdata/*` matches all the files under them.
2026-09-22 17:23:11 +00:00
Dana Jansens fcae9610bd Make SemIR::TypeType be an empty FacetType instruction (#7813)
The type `type` is now a `FacetType` inst with no constraints. This
brings the model implemented in the toolchain into better alignment with
the language design. The `SemIR::TypeType` struct remains as a scope for
holding the `TypeInstId`, `ConstantId`, and `TypeId` constants, but is
not an `InstKind` anymore.

The `TypeType` inst looks a lot like singletons, but there are many
`FacetType` insts so it doesn't quite fit that model. So we put it
alongside singletons with a fixed inst id but refer to it as a more
general "builtin" inst that is not a singleton.
`Namespace::PackageInstId` is similar, and we group it with `TypeType`
conceptually as another builtin instruction with a fixed id.

No conversion is needed anymore to use a `type` as a facet, since types
also have a `FacetType` type. This simplifies and removes a number of
helpers and branches throughout the code.

The `TypeType` inst is now part of the constant store, so we end up
printing it in the constants block in every test. But it's also named
`type` rather than `%type` to preserve the majority of existing
formatting behaviour, though this does look different from other
constants.

Assisted-by: Opus 5 was used to generate a first draft and validate the
refactoring. Though nearly everything non-trivial the tool wrote has
been modified or rewritten.
2026-09-22 15:04:40 +00:00
Lucile Rose Nihlen 83ca5b71e3 Move default value inst ids to a dedicated value store. (#7810)
Per #7737 we move the default value `InstId` storage from
a block in the `SemIR::Function` data structure to a
`SemIR::File` scoped `ValueStore`.

Moves the default value consistency checking to the general
merge argument pattern matching logic, which changes the
error message issued to the generic one.
2026-09-21 18:27:01 +00:00
Dana Jansens fa12d9ded2 Skill file docs about how to write prose, names, and to prioritize the data model (#7814)
Largely about writing less, and defining what is worth talking about and
what is not.
2026-09-21 17:48:35 +00:00
Richard Smith 76e7fc5900 Preserve the type-as-written for bindings and use it in diagnostics. (#7804)
In the `EntityName` for a binding, preserve the `TypeInstId` describing
how the type was written. When a diagnostic refers to that type via
`TypeOfInstId`, use the type-as-written in the diagnostic rather than
the canonical type.

Assisted-by: Claude Opus via Antigravity
2026-09-19 00:02:49 +00:00
Chandler Carruth d037848a96 Replace hashtable ForEach callback with range-based iteration (#7806)
Replaces the callback-based `ForEach` methods on `RawHashtable`, `Map`,
and
`Set` with a range object supporting range-for loops, structured
bindings, and
the standard range concepts.

- Adds `.entries()` on `Map`, `Set`, and `RawHashtable`, returning a
range that
  models `std::ranges::forward_range` and `std::ranges::common_range`.
  Obtaining one is an explicit call rather than `begin()`/`end()` on the
container, as scanning a whole table is costly and shouldn't be hidden.
- Iterating a `Map` yields a `std::pair` of key and value references,
which
fits in two registers and is returned without being materialized in
memory.
- `Map::Range` and `Set::Range` are aliases of the raw hashtable's range
rather
than wrappers around it. The raw iterator produces the user-facing
reference
itself -- a `KeyT&` for a set, a pair of references for a map -- picked
by
`StorageEntry`, which is already specialized on whether there is a value
  type. That leaves one iterator to reason about instead of three.
- Deletes the rvalue `.entries()` overloads on the owning containers, as
a
  range built from a temporary table would dangle. Views don't own their
  storage, so the operation remains available on them.
- In release builds, the walk over the groups is a single induction
variable: a
  negative byte offset counting up to zero, anchored at the ends of the
metadata and entry arrays. Both arrays are then reached by indexed
addressing
off a base that stays put, and the entry pointer is formed only once a
group
  with a present entry has been found.
- In debug builds, the range hashes the table's metadata when it is
built and
re-checks that hash when it is destroyed, catching mutation of the table
while a range is live. It also picks a random starting group and a
random odd
group stride, which varies the traversal order between ranges while
still
visiting every group exactly once. That entropy is drawn when the range
is
built rather than in `begin()`, so `begin()` stays a pure function of
the
  range and the multi-pass guarantee holds.
- Removes `ForEachEntry` and all of its callers.

Measured against the iteration benchmark added in its own commit, a
traversal is at or ahead of what the callback compiled to across nearly
the
whole size range. The largest tables spend 3-5% fewer cycles, small
`Set`s as
much as 24% fewer, and instruction counts stay within about 1%. What
remains
behind is a handful of mid-sized `Map`s by up to 1%, and `Set` at 65536,
which
sits at exactly half its load factor, by 2%.

Both revisions were built with `-c opt --copt=-march=x86-64-v3` and
compared
with:

```
./scripts/bench_runner.py --exp_benchmark=... --base_benchmark=... \
    --benchmark_args=--benchmark_perf_counters=INSTRUCTIONS,CYCLES \
    --benchmark_args='--benchmark_filter=(Set|Map)Iterate<(Set|Map)<' \
    --extra_metrics_filter='(INSTRUCTIONS|CYCLES)'
```

Trimmed below to the primary integer configurations and to the two
counters;
the pointer- and string-keyed configurations follow the same pattern.

```
 Benchmark                             ┃           CYCLES            ┃        INSTRUCTIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 BM_MapIterate<Map<int, int>>/1....... │ 👍  -6.032%      p=1.14e-05 │      ??          p=0.752
                             baseline: │     12.06      ±   1.520%   │     64         ±   3.125%
                           experiment: │     11.33      ±   2.765%   │     65.5       ±   3.817%
                                       │                             │
 BM_MapIterate<Map<int, int>>/2....... │      ??          p=0.155    │      ??          p=0.343
                             baseline: │      7.587     ±   1.285%   │     41         ±   0.000%
                           experiment: │      7.652     ±   0.865%   │     41         ±   2.439%
                                       │                             │
 BM_MapIterate<Map<int, int>>/3....... │      ??          p=0.343    │ 👍  -1.020%      p=0.0039
                             baseline: │      6.663     ±   4.260%   │     32.67      ±   2.041%
                           experiment: │      6.368     ±  12.224%   │     32.33      ±   2.062%
                                       │                             │
 BM_MapIterate<Map<int, int>>/4....... │      ??          p=0.343    │ 👍  -1.786%      p=0.0297
                             baseline: │      6.091     ±  15.470%   │     28         ±   3.571%
                           experiment: │      5.957     ±   8.932%   │     27.5       ±   3.636%
                                       │                             │
 BM_MapIterate<Map<int, int>>/8....... │      ??          p=0.323    │ 👍  -1.220%      p=0.000148
                             baseline: │      4.845     ±   0.800%   │     20.5       ±   0.000%
                           experiment: │      4.814     ±   3.585%   │     20.25      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/16...... │ 👍  -2.195%      p=0.00908  │ 👍   0.769%      p=6.58e-06
                             baseline: │      4.312     ±   0.187%   │     16.25      ±   0.000%
                           experiment: │      4.218     ±   2.368%   │     16.13      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/32...... │      ??          p=0.236    │ 👍   0.442%      p=9.53e-06
                             baseline: │      4.051     ±   1.084%   │     14.13      ±   0.000%
                           experiment: │      4.063     ±   0.737%   │     14.06      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/64...... │      ??          p=0.693    │ 👎   0.227%      p=4.52e-06
                             baseline: │      4.021     ±   0.239%   │     13.75      ±   0.000%
                           experiment: │      4.019     ±   0.417%   │     13.78      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/256..... │ 👍   0.360%      p=0.00119  │ 👎   0.754%      p=1.37e-05
                             baseline: │      3.996     ±   0.173%   │     13.47      ±   0.000%
                           experiment: │      3.982     ±   0.272%   │     13.57      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/4096.... │ 👍   0.581%      p=1.96e-05 │ 👎   0.923%      p=1.96e-05
                             baseline: │      4.005     ±   0.816%   │     13.38      ±   0.000%
                           experiment: │      3.981     ±   0.192%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/65536... │ 👍  -4.957%      p=1.14e-05 │ 👎   0.934%      p=1.14e-05
                             baseline: │      5.307     ±   0.501%   │     13.38      ±   0.000%
                           experiment: │      5.044     ±   1.746%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/1048576. │ 👍  -3.947%      p=9.09e-05 │ 👎   0.935%      p=3.3e-05
                             baseline: │      6.074     ±   0.807%   │     13.38      ±   0.000%
                           experiment: │      5.834     ±   2.159%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/16777216 │      ??          p=0.155    │ 👎   0.935%      p=2.11e-05
                             baseline: │      5.082     ±   3.650%   │     13.38      ±   0.000%
                           experiment: │      5.012     ±   1.316%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/56...... │ 👎   0.825%      p=0.0268   │ 👍   0.270%      p=1.14e-05
                             baseline: │      3.918     ±   0.501%   │     13.21      ±   0.000%
                           experiment: │      3.951     ±   0.342%   │     13.18      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/224..... │ 👎   0.788%      p=0.000504 │ 👎   0.346%      p=1.64e-05
                             baseline: │      3.895     ±   0.111%   │     12.89      ±   0.000%
                           experiment: │      3.926     ±   0.285%   │     12.94      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/3584.... │ 👎   1.028%      p=0.000148 │ 👎   0.545%      p=1.14e-05
                             baseline: │      3.913     ±   0.427%   │     12.79      ±   0.000%
                           experiment: │      3.954     ±   0.325%   │     12.86      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/57344... │      ??          p=0.236    │ 👎   0.558%      p=2.55e-06
                             baseline: │      4.574     ±   0.721%   │     12.79      ±   0.000%
                           experiment: │      4.51      ±   3.709%   │     12.86      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/917504.. │ 👍  -3.826%      p=6.58e-06 │ 👎   0.559%      p=2.33e-05
                             baseline: │      5.221     ±   0.507%   │     12.79      ±   0.000%
                           experiment: │      5.021     ±   0.556%   │     12.86      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/14680064 │ 👍  -3.839%      p=1.37e-05 │ 👎   0.559%      p=3.31e-05
                             baseline: │      5.129     ±   1.194%   │     12.79      ±   0.000%
                           experiment: │      4.932     ±   1.475%   │     12.86      ±   0.000%
                                       │                             │

 Benchmark                        ┃           CYCLES            ┃        INSTRUCTIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 BM_SetIterate<Set<int>>/1....... │ 👍  -3.104%      p=0.000583 │      ??          p=0.206
                        baseline: │     11.2       ±   6.323%   │     60         ±   3.333%
                      experiment: │     10.85      ±   5.820%   │     61         ±   3.279%
                                  │                             │
 BM_SetIterate<Set<int>>/2....... │ 👍  -7.037%      p=0.0362   │      ??          p=0.155
                        baseline: │      7.086     ±  16.857%   │     37         ±   0.000%
                      experiment: │      6.587     ±   0.479%   │     36         ±   4.167%
                                  │                             │
 BM_SetIterate<Set<int>>/3....... │ 👎   1.400%      p=2.34e-05 │ 👍  -1.163%      p=0.00136
                        baseline: │      5.363     ±   0.463%   │     28.67      ±   2.326%
                      experiment: │      5.438     ±  32.763%   │     28.33      ±   1.176%
                                  │                             │
 BM_SetIterate<Set<int>>/4....... │      ??          p=0.968    │      ??          p=0.286
                        baseline: │      4.642     ±  32.751%   │     23.5       ±   2.128%
                      experiment: │      4.658     ±  38.416%   │     23.63      ±   3.704%
                                  │                             │
 BM_SetIterate<Set<int>>/8....... │ 👍 -23.823%      p=3.74e-06 │ 👍  -1.515%      p=5.52e-05
                        baseline: │      4.701     ±   6.589%   │     16.5       ±   0.000%
                      experiment: │      3.581     ±   7.790%   │     16.25      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/16...... │ 👍  -4.502%      p=1.37e-05 │ 👍  -1.020%      p=3.31e-05
                        baseline: │      3.124     ±   0.585%   │     12.25      ±   0.000%
                      experiment: │      2.983     ±   0.625%   │     12.13      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/32...... │ 👍  -4.032%      p=5.46e-06 │ 👍   0.617%      p=1.96e-05
                        baseline: │      2.957     ±   0.260%   │     10.13      ±   0.000%
                      experiment: │      2.838     ±   0.434%   │     10.06      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/64...... │ 👍  -5.054%      p=4.52e-06 │ 👎   0.321%      p=1.37e-05
                        baseline: │      2.937     ±   0.301%   │      9.75      ±   0.000%
                      experiment: │      2.788     ±   1.143%   │      9.781     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/256..... │ 👍  -5.325%      p=1.14e-05 │ 👎   1.073%      p=6.58e-06
                        baseline: │      2.916     ±   0.220%   │      9.469     ±   0.000%
                      experiment: │      2.761     ±   0.142%   │      9.57      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/4096.... │ 👍  -4.865%      p=4.52e-06 │ 👎   1.317%      p=2.34e-05
                        baseline: │      2.921     ±   0.194%   │      9.381     ±   0.000%
                      experiment: │      2.779     ±   0.224%   │      9.504     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/65536... │ 👎   1.961%      p=3.93e-05 │ 👎   1.332%      p=1.49e-05
                        baseline: │      4.015     ±   0.482%   │      9.375     ±   0.000%
                      experiment: │      4.094     ±   0.613%   │      9.5       ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/1048576. │ 👍  -4.843%      p=1.14e-05 │ 👎   1.333%      p=5.38e-06
                        baseline: │      5.239     ±   0.144%   │      9.375     ±   0.000%
                      experiment: │      4.986     ±   0.139%   │      9.5       ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/16777216 │ 👍   0.840%      p=0.0362   │ 👎   1.333%      p=2.52e-06
                        baseline: │      3.719     ±   1.420%   │      9.375     ±   0.000%
                      experiment: │      3.688     ±   1.308%   │      9.5       ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/56...... │ 👍  -2.857%      p=9.53e-06 │ 👍   0.388%      p=3.31e-05
                        baseline: │      2.942     ±   0.439%   │      9.214     ±   0.000%
                      experiment: │      2.858     ±   0.619%   │      9.179     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/224..... │ 👍  -2.161%      p=2.34e-05 │ 👎   0.502%      p=4.52e-06
                        baseline: │      2.888     ±   0.347%   │      8.893     ±   0.000%
                      experiment: │      2.826     ±   0.450%   │      8.938     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/3584.... │ 👍  -1.750%      p=6.58e-06 │ 👎   0.793%      p=2.34e-05
                        baseline: │      2.89      ±   0.261%   │      8.792     ±   0.000%
                      experiment: │      2.84      ±   0.411%   │      8.862     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/57344... │      ??          p=0.502    │ 👎   0.812%      p=2.78e-05
                        baseline: │      3.684     ±   4.246%   │      8.786     ±   0.000%
                      experiment: │      3.644     ±   4.431%   │      8.857     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/917504.. │ 👍  -2.629%      p=0.000148 │ 👎   0.813%      p=3.08e-06
                        baseline: │      4.372     ±   0.693%   │      8.786     ±   0.000%
                      experiment: │      4.257     ±   0.210%   │      8.857     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/14680064 │ 👍  -2.927%      p=0.0219   │ 👎   0.813%      p=3.03e-06
                        baseline: │      4.154     ±   3.286%   │      8.786     ±   0.000%
                      experiment: │      4.032     ±   3.198%   │      8.857     ±   0.000%
                                  │                             │
```

Assisted-by: Antigravity with Opus
2026-09-18 20:19:46 +00:00
Chandler Carruth 681b3b10c4 Add a jj push wrapper that runs prek before pushing. (#7805)
`scripts/jj_push.sh` takes the same arguments as `jj git push`, runs
prek over the commits that push would send, and pushes only if they
pass. It learns what is being sent by running `jj git push --dry-run`
and reading back the plan, so `--bookmark`, `--change`, `--all` and the
rest work without reimplementing how they select commits.

Hooks that rewrite files need a commit to write into, so the checks run
with the working copy on top of the commit being pushed. When the
working copy is already an empty commit there, which is the common case,
it is used directly; otherwise one is created, and named in the error so
the fixes can be squashed.

`scripts/jj_prek.sh` gets two changes. It forwards its arguments to
`prek run`, so `jj_push.sh` can ask for a specific range, and it now
changes to the workspace root before running. It exports `GIT_DIR`,
which makes git treat the current directory as the work tree, so prek
could not find its configuration from a subdirectory.

`jj` does not expand aliases when completing arguments, so `jj push`
completed file names. `scripts/completions` has Bash, Zsh, and Fish
completions that give it the same completions as `jj git push`.

`docs/project/contribution_tools.md` documents the `push` alias, and a
`prek` alias for `jj_prek.sh`, with the other per-repository `jj`
configuration. Both are opt-in.

Assisted-by: Claude Code
2026-09-18 19:40:25 +00:00
Nicholas Bishop dbf79d5229 Fix accessing protected members from templates derived classes (#7780)
When evaluating a deferred member access action, the scope stack cannot
be relied on, so `LookupUnqualifiedName` cannot be used in
`GetHighestAllowedAccess` to get the `Self` type.

Instead, store the `Self` type in the `Context` when evaluating a
method, and use that in `GetHighestAllowedAccess`.
2026-09-18 19:12:05 +00:00
Dana Jansens 413ac55d4f Add rules for working with jj history and prek (#7808)
Add rules to not overwrite git/jj history without asking, since this
destroys the reviewer's view of things. And some information on dealing
with stacks of commits within a single bookmark/PR.

Prek can make fixes for whatever caused a failure, and then pass when
you run it again, even though the user didn't change anything, and that
is now explained.

Assisted-by: Opus 5
2026-09-18 18:36:58 +00:00
ATHARVAandDana Jansens 804359dce0 Fix crash when lowering Carbon derived class with C++ virtual base class (#7745)
If a Carbon class overrides virtual functions from a C++ base class but
is never referenced from C++, it is never exported to Clang. During
lowering, `BuildVtable` then fails to find a `CXXRecordDecl` and crashes
when attempting to get the vtable from Clang's code generator.

Ensure dynamic classes with foreign vtables are exported to Clang when
completing the class definition in `CheckCompleteClassType`, and look up
`first_decl_id()` in `BuildVtable`.

Fixes #7721

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-09-18 18:08:53 +00:00
Dana Jansens d84387f8b8 Add --build-mode to autoupdate script (#7809)
Allow the user to specify a build mode instead of detecting the last
used one.
2026-09-18 15:15:26 +00:00
David Blaikie 094742740a Handle instantiating an imported class/vtable (#7792)
Usual LoadImportRef, plus some generalization of importing entities.
2026-09-17 23:50:28 +00:00
Lucile Rose Nihlen 994bad5143 Use non-canonical instructions in default values. (#7737)
Per feedback on #7665, this PR switches the default value
table storage from canonical constant inst_ids to
non-canonical.

Furthermore, this PR simplifies the default value support in
check by requiring that the first owned declaration of a
function completely specify all of its default values.
Updates the diagnostic code and tests to reflect this new
stricter requirement.
2026-09-17 22:04:43 +00:00
Chandler Carruth ae4be1be14 Use inline small storage for small SemIR ID sets in toolchain (#7796)
Apply SmallSize = 16 to frequent identifier and instruction/function
sets in ScopeStack, Class, FacetType, and SpecificCoalescer to avoid
dynamic heap allocations on small scopes. Also defer dest_field_names
set allocation in struct conversion and provide default KeyContext for
SetBase. This was found by inspection, but does seem to be a clear 1.5%
win on overall compile time.

```
Ran baseline and experiment 10 times on 128 x 2450 MHz CPUs
CPU caches:
  L1 Data 32Ki
  L1 Instruction 32Ki
  L2 Unified 512Ki
  L3 Unified 32Mi
Load avg: 1.2041 1.16895 2.86133
Computing statistically significant deltas only wherethe P-value < 𝛂 of 0.05
Metric key:
   BenchmarkName... 👍 <delta>    p=<U-test P-value>
          baseline:    <median> ± <% at 95th conf>
        experiment:    <median> ± <% at 95th conf>

 Benchmark                                                      ┃          CPU Time          ┃           CYCLES           ┃       INSTRUCTIONS        ┃          Lines
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━
 BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Check>/256... │ 👍  -1.768%      p=0.0346  │ 👍  -1.683%      p=0.0346  │ 👍   0.160%    p=0.000428 │ ~
                                                      baseline: │     49.11  ms  ±   1.363%  │    155.6   M   ±   1.875%  │    293.9   M ±   0.015%   │     4.093 k ±   1.360%
                                                    experiment: │     48.24  ms  ±   2.213%  │    153     M   ±   2.465%  │    293.4   M ±   0.081%   │     4.166 k ±   2.165%
                                                                │                            │                            │                           │
 BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Check>/1024.. │      ??          p=0.159   │      ??          p=0.067   │ 👍   0.153%    p=0.000249 │ ~
                                                      baseline: │     50.61  ms  ±   2.379%  │    160.7   M   ±   2.777%  │    309.7   M ±   0.015%   │    19.96  k ±   2.326%
                                                    experiment: │     50.32  ms  ±   0.971%  │    159.6   M   ±   0.787%  │    309.2   M ±   0.086%   │    20.07  k ±   0.980%
                                                                │                            │                            │                           │
 BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Check>/4096.. │ 👍  -1.593%      p=0.0112  │ 👍  -1.632%      p=0.00743 │ 👍   0.138%    p=0.000328 │ ~
                                                      baseline: │     58.58  ms  ±   1.673%  │    186.5   M   ±   1.487%  │    371.2   M ±   0.102%   │    70.96  k ±   1.645%
                                                    experiment: │     57.65  ms  ±   1.032%  │    183.5   M   ±   1.079%  │    370.7   M ±   0.091%   │    72.11  k ±   1.043%
                                                                │                            │                            │                           │
 BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Check>/16384. │ 👍  -1.695%      p=0.029   │ 👍  -1.823%      p=0.0411  │ 👍   0.221%    p=0.000428 │ ~
                                                      baseline: │     90.07  ms  ±   3.686%  │    287.1   M   ±   3.694%  │    618.9   M ±   0.106%   │   186.9   k ±   3.555%
                                                    experiment: │     88.55  ms  ±   1.891%  │    281.8   M   ±   2.142%  │    617.6   M ±   0.158%   │   190.1   k ±   1.856%
                                                                │                            │                            │                           │
 BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Check>/65536. │ 👍  -1.797%      p=0.0201  │ 👍  -1.762%      p=0.0201  │ 👍   0.222%    p=0.000328 │ ~
                                                      baseline: │    222.1   ms  ±   2.560%  │    711     M   ±   2.417%  │      1.613 G ±   0.158%   │   304.2   k ±   2.496%
                                                    experiment: │    218.1   ms  ±   1.950%  │    698.5   M   ±   2.010%  │      1.61  G ±   0.075%   │   309.7   k ±   1.989%
                                                                │                            │                            │                           │
 BM_CompileApiFileDenseDecls<Lang::Carbon, Phase::Check>/262144 │      ??          p=0.398   │      ??          p=0.36    │ 👍   0.166%    p=0.000931 │ ~
                                                      baseline: │    782.2   ms  ±   2.666%  │      2.502 G   ±   2.546%  │      5.596 G ±   0.038%   │   345.8   k ±   2.597%
                                                    experiment: │    780.6   ms  ±   4.249%  │      2.483 G   ±   4.691%  │      5.587 G ±   0.024%   │   346.5   k ±   4.075%
                                                                │                            │                            │                           │
```

Assisted-by: Antigravity with Gemini
2026-09-17 15:49:43 +00:00
Chandler Carruth e65694db57 Narrow the benchmark test runs for set and benchmark (#7795)
Hopefully this reduces the occurances of timeouts on GitHub, and it
shouldn't reduce coverage meaningfully.
2026-09-17 12:42:57 +00:00
Chandler Carruth 5c601f8224 Make the filesystem benchmark test less expensive (#7794)
While some of the slowness here is unrelated, there isn't really any
reason to test even as much of the benchmark as it is.
2026-09-17 12:41:59 +00:00
Richard Smith ccb5ba1b92 Turn off -Wunneeded-internal-declaration in clangd. (#7793)
Like the other unused warnings, it misfires when the only uses are in
template instantiations.

This is misfiring in #7771's CI checks.
2026-09-17 01:23:25 +00:00
Richard Smith ebf1675356 Add linux perftools output files to gitignore. (#7791) 2026-09-16 23:34:46 +00:00
Richard Smith 843c7ce498 Improve compilation database for agents. (#7790)
Remove claim from script that it takes minutes; this caused Claude to
decide to not run it. It only takes a few seconds these days. Add note
in toolchain development skill that lints won't be accurate if the
compilation database is outdated.

Assisted-by: Claude Opus 5 via Antigravity
2026-09-16 20:12:32 +00:00
Richard Smith 59c1d6ff39 Remove refine_inst_action and its splices. (#7769)
This action was created to wrap any `MetaInstId` operand of an action
instruction. This served two purposes:

1) It had a special hook in `OperandIsDependent` to allow it to be
   performed while it had a dependent operand (the reference to the
   instruction in the generic).
2) It created a `specific_inst` so that the downstream action saw an
   instruction in the specific instead of one in the generic.

These are both replaced: the special case in `OperandIsDependent` for
`RefineInstAction` is replaced by a special case for `MetaInstId`s in
general, and the `SpecificInst` is now created as part of performing the
downstream action, rather than as a separate step carried out
beforehand.

This simplifies the produced SemIR and reduces the number of splices
significantly. It also prepares us to handle actions like
initialization, where we don't actually want to create `SpecificInst`s
immediately in the location where the action is performed, because they
actually belong somewhere else in the IR.

Assisted-by: Claude Opus 5 and Gemini via Antigravity
2026-09-16 01:21:00 +00:00
Richard Smith eb887c367a Add benchmark for missing bracket fixing and optimize various parts of the algorithm. (#7655)
Replaces several quadratic-time steps in the algorithm with linear or n
log n implementations. Worst-case runtime before hitting the complexity
bailout drops from 25ms to about 12ms, and typical runtime is
single-digit ms on my development machine.

Assisted-by: Claude Code
2026-09-15 23:22:29 +00:00
Richard Smith f3d67de480 Start to preserve type sugar in diagnostics. (#7768)
Instead of always printing types as canonical, attempt to find a sugared
type where possible, and include that type in the diagnostic. We can
only do this when given the instruction whose type is being printed
(`TypeOfInstId`) rather than the canonical type ID.

Initial support here is intentionally minimal: just looking through
calls to the callee's declared return type, and looking through pointer
dereferences and corresponding pointer types, to build out the initial
infrastructure. More cases can be added later; this degrades gracefully
to using the canonical type if a better type can't be found.

Assisted-by: Claude Opus 5 via Antigravity
2026-09-15 23:11:58 +00:00
Richard Smith d8c4fc51cd Fix SemIR for derived-to-base conversion and lowering crash. (#7783)
We use the same conversion codepath to handle both qualification
conversions and derived-to-base conversions, because we allow both to be
performed at once. However, we were previously modeling the
qualification conversion as happening *first*, and producing a result
whose type is the target type of the overall conversion (that is, the
base class type). That led to bogus SemIR, where a `Derived` -> `const
Base` conversion would first have a "compatible" conversion from
`Derived` to `const Base`, *then* an access of the base subobject (of
type `const Base`, within an object of type `const Base`).

We now reverse the order: first we do a derived-to-base conversion,
which already has logic to preserve qualifiers, and then we do any
necessary qualification conversions on the result to reach the overall
target type.

In passing, we now skip forming the `as_compatible` instruction at all
for a pure derived-to-base conversion that has no qualification
conversion, simplifying the SemIR by one instruction in the common case.
2026-09-15 23:11:51 +00:00
simontran7 64ce58dd64 fix malformed parse tree for invalid let struct pattern (#7782)
Fixes the malformed parse tree produced for an invalid let struct
pattern containing a single identifier (e.g., `let {s};`).

As pointed out by @DavidLoftus, the parser should produce a parse tree
similar to that of `let {ref s};`, since both are missing a binding
power operator `:`, and both do not have a `.` preceding the identifier
(i.e., `state.in_field_shorthand_pattern == true`).

This means that the parser can produce an the `InvalidParse` node just
as it does for `let {ref s};`.

Closes #7674
2026-09-15 23:10:17 +00:00
Chandler Carruth 437be71f1f Overhaul the TextMate grammar (#7746)
Four regions had `end` patterns that could fail to match, so `return
var;`, a `fn` with no parameter list, and an unterminated `"` each
swallowed the rest of the file; 77 of 1696 testdata files lost their
highlighting partway through. Operators were wrapped in `\b`, which only
holds next to a word character, so `a + b` highlighted nothing. And the
keywords had drifted about two years behind the lexer.

Identifiers are now classified by naming convention plus a call-site
lookahead, the way the Rust grammar does it, so nothing carries between
lines. Regions survive only for strings and embedded C++, where a
terminator reliably turns up, and raw strings spell out hash levels 0
through 2, so `\n` is an escape in `"..."` and plain text in `#"..."#`.
Trailing comments, character literals, raw identifiers, `$0`, `0o`
octal, arbitrary integer widths and six missing keywords are covered
now, `destructor` is gone, and `i32` reads as a type rather than as a
keyword.

Highlighting stays forgiving rather than diagnostic: anything after `//`
is a comment and odd numeric spellings still read as numbers. Pointing
out mistakes is the toolchain's job, and lenient rules hold steady while
you are still typing.

Every keyword and symbol in `token_kind.def` is covered, and unscoped
tokens across examples and the toolchain drop from 39% to 21%.

Note that I haven't tried to read and reason about every minute change
here as there are just too many. But I'm working on a follow-up PR that
adds testing that should be significantly easier te review.

Assisted-by: Claude Code
2026-09-15 22:03:22 +00:00
Dana Jansens bfebb7cb42 Pass SpecificInterface through custom and C++ witness generation (#7784)
We were passing a SpecificInterfaceId which just makes code have to do a
lookup to get the actual SpecificInterface. The caller already has the
SpecificInterface, so plumb that around.

SpecificInterfaceId really only exists when we need to stick a
SpecificInterface into an instruction as an operand.
2026-09-15 21:23:28 +00:00
David Blaikie 9e68ee0806 Support indirect C++ dependency by sharing domains more broadly (#7763)
Fixes #7731, at least under `--share-cpp-ast` which is expected to be
the future direction.

When --share-cpp-ast is enabled and any compilation unit has C++
imports, include all compilation units in the shared CppDomain inputs
and assign the domain to every unit. In ImportCpp, when a unit has no
direct C++ imports but is covered by a shared CppDomain, initialize
its C++ AST context and import namespace. This ensures units without
direct C++ imports have access to the C++ AST and code generator when
instantiating generics or referencing declarations from units that do.

Assisted-by: Antigravity with Gemini
2026-09-15 20:45:18 +00:00
Chandler CarruthandDana Jansens 37949a2066 Generate the TextMate sample renderings (#7762)
The images beside the samples were screenshots taken by hand, so they
drifted: they still showed `package Carbon api;`, syntax the language
dropped in 2024.

`render_sample.py` renders a sample the way the grammar in this
repository actually highlights it, using `tmlanguage.py`, a small
TextMate tokenizer. VS Code runs grammars under Oniguruma, which we
cannot depend on here, but this grammar uses no Oniguruma-only syntax,
so `re` runs its regexes unchanged and the two agree on every character
of every Carbon file in the repository. The output is SVG, so
regenerating needs nothing but Python, and a later grammar change gets a
same-path image diff showing what it did to real code.

The samples change where a construct left the language (`api`, `Carbon`
as the package name, `StringView`, `destructor`), refresh the
`keywords.carbon` inventory against `token_kind.def`, and add sections
for octal, raw and block literals, character literals, lambdas, and raw
identifiers. `interop.carbon` is new, covering inline C++. These are
highlighting fixtures rather than programs, so the deliberately invalid
lines stay.

Assisted-by: Claude Code

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-09-15 20:29:22 +00:00
Lucile Rose Nihlen e962b12e53 Fix typo in ImplDeclInInvalidScope diagnostic (#7785)
And update the associated file test.
2026-09-15 16:43:22 +00:00
Dana Jansens 4416f3525b Canonicalize generated functions for Core witnesses (#7729)
Use a single `SemIR::Function` per `Core` interface method, whether it's
generated locally or imported. This prevents generating duplicate
functions, which lead to different types when the witness appears in a
`FacetValue` as part of a specific for a class.

We use a `CanonicalValueStore` of `GeneratedFunction` objects that allow
finding an existing FunctionId for a `Generated` special function before
(re-)generating it. Mangling for `Generated` functions is also moved to
use the values from the `GeneratedFunction`'s canonicalization key, so
that we have a consistent source of truth for the unique ID of a
`Generated` function across all files.

New tests are in
`toolchain/check/testdata/impl/custom_witness/destroy.carbon`.
2026-09-15 16:02:13 +00:00
db2e26ba86 Updates to member access (#7697)
Update the rules for member access:
-   Simple member access `a.b`
- If `a` names a scope, performs name lookup and optionally `impl`
lookup.
- Otherwise, `a.b` is shorthand for `a.(typeof(a).b)` and always
performs instance binding.
- Compound member access `a.(m)` does optional `impl` lookup and always
performs instance binding.
- This is a change from only performing instance binding if `m` is an
instance member.
- New operation `a.impl(m)` is introduced. It always performs `impl`
lookup, and nothing else.
- The `BindToType` interface is removed. Only instance binding may be
customized (using the `BindToValue` and `BindToRef` interfaces).

As a result, member access doesn't use whether the right operand is an
instance member anymore. Instead, instance binding is performed whenever
it would be plausible, and a new syntax is used to opt out.

Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-09-15 00:03:41 +00:00
Nicholas Bishop cf66fb8aeb roll llvm to 7024b9e1b423b3c3c6ac76ab6a73cb2c9e4ef842 (#7781)
Updated patch 0006 to include new files added in
https://github.com/llvm/llvm-project/pull/207543.

Dropped patch 0009 which was upstreamed in:
https://github.com/llvm/llvm-project/pull/190088

Minor updates to patch 0011 for changes upstream.

Minor updates in export.cpp to use `llvm::FoldingSetInsertToken` instead
of a void pointer.
2026-09-14 21:54:09 +00:00
Dana Jansens 4081848d65 Disable new clang-tidy rules with google- prefixed aliases (#7778)
Some `google-` prefixed rules have been renamed to rules without the
prefix. The `google-` prefix still remains as an alias to these new
rules. Since we turn on the `google-` prefix rules and use those in
NOLINT expressions, disable the new aliased names. Otherwise we have to
put both names in NOLINT expressions.
2026-09-12 09:35:03 +00:00
Dana Jansens 648ccc5f9b NOLINT a cycle in semir formatting (#7774)
Add a TODO that we should address this cycle.
2026-09-11 22:29:17 +00:00
Dana Jansens 0d9560c049 Disable readability-redundant-nested-if in clang tidy (#7776)
This is a style choice we often agree with, and call out in code review.
But there are many cases where we do want to split apart nested ifs,
such as when working with LLVM apis like `dyn_cast`:
```
if (auto* thing = dyn_cast<Thing>(other)) {
  if (thing->foo()) {
    ...
  }
}
```

Or we may have TODOs or other comments in the scope of the outer if,
which the tidy check ignores.

Since this doesn't lead to bugs, we disable the check and leave this to
reviews and authors for their discretion.
2026-09-11 19:51:41 +00:00
Dana Jansens 09feee7534 Remove empty lambda parameters in handle_function (#7777)
These are marked as redundant by clang-tidy 23
2026-09-11 18:22:33 +00:00
Dana Jansens 111ec69b65 NOLINT an assignment in a complex boolean statement (#7775)
We use a complex fold statement over `operator=`, with an assignment to
a variable earlier in the folded-over expression, which is intentional.
2026-09-11 17:04:40 +00:00
Dana Jansens c45efd625f Move to clang 21 as mininum version and use it in CI (#7779)
Clang 21 is now the latest version available in Ubuntu LTS, so we can
move to it.
2026-09-11 16:58:59 +00:00
Richard Smith 7d70f72bec Remove incorrect CHECK that would fail for out-of-line template declarations. (#7772)
Add a test, which fails for now, but will eventually demonstrate why
this CHECK was incorrect.
2026-09-11 16:58:05 +00:00
Chandler CarruthandRichard Smith b1e9ced0c9 Add a design for rendering diagnostics on a terminal (#7668)
The diagnostics documentation covers how a diagnostic is produced and
worded, not the form it takes on a terminal. This adds
`toolchain/docs/diagnostics_rendering.md`: what a diagnostic is made
of, its layout, color, character set, and width, and how each degrades
when the terminal can't render it.

A diagnostic is one message plus labels read against the code they
mark, `Primary` or `Info`; a context and a path are set out apart. It
renders as one frame, anchored per file, with no headline: the message
hangs off the range that is wrong, led by the level word on a heavy
mark, with `->` in the margin on the reported lines. Labels read in
the order of their ranges, connectors that cross earlier rows break
around them, and a path draws only for the message's own location.
Ten rows on the shared example, against Clang's six and rustc's eleven.

Nothing a diagnostic says is dropped for width: source is windowed,
words wrap past the level word, connectors slide, and a label that
still can't hang is out-dented. Under sixty columns the compact form
takes over, one located line per part. Color is named per element with
a ramp per level and a light-background palette; ASCII keeps every
distinction with `^`, `.`, and the level word. The `file:line:column:`
header is the road not taken: structure comes from the language
server, and the compact form covers a grep-able line.

Assisted-by: Claude Code

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-09-11 07:15:40 +00:00
Richard Smith 455f1af2b2 jj_prek: snapshot the working copy (#7770)
Instead of running on the "current" `@` (the state at which the previous
`jj` command happened to be run), intentionally trigger a working copy
snapshot from `jj_prek`.

Assisted-by: Claude Opus 5 via Antigravity
2026-09-11 06:14:28 +00:00
Dana Jansens 49345352d6 Remove redundant use of typename (#7751)
clang-tidy 24 warns about these
2026-09-11 00:22:27 +00:00
Dana Jansens f819fafa12 NOLINT the use of sizeof() on a pointer if a pointer is hashed (#7765)
The hashing code is generic over the type of the value being given to
sizeof() so ideally this warning would not happen at all, but it does.
Possibly because the value is the return of an overload set, so it's not
obvious that it's the templated type. One of those overloads returns
`const void*` but change that to an integer does not remove the warning
still.
2026-09-10 23:54:11 +00:00
Dana Jansens dd43b50310 NOLINT an initializer list construction that clang-tidy warns on (#7759)
Clang is synthesizing a cast when using an enum value from a template
parameter, and then clang-tidy is finding and reporting that cast.
Upstream bug: https://github.com/llvm/llvm-project/issues/222793
2026-09-10 23:49:07 +00:00
Dana Jansens 981a0e9445 NOLINT the cycle through HandleAction and pattern matching (#7767)
Leave TODOs on all the places that needed to be silenced
2026-09-10 22:33:50 +00:00
Dana Jansens 656026f630 Move diagnostic emit functions to protected to match their base class (#7764)
The emit functions are inherited from a base class as protected, and
clang-tidy warns if we then expose them as public.
2026-09-10 22:29:52 +00:00
Dana Jansens 03bd40c398 Disable clang-tidy forbidding forward decls of classes with the same name in another namespace (#7766) 2026-09-10 22:14:25 +00:00
Dana Jansens e87831373f NOLINT and document use of StringLiteral::data() which subclasses StringRef (#7757)
StringRef::data() is problematic to call, but StringLiteral is always
NUL-terminated, so data() gives a valid C string.
2026-09-10 22:00:36 +00:00
Dana Jansens 8732bd9de1 Replace C-style variadic with a concept (#7761)
clang-tidy 24 warns on C-style variadics, and we don't need to use one
here anymore. Instead of a function call with an argument list, use a
concept to determine if a type can be list initialized.
2026-09-10 21:26:37 +00:00
Dana Jansens eca38a90e1 Remove empty lambda parameter lists (#7760)
clang-tidy 24 warns about these being redundant
2026-09-10 20:10:36 +00:00
Dana Jansens 52e28c02c3 Disable readability-identifier-naming in clang-tidy 24 (#7752)
This check allows styles that we don't use so it's not really useful for
enforcing our style guide. And prevents the use of `_1` or similar in
destructuring declarations where want to use `_` for multiple variables,
such as `auto [_1, _2, foo] = bar()`.
2026-09-10 20:03:26 +00:00
Dana Jansens 3942eca83f Disable the bugprone-crtp-constructor-accessibility warning in clang-tidy 24 (#7758)
The warning wants all classes inherited as CRTP base classes to hide all
their constrcuctors and friend all uses of them. We use CRTP quite a lot
and across different components of the toolchain, which would make
maintaining friend lists frustrating.
2026-09-10 19:53:15 +00:00
ATHARVA d98784b972 Fix crash when initializing class with omitted base class (#7740)
### Description
When looking up default initializers for class elements in
`ConvertStructToClass`, the compiler previously assumed that every
member looked up from the class scope was a `FieldDecl` and called
`GetAs<SemIR::FieldDecl>` directly.

For a derived class with a base class, looking up `base` returns a
`BaseDecl`, which caused a `CHECK` assertion failure when casting to
`FieldDecl`. Use `TryGetAs<SemIR::FieldDecl>` instead so non-`FieldDecl`
entries like `BaseDecl` are recognized as having no default initializer,
cleanly diagnosing that the `base` field is missing.

Fixes #7722

Assisted-by: Google Deepmind Antigravity
2026-09-10 19:29:24 +00:00
Dana Jansens 6f1ae86ce4 Disable -Wunused-template in clangd-tidy (#7750)
This is firing on some of our _used_ templates in eval.cpp in clang-tidy
24

It was coming to `-Wall` for clang as well
(https://github.com/llvm/llvm-project/issues/202945) but was reverted
due to issues like false positives
(https://github.com/llvm/llvm-project/pull/218638). Some fixes were
applied to try enable in `-Wall` in clang 23
(https://github.com/llvm/llvm-project/pull/222336) but it still remains
disabled by default for clang.
2026-09-10 19:28:25 +00:00
Dana Jansens dbcae83784 Passthrough the StringRef to mapRequired instead of just the data() pointer (#7756)
The StringRef represents a bounded region of a string, but using data()
drops the end bound, and makes LLVM construct a new StringRef starting
in the same position and going until a nul terminator. If this worked
correctly before, it was because the StringRef was always pointing to a
full `std::string` or the tail of one.
2026-09-10 19:19:56 +00:00
Dana Jansens 804dc3baaf Disable readability-use-concise-preprocessor-directives in clang-tidy 24 (#7754)
While we do adhere to its expectations most of the time, we don't
always. This is a low value check, and it's a stylistic choice to use
`#if defined(...)` when paired with `#elif defined(...)`.
2026-09-10 19:12:54 +00:00
Dana Jansens 76f52e0abb Move reserveExtraSpace to public (#7755)
The method it overrides in the base class is public, so it's already
accessible publicly. This is warned against in clang-tidy 24.
2026-09-10 19:12:00 +00:00
Dana Jansens bf8c997581 Disable bugprone-return-const-ref-from-parameter in clang tidy 24 (#7753)
We intentionally return const references from stable containers like
value stores.
2026-09-10 19:01:47 +00:00
Dana Jansens 4985e35695 Exclude .clang-tidy from rumdl checks (#7749)
Basically the whole file is an error and the formatting is not how we
want to write the file, so just exclude it.
2026-09-10 18:20:45 +00:00
Dana Jansens dd50e88168 Disable bugprone-derived-method-shadowing-base-method in clang-tidy 24 (#7748)
This fires on methods that we shadow, such as Print for a Printable<T>
subclass.
2026-09-10 17:04:10 +00:00
Dana Jansens c6c40cc444 Avoid using string operator += for a single character (#7747)
This is flagged as a mistake by clang-tidy 24. String's operator `+=` is
pretty bad in general, this moves a few uses to push_back.
2026-09-10 16:39:08 +00:00
Nicholas Bishop c24adea6fe Allow assignment to be called on a template-dependent lhs (#7741) 2026-09-10 15:07:31 +00:00
Dana Jansens eabc7f78b2 Show the errors that occurred, if any, when executing a dump command in lldb (#7743) 2026-09-10 12:47:28 +00:00
Dana Jansens 2aeecef17a Gracefully handle member access on a runtime type value (#7744)
Avoid CHECK failure when performing member access on a runtime type
value. We will just fail to find the CanonicalFacetOrTypeValue and then
fail lookup.
2026-09-09 23:05:48 +00:00
Christopher Di Bella 431e349757 Allow witness tables to support aliases and other types of StructValue (#7738)
Changing the check from "is `FunctionDecl`" to "has `FunctionType`"
provides us with more flexibilty to use aliases and other types of
`StructValue`.
2026-09-09 19:35:43 +00:00
Richard Smith e090a0ef65 autoupdate: add missing verbose check. (#7742)
A check for `args.verbose` was missing for one line of autoupdate's
verbose output. Add a wrapper function to print verbose output to fix
this and to make it easier to get verbose output right in future.
2026-09-09 19:34:28 +00:00
Richard Smith 49c6f488b6 Include spliced inst value in fingerprint while lowering. (#7739)
This prevents different template instantiations from getting
over-eagerly merged. Unfortunately we don't have a good middle-ground
yet, and this effectively disables all merging for templates. We may be
able to find some smart way to fingerprint spliced instructions so that
we can still merge template instantiations, but for now this change is
just fixing the wrong-code bug.
2026-09-09 17:54:10 +00:00
Richard Smith a9fee27bbb Add test for symbolic arguments to templates. (#7736)
Test passing a template argument or a symbolic argument to a template.
Fix a bug in the template case where we'd crash when instantiating a
dependent discarded expression, because conversion produced an
`InstId::None` which the actions machinery did not expect and crashed
on.
2026-09-09 01:39:54 +00:00
Richard Smith d92a981083 Add explicit testing for use of non-constant template arguments. (#7735)
Also move another template test into the template/ subdirectory.
2026-09-08 23:36:36 +00:00
Özgür T. Önsoy c6d8d29172 Diagnose redundant redeclarations in impl files (#7695)
While forward declarations in impl files are allowed, having one in the
impl file is redundant when we also have one in the API file.
2026-09-08 23:15:42 +00:00
Lucile Rose Nihlen ca9e985fa8 Reconcile function default values between decl and def (#7665)
Updates the pattern matching code to support unspecified default values.
Adds logic to decl and def merge code to diagnose mismatches in defaults
if specified in both places, or if let entirely unspecified.

Per https://github.com/carbon-language/carbon-lang/pull/7521.
2026-09-08 20:41:58 +00:00
Richard Smith 5a07a14fe9 Support for lowering templates (#7727)
Add basic support for lowering templates: we can now lower `SpliceInst`
in the case where the generic and specific are from the same file (and
we don't support importing templates from other files yet in general).
In order for this to work, lowering needs to be able to query the
expression category, and to handle instructions that appear to be
(template) constants in the generic but turn out to be non-constant in
the specific, so support for that is added.

Switch `type_of_inst` from being added as an action inst to being added
as a normal inst, since it's not an action and the old approach led to a
crash in lowering.
2026-09-08 18:39:57 +00:00
David Blaikie 3339dd85de Lower FacetType to TypeType to match FacetValue lowering (#7734)
SemIR::FacetValue lowers to context.GetTypeAsValue(), which produces a
constant of LLVM type %type (context.GetTypeType()). However,
SemIR::FacetType previously fell back to an anonymous empty struct {},
causing an argument type mismatch assertion failure when passing a
FacetValue to a function expecting a FacetType parameter.

Identified by @danakj in #7731

Assisted-by: Antigravity with Gemini
2026-09-08 18:32:34 +00:00
ATHARVA e5f30d1738 Cache SemIR::Mangler in FileContext (#7730)
### Description
When lowering symbols (functions, global variables, and vtables), a new
`SemIR::Mangler` was being created on each call. Each `Mangler` creates
its own `InstFingerprinter` with a fresh store, preventing any
fingerprint computations from being reused across manglings.

This PR caches a single `SemIR::Mangler` instance in `FileContext` so
that the underlying fingerprint cache is preserved and reused across all
symbol manglings within the file.

Assisted-by: Google Deepmind Antigravity
2026-09-08 17:53:10 +00:00
DavidLoftusandDavid Blaikie 301172f589 Update Carbon::Format to produce semi-reasonable output. (#7687)
Makes following changes to Carbon::Format()

- TokenKind::Period (i.e. `.`) should never have a space before or after
it.
- TokenKind::CloseSquareParen (i.e. `]`) should be treated as packed
content (no space preceeding it)
  - Only exception I can think of is `impl forall [...]`
- Remove preceeding space from `[` and `(` if previous token was an
identifier (or identifier-ish token)
- Remove seperator following `++` / `--` unary operators.
- Explicit gaps in source code should be retained, up to 2 new lines.

Multiple test files were added to test formatting. 

I imagine eventually this will need to be updated to read parse tree to
gather more context but this atleast lets us get a decent-ish format for
many of our current sample files (e.g. sieve.carbon)

Assisted-With: Gemini / Antigravity

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2026-09-08 16:20:47 +00:00
Richard Smith 812cc1e032 Add SpecificInst to represent a specific version of a template-dependent instruction (#7726)
Replace `refine_type_action` with `refine_inst_action`, and generate a
`specific_inst` instead of an `as_compatible` to represent the specific
version of an instruction that's used as an input to a template action.
This gives us a place to handle other properties of the instruction that
might vary from generic to specific beyond its type, such as its
constant value and its expression category.

For now, we provide a non-template-dependent constant value to the
`specific_inst` in addition to the non-template-dependent type we have
traditionally provided. This doesn't seem to matter for any current
actions, but sets us up to better handle future actions. The
`specific_inst` representation also allows downstream consumers of the
instruction to track which specific they should be requesting
information from. Providing a correct expression category for
`specific_inst` will be handled in a future PR.
2026-09-08 16:01:09 +00:00
Dana Jansens 386327ed4c Disable clang-tidy misc-multiple-inheritance for clang 24 (#7724)
We use multiple inheritance extensively, such as with our
EntityWithParamsBase subclasses. But we don't do this for
vtables/virtual, we do it for composing fields.
2026-09-05 06:25:30 +00:00
Dana Jansens efb7ca9b90 Include ASTContext where it's used in mangler.cpp (#7723) 2026-09-04 16:52:16 +00:00
Dana Jansens 8626d6653d Disable readability-inconsistent-ifelse-braces (#7719)
This produces a warning on every use of CARBON_KIND() with clang 24.

I tried putting NOLINT comments into the macro on the else to no avail.
It seems that comments are stripped from the macro output when it's
performing the check.

We already require {} on every if/else (outside of these weird macro
cases) so this doesn't seem like a problem to disable.
2026-09-04 01:35:46 +00:00
Lucile Rose Nihlen 2952ec9c10 Fix a crash when checking a nested tuple-pattern (#7716)
Adds a virtual node to `DefaultValuePattern` to end the
`ExprRegionForPattern` before checking the expression
for the default value.

When checking the default value expression, the context
was still configured to interpret expressions as patterns,
which caused some corruption of state with tuple-pattern
subpatterns.

Corrects an assertion failure I found while working on
feedback from #7665.
2026-09-04 01:22:16 +00:00
Dana Jansens 1b969c292b Remove a comment that looks to be left behind from a refactoring (#7718)
The GetFacetTypeForQuerySpecificInterface function has two comments on
top of it. The second one actually refers to what the function does.
2026-09-03 19:56:34 +00:00
Özgür T. Önsoy 5474347d7d Support lexing and parsing positional params (#7651)
This implements lexing and parsing positional parameters such as `$0`.
2026-09-03 19:06:20 +00:00
Nicholas Bishop 27849b385c Add TemplateInst and drop CallCppTemplateAction (#7689)
`TemplateInst` wraps another inst. If that inst is symbolic, it is
treated as a template by `OperandDependence`.

Use this to replace `CallCppTemplateAction` with the more general
`CallAction`.
2026-09-03 17:45:47 +00:00
Richard Smith 7c966c2d59 Initialize specifics in-place. (#7717)
Don't wait until we reach the end of the eval block to set the value
block on the specific. This is a prerequisite for allowing template
actions to read from the specific.
2026-09-03 17:06:22 +00:00
Richard Smith b8814f6c80 Add named constraints for Eq and Ordered. (#7714)
Also add a default for `EqWith.NotEqual`.

Switch advent examples to use these named constraints, and also go
through all the other TODOs in the advent examples and fix the ones that
are trivially fixable now.
2026-09-03 16:20:13 +00:00
Dana Jansens 48671bffe2 Use match_first and remove some workarounds in prelude float.carbon (#7713)
The float.carbon conversions for int->float, uint->float and
float->float were using various workarounds through extra indirections
in order to avoid the impls overlapping. Now we can write them all as
`impl From as ImplicitAs(Float(To))`, which makes them all appear to
overlap, though any given type will only match at most one of them. We
use `match_first` to give them an ordering regardless so that they are
allowed to overlap in type structure.
2026-09-03 14:58:27 +00:00
Dana Jansens 2299b94b20 Use match_first to make the same_self_and_interface.carbon test pass again (#7711) 2026-09-03 14:58:13 +00:00
Dana Jansens 1740b24879 Use a consistent SDK version on MacOS (#7704)
The SDK returned by `xcrun --show-sdk-path` does not always match the
SDK
that is used by clang under homebrew, because homebrew has its own
configurations per target that specify an SDK path to `-isysroot`. And
on
Darwin, the `-isysroot` flag supercedes the `--sysroot` flag entirely
when
present.

To override homebrew, and ensure we use the SDK we expect to be using
from
`xcrun`, specify `-isysroot` ourselves on the command line, both when
finding
the include paths and when building.

The compiler ends up taking a dependency on a JSON file at the root of
the
SDK as well, so add that to our allowlist of non-hermetic files,
along-side
the SDK include paths.
2026-09-03 14:58:01 +00:00
Richard Smith 1a9181edf6 Remove repository overview from AGENTS.md (#7705)
Per https://arxiv.org/pdf/2602.11988 (section 4.3), repository overviews
have no effect on the time it takes agents to find files, but do
increase the cost of operations and number of required steps to complete
tasks.
2026-09-02 23:09:03 +00:00
Dana Jansens b6ba4ecdbb Use match_first to make the impl_recurse_with_simpler_type_in_generic_param_bidirectional_no_cycle.carbon test pass again (#7712) 2026-09-02 21:56:12 +00:00
Dana Jansens 95897201ee Avoid disk cache on MacOS by default since it breaks debugging (#7702)
There's no way for the user to override and disable the disk cache once
a path is specified in our current version of bazel. Later versions
would allow the user to specify `--nodisk-cache`. If the user really
wants a disk cache anyway, they can specify as such in their
`user.bazelrc` file.
2026-09-02 21:12:48 +00:00
Richard Smith 01815b6c47 Fix refinement of call action operands. (#7710)
Two somewhat related fixes. The first is call-specific for now (because
it's the first action to take a `MetaInstId`), and the second is general
across all actions, but it seems like calls are the easiest place to hit
it.

1) Add support for refining inst blocks as action operands. Refine all
   the insts in the block, using the appropriate InstId-derived type.
2) When an action operand is a `MetaInstId` referring to an unattached
   constant, form a corresponding attached constant. This comes up when
   forming (for example) an implicit `AddWith(%T)` call, where the `%T`
   operand is an unattached constant.

This causes us to form correct specifics in more cases, where previously
we formed specifics that contained values that were still
template-dependent.

This unfortunately causes some existing template tests to produce more
errors, but those errors reflect cases where we were previously silently
doing the wrong thing.
2026-09-02 20:36:18 +00:00
Dana Jansens f2ca6f6d4a Document installing SSL certificates for Python on MacOS (#7707) 2026-09-02 20:33:54 +00:00
Nicholas Bishop d8bb181db8 Fix SemIR not showing insts used to compute FieldDecl type (#7706)
Add an `ExprRegionId` to `FieldDecl`. This required moving the `NameId`
into `Field`.
2026-09-02 20:28:05 +00:00
Dana Jansens ed074e85ab Include StringSet where it is used (#7708) 2026-09-02 19:38:23 +00:00
Dana Jansens a460ce931e Document that match_first may contain a fourth declaration of an impl. (#7709)
The declarations in a `match_first` must always be in the same file as
the first owning declaration, in order to maintain a consistent view of
impl lookup across all files.
2026-09-02 19:38:12 +00:00
Dana Jansens b8eca6a6da Include the ASTContext header where it's used (#7701) 2026-09-02 17:35:31 +00:00
Richard Smith 2209a3477e Step through splices when checking for a bound method. (#7700)
`GetCallee` is sometimes called on a spliced instruction, and is
checking its exact inst operand to see if it's a `BoundMethod`. This
fails if the `BoundMethod` is wrapped in another instruction, such as a
splice. Normally our approach for such a situation would be to
constant-evaluate the operand, but that doesn't work here because the
`BoundMethod` will be non-constant if its bound `self` is. So instead we
now step through splice instructions manually when looking for the
`BoundMethod`.
2026-09-02 15:19:59 +00:00
Richard Smith 6724d506f3 Add cycle detection to instruction fingerprinting. (#7691)
Use a version of Brent's algorithm, suitably adapted to work for our
worklist-based graph traversal, to very cheaply detect if instruction
fingerprinting fell into a cycle and terminate cleanly with a dump of
the cycle.

The algorithm does not immediately catch when we enter a cycle, but is
guaranteed to catch it eventually (generally after running through the
cycle no more than twice).
2026-09-02 00:33:32 +00:00
josh11bandJosh L fe14c83731 Use jj_prek.sh to run prek in new_proposal.py with jj (#7699)
Recently noticed this issue when creating a proposal using
`new_proposal.py` in a `jj` workspace.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-09-02 00:22:38 +00:00
Lucile Rose Nihlen 3e64670122 Transform pattern default values to SemIR (#7649)
Adds check functionality to transform the parse node to SemIR. Only
supported for single declarations of functions, re-declaration and
imports to come in a subsequent PR.

Per #7521.
2026-09-01 16:12:34 +00:00
Lucile Rose Nihlen 91c1e1049d Add parsing of default value exprs in pattern lists (#7631)
Adds parsing support only for default value expressions in pattern
lists, including leaving the default value unspecified with an
underscore `_`.

Per #7521.
2026-09-01 01:19:13 +00:00
Richard Smith 742684635a Add --verbose / -v flag to autoupdate. (#7692)
With this set, autoupdate will print messages indicating what it's
doing, such as the command that it's invoking to execute bazel. For
example:

```console
$ ./toolchain/autoupdate_testdata.py -v toolchain/check/testdata/basics/empty.carbon 
Detected --compilation_mode: fastbuild
/home/zygoloid/carbon-lang/scripts/run_bazel.py run -c fastbuild --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/basics/empty.carbon
[... normal output ...]
```
2026-08-31 20:59:40 +00:00
DavidLoftus dc2ee5bd5e Implement lsp/formatting for Carbon::LanguageServer (#7688)
Implements formatting support within LSP. Current implementation
performs while file formatting, we just replace file with output of
Carbon::Format()

https://github.com/carbon-language/carbon-lang/pull/7687 independently
improves formatting so that this output is somewhat decent.

Assisted-With: Gemini / Antigravity
2026-08-31 16:38:38 +00:00
Nicholas Bishop f519cccaf2 Add CallAction to allow deferring calls (#7682)
Calls with template callee or args can now be deferred via an
InstAction. This allows code like this to check:

```carbon
import Cpp inline '''
template<typename T>
struct C {};
''';

fn F(generic T: type) {
  let unused c: Cpp.C(T) = Cpp.C(T).C();
}
```
2026-08-28 18:00:58 +00:00
Richard Smith 0ea8fb2e74 Add documentation for our constrained overload set idiom. (#7681)
As used in #7679.
2026-08-27 18:51:30 +00:00
Chandler Carruth ba0011bca8 Enable rumdl markdown line-length enforcement and reflowing (#7667)
This should handle over-long lines. I had tried to make the normalize
method work, but it doesn't seem promising and so let's at least enable
this version.

Assisted-by: Antigravity with Gemini
2026-08-27 00:13:39 +00:00
Richard Smith 197cae22f1 Use consistent pattern to generate constrained overload sets. (#7679)
Follow the pattern used by eval_inst.h's `EvalConstantInst` to generate
declarations of an overload set that handles some but not all typed inst
classes. The pattern is:

* A template computes the signature to use for a particular overload,
producing a fallback `() -> void` signature for overloads that should
not exist.
* The `.def` file is used to generate a declaration per instruction
kind, whose signature is generated by the template.
* The `() -> void` signature that all the "should not exist" cases
generate is explicitly deleted.

This avoids the redundancy of manually declaring all the overloads, as
we did for `PerformAction`, and is less error-prone as it both catches
signature errors and definitions of overloads that are dead code and
should not exist, as it did for the `FacetAccessType` overload of
`LowerInst`.
2026-08-26 19:34:37 +00:00
Chandler Carruth 95fc6fae22 common: Decouple LLVM hashing dependencies from common/hashing.h (#7646)
- Move formatted printing to `hashing.cpp` instead of `hashing.h`
- Separate APInt and APFloat hashing specializations into a new
`hashing_llvm.h`
- Update toolchain/base dependencies and include sites that hash LLVM
data types to include `hashing_llvm.h`

Combined, this reduces the transitive includes caused by `hashing.h`.

Assisted-by: Antigravity with Gemini
2026-08-26 00:41:51 +00:00
Richard SmithandGeoff Romer c7dcc50768 language-server: Remove an unnecessary vector copy on each source change. (#7669)
We track a "next" index into each bucket when we insert instructions.
The insert loop effectively shifts each element in the "next" vector
left by one place, so if we instead start the bucket counts shifted one
place to the right, we can use the same vector for "next" and for the
bucket start indexes.

Assisted-by: Claude Code

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-08-25 21:26:46 +00:00
Özgür T. Önsoy 2bdcb1fa62 Unify MergeRedecl functions (#7632)
As discussed in #7620.
2026-08-25 18:43:52 +00:00
Geoff Romer 1410795bf7 Support arbitrary parameter forms in MakeGeneratedFunctionDecl (#7654)
This allows generated functions to have different forms for different
parameters, and by-ref or by-value return forms. As a byproduct, this
allows generated functions to supply a return type _inst_ ID when they
have one, which preserves things like location information.
2026-08-24 21:15:50 +00:00
Nicholas Bishop 0745bda899 Support using Carbon generic types as C++ template parameters (#7673)
Example:
```carbon
import Cpp library "<vector>";

class C(T: type) {
  var v: Cpp.std.vector(T);
}

inline Cpp '''
void F() {
  Carbon::C<int> c;
  c.v.push_back(123);
  std::cout << c.v.back() << std::endl;
}
''';
```

A new `CallCppTemplateAction` is used to delay performing the C++
template call until non-symbolic arguments are known.
2026-08-24 18:53:24 +00:00
Richard Smith 6515090557 Don't provide the "start of file" token to the bracket fixer. (#7675)
We previously passed in the start of file token, classified as
BracketTokenKind::Other, which allowed the bracket fixer to consider
corrections where it inserted tokens (such as a `{`) *before* the
start-of-file token.

Fixes #7672.
2026-08-24 18:14:10 +00:00
Nicholas Bishop 7f3584a123 Support constant InstActions (#7671)
Treat `InstConstantKind::InstAction` the same as
`InstConstantKind::ConstInstAction`. Drop `ConstInstAction`, since the
two now behave the same.

Fix eval for specifics in a couple places to handle `InstId::None`.
2026-08-24 18:05:15 +00:00
Chandler Carruth 369b8fd06f Fix top-of-tree Clang build warnings (#7670)
`-Wunused-template` was added to `-Wunused`, so clean up the things it
found. One of them was a bug in the Clang warning that I've worked
around and reported upstream:

https://github.com/llvm/llvm-project/issues/218429
2026-08-24 15:54:21 +00:00
Chandler CarruthandGeoff Romer 2b9fdd6e42 Fix the check that every registered diagnostic kind is declared (#7660)
`load_diagnostic_kind` matched `^\s+CARBON_DIAGNOSTIC_KIND` without
`re.MULTILINE` against a file whose entries start at column zero, so it
found nothing: `check_unused` was comparing an empty set of declarations
against every use and reporting nothing at all. The check has never run.

With it running, three kinds turn out to be registered and never
declared, and go: `BuildFailureRunningClangToLink`,
`BuildOutputFileOpenError`, and `BuildPreludeManifestError`.

`load_diagnostic_uses_in` looked only for `CARBON_DIAGNOSTIC`, so a
diagnostic declared with `CARBON_DIAGNOSTIC_ON_SCOPE` counted as unused,
and it read the two macros' own definitions in `diagnostic.h` as uses.
Both are why the kinds above could not simply be deleted before.

Assisted-by: Claude Code

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-08-21 22:21:54 +00:00
Chandler Carruth 40aa4419c0 Update the terminal library for rendering diagnostics (#7659)
Everything drawn into a buffer was checked against `columns()`. That is
right for wrapping and for line drawing, both of which have somewhere
else to put what doesn't fit, but wrong for `DrawText`, which exists for
text that must not be broken and sometimes has to run past the width
with no other answer available. It and `DrawCodePoint` now check only
that the column is non-negative and the row is one a grid can index, and
widen the buffer as far as the text needs; `DrawWrappedText`,
`DrawHorizontalLine`, `DrawVerticalLine`, and `DrawBox` are unchanged.
That also settles what a caller does after a drawing overhangs, since
`DrawEnd` exists so that a run can continue where the last one ended,
and that continuation was itself a checked error whenever the previous
run overhung. A column computed to be negative, such as a gutter
narrower than the line number it holds, still fails.

A color picked to read against black is hard to read against white, and
nothing in `Capabilities` said which a stream was going into.
`ChooseBackground` reads `COLORFGBG`, which `rxvt` and its derivatives
set to the foreground and background palette indices, and takes anything
it doesn't answer to be dark: guessing dark costs contrast, while
guessing light puts pale text on a pale background. Asking the terminal
itself with an `OSC 11` query is the accurate answer, and needs raw
mode, a timeout, and somewhere to put the reply, so there is a TODO for
it rather than an implementation.

Every corner, tee, and crossing came out of `Charset::Ascii` as `+`,
which left six of the shapes a diagnostic draws indistinguishable: the
rule closing a frame read as the one separating two snippets, and the
anchor opening a diagnostic as the one carrying it on. Each stand-in now
keeps the axis its line runs through, which leaves `+` meaning a
crossing and nothing else. A tee keeps its through-stroke and leaves the
branch to what is drawn beside it, and a corner is `.` where its line
leaves downward and `'` where it arrives from above, which is where
those characters sit in their cells. A box is a box again:

```
    +--+        .--.
    |  |   ->   |  |
    +--+        '--'
```

Assisted-by: Claude Code
2026-08-21 22:19:12 +00:00
Richard Smith c41033c315 Make template actions refer to values from the specific. (#7663)
When a template action is created, any (non-meta) instruction operand
will refer to instructions in the corresponding generic, or possibly to
a constant. This means that when the action is eventually executed when
forming a specific, it would see the generic value for that operand
rather than the intended specific value.

Fix this by refining `InstId` operands to refer to a corresponding value
in the specific, much like we would when rebuilding a constant in the
eval block.
2026-08-21 18:34:21 +00:00
Richard Smith 186a756b72 Handle more kinds of templated conversion. (#7662)
Generalize ConvertToValue template action to handle other kinds of
conversion target that don't perform initialization. Initializing
conversions will need more work since they also need to use a splice to
form the storage block.
2026-08-21 14:39:19 +00:00
4172f4d3f2 Report an uniterable for range once (#7661)
Building a `for` loop looks `Core.Iterate` up twice: once for
`NewCursor` to make the cursor, and again for `Next` to advance it. A
range that implements neither failed both lookups and reported both, so
a loop over something that isn't iterable produced two errors saying the
same thing about the same expression.

The second lookup is skipped when the first already failed, which is
what `BuildBinaryOperator`'s `diagnose` parameter is for. The
`ErrorInst` it returns instead does not reach the produced SemIR: the
loop is abandoned on the error either way.

Assisted-by: Claude Code

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-08-21 04:09:16 +00:00
Richard SmithandChandler Carruth c588eadb57 Rename and rearrange entities in tests to avoid name reuse (#7656)
Fix a bunch of cases where we use the same external name to mean
multiple different things in the same test. We've historically gotten
away with this, but under `--share-cpp-ast`, it becomes an error, at
least if the entity is either defined in, or used from, C++ code.

Assisted-by: Gemini via Antigravity (original change) and Claude Code
(suggested edits in review)

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-08-21 01:36:40 +00:00
Richard Smith 6eb900dff5 Add template action for compound member access. (#7657)
This allows various templated constructs to get further through
checking, but typically we hit another unsupported action such as a
conversion or call, so it's not enough to make much work.
2026-08-20 15:45:02 +00:00
Chandler Carruth 631f8fb6d2 Modularize driver subcommands and prune unused dependencies (#7658)
- Subdivide toolchain/driver:driver into granular subcommand targets
(compile_subcommand, format_subcommand, lld_subcommand, etc.) to enable
independent compilation and linking.
- Decouple Target and TargetMachine options from driver headers.
- Prune unused direct dependencies across toolchain BUILD files.

Assisted-by: Antigravity with Gemini
2026-08-20 13:32:46 +00:00
Chandler CarruthandRichard Smith 9c486de2de Implement a terminal rendering library in common/terminal (#7597)
Rich diagnostic rendering needs a layer underneath it that knows what
the attached terminal can do and can position styled text in two
dimensions. This adds that layer, both as the foundation the diagnostics
rendering work will build on and as something usable directly for
ordinary CLI output. Nothing depends on it yet, so it lands and is
reviewed on its own.

Four libraries, each with its own tests:

- `color`: a color, either one of the 16 named ANSI colors or a 24-bit
RGB value, and the escape sequences that select it at a given color
depth.
- `style`: colors plus text attributes, and the escapes that move a
terminal from one style to another.
- `capabilities`: what the terminal behind a stream supports, detected
from the environment.
- `buffer`: a grid of styled cells that layout code draws into and that
renders itself once.

Rationale for the design decisions lives in the headers, next to what it
explains. Four things are worth review attention in particular:

- The color detection precedence documented on `ChooseColorMode`. It
settles how a `--color` flag, `NO_COLOR`, `CLICOLOR`, `FORCE_COLOR`, and
the terminal itself interact. The policy is a pure function of those
inputs, so the whole table is tested without touching the process
environment.

- `Charset`, which decides whether any UTF-8 processing happens at all.
Column counts only follow from code points if the terminal agrees about
the encoding, so anything short of a locale naming UTF-8 is treated as
bytes.

- `Buffer` owning column accounting instead of its callers, which is
what keeps double-width characters, combining marks, and stray bytes
from misaligning everything after them.

- The API surface, which is held to operations that nothing else covers.
Junctions in line art come only from lines overlapping, and turning a
style on or off is spelled as a transition to or from the default style.

`terminal_benchmark` covers style transitions, full-screen rendering,
and text drawing. On an M-series laptop, rendering an 80x24 screen in
which every cell changes style costs about 14us with color off and
76-95us with it, and drawing a 40-column line of source costs about
140ns without UTF-8 processing and 394ns with it.

Assisted-by: Gemini and Claude

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-08-19 21:54:46 +00:00
Richard Smith 3bbc03f527 Add better algorithm for repairing mismatched brackets (#7574)
Adds an algorithm to compute where to insert brackets to repair
bracketing mismatches during lexing. This takes indentation, as well as
a number of other cues, into account to predict where the brackets
should have gone. Detects when there is ambiguity between solutions and
makes no suggestion in that case. Reduces the problem by splitting on
properly bracketed top-level constructs, then uses a beam search to find
good candidate solutions quickly.

This includes both a fuzzer and an eval tool that can be used to
determine how well the algorithm fares against a given corpus of valid
Carbon code, by damaging it in various ways and seeing whether the
algorithm can correctly fix it. On all the eval modes, this algorithm
can correctly infer the positions for over 80% of lost brackets (and can
correctly restore 95+% of brackets in some modes), with low rates of
incorrect suggestions.

See added documentation for full details.

Assisted-by: Gemini via Antigravity, Claude via Claude Code
2026-08-19 18:55:32 +00:00
Richard Smith c06165d3e0 Require exported field types to be complete in the clang AST. (#7653)
It's not enough for field types of Carbon classes to be complete in
SemIR. If the field is exported to Clang, we also need the type to be
complete in Clang's AST, since Clang assumes it has a definition
available for the types of all fields of a complete class.
2026-08-19 17:45:34 +00:00
Richard Smith c78751338b language-server: Support simple semantic queries. (#7639)
Add support for "jump to declaration", "find references", type
information on hover. This support is strictly single-file for now; only
references and declarations within the same file are found. We could go
a bit beyond that, but to properly handle cross-file references we'll
need to build an index and a compilation database, which is beyond the
scope of this change.

On hover, we provide the type information for the instruction under the
cursor as-is. This is frequently not very useful, as the type of a
function F is simply "<type of F>", but is a starting point for richer
information.

Assisted-by: Claude Code
2026-08-19 14:35:05 +00:00
Chandler CarruthandRichard Smith a872123a73 Let Printable children default their comparison operators (#7642)
A defaulted `operator==` or `operator<=>` compares every base class
subobject, so children of `Printable` couldn't default their
comparisons: `Printable` had no comparison operators of its own, which
made the defaulted operator implicitly deleted. Children that want
member-wise comparison had to write it out by hand instead.

`Printable` is empty, so it now provides comparisons that always compare
equal. Its operands are constrained template parameter rather than
`const Printable&` so that they're only viable for comparing the base
class subobjects themselves. An overload taking `const Printable&` would
also be viable when comparing two `DerivedT` objects by converting them
to the base class, and would then both make children that provide no
comparison silently compare equal and displace the comparisons of
children that provide them through a conversion of their own, as
`EnumBase` does.

Some hand-written comparisons stay, for reasons unrelated to
`Printable`: using `= default` would change their meaning.

Adds `common/ostream_test.cpp`, which covers both the member and friend
forms of defaulting, the resulting comparison categories, and both of
the hazards above.

Assisted-by: Claude Code

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-08-19 01:00:13 +00:00
Richard Smith 047555bb1c Don't crash if a macro expands to an erroneous expression. (#7652)
For certain kinds of error, clang's parser will succeed but produce an
expression marked as "contains error". Clang's constant evaluator
asserts if given one of those, so return early if we encounter one.
2026-08-19 00:47:03 +00:00
Geoff Romer d21cc3197f Fix the textual IR name of WrapperBindingPattern (#7650)
`at_binding_pattern` is a relic from an earlier revision of #6930.
2026-08-18 22:31:27 +00:00
DavidLoftus 70b6abd6f1 Implement FloatLiteral addition and subtraction (#7621)
Addresses part of issue raised in
https://github.com/carbon-language/carbon-lang/issues/7159 by
implementing float.add & float.sub builtin for FloatLiteralValues

The following code now compiles:

```
let a: f64 = 1.0 + 1.0;
```

Code handles case where operands are both decadic (base 10) and dyadic
(base 2) real literals, with the result being whichever format results
in smaller mantisssa.

File tests assert equality by converting to f128, this can possibly be
improved once CompareWith is implemented for FloatLiteral too.

Assisted-By: Gemini
2026-08-18 17:47:58 +00:00
David Blaikie 0c186053ec Fix invalid parse tree with explicit runtime on invalid var (#7635)
Found by fuzz testing, root caused to #7479 - fixing this issue for Var
in a similar way to how it was fixed for Let in that patch (by adding
`RuntimeBindingName` to the possible things in the name binding.

Not sure if this would be better fixed by adding `RuntimeBindingName` to
`AnyRuntimeBindingPatternName` or something else?

Assisted-By: Gemini with Antigravity
2026-08-17 21:30:15 +00:00
Richard Smith 9a33fc1673 language-server: attempt to negotiate UTF-8 positions. (#7636)
We currently provide UTF-8 positions, since our source representation is
UTF-8 and we use byte offsets as column numbers, but the LSP protocol
default is UTF-16 column positions. Negotiate UTF-8 positions where
possible; this is supported by essentially every LSP client other than
VS Code.

In the case where we select a UTF-16 position, we continue to not do any
actual conversions, so our column offsets in such cases will continue to
be wrong on non-ASCII source files in VS Code.

Assisted by: Claude Code
2026-08-17 20:56:37 +00:00
Christopher Di BellaandRichard Smith 0f06fe65fa Add interface modifiers (#7625)
This adds most support for default and final methods. Missing components
include rejecting definitions for non-default/final methods, and
permitting out-of-line definitions.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-08-17 20:49:23 +00:00
Chandler Carruth 1e6d554cb6 Avoid pseudo-list markers in proposals/p000162-basic-syntax.md (#7641)
Change '1)' and '2)' to '(1)' and '(2)' to prevent the reflow engine
from treating them as ordered list markers when the paragraph is
wrapped.

Assisted-by: Antigravity with Gemini
2026-08-17 20:31:30 +00:00
Geoff Romer b13f0ddaf5 Document why patterns are in separate blocks (#7469) 2026-08-17 20:05:07 +00:00
Özgür T. Önsoy 77c1ad745e Remove redundant todo_access_modifiers.carbon test and dump-sem-ir-ranges flag (#7643)
We already test this in `access_modifiers.carbon`.

This also fixes a typo in the name of `access_modifiers.carbon` and
removes the `--dump-sem-ir-ranges` flag.
2026-08-17 19:58:41 +00:00
Chandler Carruth f58de06c0d parse, lex: Decompose AST extraction and forward-declare dump types (#7645)
- Enhance toolchain/parse/node_kind.def with category x-macros
(CARBON_PARSE_NODE_KIND_DECLARATION, CARBON_PARSE_NODE_KIND_EXPRESSION,
CARBON_PARSE_NODE_KIND_PATTERN, CARBON_PARSE_NODE_KIND_STATEMENT) that
default to CARBON_PARSE_NODE_KIND, keeping node_kind.def as the single
source of truth without manual expansion divergence.
- Decompose the monolithic toolchain/parse/extract.cpp translation unit
into separate compilation units for declarations, expressions, patterns,
and statements by expanding respective category x-macros.
- Forward-declare Tree and TokenizedBuffer in parse and lex dump headers
to reduce header inclusion depth.

Assisted-by: Antigravity with Gemini
2026-08-17 17:39:42 +00:00
DavidLoftus b2900105d7 Add "file://" document filter to vscode extension (#7647)
Currently VSCode extension will try share diff views / scratch files
with Carbon language server. This results in following error:

> Request textDocument/semanticTokens/full failed.
Message: in call to `textDocument/semanticTokens/full`, JSON parse
failed: clangd only supports 'file' URI scheme for workspace files at
(root).textDocument.uri
  Code: -32602 

The change here updates vscode extension to filter for
`file://*/**.carbon` URIs, this matches how clangd extension does it:
https://github.com/clangd/vscode-clangd/blob/893dd905c2a6a7844fe32592796ef593e6f3bca6/src/clangd-context.ts#L18

Also updates tsconfig.json to node16 module resolution, this is done
since [automatic dependabot
PR](https://github.com/carbon-language/carbon-lang/pull/7575) seems to
have broken the build.

```
src/extension.ts:28:8 - error TS2307: Cannot find module 'vscode-languageclient/node' or its corresponding type declarations.
  There are types at '/usr/local/google/home/davidloftus/carbon-lang/utils/vscode/node_modules/vscode-languageclient/lib/node/main.d.ts', but this result could not be resolved under your current 'moduleResolution' setting. Consider updating to 'node16', 'nodenext', or 'bundler'.

28 } from 'vscode-languageclient/node';
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Found 1 error in src/extension.ts:28
```


[vscode-languageserver-node](https://github.com/microsoft/vscode-languageserver-node/blame/93d5fe6f443dd6c8fe37f422c271d618edd121af/README.md#L159)
recomends updating to node16.
2026-08-17 16:48:03 +00:00
Chandler Carruth 864845c0c0 lex: Optimize token_kind_test compilation by consolidating test helpers (#7644)
- Consolidate token kind test assertions into helper functions using
EXPECT_THAT(spelling.str(), MatchesRegex(...)) under a single test case
rather than generating ~130 separate TEST classes and redundant matcher
instantiations.
- Slashes individual translation unit compilation time from 59.1s to ~3s
while keeping EXPECT_THAT for clear diagnostic error output and full
token coverage.

Assisted-by: Antigravity with Gemini
2026-08-16 18:21:16 +00:00
Richard Smith 277815fd94 language-server: Stub out support for some messages we don't handle yet. (#7637)
This suppresses warnings for unhandled messages where we currently have
nothing to do. No functionality change, except for less spam in the VS
Code output tab.

Assisted-by: Claude Code
2026-08-14 20:15:42 +00:00
Richard Smith db762cca85 language-server: Fix malformed symbol output on incomplete declarations. (#7638)
When computing the token range of a declaration, we were using the first
and last parse nodes to determine the first and last tokens. That's not
correct -- the parse tree nodes can be in a different order from the
tokens, so the first parse node need not be at the start of the
declaration. For a malformed declaration such as `fn f` (with no
terminator), the first and last parse nodes were both associated with
the `fn` token for error recovery, meaning that the function name wasn't
even within the symbol we handed back to the LSP client, in violation of
the LSP requirements. This led to VS Code producing an error and
discarding all symbols in the file.

Assisted-by: Claude Code
2026-08-14 19:56:07 +00:00
Nicholas Bishop 3bb245364f Support exporting class specifics to C++ (#7634)
This is similar to the previously-added support for accessing generic
carbon classes from C++, but with the specific defined by Carbon, rather
than being derived from template args supplied by clang in
`LoadExternalSpecializations`.

Example:
```carbon
class C(T: type) {
  var t: T;
}
alias A = C(i32);

inline Cpp '''
void F() {
  Carbon::A a;
  a.t = 123;
}
'''
```
2026-08-13 23:30:24 +00:00
DavidLoftus 54b7f1345a Implement Core.Negate for float literals (#7616)
Addresses part of issue raised in #7159 by implementing float.negate
builtin for FloatLiteralValues

The following code now compiles:

```
let a: f64 = -1.0;
```

To achieve this I switch the mantissa from being unsigned to signed.
Lexed literals within source file will still always be unsigned, however
it is now possible to create negative FloatLiteralValue constants. Main
non-local changes this causes is:

- All llvm::APInt parsing / printing calls flipped isSigned param
- Zero extension replaced with sign extension
- getActiveBits() replaced with getSignificantBits() for min bit width
calculation
2026-08-13 20:28:42 +00:00
Nicholas Bishop 2784f33221 Fix clang_decls InstId for generic class export (#7633)
The exported class was being inserted with a type inst ID as the key
(and looked up that way elsewhere), but when checking if the generic
class was already exported, the `first_decl_id` was being used. Make it
consistent, and opt for `first_decl_id` everywhere since it provides a
better location for diagnostics.
2026-08-13 17:30:20 +00:00
Christopher Di BellaandRichard Smith 4ea5ef45dd Skip ImplWitnessTable::elements_id when generating fingerprints (#7629)
Implementing interface modifiers causes an infinite loop when generating
fingerprints because the witness value generates a fingerprint that's
dependent on something dependent on the witness value. We've debugged
this to the witness table's `elements_id` field.

This hack is a workaround for creating a new block type whose value is
not codependent with its identity.

Co-authored-by: Richard Smith <richard@metafoo.co.uk>

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-08-11 22:39:30 +00:00
Özgür T. Önsoy cb5e9b6555 Diagnose missing interface definition in impl files (#7622)
We can now implement this since #4071 is resolved.
2026-08-11 21:06:17 +00:00
Özgür T. ÖnsoyandRichard Smith 1f22ba91bb Handle import refs in TryGetExistingDecl (#7620)
This solves the problem where `interface` imports are incorrectly
diagnosed as duplicate names in impl files.
Follows the implementation logic used in `handle_class.cpp`.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-08-11 19:29:46 +00:00
Richard Smith 0f93cbd370 Support ranges with overloaded const/non-const begin and end. (#7627)
If we find an overload set containing mulitple methods, discard any
non-const methods and try again. This allows libc++'s `std::vector` to
be iterated with range-based for.
2026-08-11 19:14:37 +00:00
Christopher Di Bella e10827ed84 Diagnose when an impl is added for something that has a custom witness (#7623)
The toolchain crash is easily diagnosed, but looking at the log doesn't
offer immediate insight into why the program crashes. This provides us
with a graceful exit.
2026-08-11 19:13:47 +00:00
Özgür T. ÖnsoyandChristopher Di Bella c63bbf3598 Update observe design doc to reflect proposal #7545 (#7617)
This adds the new restrictions introduced for `observe` declarations
inside `interface` definitions to the docs.

---------

Co-authored-by: Christopher Di Bella <cjdb.ns@gmail.com>
2026-08-11 19:09:38 +00:00
Lucile Rose Nihlen b64d863a8f roll llvm to a6b0af7536ef (#7624)
This updates LLVM by a month.

Removes patch 10 which landed upstream.

Adds a new patch to remove more libc-dependent files
from compiler-rt builtins.
2026-08-10 19:37:40 +00:00
Nicholas Bishop de1cd701cf Add initial support for exporting generic classes (#7595)
Currently only fields of generic classes are exported; methods of
generic classes are not supported yet.

Simple example:

```carbon
class C(T: type) {
  var t: T;
}

inline Cpp '''
void F() {
  Carbon::C<int> c;
  c.t = 123;

  Carbon::C<float> c2;
  c2.t = 124.5;
}
''';
```
2026-08-10 17:47:45 +00:00
Nicholas Bishop 700e42a195 Simplify extra_name in ExportFunctionSpecializationToCpp (#7587)
Rather than appending to the thunk name for each template arg, use the
mangled form of the specific ID.
2026-08-10 15:09:58 +00:00
e7050af1c9 Fix bitwise OR markdown table pipe escapes (#7602)
https://docs.carbon-lang.dev/docs/design/expressions/#operators

Escaping `|` is needed to prevent markdown table interpreting it as a
cell edge, however using `\|` in backticks shows the backslash too.
Solution: use `<code>` instead. This overflows the `|` table cell but it
seems to render correctly anyway.

Co-authored-by: David Blaikie <dblaikie@gmail.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-08-07 18:21:03 +00:00
Christopher Di Bella 8e90e2a855 Change String.size from u64 to i64 (#7614)
`String.size` is likely to be a signed word-sized integer in the future,
(per a Discord conversation). Changing to `i64` now allows us to iterate
over a string's contents using `IntRange`.
2026-08-07 18:14:50 +00:00
Richard Smith 06a056d795 Fix crash exporting a Carbon function to C++ without a code generator. (#7619)
We can't rely on a `clang::CodeGenerator` existing when compiling C++
code; we don't build one unless we're actually emitting code for the
current file any more.
2026-08-07 18:06:36 +00:00
Richard Smith 7e861cd3c0 Split up failure tests into separate splits. (#7603)
As requested in review of #7596.
2026-08-07 17:52:06 +00:00
Richard Smith c278bea3c5 Support LP64 platforms such as Darwin where int64_t is long long. (#7596)
Add `Core.CppCompat.[U]Long64` to represent a 64-bit long that is not
`i64`. Treat it as being "just slightly smaller than" `i64`, like we
treat `Core.CppCompat.LongLong64` as being "just slightly larger than"
`i64`, so that we get implicit conversions `Cpp.long` -> `i64` ->
`Cpp.long_long` on all targets.

This follows the direction of proposal #5448, and seems like the obvious
extension of the `[U]Long32` and `[U]LongLong64` types added in #6275
for targets of this "shape".

Assisted-by: Gemini via Antigravity
2026-08-07 16:10:01 +00:00
Richard Smith ee2b3888ef Split up tests for bad imports. (#7612)
Clang treats "file not found" as a fatal error and stops emitting more
diagnostics after reaching it, so these tests don't work in
`--share-cpp-ast` mode if they are all in the same file. So split them
into distinct test files.
2026-08-06 22:55:25 +00:00
Richard Smith a1e843718e Create modules for header imports. (#7613)
Make multiple imports of the same header only parse it once per C++
domain. Reuse of the same header in `--share-cpp-ast` mode now reuses
the representation.

Importing a Carbon file with C++ dependencies now makes those transitive
C++ dependencies in the same C++ domain visible too.

Assisted-by: Gemini via Antigravity
2026-08-06 13:32:37 +00:00
Özgür T. Önsoy b9692a0e77 Restrict observe declarations to names that are part of the enclosing interface (#7545)
This proposal restricts `observe` declarations in an `interface` to only
reference names dependent on `.Self`, generic parameters, and associated
constants that are part of the enclosing `interface`, with the following
exceptions:

-   Allow at most one unrelated value in an equivalence (`==`) chain.
- Allow unrelated values that satisfy the `impls` constraint immediately
in an
    `observe .. == .. impls`.
2026-08-05 21:23:21 +00:00
Richard Smith 08605122f4 Improve diagnostic when test split unexpectedly succeeds or fails. (#7608)
When a split file in a test unexpectedly succeeds or fails, include the
test filename in the error as well as the name of the split. This should
make it a bit easier to figure out which test failed from a failing test
log.
2026-08-05 17:34:52 +00:00
Richard Smith dea290db81 Only lower files we are going to emit. (#7611)
Move `--output-last-file-only` and output filename synthesis logic out
of the general-purpose compile driver and into the `carbon compile`
subcommand, which is the only thing that should be using them. Track on
CompilationUnit whether it is being lowered, or whether it exists only
to be imported into other units.

`carbon compile` now never lowers inputs that it discovered for itself,
only inputs that were specified on the command line. In particular, it
doesn't lower (and throw away the result of lowering) the prelude any
more. This makes the toolchain tests about 10% faster in my crude
measurements.

Also, we now do not create a clang `CodeGenerator` for input files that
we are not lowering, similarly saving compilation time for units that
exist only to be imported, not lowered.

One minor change: we use the same mechanism to determine whether an
input is being lowered and to determine what the output filename is.
This means that `--phase=lower` and `--phase=optimize`, which lower but
don't produce an output file, still need an output filename to be
specified now in some cases. Given those are just debugging tools, I
think that's fine.

Assisted-by: Gemini via Antigravity
2026-08-05 12:52:24 +00:00
Richard Smith f776cf0744 Improve readability of test failures. (#7609)
Reduce use of gmock matcher infrastructure for diagnosing mismatches,
and instead manually stream an explanation of the difference. The
gmock-style "EXPECT_THAT" approach adds an unsuppressable "Actual: ..."
line into the output that only contains unreadable and redundant noise.
We're getting zero value from using a matcher diagnostic here, so don't.

Before:
```
Value of: SplitOutput(test_file.actual_stdout)
Expected: matches elements with unified diff
  Actual: { "--- else.carbon", "", "constants {", "  %F.type: type = fn_type @F [concrete]", "  %empty_tuple.type: type = tuple_type () [concrete]", "  %F: %F.type = struct_value () [concrete]", "  %H.type: type = fn_type @H [concrete]", "  %H: %H.type = struct_value () [concrete]", "  %pattern_type: type = pattern_type bool [concrete]", "  %b.param_patt: %pattern_type = value_param_pattern [concrete]", "  %b.patt: %pattern_type = at_binding_pattern b, %b.param_patt [concrete]", "  %If.type: type = fn_type @If [concrete]", "  %If: %If.type = struct_value () [concrete]", "}", "", "file {", "  %If.decl: %If.type = fn_decl @If [concrete = constants.%If] {", "    %b.param_patt: %pattern_type = value_param_pattern [concrete = constants.%b.param_patt]", "    %b.patt: %pattern_type = at_binding_pattern b, %b.param_patt [concrete = constants.%b.patt]", "  } {", "    %b.param: bool = value_param call_param0", "    %.loc8: type = type_literal bool [concrete = bool]", "    %b: bool = wrapper_binding b, %b.param", "  }", "}", "", "fn @If(%b.param: bool) {", "!entry:", "  %b.ref: bool = name_ref b, %b", "  if %b.ref br !if.then else br !if.else", "", "!if.then:", ... }, unified diff (- expected, + actual):
=== diff in expected elements 4 to 11 (1-based index):
    %F.type: type = fn_type @F [concrete]
    %empty_tuple.type: type = tuple_type () [concrete]
    %F: %F.type = struct_value () [concrete]
- is equal to "  %G.type: type = fn_type @G [concrete]"
- is equal to "  %G: %G.type = struct_value () [concrete]"
    %H.type: type = fn_type @H [concrete]
    %H: %H.type = struct_value () [concrete]
    %pattern_type: type = pattern_type bool [concrete]
=== diff in expected elements 37 to 44 (1-based index):
    br !if.done
  
  !if.else:
- is equal to "  %G.ref: %G.type = name_ref G, file.%G.decl [concrete = constants.%G]"
- is equal to "  %G.call: init %empty_tuple.type = call %G.ref()"
    br !if.done
  
  !if.done:
=== diff end
```

After:
```
Value of: testing::Value(SplitOutput(test_file.actual_stdout), testing::ElementsAreArray(test_file.expected_stdout))
  Actual: false
Expected: true
unified diff (- expected, + actual):
=== diff in expected elements 4 to 11 (1-based index):
   %F.type: type = fn_type @F [concrete]
   %empty_tuple.type: type = tuple_type () [concrete]
   %F: %F.type = struct_value () [concrete]
-  %G.type: type = fn_type @G [concrete]
-  %G: %G.type = struct_value () [concrete]
   %H.type: type = fn_type @H [concrete]
   %H: %H.type = struct_value () [concrete]
   %pattern_type: type = pattern_type bool [concrete]
=== diff in expected elements 37 to 44 (1-based index):
   br !if.done
 
 !if.else:
-  %G.ref: %G.type = name_ref G, file.%G.decl [concrete = constants.%G]
-  %G.call: init %empty_tuple.type = call %G.ref()
   br !if.done
 
 !if.done:
=== diff end
``` 

Assisted-by: Gemini via Antigravity
2026-08-04 21:23:36 +00:00
Richard Smith 34a2e270f4 Fix C++ code generation in --share-cpp-ast mode (#7605)
Instead of creating a CodeGenerator per CppDomain, and then crashing in
lowering when we try to consume the same llvm Module multiple times,
create a CodeGenerator for each CppFile within the domain.

For now, we mulitplex all of Clang's ASTConsumer output to all code
generators, which means that any strong external definitions within a
Carbon file (for example, in an inline `Cpp` fragment) will be emitted
to all output files in the same `CppDomain`, resulting in link errors
due to symbol redefinitions. This will be addressed later. But this
should be sufficient for Carbon compilations in which such symbols are
not defined.

We also don't yet attempt to classify which compilations will need C++
code generation, and instead create a clang `CodeGenerator` for every
Carbon file that has C++ imports. For `carbom compile`, only one Carbon
file will need code generation, and yet we still build multiple
`CodeGenerator` objects in general. Fixing this requires more plumbing
from the driver, and this will also be handled in a follow-up.

Assisted-by: Gemini via Antigravity
2026-08-04 17:59:06 +00:00
a9cc7bf490 File concatenation principle (#6031)
We propose a principle that it's always possible to inline the import of
a library from within the same package without changing the meaning of
or diagnostics applied to the code. This is similar to the textual
inlining of an `#include` statement in C++, but is slightly less
general. Cross-package imports place the imported names inside the name
scope of the package, so inlining those necessarily changes the paths
for name lookup.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2026-08-03 17:20:59 +00:00
Richard Smith 46b5482bb4 Create a Clang module per Carbon file. (#7594)
This isolates the C++ imports in different Carbon files from each other
in `--share-cpp-ast` mode, so that a Carbon file can only see the
portions of the shared Clang `ASTContext` that it actually imported.

Assisted-by: Gemini via Antigravity
2026-07-31 22:43:56 +00:00
Geoff Romer a5f3d45717 Fix uses of "dependent" to mean "dependency" (#7599)
For consistency with existing code I've chosen to use "dep" as an
abbreviation for "dependency", even though it's somewhat ambiguous with
"dependent".
2026-07-31 22:07:32 +00:00
Dana Jansens 2f58185c44 Find the current impl from accesses in a named constraint being implemented (#7592)
When implementing a named constraint, like `impl as N`, any accesses
through `Self` in the named constraint need to get the value of the
associated constant from the impl's witness table. This isn't possible
immediately, since the impl does not even exist until the declaration is
complete. We use the same model as for accesses found directly in the
impl declaration, but applied to the point where accesses in the named
constraint are substituted during identify to point at the impl's self
type. To get there, we need LookupImplWitness instructions in the named
constraint, when re-evaluated during construction of their enclosing
specific, to evaluate to ImplSelfWitness when they are a reference to
the type and interface being implemented.
2026-07-31 20:17:06 +00:00
Dana Jansens db88edfa1e Disable RTTI in the toolchain (#7552)
This reduces object sizes which is desirable for linking speed.

zygoloid did some analysis to determine if any of our code requires RTTI
for `dynamic_cast` here:
https://github.com/carbon-language/carbon-lang/pull/7532#discussion_r3611196721:
> The only thing I found is that libc++ requires dynamic_cast in order
for std::print to correctly write Unicode to terminals on Windows

We use `llvm::print` functionality, not `std::print`, so this doesn't
affect our toolchain.

Note that libc++ and libc++abi are built with RTTI enabled. It is
explicitly allowed to use different compiler flags when building these
libraries even though they share some headers with users of the
libraries, so this does not cause ODR violations.
2026-07-31 20:09:48 +00:00
Richard Smith 6e9e871b74 Fix handling of recursive macros. (#7593)
Inject the name of a macro rather than its contents when computing its
expansion. If the macro refers to itself, it will not expand within its
own body, rather than expanding once.

Switching from `EnterTokenStream` to `EnterToken` exposed that our Clang
preprocessing environment was a little broken -- we reached the end of
the primary source file and starting tearing stuff down before we
actually finished parsing, which we were mostly getting away with before
but aren't any more. Enabled Clang's incremental processing mode to fix
this. This causes Clang to remain in the main source file when it
reaches EOF instead of popping it. This also causes the diagnostics for
invalid `module;` declarations to change, but in a way that seems not
really any worse than before.

Also slightly changes the diagnostics produced from macro expansion
failures. The new diagnostics are a bit more precise -- they now capture
the outermost level of macro expansion -- but we don't do a good job of
rendering the Clang snippet attached to the "in macro expansion" context
note yet, so the context looks a bit weird: we get two different
snippets attached to the same diagnostic.
2026-07-31 20:09:03 +00:00
Richard Smith 87d2234d5c Fix create_compdb.py. (#7598)
pathlib's suffix includes a `.`, so make sure we include one when
validating the suffix. Otherwise, most files are missing from the
database!
2026-07-31 19:30:25 +00:00
Richard SmithandChristopher Di Bella 9bcee64b32 Add some encapsulation to CppDomain (#7579)
Start tracking the domain within `CppContext`s instead of having them
duplicate its fields. This allows us to remove the shared ownership of
the clang parser.

---------

Co-authored-by: Christopher Di Bella <cjdb.ns@gmail.com>
2026-07-31 18:08:13 +00:00
Dana Jansens 9b8a2124b9 Don't require non-class types to be complete to convert from them (#7590)
In Convert, we require the source value's type to be compete so that we
can look for `base` classes and `adapt` relationships. However these can
only be present in a `ClassType`, so we only need `ClassType`s to be
complete.

Reduce the requirement in Convert to not complete types that are not a
`ClassType`, and which can not contain a `ClassType` as part of their
class.

Ideally we would only _only_ require the `ClassType` itself to be
complete, and only if we're looking for a base or adapt. However lower
depends on us completing all Convert source types that contain a class.
This seems to suggest we're lacking checks for complete types somewhere
else and Convert is making up for it. A TODO has been added. The
`toolchain/driver/testdata/compile/optimize/optimize_debug.carbon` test
is an example that CHECKs due to failing to verify the LLVM module if we
do not compute the complete type of all class-containing types in
Convert.

The critical step this PR is doing is to stop trying to complete a
`FacetType` when converting from a facet. This avoids trying to complete
a named constraint when converting `Self` inside that named constraint.
Doing so causes a cycle when the conversion of `Self` is performed in
eval of an `extend require` decl, since requiring the named constraint
to be complete re-evaluates the `extend require` decl again. A test is
added that crashed in an infinite loop before this change.

It also depends on #7584, which was intended to be an optimization but
is now load bearing. Because converting `Self` leaves an impl lookup
inst behind, and if that inst is re-evaluated inside impl lookup (by
forming a specific of a `require` decl through identify) then we have a
similar cycle.
2026-07-31 17:35:21 +00:00
Geoff Romer 6429c1655c Make the tree structure more explicit in parse dumps (#7591)
It's hard to track 2-space indent levels across large vertical gaps, and
it can be hard to suppress the instinct to read the dump as if it were
preorder. This change introduces a new dump mode that addresses both
problems by using box-drawing characters to explicitly represent the
parent-child edges of the tree. This new mode is the default, but the
old behavior remains available with
`--parse-dump-format=yaml-postorder`.
2026-07-31 16:44:18 +00:00
Nicholas Bishop 2c91e5f5de Take specific into account in CalculateCppFieldOffsets (#7588)
Add a `SpecificID` arg to `Class::GetStructTypeFields`, and use that in
`CalculateCppFieldOffsets`. Also include the specific in the
`clang_decls` lookup. This has no immediate effect since no specific
class fields are being exported yet, but will be useful for exporting
generic classes.
2026-07-30 21:50:13 +00:00
Richard SmithandGeoff Romer 6f68a51286 Filter binaries out of compilation database. (#7589)
Since we started bootstrapping, our stage-1 toolchain binaries have been
inputs to stage-2 compilations, and to the compilation database logic,
they're indistinguishable from generated sources. This caused us to get
compilation command lines for them, which clangd would try to index by
parsing the binary, and would either run incredibly slowly or crash.

Filter out non-source files from the compilation database.

In passing, also emit the JSON dump without whitespace, which makes the
database a bit smaller and faster for clangd to parse.

Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-07-30 21:39:40 +00:00
Richard Smith f473ca994a Fix a collection of small language-server bugs in document_symbol. (#7581)
Don't CHECK-fail if the file contains mismatched braces and generates an
unbalanced parse tree.

Properly balance the start and end of symbols. This previously caused
errors to be reported in clients such as VS Code.

Compute a correct range for definitions. Don't assume we can find the
matching `}` for an opening symbol, since some of our definitions are
delimited by a `;` instead.

Assisted-by: Gemini via Antigravity
2026-07-30 21:35:08 +00:00
Dana Jansens 239ad9fe8b Disable C++ exceptions in the toolchain (#7532)
Pass `-fno-exceptions` when building the toolchain. We do not use
exceptions, so we do not have any try/catch in main, so uncaught
exceptions just unwind and exit. They do not hit our signal handler and
we do not print the stack trace.

Instead of adding a try/catch in main, and redirecting that, we can
build with `-fno-exceptions`. This turns any throw into an `abort()`.
And indeed with that flag, the following code crashes and prints a stack
trace:
```cpp
  std::variant<int, bool> a = {1};
  std::get<bool>(a);
```

Note that libc++ and libc++abi need to be built with exceptions enabled.
It is explicitly allowed to use different compiler flags when building
these libraries even though they share some headers with users of the
libraries, so this does not cause ODR violations.

Fixes #5225
2026-07-30 20:15:03 +00:00
Dana Jansens a5ba0a0f45 Use GetConstantValueInSpecific to get the impl's specific interface after deduction (#7584)
During impl lookup, for each (generic) impl candidate, we form a
specific for that impl by deducing its generic arguments. Then we
compare the query interface against the impl's specific interface. That
comparison needs the deduced arguments applied to the impl's specific
interface. Previously we were doing this by getting the impl's
constraint facet type with the impl's specific applied (via
`GetConstantValueInSpecific()`) and then identifying that facet type
with the impl's deduced self.

Identify is a fairly expensive operation. It runs subst, trying to
replace `.Self` references. It walks named constraints. It collects
require declarations. We're looking at making it do _more_ in the future
too, including rewrite constraint resolution and collecting rewrite and
same-type constraints. For this reason we have a cache to make it cheap
on the second run, but it's still a very heavyweight operation to
involve in impl lookup, when all we want is to apply the impl's specific
to its target interface.

We almost have all the information we need to avoid the identification
step. We have the impl's specific after deduction. And we have the
SpecificInterface that the impl is targeting in the `Impl` struct. When
we form the specific for the impl itself, we resolve the declaration
block and form new constant values for all instructions in there, but
that does not cover the SpecificInterface that we're storing in the
`Impl` struct. So we add a new instruction to the impl's eval block,
which will be symbolic when the impl is generic and the target interface
depends on a generic parameter. And we store the `InstId` in the `Impl`
struct. This allows us to gets its constant value later with the impl's
specific applied. From that constant value we can then pull out the
SpecificInterface that the impl is targeting.
2026-07-30 19:59:10 +00:00
oli-ej a683fb574b Add initial support for parsing struct patterns (#7446)
Implements parsing of struct patterns as per
https://github.com/carbon-language/carbon-lang/issues/6680.

This handles the full and short syntax given in the [design
doc](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/pattern_matching.md#struct-patterns),
but the handling of the shorthand syntax may need to change as I move on
to implementing Check support (currently the shorthand is represented as
one of `LetBindingPattern`, `VarBindingPattern`, or `VariablePattern`).

This implementation assumes that the answer to
https://github.com/carbon-language/carbon-lang/issues/7404 is that
trailing commas are allowed in the struct pattern, except for the case
where an `_` is present, in which case the next token must be the
closing brace `}`.
2026-07-30 16:37:46 +00:00
arhwx 8f224222a1 Export abstract methods as pure virtual (#7578)
`abstract fn` was exported to C++ as a plain virtual function rather
than a pure virtual one, so the class wasn't abstract and could be
instantiated from C++.

Abstract functions no longer get a thunk since there is no definition to
call. The tests are prefixed with `fail_` since an abstract class still
errors on `Core.Destroy` regardless.
2026-07-30 00:29:53 +00:00
Nicholas Bishop 198e447e4a Add specific_id and pattern_inst_id to ClangDecl (#7583)
Exporting class fields in class specifics will require looking up
`ClangDecl`s by the field's `InstId` and the class's `SpecificId`. Add
the `specific_id` to ClangeDecl, and rework the reverse lookup to use a
`Set` with a `KeyContext` rather than a `Map`. The `Lookup` method now
takes an optional `SpecificId` argument, although currently it is always
`None`.

For `VarStorage`, reverse lookup is performed by the pattern `InstId`
rather than the `InstId` of the `VarStorage` itself, so also add
`pattern_inst_id` to `ClangDecl`, and provide a separate
`LookupByPatternInstId` method for reverse lookups. For this lookup, the
`inst_id` part of the key is set to `None`, so only the pattern's
`InstId` is used for lookup.
2026-07-29 19:53:12 +00:00
Nicholas Bishop f4e7a84df2 Remove Class::fields_exported (#7586)
In preparation for exporting specific classes, remove `fields_exported`.
A class's fields will be exported for each specific, so a single boolean
won't work.

Instead, check in `ExportAllFieldsToCpp` if `clang_decls` already has an
export for this field, and skip if so. Once specifics are supported,
this lookup will use both the field's `InstId` and `SpecificId`.

The above changes aren't quite sufficient, because if a field fails to
be exported, it will keep being attempted on each call to
`ExportAllFieldsToCpp` resulting in multiple errors. Fix this by storing
an invalid `FieldDecl` in `ClangDeclStore` if an error occurs. This lets
`ExportAllFieldsToCpp` know not to reattempt export, and
`ExportFieldToCpp` returns `nullptr` for invalid fields same as before.
2026-07-29 19:27:05 +00:00
Lucile Rose Nihlen 3a37b89da2 Change carbon_library Bazel parameters back to srcs and hdrs (#7585)
It's come up that `carbon_library` better represents a linkage unit
instead of having to closely mirror the Carbon language library concept.
Given that we can have more than one API file in a linkage unit, and
that `srcs` and `hdrs` gives better compatibility with other C++
tooling, this PR switches `impls` and `api` back to `srcs` and `hdrs`,
and fixes up the broken code.
2026-07-29 18:49:54 +00:00
arhwx 6ea2087f0a Export methods taking self as const member functions (#7577)
A method declared with `self` does not modify the object, but it was
exported to C++ as a non-const member function, so calling it on a const
reference would fail.

```carbon
class C {
  fn Get(self);
}

inline Cpp '''
void F(const Carbon::C& c) {
  c.Get();
}
''';
```
```
error: 'this' argument to member function 'Get' has type 'const Carbon::C', but function is not marked const
```

Import already maps `f() const` to `fn f(self)`, and this PR implements
the same behavior for exporting. No ref-qualifier is added, since that
maps to `ref self`, so that is unchanged.

`GetThisArg()` now builds `this` from the method instead of the parent
record, so that it picks up the method's const-qualifier.
2026-07-29 17:28:54 +00:00
Dana Jansens f51c075f8b Avoid symbolic witnesses for .Self in an impl decl (#7564)
Point symbolic witnesses into `.Self` written inside an impl decl at the
impl that is being declared. This is tricky because the impl does not
yet exist. So we use a new instruction `ImplSelfWitness` which _will_ be
replaced by the `ImplWitness` once it becomes available. The
`ImplSelfWitness` acts like a symbolic witness, except it does not
perform lookup, since we know which impl we will get a witness from.

This prevents us from finding other impls when performing lookups into
`.Self` in an impl decl, which produces incorrect/incoherent results.
2026-07-29 16:25:23 +00:00
Geoff Romer 2ac425e591 Test calling std::make_unique on a Carbon type from Carbon. (#7563)
As a byproduct, this introduces a new top-level directory
`integration_tests` for tests like this.

This also fixes a latent bug with name mangling on Mac.
2026-07-29 16:07:10 +00:00
Dana Jansens 8ac0edb280 Add a failing test where frozen .Self is passed in generic argument and never thawed (#7582) 2026-07-29 15:18:43 +00:00
Richard Smith dbd24035f8 Fix libunwind advice. (#7580)
Debian packages github.com/libunwind/libunwind as `libunwind-dev`, and
packages LLVM libunwind as `libunwind-N-dev`, with no meta-package to
install the latest version of LLVM libunwind. The libunwind-dev is not
built as PIC, so doesn't work in our build setup. So a specific version
of LLVM libunwind must be installed.
2026-07-29 13:37:46 +00:00
Richard Smith 7d89ac98c7 Add a flag to build a single ASTContext shared across all compilations (#7567)
Instead of building one Clang `ASTContext` per compilation, the
`--share-cpp-ast` flag causes us to build a single `ASTContext` and
share it across all contexts. One new abstraction is added: `CppDomain`
represents the Carbon-side view of a Clang AST that might be shared
across multiple `SemIR::File`s. This object owns the Clang instance and
the AST.

For now, we have no isolation between the C++ state exposed to different
Carbon compilations, and we have no multiplexing of generated LLVM IR
from C++ into different Carbon compilations, so the mode is not usable
yet. The plan is to keep it behind a flag until it's ready.

Assisted-by: Gemini via Antigravity
2026-07-28 00:19:40 +00:00
josh11bandJosh L 4e77f9b6c8 Add slide and video links for NDC 2026 talks (#7572)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-07-27 22:50:58 +00:00
josh11bandJosh L 1cef214e6a Move adapters from generics to class design docs (#7561)
Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-07-27 22:33:37 +00:00
Richard Smith f38085cbca Add /external to .gitignore (#7568)
Fixes #7430
2026-07-27 19:13:36 +00:00
Richard Smith 13f335befa Add instructions for Carbon development on Windows. (#7565)
In passing, switch `uv` instructions from curl pipe to installation with
`cargo`, and add missing libunwind dependency.
2026-07-27 17:45:02 +00:00
dependabot[bot] a1efff4bcc Bump brace-expansion from 5.0.7 to 5.0.8 in /utils/vscode in the npm_and_yarn group across 1 directory (#7575)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory:
[brace-expansion](https://github.com/juliangruber/brace-expansion).

Updates `brace-expansion` from 5.0.7 to 5.0.8
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/96a63c0011c0288846ad41773c73e3fbd0906b59"><code>96a63c0</code></a>
5.0.8</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/a1bd33999ea75262c4749fff3bbb0d1372bd07b5"><code>a1bd339</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/592a36fd18455c37f81e0848a642d84c63147fa7"><code>592a36f</code></a>
Bump tar from 7.5.16 to 7.5.20 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/127">#127</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/bd146909cd6c7bedde61a5d6428ba252860a0159"><code>bd14690</code></a>
Bump brace-expansion from 2.0.2 to 2.1.2 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/126">#126</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/e729ba647887042f16b531fdb3d8ac3d7762ccad"><code>e729ba6</code></a>
Bump ws from 8.19.0 to 8.21.1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/124">#124</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/5bf809e2c6dbde64dd9ff7acec7335ea7d5f6d9e"><code>5bf809e</code></a>
Remove Node.js 18 support (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/110">#110</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/8cb5716bae73e98b63f18aae8e48b6f12522e759"><code>8cb5716</code></a>
Bump markdown-it from 14.1.0 to 14.2.0 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/113">#113</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/43122df5955511b8ec82718fa28903b6dbad0d26"><code>43122df</code></a>
Bump sigstore from 4.1.0 to 4.1.1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/119">#119</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/69bd65a46e9361c992bb43b898c9df0d9720cc5c"><code>69bd65a</code></a>
Bump <code>@​sigstore/verify</code> from 3.1.0 to 3.1.1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/118">#118</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/b3bfbf06746fe92645ffd17d1f44e95f480cfe59"><code>b3bfbf0</code></a>
Bump <code>@​sigstore/core</code> from 3.1.0 to 3.2.1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/117">#117</a>)</li>
<li>See full diff in <a
href="https://github.com/juliangruber/brace-expansion/compare/v5.0.7...v5.0.8">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=brace-expansion&package-manager=npm_and_yarn&previous-version=5.0.7&new-version=5.0.8)](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-07-27 15:01:22 +00:00
arhwx 07111398d8 Anchor the orphan rule on the first owning declaration (#7573)
`DiagnoseOrphanImpl` used `definition_id`, but #7140 defines the anchor
as the first owning declaration, so a class declared but not defined was
rejected, which is why three cases in `orphan.carbon` were marked
`fail_todo`, and they now pass.

`fail_use_extern_class` no longer errors, `handle_class.cpp` never
passes the `extern library` name into the class entity, so `C` is
treated as locally owned and counts as an anchor. The expected error is
replaced with a TODO in the test, but it should come back once `extern
library` is implemented for classes.
2026-07-27 14:49:06 +00:00
dependabot[bot] 420b34ed9d Bump the npm_and_yarn group across 1 directory with 2 updates (#7569)
Bumps the npm_and_yarn group with 2 updates in the /utils/vscode
directory: [fast-uri](https://github.com/fastify/fast-uri) and
[linkify-it](https://github.com/markdown-it/linkify-it).

Updates `fast-uri` from 3.1.2 to 3.1.4
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/fastify/fast-uri/releases">fast-uri's
releases</a>.</em></p>
<blockquote>
<h2>v3.1.4</h2>
<h2>⚠️ Security Release</h2>
<p>Fix for <a
href="https://github.com/fastify/fast-uri/security/advisories/GHSA-v2hh-gcrm-f6hx">https://github.com/fastify/fast-uri/security/advisories/GHSA-v2hh-gcrm-f6hx</a></p>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/fastify/fast-uri/compare/v3.1.3...v3.1.4">https://github.com/fastify/fast-uri/compare/v3.1.3...v3.1.4</a></p>
<h2>v3.1.3</h2>
<h2>⚠️ Security Release</h2>
<ul>
<li>Fixes: <a
href="https://github.com/fastify/fast-uri/security/advisories/GHSA-4c8g-83qw-93j6">https://github.com/fastify/fast-uri/security/advisories/GHSA-4c8g-83qw-93j6</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/fastify/fast-uri/compare/v3.1.2...v3.1.3">https://github.com/fastify/fast-uri/compare/v3.1.2...v3.1.3</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/fastify/fast-uri/commit/6aeece669e4166b2446a89f17c07a3b15dfb7ed4"><code>6aeece6</code></a>
Bumped v3.1.4</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/2d50fbabc80e4d0884fe0f6a98fe118ce6faa353"><code>2d50fba</code></a>
fix: reject literal backslash in URI authority</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/0549fe35b0d482233f3be2816439f3ec803603fa"><code>0549fe3</code></a>
Bumped v3.1.3</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/2a6d357a18a68e6d812824379fd3388a1ae50d05"><code>2a6d357</code></a>
Merge commit from fork</li>
<li>See full diff in <a
href="https://github.com/fastify/fast-uri/compare/v3.1.2...v3.1.4">compare
view</a></li>
</ul>
</details>
<br />

Updates `linkify-it` from 5.0.1 to 5.0.2
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/markdown-it/linkify-it/blob/master/CHANGELOG.md">linkify-it's
changelog</a>.</em></p>
<blockquote>
<h2>5.0.2 / 2026-07-02</h2>
<ul>
<li>Fixed DoS in <code>mailto:</code> links (restrict user name to 64
chars).</li>
<li>Restricted user/pass part length in links.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/50a0c914f834b201cab25ff4faefd1f832b37332"><code>50a0c91</code></a>
5.0.2 released</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/de3b88554b5e465d5fa19914e2a1801ebb3069ef"><code>de3b885</code></a>
Update package hooks</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/13effaaa4600d1fcff9f63c38fecdd601bfd83e7"><code>13effaa</code></a>
Add package lock</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/39d748dbfc77534e9be04d87cd9f57a13b9b4216"><code>39d748d</code></a>
Bump c8</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/00ce8771ac0c3e6784dcacaa1625ca0fc1b62a12"><code>00ce877</code></a>
Drop tlds deps</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/ecde82341a1b2e349b03eb01f3e1d2cc105bcd7f"><code>ecde823</code></a>
Update benchmark to mitata</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/23c62cdd14ef36e89c175c6726e2229e5b76e75f"><code>23c62cd</code></a>
Refactor demo / doc build and publish</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/fd63f3b4ab433ca3561304409b572eed465706cd"><code>fd63f3b</code></a>
CI config update</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/f4ea5afaa6a8e1109c44898158d4910b3fb128fb"><code>f4ea5af</code></a>
demo: update bootstrap &amp; layout</li>
<li><a
href="https://github.com/markdown-it/linkify-it/commit/1454fb645f00c33a05edbded18640d5078ba7710"><code>1454fb6</code></a>
lint: dim warnings</li>
<li>Additional commits viewable in <a
href="https://github.com/markdown-it/linkify-it/compare/5.0.1...5.0.2">compare
view</a></li>
</ul>
</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 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-07-27 14:36:16 +00:00
Richard Smith 39916ad2ca Split up C++ diagnostic emitter and factor it out. (#7558)
Split the diagnostic emitter into a separate emitter (regietered with
Clang) and listener (registered with the emitter). The purpose of this
split is to make the Clang emitter not depend on the `Check::Context`,
so that we can use it, and hence the same Clang instance, with multiple
`Check::Context`s. A fallback listener is registered to collect and emit
any diagnostics produced while we don't have a `Check::Context`
registered with the emitter.

Assisted-by: Gemini via Antigravity
2026-07-24 20:14:50 +00:00
Dana Jansens 48a03e6a1c Remove TODO to check for orphan impls (#7562)
Orphan impls are found at the end of checking the file, in
`ValidateImplsInFile()`.
2026-07-24 19:11:21 +00:00
Geoff RomerandNicholas Bishop 3cb143e878 Add support for exporting Carbon functions as constructors. (#7560)
Co-authored-by: Nicholas Bishop <nbishop@nbishop.net>
2026-07-24 18:43:12 +00:00
Lucile Rose Nihlen de68b19784 fix build-runtimes subcommand for prelude (#7559)
Fixes a bug in CarbonPreludeBuilder that caused runtimes build
failures due to a incorrectly created output directory.

Also removes some debug printing that I mistakenly checked in
last time.
2026-07-23 18:42:27 +00:00
Dana Jansens 8c42d383c7 Use SubstOperandsSkipType to allow using SubstPeriodSelf on a facet type (#7556)
This makes SubstPeriodSelf more generally useful, with one less gotcha.
Previously calling it with a facet type would just do nothing.

This is possible now because we
- Have SubstOperandsSkipType to make use of
- Have banned constructs which introduce ambiguous .Self, so we don't
need to try avoid finding undesired .Self insts in facet types in other
positions (like in specifics).
2026-07-23 18:31:46 +00:00
Richard Smith 9477e32936 Add explanation of TypeInstId to check docs. (#7555) 2026-07-22 22:53:30 +00:00
Richard Smith 43df8c474a Replace typeid(T).name() with llvm::getTypeName<T>(). (#7554)
This produces prettier, demangled type names, and works when building
with `-fno-rtti`.

Before:
```
Optional N6Carbon5Parse13NodeIdForKindIL_ZNS0_8NodeKind16LibrarySpecifierEEEE: begin
```
After:
```
Optional Carbon::Parse::NodeIdForKind<Carbon::Parse::NodeKind::LibrarySpecifier>: begin
```

Assisted-by: Gemini via Antigravity
2026-07-22 20:25:41 +00:00
Dana Jansens 453b5474e4 CHECK that the self is a symbolic type when looking for a Destroy and its type is a facet (#7553)
As a follow up to #7546 (and see the discussion there), verify our
assumptions that you can't have an object of type facet where the facet
is not symbolic, and then need to find a Destroy witness for the object.
2026-07-22 18:08:35 +00:00
Nicholas Bishop 33bd953a2e Deduplicate class export and fix identifier error in ExportNameScopeToCpp (#7550)
Added method_alias.carbon test so that the class export code in
`ExportNameScopeToCpp` is tested. Refactored `ExportClassToCpp` so that
`ExportNameScopeToCpp` can reuse that code.

Moved the `identifier_info` code in `ExportNameScopeToCpp` into the
namespace block, because the name scope's name ID is not valid for
classes.

Added a call to `CompleteType` for classes exported via
`ExportNameScopeToCpp`, otherwise a "queried property of class with no
definition" assert is later reached (when adding methods) in the call
chain `BuildCppToCarbonThunkDecl` -> `DeclContext::addHiddenDecl` ->
`CXXRecordDecl::addedMember` -> `CXXRecordDecl::data`.
2026-07-22 18:02:44 +00:00
pjmlp 0b0918274c Added video link for NDC 2026 talk, Carbon: graduating from the experiment. (#7549) 2026-07-22 18:02:26 +00:00
Dana Jansens 9796b7bc78 Add tests (mostly failing) that rewrites in an impl can satisfy required constraints (#7547)
A rewrite's RHS value should be used when checking that the rewritten
associated constant impls an interface.
2026-07-22 17:00:53 +00:00
Dana Jansens d2ac9b3933 Diagnose where in a binding that introduces a .Self that does not refer to the binding (#7517)
This is in addition to finding a `where` on the RHS of another `where`.
Since a generic binding introduces `.Self`, any `where` expression that
isn't part of a facet type modifying the binding itself would introduce
an ambiguous `.Self`.

Add virtual parse nodes for let, var, and form bindings, which goes
before the type. This allows us to track if `where` appears in the
binding's type. We only need to look for an invalid `where` if any
appeared in the type. We combine these three nodes together into a
single node kind, which requires us to remove the name from it as a
child. We move it up to the Pattern node again, and rename the
PatternStart nodes to PatternTypeStart as they are now located in the
middle of the Pattern nodes, just before the type.

And we only need to thaw `.Self` in generic bindings. Non-generic
bindings can only have `.Self` through a `where` expression, since the
name is not provided otherwise to non-generic bindings. And `where`
expressions thaw their `.Self` independently. So the binding only needs
to thaw a `.Self` that it introduced, which is only for generic
bindings.
2026-07-22 16:45:00 +00:00
Dana Jansens 21dc5cde04 Ensure where requirements in named constraints are visible to lookups (#7299)
Require rewrite and same-type constraints that do not depend on `.Self`
to be satisfied when a facet type is identified, since those constraints
may not be found later.
2026-07-22 16:18:57 +00:00
josh11bandJosh L a48d14e451 Add memory safety talk links to README (#7520)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-07-21 21:43:44 +00:00
Dana Jansens f8f50cb167 Don't try produce a custom witness for a symbolic value of type facet (#7546)
For a symbolic value with a type being a facet, we need to find a
witness either from the facet's type or from an impl. Custom witness is
for producing a concrete final witness, but there is no such witness in
this case. We should fail to find a witness, and defer to impl lookup to
find the Destroy witness.

Currently it tries to find a witness from the facet type, but it ignores
named constraints, which means it's incomplete at best. But there's no
value in trying to say that the value is trivially destroyable, when it
has a type that impls Destroy. It may not be trivial, and we can't
actually make a witness for it while symbolic.
2026-07-21 19:39:31 +00:00
Dana Jansens 63757d281e Require all impls constraints in impl as to be satisfied (#7531)
We checked that requirements inside the impl-as target interface were
satisfied. But we also need to check that requirements coming from the
constraint facet type, or named constraints that it targets, are
satisfied.
2026-07-21 19:31:54 +00:00
Nicholas Bishop 2e61685658 Remove duplicate check for exporting a specific class (#7541)
The check for a specific in `TryMapClassType` is unnecessary;
immediately after it calls `ExportClassToCpp`, which has the same check.
The latter also has a `context.TODO`, which provides a clearer error.

Also improved the `LocId` in `ExportClassToCpp` to use the location of
the first decl rather than the empty location of the class type. This is
the same fix as
https://github.com/carbon-language/carbon-lang/pull/7533, just applied a
little more broadly. This makes the `context.TODO` above point at the
class rather than the start of the source file.
2026-07-21 18:35:20 +00:00
dependabot[bot] d234de41e7 Bump brace-expansion from 1.1.14 to 1.1.16 in /utils/vscode in the npm_and_yarn group across 1 directory (#7543)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory:
[brace-expansion](https://github.com/juliangruber/brace-expansion).

Updates `brace-expansion` from 1.1.14 to 1.1.16
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/juliangruber/brace-expansion/releases">brace-expansion's
releases</a>.</em></p>
<blockquote>
<h2>v1.1.15</h2>
<ul>
<li>Backport v5.0.6 change to v1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/111">#111</a>)
0b09384</li>
</ul>
<hr />
<p><a
href="https://github.com/juliangruber/brace-expansion/compare/v1.1.14...v1.1.15">https://github.com/juliangruber/brace-expansion/compare/v1.1.14...v1.1.15</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/447763a91a613cfa67ac73096cbc1de9a2304f97"><code>447763a</code></a>
1.1.16</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/d74e63030c012e3b7ae81657b8d665619cd51b95"><code>d74e630</code></a>
fix: v1 backport for CVE-2026-13149 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/122">#122</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/2203f4f4895eba16c4d408b4219ce1b8e5f6ff24"><code>2203f4f</code></a>
1.1.15</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/0b0938410732370559704230724ca4a44d1b29fd"><code>0b09384</code></a>
Backport v5.0.6 change to v1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/111">#111</a>)</li>
<li>See full diff in <a
href="https://github.com/juliangruber/brace-expansion/compare/v1.1.14...v1.1.16">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=brace-expansion&package-manager=npm_and_yarn&previous-version=1.1.14&new-version=1.1.16)](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-07-21 18:18:02 +00:00
David Blaikie 973e499f82 new_proposal.py fix for rumdl missing anchor from dangling ToC TODO entry (#7540)
rumdl error broke the proposal script execution:
```
rumdl check..............................................................Failed
- hook id: rumdl
- exit code: 1

  proposals/p000003-test-proposal.md:15:5: [MD051] Link anchor '#todo-initial-proposal-setup' does not exist in document headings

  Issues: Found 1 issues in 1 file (11ms)
```
So update the script to remove the TODO entry in the ToC to match
removing the TODO section.
2026-07-20 23:01:29 +00:00
oli-ej 0553d5f165 Update Textmate for types in a list and add unused keyword (#7535)
Setting "type" to bright red to make comparison obvious:
(screenshots taken from VSCode)
Before
<img width="446" height="150" alt="Screenshot 2026-07-20 135558"
src="https://github.com/user-attachments/assets/81249005-99f1-47bb-af4f-ad6e8f2404fb"
/>

After
<img width="429" height="149" alt="Screenshot 2026-07-20 135738"
src="https://github.com/user-attachments/assets/acc83086-fe19-4a18-a833-968daed56229"
/>

I'm not super familiar with textmate/highlightjs, but I think what was
happening on line 5 is that the "type" scope is being extended to the
`=` after `.y`.
Adding `,` as an "end" token fixes this, and I think this is what
highlightjs already does.

I've also added "unused" as a keyword.
2026-07-20 22:37:37 +00:00
Dana Jansens 4b46e63b41 Move IdentifiedFacetType to its own file (#7542)
I wanted to move it to check but there'd still be an
IdentifiedFacetTypeId and we keep all Ids in sem_ir. So leaving it in
sem_ir, but moving it to its own file. This more clearly separates
DeclaredFacetTypes and IdentifiedFacetTypes.
2026-07-20 21:45:17 +00:00
Nicholas Bishop 3a3439c681 Support exporting functions with generic return types to C++ (#7537)
Add a `return_type_id` field to `FunctionInfo` in
`toolchain/check/cpp/export.cpp`. As with the `explicit_params` field,
`ExportFunctionSpecializationToCpp` updates this to the return type in
the specific.

Refactored `BuildCppFunctionDeclForCarbonFn` into
`BuildCppFunctionDeclForNonGenericCarbonFn` and
`BuildCppFunctionDeclForGenericCarbonFn`, with `BuildCppFunctionDecl`
containing shared code.

The `generic_type_impls_interface.carbon` test is updated to include a
generic return type.
2026-07-20 20:44:58 +00:00
Lucile Rose Nihlen a502ff006e move carbon_prelude to carbon_runtimes.bzl (#7539)
The `carbon_prelude` macro was defined in bazel/carbon_rules/defs.bzl.
This file contains `carbon_library` and `carbon_binary` which are
mostly intended as example Bazel rules for building Carbon binaries.

The `carbon_prelude` macro, however, is used now to build the runtimes
for the Carbon toolchain. We move it to a more central location where
the rest of the runtimes are processed, in
toolchain/runtimes/carbon_runtimes.bzl.
2026-07-20 20:38:17 +00:00
Özgür T. Önsoy 40028098ce Rename FacetTypeInfo to DeclaredFacetType (#7528)
This resolves a TODO comment in code.
2026-07-20 19:15:09 +00:00
Dana Jansens 085e45093e Avoid consuming a token after an invalid match_first opening (#7538)
If the `match_first` is not followed by `{` avoid consuming whatever
comes after it. Recover by leaving whatever comes next alone. It could
even be the `FileEnd` token, and then we would crash when we read off
the end of the token stream looking for `FileEnd`.
2026-07-20 19:09:16 +00:00
David Blaikie 99cda60df7 Add location to clang classes created via reverse interop (#7533)
The specific location's not ideal (rather than the open curly, or
semicolon for a declaration - the two locations should be the `class`
and then the class name), but the same as we do for functions for now &
enough to get by.

This specifically also fixes a crash I found due to dtors being
generated without a location (because implicitly created functions would
use the class's location), creating a function call without a debug
location, which fails the LLVM IR verifier.
2026-07-18 00:13:05 +00:00
Richard Smith 5c544f7c2f Give thunks weak_odr linkage. (#7525)
We can end up emitting the same thunk from multiple compilations in some
cases -- in particular, when the thunk is wrapping a function that is
either synthesized by the compiler or imported from C++. When this
happens, we will have multiple-definition link errors unless we allow
redefinitions across multiple files.

It'd be nice to detect when we need to do this and when we don't, but
that's a bit tricky to do in practice. Ideally, in fact, we would use a
different strategy, and emit the thunks as discardable definitions in
each compilation that *uses* them. But for now emitting them with
weak_odr linkage seems like a good way to make progress.
2026-07-17 13:25:19 +00:00
Richard SmithandDana Jansens 643ab57f5a Refactor CppRange interface and fix a crash exposed by doing so. (#7515)
Split up the CppRange interface into smaller parts, with the intent of
improving the diagnostic quality and making the implementation easier to
understand.

This also makes the implementation details of the CppRange machinery
private, which breaks one of the existing tests; that test is split into
two files, one which tests the low-level machinery works, and another
that tests the resulting prelude behavior.

This change exposes a crash in `where` expression handling, where we
would perform a substitution that creates a new `SpecificConstant` that
refers into a region of a generic that has never been resolved. Fix that
by resolving the definition region of a generic if eval sees a
`SpecificConstant` that refers into it. This is usually not necessary
because something else should have resolved that region first, but that
doesn't happen here.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-07-17 00:31:12 +00:00
Lucile Rose Nihlen 31cc20f6e3 move Core//range into prelude (#7524)
As discussed in the 2026-06-14 toolchain open meeting, `Range`
is a better fit for the prelude than as a general library in
`Core`. This PR moves `Range` into the prelude, and updates
the build infrastructure and various tests to reflect that
change.
2026-07-16 21:36:45 +00:00
Dana Jansens 2d9e3fee67 Use identified facet type to get impl-as target (#7519)
This supports impl lookup choosing an impl that targets a generic
interface through a named constraint, without crashing.

Instead of assuming the impl's target is a facet type containing an
interface, we use the identified facet type to find the specific
interface it targets.
2026-07-16 19:11:23 +00:00
Dana Jansens 0848cf941d Look outside constant values for designators in where constraints (#7367)
The constant value may lose the designator during eval, such as an
`ImplWitnessAccess` that resolves to some concrete type. Look in the
non-canonical instructions instead.
2026-07-16 19:00:06 +00:00
Richard Smith ee81a4e48e Bump vscode extension version to 0.0.9 for release. (#7522) 2026-07-16 18:49:59 +00:00
Dana Jansens b3e9dd3ea2 Consolidate checking for and rejecting other_requirements in impl lookup (#7518)
Since the introduction of `other_requirements`, we now have a dedicated
step in impl lookup for checking that the requirements of the query
facet type are satisfied. That is the place where we will be checking
same-type constraints, which `other_requirements` signals the presence
of.

Consolidate all checking of `other_requirements` to that step, which
reduces our use of `FacetTypeInfo` (as opposed to the
`IdentifiedFacetType`) and removes interest in same-type constraints
from code that is not related to them.
2026-07-16 18:09:46 +00:00
Lucile Rose Nihlen 625f2ca629 precompile and cache Carbon prelude (#7432)
Refactors the link driver to automatically compile and cache the carbon
prelude for use in linking.

Implements a `carbon_library` rule for compiling the Core library
dependencies in the examples.
2026-07-16 18:02:14 +00:00
Richard Smith 90f6654b48 Fix crash attempting constant evaluation of a constexpr constructor. (#7514)
We can't use a `CallExpr` to call a constructor; use a
`CXXConstructExpr` instead. While this fixes the crash and gets us past
the initial constant evaluation, we still can't map the constant value
back into Carbon, so this doesn't actually make constexpr constructors
work yet. But it does stop Clang from crashing.

Fixes #7498.
2026-07-16 15:17:08 +00:00
Richard Smith 703529fc55 Destroy temporaries at the end of expression statements. (#7513)
Instead of tracking the cleanup scope depth on entry to each scope,
track an "ambient" cleanup scope depth that's *after* the destructors of
local variables in that scope. This gets increased to include the
destructors of local variables when we create a name-binding
declaration. Then, when we reach a point where temporaries should be
destroyed, run cleanups that are after the ambient cleanup scope depth
on the stack. This happens:

* At the `;` of a statement expression.
* At the `)` of an `if` or `while` statement.
* After performing the implied `HasValue()` call in a `for` statement.

Per informal agreement with leads, this means we lifetime-extend all
temporaries created in the initializer of a name-binding declaration to
the full scope of that declaration, but that temporaries created in an
expression statement are destroyed at the `;`.
2026-07-16 15:12:39 +00:00
Dana Jansens 81e495ee53 Impls in final match_first block aren't always final (#7512)
If an earlier impl may match a more specific query, then later impls can
not be treated as final for the given query.

See
https://github.com/carbon-language/carbon-lang/blob/de8b03faa3178ae683d8e7124fbcba81eb88e00c/proposals/p005337-interface-extension-and-final-impl-update.md#using-associated-constants-from-impls-in-a-final-match_first
2026-07-16 13:10:09 +00:00
Dana Jansens cda1f256bb Use match_first to prioritize impls (#7492)
Allow (don't diagnose) impls that have the same type structure if they
are associated with the same match_first block. Similarly, allow final
impls (made final by their enclosing match_first block) that overlap in
type structure when they are associated with the same match_first block.

If the type structures are the same, choose the first impl from the
match_first block.same.

If the type structures overlap but are not the same, and share a
match_first block, then we should choose the first overlapping impl from
the match_first block. This is true both for final and non-final impls.
See
https://github.com/carbon-language/carbon-lang/blob/de8b03faa3178ae683d8e7124fbcba81eb88e00c/proposals/p005337-interface-extension-and-final-impl-update.md#impl-selection-algorithm

But in the non-final case if there is an overlapping impl outside the
match_first, it can win if it's more specific.
2026-07-15 21:25:25 +00:00
Richard Smith 9ae73d2847 Handle signature mismatch when a Carbon function overrides a C++ virtual function. (#7499)
When a Carbon virtual function overrides a C++ virtual function, we need
to export it with the C++ signature in order for it to work as an
override. Instead of mapping the C++ signature into Carbon and then back
again, use the original C++ signature from the base class as the
signature exported to C++.

Also add documentation explaining how we use thunks in C++ interop,
including in this new virtual function handling logic.
2026-07-15 18:42:03 +00:00
Chandler Carruth 14e8bffe24 Refactor ValueStore to use custom iterators and ranges (#7506)
Replace the llvm::map_range based anonymous ranges returned by values()
and enumerate() with custom range and iterator types. This avoids
exposing complex template return types and improves encapsulation. But
most importantly, it is *much* cheaper to compile.

This change:
- Defines ValueStoreIterator, ValueStoreEnumerateIterator, and
ValueStoreRange templates in the Internal namespace.
- Exposes them via aliases in ValueStore: Iterator, ConstIterator,
Range, MutableRange, and EnumerateRange.
- Supports safe implicit conversion from Iterator to ConstIterator.
- Supports operator-> even when the value type is returned by value
(e.g., llvm::StringRef) by conditionally const-qualifying the pointer
type.
- Ensures C++20 comparison consistency with custom operator<=> and
operator== definitions.
- Restricts construction of these iterators and ranges to ValueStore
methods by using private constructors and friend declarations.

Assisted-by: Antigravity with Gemini
2026-07-15 17:06:52 +00:00
Dana Jansens 168420f805 Allow impl redecl in match_first after a definition (#7491)
Previously the last decl had to be the definition. Now we allow a
declaration after a definition, so that the user can write a match_first
block last, and put (re-)declarations of impls in it, after the
definitions have already been written elsewhere.

We track the location of the decl that was associated with a match_first
block so that we can correctly point to it in diagnostics when an impl
is written twice in match_first blocks. Since impls may not be
redeclared across an import boundary, we will never have a `SemIR::Impl`
with a match_first from a different file in a redeclaration, so we don't
need to import the location of a previous decl that was in a match_first
for diagnostics. As such we just store a LocId on the `SemIR::Impl`
struct.
2026-07-15 14:12:37 +00:00
Chandler Carruth 474090f439 Record //@... directive lines as comments when lexing. (#7494)
The `//@include-in-dumps` and `//@dump-sem-ir-begin`/`-end` tooling
directives were consumed for their side effects without a comment
record, so the tokens and comments together no longer reconstructed the
source: tooling that re-emits a file from them, such as `carbon format`,
silently dropped the directive lines. Now each recognized directive line
is also recorded as an ordinary full-line comment alongside its side
effect.

Adjacent full-line comments coalesce into one comment record only within
a category, determined by the byte after the `//` introducer: ordinary
comments (whitespace, or the end of the line or file), `//@...`
directives, and invalid introducers. A transition between categories
starts a new record, so a directive next to a comment block is its own
comment, while all the invalid spellings lump together to keep the
diagnostic noise at one per run.

The category boundary also fixes a lost directive: the invalid-comment
bulk skip compared only the `//` prefix, so `//!x` directly above
`//@dump-sem-ir-begin` absorbed the directive line and its side effect
was never recorded. Invalid comment runs now skip line by line (they
start from a diagnosed error, so they are not hot) and stop at a
whitespace or `@` introducer; the SIMD bulk skip handles only ordinary
comment blocks, whose prefix comparison already includes the whitespace
byte.

Nothing outside the lexer and the formatter reads comment records, and
lex dumps do not include comments, so no other behavior changes.

Assisted-by: Claude Code
2026-07-15 03:21:04 +00:00
Chandler Carruth 1c1870cd10 Remove typed_nodes.h from tree.h and node_stack.h (#7510)
Remove toolchain/parse/typed_nodes.h from transitive imports of tree.h
and node_stack.h to reduce compile-time overhead in toolchain/check.

Add an explicit include of typed_nodes.h to tree_and_subtrees.cpp where
it is needed for instantiating templates.

Assisted-by: Antigravity with Gemini
2026-07-15 01:08:15 +00:00
Chandler Carruth 0a09ab1e3c Reduce Clang header exposure in check_unit.h (#7509)
Remove clang/Frontend/CompilerInvocation.h from check_unit.h and forward
declare clang::CompilerInvocation instead to reduce header exposure.

Add an explicit include of CompilerInvocation.h to check_unit.cpp.

Assisted-by: Antigravity with Gemini
2026-07-15 00:59:58 +00:00
Chandler Carruth 730db0f903 Reduce Clang header exposure in lower library (#7511)
Remove clang/CodeGen/ModuleBuilder.h from toolchain/lower/file_context.h
to reduce transitive dependencies. Forward declare clang::CodeGenerator
and clang::FunctionDecl instead.

Add an explicit include of ModuleBuilder.h to context.cpp where the
complete types are required.

Assisted-by: Antigravity with Gemini
2026-07-15 00:59:03 +00:00
Richard Smith 45d1c74df8 Stop using ArrayStack for the cleanup stack. (#7505)
Because we merge cleanups across scopes in various cases, and want to
use linear indexes into the complete stack, the ArrayStack abstraction
is getting in the way more than it's helping. Switch to just a
SmallVector.

This loses the unit testing of the MergeIntoGrandparent logic. This is
covered indirectly by check tests still, but direct testing of it is a
bit tricky given that ScopeStack isn't set up for use without a Context.
2026-07-15 00:47:47 +00:00
Chandler Carruth 5b48274e58 Add extern template declarations for ValueStore in inst.h and entity_name.h (#7507)
Add extern template declarations and explicit template instantiations
for ValueStore<InstId, Inst> and ValueStore<EntityNameId, EntityName> to
prevent redundant template instantiations.

Place them in their respective domain files (inst.h/cpp and
entity_name.h/cpp) to maintain modularity.

Assisted-by: Antigravity with Gemini
2026-07-14 22:58:05 +00:00
Lucile Rose Nihlen 6c010816a4 update llvm to 615644763ffc (#7504)
* Fixes some build issues in clang headers that have changed upstream
* Adds patch 0011 to work around an upstream commit that broke Bazel
builds
2026-07-14 20:32:11 +00:00
Dana Jansens d47de6443e Freeze the .Self type and make non-extend constraints available after where (#7501)
The type of `.Self` introduced by `where` may contain a `.Self` inside
it. Freeze the type so that we have a consistent view of `.Self` inside
the facet type, where they are all frozen.

The type of `.Self` only has extend constraints from the LHS of the
`where`. So we need to copy any non-extend constraints into the
`where_stack` so they are available as early-impls and can be used for
impl lookups on the RHS of the where. We need to freeze any `.Self`
references in these just as we do for rewrite constraints.
2026-07-14 19:04:33 +00:00
Chandler Carruth 2e59804b9f Remove a long-deprecated and no-op flag (#7496)
See https://github.com/bazelbuild/bazel/pull/29931 -- this is going away
in upstream Bazel as well and has been a no-op since 2021.
2026-07-14 17:08:20 +00:00
Richard SmithandGeoff Romer 6e62a7d4a2 Destroy locals at the end of blocks, not only on return (#7448)
Destroy local variables and temporaries at each `}`, and when branching
with `break` and `continue`. In `for` statements, destroy loop variables
along with anything created within the loop at the end of each loop
iteration, and destroy the cursor and range object when the loop
terminates.

Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-07-14 00:59:22 +00:00
Richard Smith 8bae79f44a Update to a more recent LLVM. (#7488)
Fix a few API issues. There's also a newly-added file in compiler-rt
that is not supposed to be built by default but is not being excluded
properly by a glob. Added a patch to exclude that and sent
https://github.com/llvm/llvm-project/pull/208861 upstream.
2026-07-13 22:29:39 +00:00
Dana Jansens 8ea32187d4 Disallow impl in match_first twice (#7493)
Prevent dead code by diagnosing putting the same `impl` in a
`match_first` block more than once.
2026-07-13 21:58:06 +00:00
Nicholas Bishop 3d71858386 Improve type substitution in ExportFunctionSpecializationToCpp (#7495)
Instead of manually creating a map from symbolic types to concrete
types, create a Specific and look up parameter types via that Specific.

This allows C++ to call a Carbon function like `fn F[T: type](unused t:
T*) {}`. See generic_pointer.carbon.
2026-07-13 21:11:31 +00:00
Richard Smith b6179ecbbb Disable prelude import in language-server tests. (#7489)
This was substantially slowing down the overall test suite.

Fixes #7453

Assisted-by: Gemini via Antigravity
2026-07-13 20:48:28 +00:00
Richard Smith a8afc45ed5 Omit empty observe: blocks from formatted SemIR. (#7487)
Also add SemIR ranges to observe test, removing 5K lines of
uninteresting SemIR output.
2026-07-13 20:38:19 +00:00
Chandler Carruth 7612b3d821 Address post-merge review comments on #7254 and terminology discussions (#7490)
Document the phase of associated constants, which the discussions of
contextual phase defaults never covered: an associated constant is
always a checked generic binding. This is deliberately not presented as
a contextual default, because no other phase is possible for the
construct; correspondingly, no phase keyword (including `template`) is
allowed on one. Also rework the associated constants section of the
design README where the migration left a non-sequitur ("set to
compile-time values ... and so are defined using a `let` declaration"):
describe the `let` syntax and the binding's contextual phase separately.

Use consistent terminology for bindings versus constants. Bindings are
"checked" or "template" (generic) bindings, replacing the "symbolic
binding" and bare "generic binding" terms, so "symbolic" now only
describes constants and values. The "Symbolic facet bindings" section of
the generics details becomes "Checked facet bindings". The
expression-phase terms "symbolic constant" and "template constant" are
unchanged, and the binding-pattern definitions now name the constant
each kind binds. Template bindings are additionally described as
dependent and late checked, with each instantiation providing the
binding's value.

Also normalize the remaining "regular parameter" mentions to "runtime
parameter" to match the binding terminology, and describe the
compile-time "let template" as introducing a template generic binding
"T: C" whose uses are template constants.

Assisted-by: Claude Code
2026-07-13 19:22:35 +00:00
Dana Jansens d46b040290 Connect impls to their containing match_first block (#7486)
When we check an `impl` decl, find the containing `match_first` block,
if any, and store a connection to it in the `SemIR::Impl` structure,
along with the impl's position in that `match_first` block so that we
can sort/prioritize the `SemIR::Impl`s later.

Also, update the `is_final` flag if the `match_first` block is modified
as `final`. But ensure we diagnose trying to put a `final impl`, or a
redeclaration of one, in a `match_first` block. Also diagnose if an impl
is attached to a `match_first` block more than once - either in two
different blocks or in the same block at different positions.

Putting the `match_first` connection on the `SemIR::Impl` structure
means we have to import it, so implement import and add a smoke test for
that, which ensures nothing explodes.

Drop the `scope_stack` entry for the `match_first` block, as it was not
needed. Once we started tracking the `match_first` size on the `Context`
class, it became more straightforward to just store the `match_first`
decl `InstId` in the same place. The `match_first` block is not supposed
to act like a different scope for the purpose of redecls anyhow, so it's
a bit simpler this way.
2026-07-13 19:14:38 +00:00
Dana Jansens d6f9559cfb Diagnose if match_first is not in a valid scope (#7482)
It must be in a namespace, function, or class. In particular, it can't
be in another match_first, doing so immediately associates any impl
inside with two different match_first scopes, but we only want them
associated with one for prioritization.
2026-07-11 14:54:42 +00:00
Dana Jansens a46f4863db Basic checking for match_first blocks (#7481)
Push a scope_stack entry for match_first blocks, and handle impls being
inside those scope entries. An impl should not use the `match_first`
block as its "enclosing scope" for the purpose of deciding if the impl
is a redecl of another impl. We should look through it to the class or
namespace the impl (and match_first) are located inside.

We don't yet store the relationship between the impl and its match_first
block, nor then can we use it in impl lookup for prioritization.
2026-07-11 14:01:38 +00:00
Chandler Carruth 8be274cf60 Replace :! binding syntax with phase keywords and contextual defaults (#7479)
Implement the toolchain side of proposal #7254, removing the `:!`
binding
syntax for generic and template parameters in favor of the keywords
`generic`,
`template`, and `runtime` plus contextual defaults for phase.

For valid programs this is semantics-preserving: each binding resolves
to the
same phase, and produces the same SemIR, as it did under `:!`/`:`. The
parser
derives a binding's phase from its syntactic context plus any explicit
phase
keyword; new diagnostics and error recovery for misused keywords are
described
below.

Implementation details for each component:

- Lexer: remove the `:!` (`ColonExclaim`) token, move its virtual
parse-node
  budget onto `:`, and add the `generic` and `runtime` keywords.
- Parser: thread a `BindingContext` (`ExplicitParam`, `DeducedParam`, or
`CompileTimeEntityParam`) from declaration introducers down through
parameter
lists to each binding pattern, using a one-token lookahead to
distinguish a
name-qualifier parameter list from a declaration's own final list.
Parameters
of a compile-time entity (`class`, `interface`, `constraint`, `choice`,
`alias`, `export`, `namespace`) and deduced `[]` parameters default to
checked
generic; explicit function parameters and local bindings default to
runtime.
`HandleBindingPattern` resolves the phase from that context plus the
keyword: a
`generic` keyword needs no node of its own (the phase is carried by the
  binding's node kind), while a `runtime` keyword is preserved as a
`RuntimeBindingName` node so `check` can name it in a diagnostic. A
phase
keyword that is merely redundant with the contextual default is
diagnosed
  here, without invalidating the parse tree.
- Check: a phase keyword that is invalid for its context (for example
`runtime`
on a checked-generic parameter) is diagnosed here, and recovers by
building an
error binding that still introduces the name so that later uses of it do
not
  produce cascading errors.

The removed `:!` syntax is now rejected as an ordinary parse error.

The `form`/`:?`/`->?` ("extended types") portion of proposal #7254 is
left for a
separate change.

Assisted-by: Claude Code
2026-07-11 01:22:44 +00:00
Dana Jansens bf106c3b4b Handle missing curlies after match_first without crashing in parse (#7480) 2026-07-11 00:03:31 +00:00
Dana Jansens 783f1601fd Include whether the impl is final in textual semir (#7485)
When formatting an impl definition, include in the textual output if the
impl is final. Since we (mostly) write them as `final impl` in the code,
use the same notation in the textual semir.
2026-07-10 21:09:10 +00:00
Dana Jansens 69433a1834 Remove the ImplicitOnly option from SubstPeriodSelf (#7461)
The implicit/explicit `.Self` concept is a heuristic at best, so we
should avoid relying on it. The ImplicitOnly option is no longer used,
as it was used to remove/disambiguate `.Self` in nested facet types, but
we have banned nesting `where` on the RHS of a `where`. So we no longer
have to worry about ambiguous `.Self`.

We can remove all the designator tracking heuristics in `.Self`
substitution as well now, as they were used for the now-removed
ExplicitOnly (removed in
https://github.com/carbon-language/carbon-lang/pull/7460) and
ImplicitOnly options.
2026-07-10 17:58:33 +00:00
Chandler Carruth de8b03faa3 Update to latest rumdl release and enable another option (#7483)
The `style = "fixed"` is partially implied by `indent = 4`, but not
fully in some specific cases. There were also bugs in fully applying it
that are now fixed, and so we can specify it explicitly to get rumdl to
canonicalize nested list indentation more thoroughly.

Assisted-by: Antigravity with Gemini
2026-07-10 16:16:28 +00:00
Dana Jansens 55dcf66584 Remove extra SubstPeriodSelf and canonicalization (#7474)
The self and interface given to TryFindMatchingWitnessFromImplLookup
come from the output of SubstPeriodSelf, so there is no need to do the
substitution again. And the self came from a LookupImplWitness
instruction so it is already fully canonicalized.
2026-07-09 22:12:18 +00:00
Dana Jansens 7b0da12696 Remove the ExplicitOnly option from SubstPeriodSelf (#7460)
The implicit/explicit `.Self` concept is a heuristic at best, so we
should avoid relying on it. We now only have one value of `.Self` in a
facet type (we have banned nested `where` on the RHS of a `where`). So
we don't need to preserve any `.Self` for the purpose of disambiguation,
and we can subst all `.Self` on the the RHS of a rewrite constraint.
2026-07-09 21:31:52 +00:00
Dana Jansens c74bb933d2 Avoid impl lookup cycles from evaluating lookup instructions inside an impl decl (#7454)
`LookupImplWitness` instructions inside the impl declaration can't use
the impl they are apart of. Previously we had an heuristic in eval which
would try to prevent finding the impl for a lookup from inside that
impl. But it breaks when the `.Self` is replaced in a generic impl with
a symbolic, and then that symbolic is replaced in a specific. The
specific's decl block contains that `LookupImplWitness` instruction and
it tries to use the impl it came from. This causes the same specific to
be formed again, but now it exists, so it's used as-is but it has no
decl block yet, and so we crash.

Now we ban an impl while we resolve its specific, both deduction of its
arguments and from any other substitution. The prevents instructions
from inside the impl (which are evaluated when resolving the specific)
from finding their own impl. We do so by adding the ImplId to a stack on
the Context, and then skipping such impls when looking for candidates
during eval.

This fixes a crash, which was demonstrated by the new test being added.
It also makes another todo test pass.

There's a whole lot of other semir churn, which seems to be mostly
reordering of constants. There are some fingerprint changes in
constants, but it appears they are the same canonical instructions, so
they don't represent a behaviour change. For example in
`toolchain/check/testdata/for/actual.carbon` the `%N.patt` constant has
been given its fingerprint suffix now as `%N.patt.aa5`. But they are
both this instruction, so it is just a formatting change:

```
inst6100001A: {kind: SymbolicBindingPattern, arg0: entity_name61000002, type: type(inst61000018)}
  - name: `N`
  - type: type(inst61000018): <pattern for Core.IntLiteral>; {kind: PatternType, arg0: inst(IntLiteralType), type: type(TypeType)} (concrete)
  - value: symbolic_constant61000001
```
2026-07-09 20:38:56 +00:00
Dana Jansens 06e31437b9 Some slight tweaks to comments in/on WitnessQueryMatchesInterface (#7475)
I attempted the TODO as stated but we can't remove the `.Self` from the
LHS of a rewrite right now, without causing evaluation to run and
potentially find a concrete value to replace the access with, which then
breaks the association with the associated constant. There's a separate
TODO about that in SubstPeriodSelfInFacetType.
2026-07-09 19:34:55 +00:00
Dana Jansens b1c7e585f9 Diagnose .Self being used in a type that is not a facet type (#7471)
`.Self` will only be replaced in a facet type, as the facet type
constrains a facet. If it's part of a (non-facet) type, then the object
of that type is not a facet, and we can never replace that `.Self`.
2026-07-09 19:09:06 +00:00
Dana Jansens 11901b1a59 Parse match_first blocks (#7478)
`match_first` is a declaration followed by a curly-brace block of
declarations.

The check phase will ensure only impl decls (or defns) are inside the
block.
2026-07-09 15:34:52 +00:00
Dana Jansens bb0d74ba39 Remove an extra canonicalization of a self that is already canonicalized (#7477)
Clarify that the functions that search for a witness in a facet type no
longer take inputs from the query directly, but now take them from an
identified facet type constructed from the query. That means the self
type is already canonicalized.
2026-07-09 13:59:51 +00:00
Geoff Romer 96c7cfe41c Emit VarStorages eagerly (#7468)
We used to have to batch these at the end of pattern traversal in order
to avoid accidentally adding them to a block that was speculatively
pushed for an expression within a pattern, but that's no longer a
concern with the more precise handling of those speculative blocks in
#7445.
2026-07-08 19:33:46 +00:00
Dana Jansens 4261bb2dd2 Track and don't replace active .Self (#7443)
In #7436 we stopped substituting `.Self` when collecting witnesses out
of a facet type. While this was correct, it did not capture all the
cases that need to avoid substituting `.Self`. And it poisoned the
`IdentifiedFacetType` cache by not replacing `.Self` but storing the
result in the cache. This led to incoherent behaviour, where the result
of an impl lookup would change depending on which ones had been done
previously.

Now we use a flag to track for each `.Self` if we're currently
type-checking inside the scope where it was introduced in a facet type.
While inside that scope, identify should not replace the `.Self`. Any
use of it should remain as-is since we don't yet know what value will
replace it. We call this state "frozen" since it should not be modified
by identify. This requires a substitution step when we leave the scope
that introduced the `.Self`, to remove the flag. The flag is set in the
`EntityName` of the `SymbolicBinding`, and is part of the canonical
value, since `.Self` can become part of types, which are constants, and
the flag needs to follow it for correct behaviour.

We also have to ensure the flag is the same when doing comparison with
constants from inside a facet type and constants from outside. For
instance in `(Z where .Z1 = ()) where .Z2 = .Z1`, when we arrive at the
second `.Z1` its `.Self` will be frozen, while the `.Z1 = ()` contains a
non-frozen `.Self`. So we add the frozen flag to the first when storing
it in `where_stack` in order to compare the constant values of the two
`.Z1`.

The `WhereExpr` requirement inst kinds now have an `InstConstantKind` of
`AlwaysUnique` instead of `Never`. This allows us to add them to the
usual InstBlocks, and in an `eval fn` body they have a constant value,
so eval does not fail when trying to call that function. We have to be
careful to not consider `AlwaysUnique` as being actually concrete
though, since their constant value erases `.Self`-dependence. This
allows us to stop special casing them when thawing the requirements
block in a `WhereExpr`, and we can just thaw each `InstId` in the block
in a straightforward manner.

We add the new flag to the instruction's fingerprint and name in
formatted semir.
2026-07-08 18:04:56 +00:00
Nicholas Bishop ae9abe615e Fix ImportCppType doc (#7476)
Fixup for #6474. The previous doc was accidentally copied from
ImportCppFunctionDecl.
2026-07-08 17:33:16 +00:00
Özgür T. ÖnsoyandDana Jansens 08385adeb5 Implement checking observe declarations (#6709)
This adds SemIR structs and implements building `observe` lists, as well
as naming, formatting, and importing `observe` declarations.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-07-08 17:07:10 +00:00
Nicholas Bishop 918bb9364f Fix a few proposal URLs (#7473)
Fixup for #7245
2026-07-08 16:24:41 +00:00
Nicholas Bishop c8fdeef911 Add initial support for exporting generic Carbon functions to C++ (#7462)
This allows C++ to call Carbon functions with generic type parameters,
with some conditions. Example:
```carbon
interface I {
  fn Doit(self);
}
class A {
  impl as I { fn Doit(unused self) {} }
}
class B {
  impl as I { fn Doit(unused self) {} }
}
fn F[T:! I](t: T) {
  t.Doit();
}

inline Cpp '''
void G() {
  Carbon::A a;
  Carbon::B b;
  Carbon::F(a);
  Carbon::F(b);
}
''';
```

The initial support is limited; only explicit parameters are handled
currently.

`CarbonExternalASTSource::GetOrExportFunctionToCpp` now generates a
`clang::FunctionTemplateDecl` for generic Carbon functions. If C++ code
attempts to call that templated function,
`CarbonExternalASTSource::LoadExternalSpecializations` will be called
with the template argument types of that call site. Then we can generate
a specialized thunk for those argument types for C++ to call.
2026-07-08 00:51:21 +00:00
Lucile Rose Nihlen eab71802f7 prevent clangd_tidy github workflow from checking generated files (#7470)
This prevents an issue when trying to check in changes top
bazel-generated template files,
which aren't actually valid C++, making clangd_tidy issue errors and
block the commit.
2026-07-07 20:50:44 +00:00
Chandler Carruth 8aa14eab46 Introduce subprocess executing compile benchmarks (#7456)
This follows the pattern of our main compile benchmarks, but instead of
running the compile through a library API, it does so by running a
separate process. This lets us see the performance that we would expect
from `make` or another build system invoking the compiler, as opposed to
a minimal view from the library API.

Assisted-by: Claude Code
2026-07-07 20:17:39 +00:00
Geoff Romer 8945305dfc Emit NameBindingDecl after the initializer (if any) (#7467)
In some cases the pattern block can depend on the initializer, so it
must be sequenced after it. See #7469 for a more detailed explanation of
why this is necessary.
2026-07-07 19:18:33 +00:00
Geoff Romer ae3c4266d4 Add separators between files in LLVM IR dumps (#7463)
Each file dump now starts with a `; ---` comment and ends with a blank
line. This makes it easier to visually scan the dump for a file of
interest. The comment format is somewhat arbitrary; I chose `---` to
align with the `--- filename.carbon` separator in SemIR dumps, but
without the filename, because that appears on each of the next two lines
already.
2026-07-07 16:31:24 +00:00
Chandler Carruth e1cf833c45 Fix ASan heap-use-after-free in SourceGenTest (#7465)
In `SourceGenTest.IdentifierByteSumStableAcrossSeeds`, the `first`
variable was storing `llvm::StringRef`s pointing to memory allocated by
a temporary `SourceGen` instance. This memory was freed at the end of
the loop iteration, leaving `first` with dangling references that were
accessed in subsequent iterations.

Fix this by storing `std::string` copies of the identifiers in `first`
to own the memory, and use `llvm::equal` to compare them.

Assisted-by: Antigravity with Gemini
2026-07-07 15:04:40 +00:00
Dana Jansens bd3ca2b72b Subst the whole facet type to replace .Self in identify (#7449)
This performs `.Self` substitution in a single step, for the whole facet
type, instead of doing it individually for each constraint visited in
the top-level facet type. Then we don't need to track state to avoid
subst in constraints that come from other named constraints.

The semir changes are because we now generate a whole other FacetType
from the substitution.
2026-07-07 13:30:53 +00:00
Dana Jansens 11dca8f227 Add SubstResult::SubstOperandsSkipType to not subst the type_id (#7452)
Add a result for Subst() to return when you want to recurse into the
instructions operands but not the type_id. This comes up when recursing
and looking for facet types written in an instruction, but not
referenced indirectly through a type_id.

We can't skip adding the instruction to the worklist entirely, since we
need to pop it back off to rebuild the containing instruction later. So
we just mark it with a skip flag, and don't call Subst() on it.

The suggestion for a change to Subst was made in
https://github.com/carbon-language/carbon-lang/pull/7367#discussion_r3423446839.
2026-07-07 13:23:47 +00:00
Chandler Carruthandjosh11b 383cfbb023 Fix uniform identifier generation for lengths over 64 (#7459)
`GetIdentifiersImpl` unconditionally sliced the 64-entry
`IdentifierLengthCounts` table even for uniform distributions, which the
API documents as having no `max_length` limit. Requesting a uniform
distribution with `max_length > 64` therefore tripped an out-of-bounds
slice assertion. Only compute the table slice on the non-uniform path,
where `max_length <= 64` is already enforced.

Add `IdentifierByteSumStableAcrossSeeds`, which exercises this path (a
uniform request up to length 200) and checks the core invariant that the
total identifier byte count is independent of the random seed across a
spread of parameters.

Assisted-by: Claude Code

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2026-07-07 06:52:57 +00:00
a2890716ba Systematically update syntax in the design for #7254 (#7259)
Assisted-by: Claude and Antigravity with Gemini

---------

Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2026-07-07 00:41:06 +00:00
Chandler Carruth 88160496e1 Fix which tokens the lexer flags as bracket-recovery tokens. (#7457)
`ErrorRecoveryBuffer::Apply` flagged each inserted token via the
pre-insertion index of the token it was inserted before. Once any
earlier insertion had been applied, that index no longer matches the
token's position in the merged list: with two closers inserted at the
same point (`{((}`), the second recovery token was left unflagged, and
with insertions at two separate points (`{(} {(}`), a real token was
flagged in the second one's place.

`IsRecoveryToken` now reports exactly the inserted tokens. This will
matter for `carbon format`: a recovery token's text exists in no source
byte range, so a minimal-edit model must know not to anchor edits on it.

Assisted-by: Claude Code
2026-07-06 14:39:50 +00:00
Chandler Carruth f0848b1f5e Trailing comments (#7441)
Carbon currently requires a comment to be the only non-whitespace on its
line. A `//` comment that follows other content on a line, called a
_trailing comment_, is a lexer error. This proposal removes that
restriction, allowing a comment to follow other content on a line.
Everything else about comments is unchanged: a comment still begins with
`//`, still requires whitespace after the `//`, and still runs to the
end of the line. Carbon continues to provide only line comments; no
block or intra-line comments are added.

Three observations motivate the change. First, trailing comments are
well suited to short _annotations_ attached to a specific entity or
value on a line. Second, the lexer design now makes it trivial to lex
trailing comments, and in fact requires extra logic and potentially cost
to reject them. Third, C++ code routinely uses trailing comments, so
allowing them lets Carbon carry the layout of migrated code over
directly, rather than reworking each comment to read well in a different
structure.

Implementation notes (beyond the proposal's design):

Keeping trailing comments cheap to lex required a few supporting
changes, all of which keep the cost off the lexer's hot path:

- The lexer already dispatches `//` to comment lexing wherever it
appears, so classifying a comment as trailing is a single O(1) check of
whether the `//` is the line's first non-whitespace (`start + indent`).
The hot comment path is otherwise unchanged.

- That check relies on each line's recorded indentation being its real
leading whitespace. Multi-line string literals previously recorded the
column where the literal opened for the lines they span; they now record
the true (closing-delimiter) indentation instead.

- Parser error recovery (`SkipPastLikelyEnd`) had relied on that
opening-column indentation to keep tokens following a multi-line string
literal attached to the same construct. It now reconstructs that
relationship directly by consulting the line on which the literal
opened, including when other tokens follow the closing delimiter (such
as `''' + "more"`). This is on the cold recovery path.

- `CommentData` records the trailing bit in the high bit of its length
field, keeping it at 8 bytes.

Assisted-by: Claude Code
2026-07-04 06:42:02 +00:00
Geoff Romer 0460f6b7ba Label VarStorage as var_storage instead of var (#7447)
This makes the textual format clearer and more self-explanatory, and
avoids ambiguity about whether this inst refers to the storage or the
pattern.
2026-07-02 01:02:19 +00:00
Geoff Romer 11eaeeda7d Restructure handling of expressions in patterns (#7445)
Instead of maintaining a stack of pending subpatterns which might or
might not contain expressions, we mark non-nesting regions during
pattern handling that might contain an expression. The implementation
remains largely the same; the difference is that callers are expected to
end a pending expression region as soon as possible, rather than wait
for the end of the subpattern. This makes it possible to emit
non-pattern insts during pattern handling, without the risk that they
will get caught in a pending expression region further up the stack.
2026-07-01 19:15:34 +00:00
Dana Jansens e7771c2f6d During identify replace .Self only in the initial facet type (#7436)
When we find a named constraint during identity, we recurse into it. The
specific args of the named constraint may contain references to `.Self`
which can then make `.Self` appear inside the named constraint, which
was making us replace `.Self` at multiple levels and incorrectly. The
first specific argument replaces `Self` in the named constraint, and we
pass in the self-type of the identify operation. This may contain
`.Self` and we should _not_ be replacing the `.Self` references with the
self-type that they are contained within. This led to infinite cycles.

In the meantime, we have made the toolchain reject any ambiguous `.Self`
from being constructed. So we know there is only one value of `.Self`
around in a facet type.

So now we replace `.Self` only in the top level facet type during
identity. That means replacing `.Self` in the specifics of the named
constraints that we recurse into. But we do _not_ replace `.Self`
anymore inside those named constraints. This resolves the infinite loop.

At the same time, when we are identifying an `impls` constraint from
earlier in the same facet type, like `C impls Z(.Self)` we are
identifying with a self-type of `C`. We want the output to use `C` as
the self-type since we should get back an identified facet type that
says `C impls Z(.Self)`. But we do _not_ want to replace the `.Self`
there since we're inside a facet type and the `.Self` does not refer to
`C`. So we parameterize `TryToIdentifyFacetType` to not replace `.Self`
when identifying an `impls` constraint from the `where_stack()`. This
resolves a large number of `fail_todo_` tests.
2026-06-30 23:33:30 +00:00
Dana Jansens 8928268a95 Add script that pulls review stats from Github (#7444)
The script grabs all PRs and dumps them into CSV format
2026-06-30 23:11:46 +00:00
Richard Smith 157ca42ab3 Support for overriding virtual functions overloaded on arity. (#7438)
Very basic support for determining which function in an overload set an
`override fn` intended to override.

Assisted-by: Gemini via Antigravity
2026-06-30 19:36:38 +00:00
Dana Jansens a068806f67 Test and mitigate infinite cycles in impl lookup (#7428)
Impl lookup identifies the types of facets in the query, replacing
`.Self` in each type with the facet. This allows references using the
facet from outside the facet type to match similar structures inside the
facet type.

However replacing `.Self` with the facet can re-evaluate symbolic impl
lookups inside the facet type. These can perform deduction in generic
`final impl`s, which can attempt to convert the facet. Convert does an
impl lookup with that facet in the query, which causes us to form an
infinite recursion cycle.

Add tests that caused such a cycle, to demonstrate we no longer crash.
Some of these tests fail impl lookups using concrete values in the query
that match values from a `final impl`, with TODOs to address them.
2026-06-30 06:03:33 +00:00
Chandler CarruthandGeoff Romer 6e6405c0bb Replace :! and :? with keywords and contextual defaults (#7254)
This proposal removes the `:!` syntax for generics and templates in
favor of keywords (`generic`, `template`, `runtime`) and contextual
defaults for phase. It also replaces `:?` with `fwd` and introduces
`exttype` for extended types.

Assisted-by: Antigravity with Gemini, and Claude

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-06-29 22:51:57 +00:00
Chandler Carruth 366cb1010b Recover an incomplete lambda as a complete expression. (#7435)
A lambda introducer (`fn` in expression context) with no parameters and
no body -- for example `(fn)`, where `)` immediately follows `fn` --
left `HandleLambdaAfterParams` calling `ReturnErrorOnState()` without
ever emitting a `Lambda` node. The orphaned `LambdaIntroducer` leaf was
then left where an expression was required, so `Parse` produced a tree
that failed its own verification and aborted via `CARBON_FATAL`.

Recover the way `HandleLambdaBody` already does for a missing body after
a return type: emit a placeholder `InvalidParse` body and finish a
complete `Lambda` node, so the lambda stays a valid expression and the
surrounding construct (here a `ParenExpr`) extracts cleanly.

Found by fuzzing.

Assisted-by: Claude Code
2026-06-29 21:12:58 +00:00
Richard Smith baa91882dc Update to newer LLVM. (#7433)
One API fix: BumpPtrAllocator no longer tracks the amount of memory it's
handed out separately from the amount of memory it has allocated from
the system.

Assisted-by: Gemini via Antigravity
2026-06-29 21:11:16 +00:00
Chandler Carruth fd62f5a58d Fix an out-of-bounds read in TokenizedBuffer::IsRawIdentifier. (#7434)
`IsRawIdentifier` checked `token_text.starts_with("r#")` and then read
`token_text[2]`, but `starts_with` only guarantees a length of two. An
`r` identifier immediately followed by `#` at the end of the source --
so the token text is exactly `r#` -- made the `token_text[2]` read run
off the end. Guard on the length first.

Found by fuzzing. The read is reached only via `GetTokenText`, so the
parser fuzzer, which does not request token text, never hit it.

Assisted-by: Claude Code
2026-06-29 20:06:39 +00:00
Dana Jansens 7a7aefe486 Add a cargo_update.py script (#7431)
Our development instructions now recommend installing a number of
binaries through `cargo`. Updating these binaries has to be done by
hand. So we can provide a script that users can use to update them
easily and regularly.
2026-06-29 19:15:41 +00:00
73744544fc Merge functions.md and lambdas.md design documents (#7425)
Implements suggestion from
https://github.com/carbon-language/carbon-lang/pull/7355#discussion_r3416055969
.

Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2026-06-29 18:24:16 +00:00
Geoff Romer e4b0903d2e Remove ValueBinding and RefBinding (#7427)
These inst kinds are now redundant with `WrapperBinding`.
2026-06-29 17:41:23 +00:00
Chandler CarruthandChristopher Di Bella 361c832713 Add a prelude compilation benchmark (#7368)
Adds `toolchain/benchmarking/prelude_benchmark.cpp`, which measures the
time to compile the Core prelude and reports the most interesting SemIR
memory statistics as benchmark counters.

The prelude is compiled by checking a file that imports it: the implicit
prelude import causes the check phase to lex, parse, and check the full
set of prelude files, so this is a direct measure of prelude compilation
cost. Four input variations exercise increasing amounts of the prelude:
an empty file, a minimal single-type use, an operator-heavy file that
hits many impls, and a compact file that pulls in a wide swath of the
prelude.

Memory usage is queried directly: `Driver::set_mem_usage` takes a
`MemUsage` that a compile merges each file's usage into; the benchmark
passes one, compiles, and sums the entries by label. A compilation unit
collects into its own `MemUsage` whenever usage is dumped or a sink is
provided (decided in `SetMultiUnitCache`); after a file is done it dumps
that `MemUsage` per-file as before and, if a sink was provided, merges
into it via a new `MemUsage::Add(const MemUsage&)` overload. `MemUsage`
also exposes its entries via a public `Entry` type and an `entries()`
accessor.

Also extends `scripts/bench_runner.py` to (1) treat Mem-prefixed
counters as cost metrics (smaller is better) and (2) tolerate metrics
that aren't reported by every benchmark in a binary.

Assisted-by: Claude Code

---------

Co-authored-by: Christopher Di Bella <cjdb.ns@gmail.com>
2026-06-29 05:39:44 +00:00
Geoff Romer 34a63b1cae Option to run all of file_test under LLDB (#7429)
This is handy when `file_test`'s stack trace fails to report which file
caused the crash.
2026-06-27 00:53:42 +00:00
Geoff Romer 1a3966d2c4 Build VarStorage insts more efficiently. (#7422)
Instead of traversing the entire pattern block looking for
`VarPattern`s, we keep track of them on creation, and then build
`VarStorage`s directly from that list.

This also gets rid of the global `var_storage_map`, and instead keep
that information narrowly scoped to each full-pattern, and consume it in
a single linear traversal instead of with random-access lookups. To
enable that, this fixes a parse bug where nested `var` patterns were
getting diagnosed but not marked as errors.
2026-06-26 22:26:13 +00:00
Chandler CarruthandRichard Smith cfd1ed8484 Switch from Prettier to Rumdl for Markdown formatting (#7423)
Rumdl already appears to have _significantly_ fewer bugs than prettier,
and a solid LSP for editor integration.

The tool is: https://github.com/rvben/rumdl/

I've separated out the change across three commits for easier review.

The configuration tries to match the existing formatting, the changes to
the all the files are to correct issues found by the new tool.

Assisted-by: Antigravity with Gemini

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-06-26 21:42:01 +00:00
Richard Smith 6181259cf1 Language server: prelude support. (#7417)
Support multi-file compilation, and in particular imports of files from
the prelude, in `carbon language_server`.

In order to properly interface with `CompileDriver`, also switch over to
building a proper VFS from the documents we're given.

Assisted-by: Gemini via Antigravity
2026-06-26 20:16:28 +00:00
Geoff Romer f203a9c18b Give splice_inst a concrete category where possible. (#7426)
This ensures that splices are put in the pattern block when they produce
patterns, and also fixes some latent bugs in how actions were
categorized.
2026-06-26 18:53:26 +00:00
Dana JansensandDavid Blaikie fb12984713 Forbid nested where inside a where expression through eval (#7397)
In #7378 we forbid writing `where` on the RHS of another `where`
expression. However it's still possible to inject a `where` expression
through eval, using an `alias` or an `eval fn`. We address this by
looking in the constant value of constraints of a `WhereExpr` (which
sees the outcome of eval) and searching for a nested `where` there. We
can determine a facet type was written with a nested `where` by seeing
that it has some non-extend constraint.

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2026-06-26 18:31:26 +00:00
Geoff Romer 8158d4ffd4 Basic support for symbolic forms (#7408) 2026-06-25 22:46:48 +00:00
Dana Jansens 5aae6a1ca5 Ensure a location for monomorphization diagnostics in call argument deduction (#7401)
If the deduction fails while forming the parameter type, ensure that we
print an actual diagnostic saying what went wrong.

And always ensure that an invalid array bounds error points at a
location. The `inst_id` given to `EvalConstantInst` always has a
location, but the `bounds_id` instruction inside it may be canonical
when it's coming from inside a larger type. So when it is, fall back to
using the location of the whole array inst.
2026-06-25 22:37:14 +00:00
Richard Smith bd8c565c74 vscode: don't use carbon LSP for testdata files (#7420)
These files aren't exactly written in Carbon, but rather in some
meta-language with file splits and semantically meaningful comments, and
in any case getting red squiggles for expected errors is distracting and
largely unhelpful.

(We *could* teach the LSP to run the test and produce errors if the test
doesn't match its expectations, but it's not clear that that would be
helpful in practice either.)
2026-06-25 21:24:25 +00:00
Dana Jansens b22ee48c9b Forbid nested where inside a where expression (#7378)
This disallows building a facet type that contains another facet type
with non-extend constraints in it. Which in turn prevents the
possibility of introducing a different `.Self` into a facet type.

Eval can still insert a facet type with non-extend constraints, as we
only prevent it for `where` being written into the facet type. There is
a TODO in handle_where.cpp for this and some tests in
toolchain/check/testdata/facet/nested_facet_types_from_eval.carbon
2026-06-25 18:56:36 +00:00
Nicholas Bishop 093dc04db6 Switch back to clang's MultiplexExternalSemaSource (#7416)
The necessary changes were upstreamed, and made available in #7413.
2026-06-25 17:10:06 +00:00
Richard Smith 9108812bc2 Apply some workflow fixes generated by zizmor. (#7418)
See https://github.com/zizmorcore/zizmor
2026-06-25 15:18:33 +00:00
Richard Smith be6bcbcfd3 Narrow down overly-broad workflow permissions. (#7419) 2026-06-25 01:44:13 +00:00
Nicholas Bishop 36d9bed4ca Fix accessing members of const/partial types (#7406)
In `PerformActionHelper`, use the unqualified type for lookup.

In `PerformInstanceBinding`, propagate qualifiers to the unbound element
type's class type when doing the `ConvertToValueOrRefOfType` conversion,
and to the element type when forming the `ClassElementAccess` instr
(except for `partial`, which is only used if the member being accessed
is `base`).

In handle_operator.cpp, prevent assignment to a reference to a const
type.
2026-06-25 00:07:39 +00:00
Nicholas Bishop 885b1110d5 Allow derived->base conversions with compatible qualifiers (#7415)
Move the existing derived->base conversion earlier in
`PerformBuiltinConversion`, into the block that handles qualifier
conversions. This allows, for example, converting from `partial Derived`
to `partial Base` -- see the tests in
`toolchain/check/testdata/class/inheritance/derived_to_base.carbon`.
2026-06-24 21:08:24 +00:00
Richard Smith f2d99f31f0 Fix contention between Clang and Carbon over external name lookup. (#7411)
The function to set the visible declarations with a given name
overwrites any existing declarations imported from an AST file, so we
need to avoid calling that for declaration contexts whose names are
managed by Clang to avoid clobbering names imported from modules.

Assisted-by: Gemini via Antigravity
2026-06-24 18:36:59 +00:00
Nicholas Bishop 999dcc5bf0 Update LLVM to bab165ecb0d (#7413)
This required a minor change to patch 0009, and allows us to drop patch
0010.
2026-06-24 18:04:48 +00:00
dependabot[bot] 039b4e9b17 Bump concurrent-ruby from 1.3.4 to 1.3.7 in /website in the bundler group across 1 directory (#7409)
Bumps the bundler group with 1 update in the /website directory:
[concurrent-ruby](https://github.com/ruby-concurrency/concurrent-ruby).

Updates `concurrent-ruby` from 1.3.4 to 1.3.7
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/ruby-concurrency/concurrent-ruby/releases">concurrent-ruby's
releases</a>.</em></p>
<blockquote>
<h2>v1.3.7</h2>
<!-- raw HTML omitted -->
<p>There are 3 security fixes in this release, so updating is
recommended.
These security vulnerabilities are not very likely to be hit in practice
and have a corresponding <code>Low</code> severity score.</p>
<!-- raw HTML omitted -->
<h2>What's Changed</h2>
<ul>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/security/advisories/GHSA-h8w8-99g7-qmvj">CVE-2026-54904</a>
<code>AtomicReference#update</code> livelocks when the stored value is
<code>Float::NAN</code>. Fix by <a
href="https://github.com/joshuay03"><code>@​joshuay03</code></a> and <a
href="https://github.com/eregon"><code>@​eregon</code></a></li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/security/advisories/GHSA-wv3x-4vxv-whpp">CVE-2026-54905</a>
<code>ReentrantReadWriteLock</code> read-count overflow grants a write
lock without exclusivity. Fix by <a
href="https://github.com/joshuay03"><code>@​joshuay03</code></a></li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/security/advisories/GHSA-6wx8-w4f5-wwcr">CVE-2026-54906</a>
<code>ReadWriteLock</code> allows wrong-thread write release and stray
read-release counter corruption. Fix by <a
href="https://github.com/joshuay03"><code>@​joshuay03</code></a></li>
<li>concurrent-ruby-ext: fix build on Darwin 32-bit by <a
href="https://github.com/barracuda156"><code>@​barracuda156</code></a>
in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1064">ruby-concurrency/concurrent-ruby#1064</a></li>
<li>Add SECURITY.md by <a
href="https://github.com/eregon"><code>@​eregon</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1104">ruby-concurrency/concurrent-ruby#1104</a></li>
<li>Add Ruby 4.0 in CI by <a
href="https://github.com/eregon"><code>@​eregon</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1106">ruby-concurrency/concurrent-ruby#1106</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a
href="https://github.com/barracuda156"><code>@​barracuda156</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1064">ruby-concurrency/concurrent-ruby#1064</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/ruby-concurrency/concurrent-ruby/compare/v1.3.6...v1.3.7">https://github.com/ruby-concurrency/concurrent-ruby/compare/v1.3.6...v1.3.7</a></p>
<h2>v1.3.6</h2>
<!-- raw HTML omitted -->
<h2>What's Changed</h2>
<ul>
<li>Run tests without the C extension in CI by <a
href="https://github.com/eregon"><code>@​eregon</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1081">ruby-concurrency/concurrent-ruby#1081</a></li>
<li>Fix typo in Promise docs by <a
href="https://github.com/danieldiekmeier"><code>@​danieldiekmeier</code></a>
in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1083">ruby-concurrency/concurrent-ruby#1083</a></li>
<li>Correct word in readme by <a
href="https://github.com/wwahammy"><code>@​wwahammy</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1084">ruby-concurrency/concurrent-ruby#1084</a></li>
<li>Fix mistakes in MVar documentation by <a
href="https://github.com/trinistr"><code>@​trinistr</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1087">ruby-concurrency/concurrent-ruby#1087</a></li>
<li>Fix multi require concurrent/executor/cached_thread_pool by <a
href="https://github.com/OuYangJinTing"><code>@​OuYangJinTing</code></a>
in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1085">ruby-concurrency/concurrent-ruby#1085</a></li>
<li>Use typed data APIs by <a
href="https://github.com/nobu"><code>@​nobu</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1096">ruby-concurrency/concurrent-ruby#1096</a></li>
<li>Add Joshua Young to the list of maintainers by <a
href="https://github.com/eregon"><code>@​eregon</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1097">ruby-concurrency/concurrent-ruby#1097</a></li>
<li>Asynchronous pruning for RubyThreadPoolExecutor by <a
href="https://github.com/joshuay03"><code>@​joshuay03</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1082">ruby-concurrency/concurrent-ruby#1082</a></li>
<li>Mark RubySingleThreadExecutor as a SerialExecutorService by <a
href="https://github.com/meineerde"><code>@​meineerde</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1070">ruby-concurrency/concurrent-ruby#1070</a></li>
<li>Allow TimerTask to be safely restarted after shutdown and avoid
duplicate tasks by <a
href="https://github.com/bensheldon"><code>@​bensheldon</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1001">ruby-concurrency/concurrent-ruby#1001</a></li>
<li>Flaky test fix: allow ThreadPool to shutdown before asserting
completed_task_count by <a
href="https://github.com/bensheldon"><code>@​bensheldon</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1098">ruby-concurrency/concurrent-ruby#1098</a></li>
<li><code>ThreadPoolExecutor#kill</code> will
<code>wait_for_termination</code> in JRuby; ensure <code>TimerSet</code>
timer thread shuts down cleanly by <a
href="https://github.com/bensheldon"><code>@​bensheldon</code></a> in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1044">ruby-concurrency/concurrent-ruby#1044</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a
href="https://github.com/danieldiekmeier"><code>@​danieldiekmeier</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1083">ruby-concurrency/concurrent-ruby#1083</a></li>
<li><a href="https://github.com/wwahammy"><code>@​wwahammy</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1084">ruby-concurrency/concurrent-ruby#1084</a></li>
<li><a href="https://github.com/trinistr"><code>@​trinistr</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1087">ruby-concurrency/concurrent-ruby#1087</a></li>
<li><a
href="https://github.com/OuYangJinTing"><code>@​OuYangJinTing</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1085">ruby-concurrency/concurrent-ruby#1085</a></li>
<li><a href="https://github.com/nobu"><code>@​nobu</code></a> made their
first contribution in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1096">ruby-concurrency/concurrent-ruby#1096</a></li>
<li><a href="https://github.com/joshuay03"><code>@​joshuay03</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/pull/1082">ruby-concurrency/concurrent-ruby#1082</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/ruby-concurrency/concurrent-ruby/compare/v1.3.5...v1.3.6">https://github.com/ruby-concurrency/concurrent-ruby/compare/v1.3.5...v1.3.6</a></p>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ruby-concurrency/concurrent-ruby/blob/master/CHANGELOG.md">concurrent-ruby's
changelog</a>.</em></p>
<blockquote>
<h2>Release v1.3.7 (16 June 2026)</h2>
<p>concurrent-ruby:</p>
<ul>
<li>See the <a
href="https://github.com/ruby-concurrency/concurrent-ruby/releases/tag/v1.3.7">release
notes on GitHub</a>.</li>
</ul>
<h2>Release v1.3.6 (13 December 2025)</h2>
<p>concurrent-ruby:</p>
<ul>
<li>See the <a
href="https://github.com/ruby-concurrency/concurrent-ruby/releases/tag/v1.3.6">release
notes on GitHub</a>.</li>
</ul>
<h2>Release v1.3.5, edge v0.7.2 (15 January 2025)</h2>
<p>concurrent-ruby:</p>
<ul>
<li>(<a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/issues/1062">#1062</a>)
Remove dependency on logger.</li>
</ul>
<p>concurrent-ruby-edge:</p>
<ul>
<li>(<a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/issues/1062">#1062</a>)
Remove dependency on logger.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/4c8fc28ab6bb9bd8258a4c0c2fa6d35ebe77b3cb"><code>4c8fc28</code></a>
Release 1.3.7</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/d91ca9426cb819d6cc63f1bd64bfe54644d0beca"><code>d91ca94</code></a>
Fix AtomicReference#update livelock when stored value is Float::NAN on
JRuby ...</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/7e4d711bacf7a1dac3ef6bda44004387be2dc7e6"><code>7e4d711</code></a>
Fix <code>ReentrantReadWriteLock</code> read hold overflow into
write-lock bit</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/6e37e0644b83b182971dc540d2e4bee38df61386"><code>6e37e06</code></a>
Fix <code>AtomicReference#update</code> livelock when stored value is
<code>Float::NAN</code></li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/2825cfa12cb708b76557803957f76862eb1151a2"><code>2825cfa</code></a>
Cleanup spec</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/3fd493283ca5f84f0ef4e84aabd43ad68df4626b"><code>3fd4932</code></a>
Fix <code>ReadWriteLock</code> wrong-thread write release and stray read
release</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/1974b4772efc034ee8eaa562b4370343f4c5c54b"><code>1974b47</code></a>
Add Ruby 4.0 in CI</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/df8706d40c483d76bbb0b3a35a633c68fa9e17be"><code>df8706d</code></a>
Add SECURITY.md (<a
href="https://redirect.github.com/ruby-concurrency/concurrent-ruby/issues/1104">#1104</a>)</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/7a1b78941c081106c20a9ca0144ac73a48d254ab"><code>7a1b789</code></a>
Bump actions/upload-pages-artifact from 4 to 5</li>
<li><a
href="https://github.com/ruby-concurrency/concurrent-ruby/commit/9b2dbf712896a638a73d2fa221206961c8d6484d"><code>9b2dbf7</code></a>
Bump actions/deploy-pages from 4 to 5</li>
<li>Additional commits viewable in <a
href="https://github.com/ruby-concurrency/concurrent-ruby/compare/v1.3.4...v1.3.7">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=concurrent-ruby&package-manager=bundler&previous-version=1.3.4&new-version=1.3.7)](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-06-24 15:16:36 +00:00
Dana Jansens e2d32ab81c Don't crash on monomorphization failure when replacing .Self (#7400)
Depending on the order in which type completion identifies things in the
facet type, it may try to replace `.Self` with a facet that fails to
convert to the type of `.Self` due to a monomorphization error. We
should fail gracefully, not crash.
2026-06-24 13:50:59 +00:00
Richard Smith de6c8b0990 Delete some dead variables. (#7410) 2026-06-24 04:24:40 +00:00
Geoff Romer a8668c9b4e Remove RefineFormAction (#7393)
Wrapping symbolic forms in `RefineFormAction` was making it very
difficult to reason about them symbolically, and at least for now we
don't really need it. See [this
discussion](https://discord.com/channels/655572317891461132/655578254970716160/1516867358751195136)
for background and possible future approaches.
2026-06-23 20:12:22 +00:00
Richard Smith 2271583d6d Switch from text to curves in SVG C++ logo. (#7395)
The text SVG would sometimes be processed by vscode before it finished
initializing its font engine and then get aggressively cached, resulting
in the logo sometimes missing one of the characters.

The new SVG logo is a bit more dense than the old text one was, so shows
up as a C++ "banner" a bit better, and should be displayed more
consistently.

Assisted-by: Gemini via Antigravity
2026-06-23 19:22:53 +00:00
Geoff Romer fee00c6f3c Move FormInfo to SemIR for reuse (#7392) 2026-06-23 19:14:25 +00:00
Richard Smith b8aa0ee164 Use plain Apache 2.0 license for mirrors. (#7407)
Our mirror repositories contain vim scripts and textmate grammars,
neither of which have any need for the LLVM exception, so we can use the
base Apache 2.0 license there with no loss of relevant permissions. This
is a compatible license, so providing these repositories under these
license terms is valid.

Other than removing the LLVM exception, the new license file has one
other change compared to LICENSE: the amount of whitespace on some lines
is reduced from four spaces to three. This makes the new license
*exactly* match the Apache 2.0 license, byte-for-byte.

This is important because the license checking done by GitHub's linguist
project doesn't recognize Apache-2.0-with-LLVM-exception as an
acceptable license, but does allow plain Apache-2.0.
2026-06-23 17:18:47 +00:00
Nicholas Bishop e5cc550554 Import modified copy of MultiplexExternalSemaSource and drop LLVM patch (#7405)
Copy MultiplexExternalSemaSource.h and MultiplexExternalSemaSource.cpp
from https://github.com/llvm/llvm-project/pull/204458 into
third_party/llvm, and apply a few minor changes to allow them to compile
and pass precommit checks.

This allows
`0011-Add-empty-constructor-and-GetSources-method-to-Multi.patch` to be
removed, which brings Carbon closer to being able to compile on an
unmodified LLVM toolchain.
2026-06-22 19:42:52 +00:00
Dana Jansens 513b0c9e3b Support dumping ImportIRInstId from its printed id (#7398)
Add support to the dump command to `dump context import_ir_inst123`

Support for dumping the ids was previously added, but missed support for
parsing and creating a C++ id from its printed id.
2026-06-22 15:01:59 +00:00
Dana Jansens 02df90e265 Support imported insts in FindStorageArgForInitializer (#7399)
Formatting an instruction with an initializing expr category will call
`FindStorageArgForInitializer()` to get the target id.

`GetExprCategory()` supports imported instructions by walking to the
imported IR, in order to get the expr category. We do the same in
`FindStorageArgForInitializer()`, instead of hitting a CARBON_CHECK.

The new test crashes without the changes here.
2026-06-21 22:56:02 +00:00
Geoff Romer 4e086a6615 Include bundle operands in operand refinement (#7391)
Also some Bundle API tweaks:
- Remove support for non-canonical bundle IDs. Bundles don't have a
unique identity, so non-canonical bundle IDs would bloat the SemIR for
no benefit.
- Adjust the conversions between raw and typed bundle IDs to not be
templated. This makes the conversions easier to access in a debugger.
2026-06-19 00:22:05 +00:00
Nicholas Bishop 2ebc7cdb40 Allow abstract types to be used in Convert (#7388)
Notably this allows accessing fields in an abstract base class via a
derived class without going through `base`. E.g.
`my_obj.field_in_base_class` rather than
`my_obj.base.field_in_base_class`.
2026-06-19 00:18:48 +00:00
Geoff Romer 833e0c418e Bug fix: give output pattern splices correct types. (#7390)
Also add a CHECK to catch bugs like this.
2026-06-18 22:59:45 +00:00
2ec915eab6 Update functions design doc (#7355)
Incorporates changes from these proposals:

- #2022 
- #2875 
- #3262 
- #3763 
- #3848 
- #5434 

A small amount of updating was done to lambdas.md and variadics.md to
harmonize with these changes.

Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2026-06-18 22:58:51 +00:00
Richard Smith 974850788c Make our TextMate bundle actually work in TextMate. (#7386)
TextMate doesn't support JSON grammars, so convert our JSON grammar to a
plist automatically as a pre-commit check. Fix malformed info.plist
file. Add missing uuid to grammar file.

Assisted-by: Gemini via Antigravity
2026-06-18 21:06:24 +00:00
Richard Smith 6fd7c84a89 Fix conflict between #7384 and #7385. (#7394) 2026-06-18 21:05:45 +00:00
josh11bandJosh L cbd79529b2 Update design docs to reflect proposal #1885: for statement and user types (#7350)
Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-06-18 20:55:07 +00:00
Richard Smith 870a1a4cc6 Highlight inline C++ as C++. (#7384)
Switch into C++ syntax highlighting mode inside inline C++ fragments in
Carbon code. Add a background to them to make their boundaries stand out
a bit more.

Assisted-by: Gemini via Antigravity
2026-06-18 19:18:39 +00:00
dependabot[bot] 366ce25302 Bump undici from 7.25.0 to 7.28.0 in /utils/vscode in the npm_and_yarn group across 1 directory (#7387)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [undici](https://github.com/nodejs/undici).

Updates `undici` from 7.25.0 to 7.28.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>v7.28.0</h2>
<h1>⚠️ Security Release</h1>
<p>This release line addresses <strong>7 security advisories</strong>,
all shipped in <strong>v7.28.0</strong>.</p>
<blockquote>
<p><strong>Action required:</strong> Upgrade to <strong>undici
7.28.0</strong> or later.</p>
<pre lang="sh"><code>npm install undici@^7.28.0
</code></pre>
</blockquote>
<p>The v7 line is <strong>not</strong> affected by GHSA-38rv-x7px-6hhq
(CVE-2026-9675), which is
an 8.x-only regression.</p>
<blockquote>
<p><strong>Note on GHSA-hm92-r4w5-c3mj:</strong> this fix shipped in
<strong>v7.28.0</strong>, not the
earlier 7.2x line — the vulnerable single-pool code was still present
through
<code>v7.27.2</code>. The per-origin pool fix is
<a
href="https://github.com/nodejs/undici/commit/3805b8f8"><code>3805b8f8</code></a>
(<a
href="https://redirect.github.com/nodejs/undici/pull/5041">#5041</a>).</p>
</blockquote>
<h2>Summary</h2>
<table>
<thead>
<tr>
<th>Advisory</th>
<th>CVE</th>
<th>Severity (CVSS)</th>
<th>Fixed in</th>
<th>Fix commit</th>
</tr>
</thead>
<tbody>
<tr>
<td><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-vxpw-j846-p89q">GHSA-vxpw-j846-p89q</a></td>
<td>CVE-2026-12151</td>
<td>High (7.5)</td>
<td>7.28.0</td>
<td><a
href="https://github.com/nodejs/undici/commit/8cb10f98"><code>8cb10f98</code></a></td>
</tr>
<tr>
<td><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-vmh5-mc38-953g">GHSA-vmh5-mc38-953g</a></td>
<td>CVE-2026-9697</td>
<td>High (7.4)</td>
<td>7.28.0</td>
<td><a
href="https://github.com/nodejs/undici/commit/04201f89"><code>04201f89</code></a></td>
</tr>
<tr>
<td><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-hm92-r4w5-c3mj">GHSA-hm92-r4w5-c3mj</a></td>
<td>CVE-2026-6734</td>
<td>High (7.5)</td>
<td>7.28.0</td>
<td><a
href="https://github.com/nodejs/undici/commit/3805b8f8"><code>3805b8f8</code></a></td>
</tr>
<tr>
<td><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-pr7r-676h-xcf6">GHSA-pr7r-676h-xcf6</a></td>
<td>CVE-2026-9678</td>
<td>Moderate (5.9)</td>
<td>7.28.0</td>
<td><a
href="https://github.com/nodejs/undici/commit/85a24055"><code>85a24055</code></a></td>
</tr>
<tr>
<td><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-p88m-4jfj-68fv">GHSA-p88m-4jfj-68fv</a></td>
<td>CVE-2026-9679</td>
<td>Moderate (5.9)</td>
<td>7.28.0</td>
<td><a
href="https://github.com/nodejs/undici/commit/d0574cc4"><code>d0574cc4</code></a></td>
</tr>
<tr>
<td><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-g8m3-5g58-fq7m">GHSA-g8m3-5g58-fq7m</a></td>
<td>CVE-2026-11525</td>
<td>Low (3.7)</td>
<td>7.28.0</td>
<td><a
href="https://github.com/nodejs/undici/commit/d0574cc4"><code>d0574cc4</code></a></td>
</tr>
<tr>
<td><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-35p6-xmwp-9g52">GHSA-35p6-xmwp-9g52</a></td>
<td>CVE-2026-6733</td>
<td>Low (3.7)</td>
<td>7.28.0</td>
<td><a
href="https://github.com/nodejs/undici/commit/ea8930cf"><code>ea8930cf</code></a></td>
</tr>
</tbody>
</table>
<hr />
<h2>High severity</h2>
<h3>WebSocket DoS via fragment count bypass — CVE-2026-12151</h3>
<p><strong><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-vxpw-j846-p89q">GHSA-vxpw-j846-p89q</a></strong>
· CWE-400, CWE-770
<strong>Fix:</strong> <a
href="https://github.com/nodejs/undici/commit/8cb10f98"><code>8cb10f98</code></a>
<em>websocket: limit the number of fragments in a message</em> (part of
backport <a
href="https://github.com/nodejs/undici/commit/a027a4a0"><code>a027a4a0</code></a>
<em>Backport WebSocket maxPayloadSize fixes to v7.x</em>, <a
href="https://redirect.github.com/nodejs/undici/pull/5423">#5423</a>)</p>
<p>A malicious WebSocket server can stream a large number of small or
empty
continuation frames. Undici enforced a limit on cumulative payload size
but did
not limit the <em>number</em> of fragments per message, leading to
unbounded memory
growth and denial of service.</p>
<ul>
<li><strong>Affected:</strong> applications using <code>new
WebSocket(...)</code> or <code>WebSocketStream</code>
against untrusted endpoints.</li>
<li><strong>Workaround:</strong> none — upgrade is required.</li>
</ul>
<h3>TLS certificate validation bypass in SOCKS5 ProxyAgent —
CVE-2026-9697</h3>
<p><strong><a
href="https://github.com/nodejs/undici/security/advisories/GHSA-vmh5-mc38-953g">GHSA-vmh5-mc38-953g</a></strong>
· CWE-295</p>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/nodejs/undici/commit/f9eba0ad9134e1c0977848476bba9d49734696e4"><code>f9eba0a</code></a>
Bumped v7.28.0 (<a
href="https://redirect.github.com/nodejs/undici/issues/5430">#5430</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/a027a4a04c6c055877d1abaf5f60ee4917e7e01f"><code>a027a4a</code></a>
Backport WebSocket maxPayloadSize fixes to v7.x (<a
href="https://redirect.github.com/nodejs/undici/issues/5423">#5423</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/8cb10f983eb6005dd53f3744d95d3b6d7dbcee0f"><code>8cb10f9</code></a>
websocket: limit the number of fragments in a message</li>
<li><a
href="https://github.com/nodejs/undici/commit/04201f8947041f0f4f2ac865dbdb1677e46a8844"><code>04201f8</code></a>
fix: honor requestTls when proxy is SOCKS5</li>
<li><a
href="https://github.com/nodejs/undici/commit/fcd642ff613ea9030dec87cf622e68d4b1ae9847"><code>fcd642f</code></a>
fix(socks5): preserve dispatch backpressure return value (<a
href="https://redirect.github.com/nodejs/undici/issues/5166">#5166</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/bc98c97906abf26fa1e959b2f6111b53ade0e18f"><code>bc98c97</code></a>
fix(socks5): use configured connector in Socks5ProxyAgent (<a
href="https://redirect.github.com/nodejs/undici/issues/5168">#5168</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/9e1c74372a2b27cacd92d27c13a83a6d84f10e0e"><code>9e1c743</code></a>
fix(socks5): encode embedded IPv4 tails in IPv6 literals correctly (<a
href="https://redirect.github.com/nodejs/undici/issues/5099">#5099</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/376c8be27cb40cc17ccaad6b6ebb317fa7148d65"><code>376c8be</code></a>
fix(socks5): enforce authenticated state before CONNECT (<a
href="https://redirect.github.com/nodejs/undici/issues/5097">#5097</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/3805b8f8518882991044048c256e005dc3c10a85"><code>3805b8f</code></a>
fix(socks5-proxy-agent): use per-origin pools to prevent cross-origin
routing...</li>
<li><a
href="https://github.com/nodejs/undici/commit/85a240551c9feb8b8a0ecc56c84b2b3015add8a9"><code>85a2405</code></a>
fix(cache): trim qualified field names</li>
<li>Additional commits viewable in <a
href="https://github.com/nodejs/undici/compare/v7.25.0...v7.28.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=undici&package-manager=npm_and_yarn&previous-version=7.25.0&new-version=7.28.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-06-18 15:55:08 +00:00
Richard Smith 805dca1dc3 Use C++ formatting for C++ splits in testdata files. (#7385)
Refactor the textmate grammar to use a different scope for testdata
files. Move the existing handling for `CHECK:STDOUT:` there, and add
handling for C++ file splits there too.

Assisted-by: Gemini via Antigravity
2026-06-18 14:47:34 +00:00
dependabot[bot] c44ead3b14 Bump the npm_and_yarn group across 1 directory with 2 updates (#7382)
Bumps the npm_and_yarn group with 2 updates in the /utils/vscode
directory: [form-data](https://github.com/form-data/form-data) and
[js-yaml](https://github.com/nodeca/js-yaml).

Updates `form-data` from 4.0.5 to 4.0.6
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/form-data/form-data/blob/master/CHANGELOG.md">form-data's
changelog</a>.</em></p>
<blockquote>
<h2><a
href="https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6">v4.0.6</a>
- 2026-06-12</h2>
<h3>Commits</h3>
<ul>
<li>[Fix] escape CR, LF, and <code>&quot;</code> in field names and
filenames <a
href="https://github.com/form-data/form-data/commit/8dff42c6da654ed4e7ad4acb7f8ccd3831217c99"><code>8dff42c</code></a></li>
<li>[Dev Deps] update <code>@ljharb/eslint-config</code>,
<code>auto-changelog</code>, <code>tape</code> <a
href="https://github.com/form-data/form-data/commit/f31d21ef10bf46e46344c3ee4f99acbef6be43e1"><code>f31d21e</code></a></li>
<li>[Deps] update <code>hasown</code>, <code>mime-types</code> <a
href="https://github.com/form-data/form-data/commit/92ae0eb5da94d6f01925d5f4fcffb2a1e50ed7cd"><code>92ae0eb</code></a></li>
<li>[Dev Deps] update <code>js-randomness-predictor</code> <a
href="https://github.com/form-data/form-data/commit/67b0f65c2e0b065a511d42227d35e4d367644e97"><code>67b0f65</code></a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/form-data/form-data/commit/64190db548c0179e37206858e39f27cf513e9435"><code>64190db</code></a>
v4.0.6</li>
<li><a
href="https://github.com/form-data/form-data/commit/92ae0eb5da94d6f01925d5f4fcffb2a1e50ed7cd"><code>92ae0eb</code></a>
[Deps] update <code>hasown</code>, <code>mime-types</code></li>
<li><a
href="https://github.com/form-data/form-data/commit/f31d21ef10bf46e46344c3ee4f99acbef6be43e1"><code>f31d21e</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code>,
<code>auto-changelog</code>, <code>tape</code></li>
<li><a
href="https://github.com/form-data/form-data/commit/8dff42c6da654ed4e7ad4acb7f8ccd3831217c99"><code>8dff42c</code></a>
[Fix] escape CR, LF, and <code>&quot;</code> in field names and
filenames</li>
<li><a
href="https://github.com/form-data/form-data/commit/67b0f65c2e0b065a511d42227d35e4d367644e97"><code>67b0f65</code></a>
[Dev Deps] update <code>js-randomness-predictor</code></li>
<li>See full diff in <a
href="https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6">compare
view</a></li>
</ul>
</details>
<br />

Updates `js-yaml` from 4.1.1 to 4.2.0
<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.2.0] - 2026-06-01</h2>
<h3>Added</h3>
<ul>
<li>Added <code>docs/safety.md</code> with notes about processing
untrusted YAML.</li>
<li>Added <code>maxDepth</code> (100) loader option. Not a problem, but
gives a better
exception instead of RangeError on stack overflow.</li>
<li>Added <code>maxMergeSeqLength</code> (20) loader option. Not a
problem after <code>merge</code> fix,
but an additional restriction for safety.</li>
<li>Added sourcemaps to <code>dist/</code> builds.</li>
</ul>
<h3>Changed</h3>
<ul>
<li>Stop resolving numbers with underscores as numeric scalars, <a
href="https://redirect.github.com/nodeca/js-yaml/issues/627">#627</a>.</li>
<li>Switched dev toolchains to Vite / neostandard.</li>
<li>Updated demo.</li>
<li>Reorganized tests.</li>
<li><code>dist/</code> files are no longer kept in the repository.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Fix parsing of properties on the first implicit block mapping key,
<a
href="https://redirect.github.com/nodeca/js-yaml/issues/62">#62</a>.</li>
<li>Fix trailing whitespace handling when folding flow scalar lines, <a
href="https://redirect.github.com/nodeca/js-yaml/issues/307">#307</a>.</li>
<li>Reject top-level block scalars without content indentation, <a
href="https://redirect.github.com/nodeca/js-yaml/issues/280">#280</a>.</li>
<li>Ensure numbers survive round-trip, <a
href="https://redirect.github.com/nodeca/js-yaml/issues/737">#737</a>.</li>
<li>Fix test coverage for issue <a
href="https://redirect.github.com/nodeca/js-yaml/issues/221">#221</a>.</li>
<li>Fix flow scalar trailing whitespace folding, <a
href="https://redirect.github.com/nodeca/js-yaml/issues/307">#307</a>.</li>
<li>Fix digits in YAML named tag handles.</li>
</ul>
<h3>Security</h3>
<ul>
<li>Fix potential DoS via quadratic complexity in merge - deduplicate
repeated
elements (makes sense for malformed files &gt; 10K).</li>
</ul>
<h2>[3.14.2] - 2025-11-15</h2>
<h3>Security</h3>
<ul>
<li>Backported v4.1.1 fix to v3</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/nodeca/js-yaml/commits">compare view</a></li>
</ul>
</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 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-06-18 12:45:30 +00:00
Richard Smith 4fcf818b58 Fix handling of backticks in proposal names. (#7383)
Use slugify, as it properly handles all proposal names. This also makes
our branch name consistent with the file name of the proposal.
2026-06-17 23:17:11 +00:00
dependabot[bot] fe58c5e46b Bump markdown-it from 14.1.1 to 14.2.0 in /utils/vscode in the npm_and_yarn group across 1 directory (#7380)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [markdown-it](https://github.com/markdown-it/markdown-it).

Updates `markdown-it` from 14.1.1 to 14.2.0
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/markdown-it/markdown-it/blob/master/CHANGELOG.md">markdown-it's
changelog</a>.</em></p>
<blockquote>
<h2>[14.2.0] - 2026-05-24</h2>
<h3>Added</h3>
<ul>
<li><code>isPunctCharCode</code> to utilities.</li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Don't end HTML comment blocks on a blank line, <a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1155">#1155</a>.</li>
<li>Properly recognize astral chars (surrogates) in delimiter scans for
emphasis-like markers, <a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1072">#1072</a>.
Big thanks to <a
href="https://github.com/tats-u"><code>@​tats-u</code></a> for his
global efforts
with improving CJK support.</li>
<li>Preserve unicode whitespaces when trimm headings/paragraphs, <a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1074">#1074</a>.</li>
<li>More strict entities decode to avoid false positives <code>;</code>,
<a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1096">#1096</a>.</li>
<li>Restore block parser state on fail in <code>lheading</code> rule, <a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1131">#1131</a>.</li>
</ul>
<h3>Security</h3>
<ul>
<li>Fixed poor smartquotes perfomance on &gt; 70k quotes in single
block</li>
<li>Bumped linkify-it to 5.0.1 with fixed potential perfomance
issues.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/829797aa00353ce0b62ddeb9b4583b837b1ffd9b"><code>829797a</code></a>
14.2.0 released</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/9ce2087562c45d1e5ddd9f76b990f4b3fbe040e5"><code>9ce2087</code></a>
Fix smartquotes perfomance</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/02e73b88fdbaddf7ecee7e567a3da62b98e57a4d"><code>02e73b8</code></a>
linkify-it bump</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/68cfb8c0792ba87992d21ffb4d22ee6cf635afb7"><code>68cfb8c</code></a>
fix: don't end HTML comment blocks on a blank line (<a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1155">#1155</a>)</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/108313756cfffba31166df0140e27dd58e4da115"><code>1083137</code></a>
Readme cleanup</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/97c7ca2571f4255ff1d0f465958dda5293d20fe8"><code>97c7ca2</code></a>
Update funding info</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/c471b55c10501aba7b62817df613adc5f451da43"><code>c471b55</code></a>
Changelog update</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/77696210d1c7c56e4ffd49ff28ba15b460cb01e4"><code>7769621</code></a>
isPunctChar =&gt; isPunctCharCode</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/aa2aa70b3001ed6aea67c22f1ff52e1ca158d2e1"><code>aa2aa70</code></a>
fix: always reset parentType in lheading rule (<a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1131">#1131</a>)</li>
<li><a
href="https://github.com/markdown-it/markdown-it/commit/59955f2ad35cbb0e3f41ad779c7363a94b4bf38e"><code>59955f2</code></a>
Polish PRs <a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1072">#1072</a>,
<a
href="https://redirect.github.com/markdown-it/markdown-it/issues/1074">#1074</a></li>
<li>Additional commits viewable in <a
href="https://github.com/markdown-it/markdown-it/compare/14.1.1...14.2.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=markdown-it&package-manager=npm_and_yarn&previous-version=14.1.1&new-version=14.2.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-06-17 21:53:14 +00:00
Nicholas Bishop c684183ed8 Allow accessing abstract class fields (#7379)
In `Convert`, allow forming a value or reference of abstract class type,
but not an initializer.

For now, limit the scope to just `ClassElementAccess` to avoid affecting
tests where I'm unclear if allowing abstract types is correct.
2026-06-17 20:41:08 +00:00
Christopher Di Bella f55ffe5914 Add Iterate to the list of non-Clang operators (#7369)
This allows us to use non-generic C++ range types in Carbon range-for
loops.
2026-06-17 19:13:33 +00:00
Dana Jansens 0f14882dd1 Remove fail_todo_class_with_qualified_rewrite test (#7377)
This test was assuming that we'd allow qualified lookup in rewrite
constraints, but that is not in agreement with the design. The design
says that the LHS of a rewrite must be a member access designator like
`.Member`.
2026-06-17 16:31:26 +00:00
josh11bandJosh L a7f8df0383 Update svg code snippets to reflect changes from #7354 (#7370)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-06-17 15:13:23 +00:00
Richard Smith c1080b25ae Sync utils/textmate directory to carbon.tmbundle repository. (#7374)
Provide a cut-down repository containing just our textmate bundle, both
for easy installation in general and so that github's linguist in
particular can pick it up and use it for highlighting Carbon files.

The sync_repos script is automatically run by our github workflow
whenever utils/ changes.
2026-06-17 14:00:39 +00:00
Richard Smith 5fc8e1cf3e Textmate grammar: avoid variable-width lookbehind. (#7373)
This is not supported by the textmate parser in github's linguist.

Assisted-by: Gemini via Antigravity
2026-06-17 05:43:44 +00:00
Richard Smith 1106d967df Add support for enum comparisons and bitwise operators (#7356)
If C++ overload resolution selects a builtin operator candidate for an
enum comparison or bitwise operator, provide support for that operator
by generating a corresponding Carbon builtin function. This is
structured to be easily extensible to other C++ builtin overload
candidates if we so choose, but for now the operators defined in the
prelude are doing what we want in most cases.

Bitwise operators on enums produce the same enum type as a result. This
intentionally deviates from C++, where they produce a promoted integral
type.

Assisted-by: Gemini via Antigravity
2026-06-16 19:51:11 +00:00
Richard Smith 30b6c22444 Remove comment missed by #7013. (#7365)
This comment reflects a special case that no longer exists.
2026-06-16 16:29:21 +00:00
Dana Jansens d68b3fa912 Don't crash when converting a tuple to type if it contains an ErrorInst (#7352)
The conversion will just produce an ErrorInst output.

Right now I am not sure how to get an ErrorInst into that position, but
with https://github.com/carbon-language/carbon-lang/pull/7364 rejecting
`.Self` we end up with this, and it crashes otherwise.
2026-06-16 13:51:38 +00:00
David Blaikie cf6a89db3f Init vptrs in Carbon initialization of Carbon-derived-from-C++ objects (#7323)
For review convenience, the Clang patch is available as an LLVM Draft PR
here: https://github.com/llvm/llvm-project/pull/202807
2026-06-16 04:50:57 +00:00
David Blaikie 88b3605eac Fix #7289: Add debug info module flags as-needed and verify if already present (#7336)
This avoids duplicate module flags when compiling C++ interop with debug
info.

Assisted-by: Gemini via Antigravity
2026-06-16 03:18:05 +00:00
Geoff Romer d13495771a Recover from an empty Label field in debug printing (#7363)
Closes #7361
2026-06-15 22:23:18 +00:00
josh11bandJosh L 988c47631e Update design docs to reflect #6177: C++ Interop: Mapping std::string_view to Core.Str (#7349)
Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-06-15 22:19:45 +00:00
Nicholas Bishop f2c94517cc Reland "Fix crash from accessing a Check::Context during lowering (#7335)" (#7359)
In generate_ast.cpp, an `CarbonExternalASTSource` is installed that has
a `Check::Context` pointer. During lowering, this `ExternalASTSource` is
still installed, and using it can cause a crash if the now-invalid
pointer is dereferenced.

Fix by adding a new `ReadOnlyASTSource` in sem_ir, and using that during
lowering.

`CarbonExternalASTSource` now inherits from `ReadOnlyASTSource` to avoid
some code duplication.

In generate_ast.cpp, we now always install a multiplex source, even if
there's only one child source. Clang internally keeps pointers to the
top-level `ExternalASTSource` installed via `setExternalSource`, and
those pointers aren't updated if `setExternalSource` is called again. By
using `MultiplexExternalSemaSource`, we can keep the top-level
`ExternalASTSource` pointer the same, and only update its children.

Using `MultiplexExternalSemaSource` this way requires a new constructor
and a method to modify its child sources; added a new LLVM patch adding
those.

Originally landed in #7335, reverted in #7353 due to ASAN errors.
Changes since original:
* Use LLVM RTTI to make `Lower::Context::Finalize` less brittle.
Add LLVM RTTI to `ReadOnlyASTSource` (and `CarbonExternalASTSource`).
Change Finalize so that instead of just deleting the last multiplex
child source, it erases any multiplex child sources that match
`ReadOnlyASTSource`; this includes `CarbonExternalASTSource` since it's
a subclass.
* Fix ASAN error by updating the `MultiplexExternalSemaSource` earlier
in lowering. It is sometimes accessed during PrepareToLower, so update
it in `Context::GetFileContext` rather than `Context::Finalize`.

Fixes https://github.com/carbon-language/carbon-lang/issues/7142
2026-06-15 20:30:07 +00:00
Dana Jansens c3b6b084d4 Find correct nested rewrite constraints (#7280)
When a facet type contains a rewrite constraint like `.(J.J1).(I.I1)`
the ImplWitnessAccess should only use its RHS value if it's trying to
find `.(J.J1).(I.I1)`. It can't just look at the `.(I.I1)` part or it
may grab the RHS for a similar `.(K.K2).(I.I1)` rewrite.

While it's not possible to write a nested access on the LHS of a rewrite
constraint like `.(J.J1).(I.I1)`, it is possible to construct a facet
type that ends up with that as its rewrite using nested facet types:
```carbon
T:! J where .J1 impls (I where .I1 = ())
```

The access `T.(J.J1).(I.I1)` should evaluate to `()`. The
ImplWitnessAccess evaluation starts by looking for a rewrite of
`.(I.I1)` in the type of the access self, which is `T.(J.J1)`. Then it
looks for `.(I.I1)` in the type of that access self, which is `T`. At
that point it finds the rewrite of `.(J.J1).(I.I1) = ()` and can use the
`()`. However it can also find other rewrites that end in `.(I.I1)`.

To do this correctly, when moving through an ImplWitnessAccess to the
next nested access self, we record the access (interface, element) pair
that we are looking through. And then we require the rewrite constraint
to be prefixed by all of the (interface, element) pairs that we have
recorded.
2026-06-15 18:12:44 +00:00
ed51ba4b1a Update design docs to reflect proposal #4682: The Core.Array type... (#7354)
Also:

- Introduce `buf` so that existing examples using arrays can be updated
to use it.
- Update the examples linked to on the Carbon front page to something
closer to what we expect, moving away from old array syntax. Uses
`slice` though that name hasn't been settled. Updating the SVGs actually
referenced will need to be done as a separate step.
- Update links to the expression operators while I'm touching that
section.

Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Nicholas Bishop <nbishop@nbishop.net>
2026-06-15 17:36:06 +00:00
Dana Jansens 3a7b49efaa Add some more test coverage of designators (#7347)
- A test showing we need to search facets in the specific interface of
an access to find a witness
- A test using a `<type> impls ...` constraint from earlier in the same
facet type
- Some tests to show a rewrite constraint from earlier in the same facet
type is not incorrectly used when it's applied to a different facet
- A test of a facet type with a rewrite as the RHS of another rewrite,
and the rewrite there should not leak or access things from the outer
facet type
2026-06-15 14:27:32 +00:00
dependabot[bot] fbf0157998 Bump esbuild from 0.25.12 to 0.28.1 in /utils/vscode in the npm_and_yarn group across 1 directory (#7358)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [esbuild](https://github.com/evanw/esbuild).

Updates `esbuild` from 0.25.12 to 0.28.1
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/evanw/esbuild/releases">esbuild's
releases</a>.</em></p>
<blockquote>
<h2>v0.28.1</h2>
<ul>
<li>
<p>Disallow <code>\</code> in local development server HTTP requests (<a
href="https://github.com/evanw/esbuild/security/advisories/GHSA-g7r4-m6w7-qqqr">GHSA-g7r4-m6w7-qqqr</a>)</p>
<p>This release fixes a security issue where HTTP requests to esbuild's
local development server could traverse outside of the serve directory
on Windows using a <code>\</code> backslash character. It happened due
to the use of Go's <code>path.Clean()</code> function, which only
handles Unix-style <code>/</code> characters. HTTP requests with paths
containing <code>\</code> are no longer allowed.</p>
<p>Thanks to <a
href="https://github.com/dellalibera"><code>@​dellalibera</code></a> for
reporting this issue.</p>
</li>
<li>
<p>Add integrity checks to the Deno API (<a
href="https://github.com/evanw/esbuild/security/advisories/GHSA-gv7w-rqvm-qjhr">GHSA-gv7w-rqvm-qjhr</a>)</p>
<p>The previous release of esbuild added integrity checks to esbuild's
npm install script. This release also adds integrity checks to esbuild's
Deno install script. Now esbuild's Deno API will also fail with an error
if the downloaded esbuild binary contains something other than the
expected content.</p>
<p>Note that esbuild's Deno API installs from
<code>registry.npmjs.org</code> by default, but allows the
<code>NPM_CONFIG_REGISTRY</code> environment variable to override this
with a custom package registry. This change means that the esbuild
executable served by <code>NPM_CONFIG_REGISTRY</code> must now match the
expected content.</p>
<p>Thanks to <a
href="https://github.com/sondt99"><code>@​sondt99</code></a> for
reporting this issue.</p>
</li>
<li>
<p>Avoid inlining <code>using</code> and <code>await using</code>
declarations (<a
href="https://redirect.github.com/evanw/esbuild/issues/4482">#4482</a>)</p>
<p>Previously esbuild's minifier sometimes incorrectly inlined
<code>using</code> and <code>await using</code> declarations into
subsequent uses of that declaration, which then fails to dispose of the
resource correctly. This bug happened because inlining was done for
<code>let</code> and <code>const</code> declarations by avoiding doing
it for <code>var</code> declarations, which no longer worked when more
declaration types were added. Here's an example:</p>
<pre lang="js"><code>// Original code
{
  using x = new Resource()
  x.activate()
}
<p>// Old output (with --minify)<br />
new Resource().activate();</p>
<p>// New output (with --minify)<br />
{using e=new Resource;e.activate()}<br />
</code></pre></p>
</li>
<li>
<p>Fix module evaluation when an error is thrown (<a
href="https://redirect.github.com/evanw/esbuild/issues/4461">#4461</a>,
<a
href="https://redirect.github.com/evanw/esbuild/pull/4467">#4467</a>)</p>
<p>If an error is thrown during module evaluation, esbuild previously
didn't preserve the state of the module for subsequent module
references. This was observable if <code>import()</code> or
<code>require()</code> is used to import a module multiple times. The
thrown error is supposed to be thrown by every call to
<code>import()</code> or <code>require()</code>, not just the first.
With this release, esbuild will now throw the same error every time you
call <code>import()</code> or <code>require()</code> on a module that
throws during its evaluation.</p>
</li>
<li>
<p>Fix some edge cases around the <code>new</code> operator (<a
href="https://redirect.github.com/evanw/esbuild/issues/4477">#4477</a>)</p>
<p>Previously esbuild incorrectly printed certain edge cases involving
complex expressions inside the target of a <code>new</code> expression
(specifically an optional chain and/or a tagged template literal). The
generated code for the <code>new</code> target was not correctly wrapped
with parentheses, and either contained a syntax error or had different
semantics. These edge cases have been fixed so that they now correctly
wrap the <code>new</code> target in parentheses. Here is an example of
some affected code:</p>
<pre lang="js"><code>// Original code
new (foo()`bar`)()
new (foo()?.bar)()
<p>// Old output<br />
new foo()<code>bar</code>();<br />
new (foo())?.bar();</p>
<p></code></pre></p>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/evanw/esbuild/blob/main/CHANGELOG-2025.md">esbuild's
changelog</a>.</em></p>
<blockquote>
<h1>Changelog: 2025</h1>
<p>This changelog documents all esbuild versions published in the year
2025 (versions 0.25.0 through 0.27.2).</p>
<h2>0.27.2</h2>
<ul>
<li>
<p>Allow import path specifiers starting with <code>#/</code> (<a
href="https://redirect.github.com/evanw/esbuild/pull/4361">#4361</a>)</p>
<p>Previously the specification for <code>package.json</code> disallowed
import path specifiers starting with <code>#/</code>, but this
restriction <a
href="https://redirect.github.com/nodejs/node/pull/60864">has recently
been relaxed</a> and support for it is being added across the JavaScript
ecosystem. One use case is using it for a wildcard pattern such as
mapping <code>#/*</code> to <code>./src/*</code> (previously you had to
use another character such as <code>#_*</code> instead, which was more
confusing). There is some more context in <a
href="https://redirect.github.com/nodejs/node/issues/49182">nodejs/node#49182</a>.</p>
<p>This change was contributed by <a
href="https://github.com/hybrist"><code>@​hybrist</code></a>.</p>
</li>
<li>
<p>Automatically add the <code>-webkit-mask</code> prefix (<a
href="https://redirect.github.com/evanw/esbuild/issues/4357">#4357</a>,
<a
href="https://redirect.github.com/evanw/esbuild/issues/4358">#4358</a>)</p>
<p>This release automatically adds the <code>-webkit-</code> vendor
prefix for the <a
href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/mask"><code>mask</code></a>
CSS shorthand property:</p>
<pre lang="css"><code>/* Original code */
main {
  mask: url(x.png) center/5rem no-repeat
}
<p>/* Old output (with --target=chrome110) */<br />
main {<br />
mask: url(x.png) center/5rem no-repeat;<br />
}</p>
<p>/* New output (with --target=chrome110) */<br />
main {<br />
-webkit-mask: url(x.png) center/5rem no-repeat;<br />
mask: url(x.png) center/5rem no-repeat;<br />
}<br />
</code></pre></p>
<p>This change was contributed by <a
href="https://github.com/BPJEnnova"><code>@​BPJEnnova</code></a>.</p>
</li>
<li>
<p>Additional minification of <code>switch</code> statements (<a
href="https://redirect.github.com/evanw/esbuild/issues/4176">#4176</a>,
<a
href="https://redirect.github.com/evanw/esbuild/issues/4359">#4359</a>)</p>
<p>This release contains additional minification patterns for reducing
<code>switch</code> statements. Here is an example:</p>
<pre lang="js"><code>// Original code
switch (x) {
  case 0:
    foo()
    break
  case 1:
  default:
    bar()
}
</code></pre>
</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/evanw/esbuild/commit/bb9db84c02433fbe37b3509f53f9f3e3cc48725e"><code>bb9db84</code></a>
publish 0.28.1 to npm</li>
<li><a
href="https://github.com/evanw/esbuild/commit/9ff053e53b8eeb990f59355dbea365277ac45ee2"><code>9ff053e</code></a>
security: add integrity checks to the Deno API</li>
<li><a
href="https://github.com/evanw/esbuild/commit/0a9bf2135b67c7e28989a5ba19f0f000805a5ab5"><code>0a9bf21</code></a>
enforce non-negative size in gzip parser</li>
<li><a
href="https://github.com/evanw/esbuild/commit/e2a1a7132058ee067fe736eac15f695861b8654e"><code>e2a1a71</code></a>
security: forbid <code>\\</code> in local dev server requests</li>
<li><a
href="https://github.com/evanw/esbuild/commit/83a2cbfc35809f4fd5152da59572d7bed7739d78"><code>83a2cbf</code></a>
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/4482">#4482</a>:
don't inline <code>using</code> declarations</li>
<li><a
href="https://github.com/evanw/esbuild/commit/308ad745d824c77bc607603451b257d0f2fd9a38"><code>308ad74</code></a>
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/4471">#4471</a>:
renaming of nested <code>var</code> declarations</li>
<li><a
href="https://github.com/evanw/esbuild/commit/f013f5f99a015bce92ec48d49181d4ad3177b29b"><code>f013f5f</code></a>
fix some typos</li>
<li><a
href="https://github.com/evanw/esbuild/commit/aafd6e48b1088336a5f5a17e930be7e840d43d8c"><code>aafd6e4</code></a>
chore: fix some minor issues in comments (<a
href="https://redirect.github.com/evanw/esbuild/issues/4462">#4462</a>)</li>
<li><a
href="https://github.com/evanw/esbuild/commit/15300c30b5e22f7cfcbed850c246d35095658386"><code>15300c3</code></a>
follow up: cjs evaluation fixes</li>
<li><a
href="https://github.com/evanw/esbuild/commit/1bda0c31d7697c0af44b3ab39b81e599e559a395"><code>1bda0c3</code></a>
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/4461">#4461</a>,
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/4467">#4467</a>:
esm evaluation fixes</li>
<li>Additional commits viewable in <a
href="https://github.com/evanw/esbuild/compare/v0.25.12...v0.28.1">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/~GitHub%20Actions">GitHub Actions</a>, a new
releaser for esbuild since your current version.</p>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=esbuild&package-manager=npm_and_yarn&previous-version=0.25.12&new-version=0.28.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 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-06-14 22:43:32 +00:00
Geoff RomerandRichard Smith e023f75254 Implement thunking in terms of constant evaluation (#7332)
The bulk of this change is changing most pattern insts to be `Always`
rather than `AlwaysUnique` constants, so that they can be wrapped in
`SpecificConstant`s to perform substitution. That then lets thunking
rely much more on `SpecificConstant` wrappers instead of deep-copying
the inst tree with modified types.

This approach to thunking should scale better, particularly as things
like form generics make function signatures more complex, because we can
leverage the existing support for constant evaluation and substitution.
Unfortunately, applying this approach to binding patterns will require
more work; see the TODO near the top of `thunk.cpp` for details.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-06-13 00:22:00 +00:00
Nicholas Bishop 40d2d8f68c Revert "Fix crash from accessing a Check::Context during lowering (#7335)" (#7353)
This reverts commit afd679129d.

The commit introduced ASAN errors:

https://github.com/carbon-language/carbon-lang/actions/runs/27436787960/job/81100665405
2026-06-12 23:04:50 +00:00
mstr-six 250da35c3b Recover when converting to an invalid integer type (#7342)
Converting an integer value to a destination type that is not a valid
integer type -- such as `i8388609` or `i16777216`, whose bit widths are
diagnosed as invalid -- hit a CHECK failure in
`TypeStore::GetIntTypeInfo` during constant evaluation of `int.convert`
/ `int.convert_checked`:

```
CHECK failure at toolchain/sem_ir/type.cpp:189: int_info: Type type(...) is not an integer type
```

The width error is already diagnosed when forming the type
(`IntWidthNotMultipleOf8` / `IntWidthTooLarge`), so `PerformIntConvert`
and `PerformCheckedIntConvert` now use `TryGetIntTypeInfo` and produce
an error value instead of crashing, following the existing
`SemIR::ErrorInst::ConstantId` convention in `eval.cpp`.

Added a file test covering all three reproducers from the issue
(`i8388609`, `i16777216`, `Core.Int(8388609)`); it crashes without this
change. The full `//toolchain/testing:file_test` suite (1578 tests)
passes.

Fixes #7278.

I have reviewed this change and take responsibility for it.

Assisted-by: Claude
2026-06-12 21:19:57 +00:00
Nicholas Bishop afd679129d Fix crash from accessing a Check::Context during lowering (#7335)
In generate_ast.cpp, an `CarbonExternalASTSource` is installed that has
a `Check::Context` pointer. During lowering, this `ExternalASTSource` is
still installed, and using it can cause a crash if the now-invalid
pointer is dereferenced.

Fix by adding a new `ReadOnlyASTSource` in sem_ir, and using that during
lowering.

`CarbonExternalASTSource` now inherits from `ReadOnlyASTSource` to avoid
some code duplication.

In generate_ast.cpp, we now always install a multiplex source, even if
there's only one child source. Clang internally keeps pointers to the
top-level `ExternalASTSource` installed via `setExternalSource`, and
those pointers aren't updated if `setExternalSource` is called again. By
using `MultiplexExternalSemaSource`, we can keep the top-level
`ExternalASTSource` pointer the same, and only update its children.

Using `MultiplexExternalSemaSource` this way requires a new constructor
and a method to modify its child sources; added a new LLVM patch adding
those.

https://github.com/carbon-language/carbon-lang/issues/7142
2026-06-12 18:05:19 +00:00
mstr-six f3b8e231ca Recover base declarations missing a colon (#7341)
Malformed `base` declarations with an omitted colon need two different
recovery paths. For `extend base`, the consumed `extend` modifier
requires the parse tree to retain its `BaseColon` and base expression
children, so this synthesizes an errored `BaseColon` and continues
parsing the expression.

Other malformed forms, such as `base calss X {}`, now use the standard
declaration-error recovery: emit `ExpectedAfterBase`, skip past the
likely declaration end, and form an errored `BaseDecl` without inventing
a colon or cascading diagnostics.

The regression covers `extend base Foo;`, bare `base;`, and the reviewer
counterexample `base calss X {}`.

Tests:
- `prek run --files toolchain/parse/handle_base.cpp
toolchain/parse/testdata/class/fail_base.carbon`
- `./scripts/run_bazelisk.py test -c dbg //toolchain/parse/...`
- `./scripts/run_bazelisk.py test -c dbg //toolchain/testing:file_test`

AI assistance: OpenAI Codex helped inspect the parser recovery path,
implement the change, and run verification. The operator reviewed and
authorized the contribution.

Assisted-by: OpenAI Codex
2026-06-11 22:33:29 +00:00
Christopher Di Bella 103fa5dadf Remove LICENSE from exported files (#7344) 2026-06-11 22:09:42 +00:00
Richard Smith c3fc59b8b9 Don't form a bound method when calling a C++ operator. (#7345)
Because we now support calling a function with a `self` parameter
directly, we can unconditionally call `operator$(lhs, rhs)` rather than
calling `lhs.operator$(rhs)` if the selected operator function happens
to be a member function.

This makes the logic a bit simpler and the SemIR a bit smaller.

We can't do the same for Carbon operators, unfortunately, as we use the
member access to trigger impl lookup.
2026-06-11 21:49:20 +00:00
Christopher Di Bella e83422b375 Declare package licence type (#7343) 2026-06-11 20:28:37 +00:00
Richard Smith 6fe9db297d Fix crash after anonymous generic binding deduction failure (#7330)
A binding can have a constant value that is an `ErrorInst` during error
recovery. In that case, deduction would crash when attempting to
diagnose that the binding had no deduced value.
2026-06-11 19:20:22 +00:00
Chandler CarruthandGeoff Romer f7e628562f Shrink debug info emitted for CARBON_CHECK message formatting (#7339)
This is based on an idea suggested during review of the original type
erasure PR.

The type-erased check failure path lowers each check through
`CheckFailFormat<Ts...>`, which builds one format adapter per value,
down to the out-of-line `CheckFailImpl`, which takes an array of
base-class `format_adapter*` pointers. Previously a separate variadic
`CheckFailWithAdapters<Adapters...>` template sat in between: it existed
only to bind the adapter temporaries to named parameters so that
pointers to their base class could be collected into a `std::array` and
outlive the call to `CheckFailImpl`.

This removes that layer. `CheckFailFormat` now builds the pointer array
directly, in the braced-init-list of the `CheckFailImpl` call, using a
small `CheckFailFormatAdapterAddr<T>` helper to take the base-class
address of each adapter. The adapter temporaries are materialized as
named parameters of that helper within the same full-expression as the
`CheckFailImpl` call, so they remain alive across the call without a
dedicated function for that purpose.

The win is in debug info, not code. `CheckFailWithAdapters<Adapters...>`
was instantiated once per distinct adapter-type sequence in every
translation unit that uses `CARBON_CHECK`, and each instantiation
carried its own DWARF records -- type entries, string-table offsets, and
range lists. Dropping it removes those records from every such
translation unit. The generated machine code is unchanged.

Measured impact (fastbuild, the inputs to the inner-loop links):

- First-party object files shrink by 173,728 bytes (-0.233%) across the
`carbon-busybox` link inputs; 232 of 270 objects get smaller and none
grow. The largest reductions are in the check-densest translation units
(`type_completion`, `type`, `import_ref`, `function_context`,
`constant`, ...).
- Per `bloaty`, the reduction is almost entirely DWARF (`.debug_info`,
`.debug_str`, `.rela.debug_str_offsets`, `.debug_rnglists`); the loaded
code (VM size) is unchanged.

Assisted-by: Claude Code

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2026-06-11 17:53:31 +00:00
Richard Smith 77790e44a6 Refactor and extend tool usage skills (#7338)
Split out the `prek` tool usage instructions into a separate skill. This
should make the agent more likely to realize the skill is relevant to a
particular task and consult it. Extend the skill to include instructions
for using `prek` in a jj workspace, and add a helper script for that
situation.

Add a `jj` skill, with the main purpose being to instruct the agent to
use `jj` not `git`, and to use `--no-pager` when running it.

Extend the `bazel` tool description slightly to more strongly encourage
agents to read and follow it.

Assisted-by: Gemini via Antigravity
2026-06-11 17:18:16 +00:00
Richard Smith 25e72882fc Implement Core.CharLiteral operations from #6710 and #7314 (#7316)
Adds support for arithmetic and comparison operators on
`Core.CharLiteral`s, as well as conversions between `CharLiteral` and
integer types.

Make some minor tweaks to fix skill issues encountered while making this
change.

Assisted-by: Gemini via Antigravity
2026-06-11 16:45:39 +00:00
Christopher Di Bella a914dba888 Add utils/vscode/BUILD (#7337)
This helps with some VSCode derivatives' extension management.
2026-06-10 23:04:09 +00:00
Geoff Romer b04634a0cd Implement a custom LLDB formatter for Carbon IDs (#7333)
This removes the inheritance noise, and adds label prefixes for
consistency with the raw textual format.

Before:
```
> p function_info.first_owning_decl_id
(Carbon::SemIR::InstId) {
  Carbon::IdBase<Carbon::SemIR::InstId> = {
    Carbon::AnyIdBase = (index = 0x50000023)
  }
}

> p function_info.call_param_ranges.implicit_end_
(Carbon::SemIR::CallParamIndex) {
  Carbon::IndexBase<Carbon::SemIR::CallParamIndex> = {
    Carbon::IdBase<Carbon::SemIR::CallParamIndex> = {
      Carbon::AnyIdBase = (index = 0x00000001)
    }
  }
}
```

After:
```
> p function_info.first_owning_decl_id
(Carbon::SemIR::InstId) inst50000023

> p function_info.call_param_ranges.implicit_end_
(Carbon::SemIR::CallParamIndex) call_param1
```

The benefit compounds when printing aggregates (which often lack `Dump`
support or omit information from it). For example, this change reduces
`p function_info` from 129 lines to just 31 (including reducing the
`call_param_ranges` field from 32 lines to just 1):

```
> p function_info
(Carbon::SemIR::Function) {
  Carbon::SemIR::EntityWithParamsBase = {
    name_id = name1
    parent_scope_id = name_scope50000002
    generic_id = generic<none>
    first_param_node_id = nodeB
    last_param_node_id = node12
    pattern_block_id = inst_block5000000E
    implicit_param_patterns_id = inst_block5000000A
    param_patterns_id = inst_block0
    is_extern = false
    extern_library_id = library_name<none>
    non_owning_decl_id = inst<none>
    first_owning_decl_id = inst50000023
    definition_id = inst<none>
  }
  Carbon::SemIR::FunctionFields = {
    call_param_patterns_id = inst_block5000000C
    call_params_id = inst_block5000000D
    call_param_ranges = (implicit_end_ = call_param1, explicit_end_ = call_param1, return_end_ = call_param1)
    return_type_inst_id = inst<none>
    return_form_inst_id = inst<none>
    return_pattern_id = inst<none>
    special_function_kind = None
    virtual_modifier = None
    virtual_index = 0xffffffff
    evaluation_mode = None
    self_param_id = inst50000020
    special_function_kind_data = any_raw<none>
    body_block_ids = size=0 {}
  }
}
```
2026-06-10 18:19:07 +00:00
Chandler Carruthandjosh11b 7871237c15 Move self to the explicit () parameter list (proposal #7016) (#7272)
Implements proposal #7016: `self` moves from the deduced implicit list
(`fn F[self: Self]()`) to the front of the explicit list. Its type may
be written explicitly (`fn F(self: Self)`) or omitted, in which case it
defaults to `Self` (`fn F(self)`, `fn F(ref self)`); `self` in the
implicit list is rejected.

Throughout checking, `self` is modeled as the first explicit parameter.
Because a method is just a function whose first parameter is `self`, it
can also be called as an ordinary function with the receiver passed
explicitly (`Type.M(obj, ...)`), not only as `obj.M(...)`. A new
`SemIR::CallArgParamPatterns` helper chooses the parameters matched
against the explicit arguments, excluding a leading `self` only when it
is supplied as a method-call receiver; arity checking, conversion, and
generic deduction use it. The resulting SemIR and lowering are
unchanged: `self` is still `call_param0`, and witnesses, thunks, and
vtables are unaffected.

An omitted `self` type is parsed as a `SelfBindingPattern` node with no
type expression; checking synthesizes the `Self` type so it behaves
exactly like `self: Self`. However, the exact spelling used must match
between a forward declaration and a definition, following #3763's rules
around declaration matching.

Generated functions, thunks, and C++ interop import/export build `self`
as the first explicit parameter, and the `self`-type override (e.g.
Derived->Base for a virtual override) applies to the explicit `self`.
Placement is validated by new diagnostics: `SelfInImplicitParamList`,
`SelfNotFirstParam`, and `SelfOutsideParamList`. The benchmark source
generator and the documentation adopt the `(self)` shorthand; the
prelude, the examples, and the test data are migrated in the following
commits.

Assisted-by: Claude Code with Claude Opus 4.7

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2026-06-10 15:30:43 +00:00
Richard Smith fb05da761f Fix formation of invalid value_of_initializer instructions. (#7329)
This is only valid when the operand is an initializing expression that
holds a copy of the value, but we were incorrectly also forming it when
the operand was an in-place initializing expression.

Fixes a crash in lowering when attempting to lower an invalid
`value_of_initializer`.
2026-06-10 15:28:56 +00:00
Chandler Carruth 41e3c9bd82 Type-erase CARBON_CHECK message formatting. (#7325)
`CARBON_CHECK` and `CARBON_FATAL` messages are formatted with
`llvm::formatv`. Previously each check site that had a message
instantiated its own copy of the formatv machinery -- a `formatv_object`
over a tuple of per-argument format adapters, plus that tuple -- in
every translation unit, keyed on the site's file, line, condition, and
format strings. A translation unit with many checks paid for that
machinery over and over.

This restructures check failure so that the formatting machinery is
compiled exactly once, and only a single small adapter is instantiated
per distinct value type per translation unit:

- `CheckFailImpl` (out-of-line) now takes the message's format string
and an array of already-type-erased `format_adapter`s, and renders the
whole failure message -- prefix plus the extra message -- directly into
one stream. The extra message is rendered in place, so no separate
string is ever materialized for it.

- `FormatvInto` (in the `.cpp`) renders a format string over that
adapter array. Rather than instantiate `llvm::formatv`, it drives the
formatv replacement loop over the public
`formatv_object_base::parseFormatString`, so this rendering code exists
exactly once. (A TODO notes that we should add a type-erased entry point
upstream in LLVM rather than reimplement the loop here.)

- The lowering from the macro down to that out-of-line call is split so
that the only per-check-site instantiation is trivial:
- `CheckFail<...>` is instantiated once per site, since its file, line,
condition, and format template-string parameters are unique to the site.
It just lowers those compile-time strings to ordinary arguments and
forwards to `CheckFailFormat`.
- `CheckFailFormat<Ts...>` is instantiated once per distinct value-type
sequence and shared across sites; it builds one type-erased adapter per
value.
- `CheckFailWithAdapters<Adapters...>` collects pointers to those
adapters into an array and calls `CheckFailImpl`. It is a distinct
function so the adapter temporaries stay alive while pointers to their
base class are in flight.

Format semantics, including runtime format-string validation, are
unchanged, and the rendered message is byte-for-byte identical.

For `DCHECK` in optimized builds the check is dead code; its arguments
are now routed through a trivial `IgnoreDeadCheckArgs` no-op rather than
`CheckFail`. This still type-checks the arguments so they cannot bitrot,
without instantiating any formatting machinery for them and without
provoking unused-variable warnings.

Measured full-rebuild impact (353 first-party translation units,
fastbuild): -112.6s CPU, -6.9% relative to trunk.

Assisted-by: Claude
2026-06-10 06:49:00 +00:00
Christopher Di Bella eaf16a5250 Adapters should only be destroyable if their adapted type is destroyable (#7271)
Adapters were erroneously satisfying `Core.Destroy` because we were
directly getting the object's representation without consideration for
abstract and adapted types. This change ensures that adapted types'
representations are used instead of the adapter types.
2026-06-10 00:48:33 +00:00
Richard Smith c7b60662f7 CharLiteral difference should be an IntLiteral (#7314)
Change the result type `CharLiteral - CharLiteral` from `i32` to
`Core.IntLiteral`.

Assisted-by: Gemini via Antigravity
2026-06-09 23:26:22 +00:00
Chandler Carruth ad1578166f Freeze the ruff pre-commit and pin ty's version (#7331)
Hopefully this will get us to more consistent behavior between local and
CI runs of these checks.

Assisted-by: Antigravity with Gemini
2026-06-09 22:48:16 +00:00
Geoff Romer d63e929135 Support dumping ImportIRInstIds (#7328) 2026-06-09 22:17:18 +00:00
Geoff RomerandRichard Smith 85c53fa00c Reimplement derived class thunk in terms of down-casting (#7322)
This helps us move away from the clone-with-modifications approach to
thunking, which gets unwieldy as signatures get more complex.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-06-09 21:10:18 +00:00
Lucile Rose Nihlen 1a26b57732 add first implementation of carbon build subcommand (#7239)
This is the first draft of the implementation of
[p6333](https://docs.carbon-lang.dev/proposals/p6333.html).

The `build` subcommand shared logic with the `compile` and `link`
subcommands,
so I've moved some of the functionality in `compile` and `link` to
shared
`CompileDriver` and `LinkDriver` classes, respectively. This also
required exposing the
`CompileOptions` and `LinkOptions` subcommand structs for re-use.

There's still some work to do on the proposal, most notably the package
include automatic path resolution and import, and the refactors to
`carbon compile`.
2026-06-09 20:24:01 +00:00
Richard Smith e7ffb559f5 Reorganize lower interop tests. (#7327)
Split existing class and function tests into
`{class,function}/{import,export}` as appropriate. Remove the now-empty
`reverse/` directory.
2026-06-09 17:50:52 +00:00
d173121dc6 Name lookup design doc update (#7317)
Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-06-09 16:50:18 +00:00
Dana Jansens 233a58fcb1 Fix ty errors for missing generic parameters (#7326)
Mostly these errors were around `dict` missing arguments, and they are
almost always `[str, Any]`.

But a real thorn here was `xml.etree.ElementTree.Element`. `ty` insists
that this is a generic type, and indeed it appears to be one, or
becoming one, in some python version. But it is not generic in python
3.12. So we are stuck in an unsolvable land where:
- `ty` gives an error unless you write `[str]` on the type, because it
thinks it is generic.
- python3.12 gives an error if you do write `[str]` on the type, because
it thinks it is not generic.

Forcing `ty` to target exactly python 3.12 does not help. So I have just
used a linter-ignore comment on that line.
2026-06-09 15:08:39 +00:00
josh11bandJosh L efb78c593c Update design for proposal #6395: Type completeness in extend (#7315)
Assisted-by: Gemini via Antigravity

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-06-08 21:27:48 +00:00
Lucile Rose Nihlen 014c7346d6 Canonicalize the path to clang resource directory (#7321)
When building Carbon on Fedora, clang reports the
resource directory as `/usr/bin/../lib/clang/22`.
This fails to string match against `/usr/lib/clang/22`
and so bazel reports an error.

This PR canonicalizes the path returned by clang
so that it will string match successfully.
2026-06-08 18:56:07 +00:00
Chandler Carruth 3625e74a7d Out-of-line cold YAML and debug-printing paths from widely-included headers (#7320)
These were defined inline in headers reached by most of the toolchain,
and as non-template functions their bodies -- including some very
expensive template instantiations -- are compiled in every including TU
even though they are only cold debug/dump paths:

- BundleStore's YAML output entry points instantiate IdAndKind::Dispatch
  over all ~50 ID kinds (two ~365ms instantiations per TU) plus
  Yaml::OutputScalar/std::function machinery; moved to a new bundle.cpp.
- TypeStore, ConstantValueStore, NameStoreWrapper, and SharedValueStores
  OutputYaml bodies wrap capturing lambdas in std::function via
  Yaml::OutputMapping; moved to their existing .cpp files.

This change appears to be worth another 10% compile time reduction.

Assisted-by: Claude
2026-06-08 02:42:23 +00:00
Chandler Carruth 7901fb3857 Don't include expensive Clang headers in widely-included headers (#7319)
Fundamentally, this uses forward declarations of Clang types to reduce
the overall compile time cost of Clang headers across the codebase.

Tracing and profiling showed ~2s of every check TU's ~8-12s compile time
going just to parsing Clang frontend and AST headers pulled in via a few
sem_ir and check headers that only use the Clang types by pointer or
reference:

- sem_ir/cpp_file.h (reached via sem_ir/file.h by ~150 TUs) included
clang/Frontend/CompilerInstance.h, clang/CodeGen/ModuleBuilder.h,
clang/AST/Mangle.h, and llvm/IR/Module.h. CppFile's accessors move out
of line to a new cpp_file.cpp and the header now forward-declares the
Clang types.
- check/cpp/context.h (reached via check/context.h by ~100 TUs) included
clang/Frontend/FrontendAction.h and clang/Parse/Parser.h, pulling in
clang's Sema.h and ASTUnit.h.
- sem_ir/clang_decl.h included clang/AST/Decl.h; the three small
functions that need complete Clang types move out of line.
- sem_ir/cpp_overload_set.h included clang/Sema/Overload.h solely for
the three-field OverloadCandidateSet::OperatorRewriteInfo, which is now
mirrored as CppOverloadSet::OperatorRewriteInfo, and clang/AST/Decl.h
solely for a pointer.
- sem_ir/name_scope.h's clang/AST/DeclBase.h include was vestigial.

TUs (and more narrowly included headers) that genuinely use the Clang
definitions now include the Clang headers directly.

Representative compile times (fastbuild, aarch64), combined with the
preceding instantiation-cost changes, relative to trunk:
- check/eval.cpp: 11.85s -> 6.94s (-41%)
- check/handle_operator.cpp: 7.71s -> 3.30s (-57%)
- language_server.cpp: 6.68s -> 3.16s (-53%)
- lower/handle.cpp: 6.75s -> 3.66s (-46%)
- sem_ir/file.cpp: 8.60s -> 6.11s (-29%)
- driver.cpp: 6.68s -> 4.78s (-28%)

Measured full-rebuild impact (316 first-party TUs, fastbuild): -689.5s
CPU, -29.9% relative to trunk.

Assisted-by: Claude
2026-06-07 16:27:22 +00:00
Richard Smith 20972ec748 Don't perform access-control checks on namespace-scope entities. (#7310)
Instead of silently producing an `ErrorInst::InstId` when looking up a
private qualified name in the current package, bypass the access check.
We don't need it -- private names from other libraries are filtered out
by the import logic.

Also fix `DiagnoseInvalidQualifiedNameAccess` to actually always produce
a diagnostic, instead of silently ignoring access control failures in
non-class types. This is a no-op after the fix to the access logic,
since we only allow access control at class and namespace scope
currently, but should avoid this issue from recurring when that changes.

Assisted-by: Gemini via Antigravity
2026-06-05 23:30:09 +00:00
Richard Smith ae6846197a Remove trailing () from Core.*Literal and Core.Bool. (#7313)
We exposed `Core.IntLiteral()`, `Core.FloatLiteral()`,
`Core.CharLiteral()`, and `Core.Bool()` as functions as a workaround,
because we had no way to provide the type names without parentheses that
the design requests. But now we can do so, by using an alias. Switch all
of these over from being functions to simply being names of the
corresponding types.

Assisted-by: Gemini via Antigravity
2026-06-05 22:33:30 +00:00
Nicholas Bishop 5e62791ad2 Improve ClangDeclStore ergonomics (#7311)
Change `Lookup` by InstId to return a ClangDecl pointer. All callers
were immediately calling `Get` anyway, so this makes call sites a little
shorter. The other `Lookup` method, by ClangDeclKey, is sometimes called
without calling `Get`, so left that as-is, but renamed to `LookupId`.

Also add a `decl` method to ClangDecl so that the commonly repeated
`clang_decl->key.decl` can be written `clang_decl->decl()`.
2026-06-05 20:49:34 +00:00
Nicholas Bishop 44b17ff436 Set correct C++ access type for fields and static vars (#7312) 2026-06-05 20:07:27 +00:00
Geoff Romer bf2ed6174d Move variable naming to its own section. (#7307)
My understanding is that `auto` is encouraged even when there's no
applicable naming convention for the variable, and that suffixes like
`_id` are encouraged where applicable, even if the type is explicit, so
there's really no connection between the two policies.
2026-06-05 19:07:39 +00:00
David Blaikie b42300cfa3 Ensure exported entities aren't remapped/duplicated (#7304)
This ensures the clang_decls map is used as a cache - without this,
visiting the same entity twice could cause it to be
re-exported/duplicated. See attached test case.
2026-06-05 19:07:33 +00:00
Nicholas BishopandRichard Smith 1aa34d7642 Remove CppGlobalVarStore (#7309)
Replace all uses of CppGlobalVarStore store with ClangDeclStore.

Adding a VarStorage->VarDecl mapping to ClangDeclStore is now done with
the `AddVar` method, which takes an extra `pattern_id` arg. While the
corresponding `ClangDecl` is unchanged from before, the reverse mapping
in `inst_id_to_clang_decl_id_` now uses the `pattern_id` as the key.
This is necessary because in some places the original VarStorage
instructions gets replaced (e.g. by a call to `Convert`). The
`pattern_id` remains stable in those cases.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-06-05 02:07:46 +00:00
David Blaikie d652cb0dfd Update .python-version to match #7296 (#7306) 2026-06-05 01:46:04 +00:00
Geoff Romer 64ff3dd3be Clarify support for imported object-like macros (#7308)
This proposal clarifies some unclear aspects of the interop support for
object-like macros. In particular:
- Carbon supports importing an object-like macro if its definition can
be evaluated as a constant expression, without further restrictions on
that definition.
- When importing the result of that evaluation, C++ lvalues are imported
as references, and rvalues are imported as values.
2026-06-05 00:33:51 +00:00
David Blaikie 2d87bb02d9 Use clang_decls as the source of truth for function interop mapping (#7303)
Removing the clang_decl_id on SemIR::Function - using only the
clang_decls map to create the association between SemIR::Function and
clang::FunctionDecls.

This adds an `is_external` flag to ClangDecl to indicate whether the
entity originated from Carbon or was imported from another language.
(I'm open to names - I guess for now we mostly use "is this from C++" to
be more specific than "is this external" - eg: NameScope::is_cpp_scope)
2026-06-04 23:16:11 +00:00
Dana Jansens b6774ab4c8 Remove TODO in impls handler that is already done (#7305) 2026-06-04 20:47:07 +00:00
341069fdcf Add design doc for proposal #6676: Importing C/C++ object-like macros (#7291)
Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2026-06-04 20:07:42 +00:00
David Blaikie 2f9bbd067a Refactor: Inline global init function lowering (#7302)
This removes the need to support a function without a declaration in
these codepaths.
2026-06-04 19:13:18 +00:00
Richard Smith cefa0397bb More fixes to package and library fingerprinting. (#7297)
Fix import logic to make all imported packages be children of the
`NameScopeId::Package` scope. Previously, indirectly-imported packages
would end up as children of their importing package's scope, which
resulted in them not being treated as packages at all, and in particular
not being fingerprinted as packages.

Fixing that caused a failure in the fingerprinting logic as we started
to encounter packages with no correspoding import scopes. Instead of
looking for import scopes, use a simpler mechanism to map packages to
their package names, and clean up.

Unfortunately the latter change churns all the fingerprints again :(
Hopefully this is the last time for a while.
2026-06-04 17:41:46 +00:00
Richard Smith c69b882379 Fix crash lowering reference return. (#7301)
Fix a lowering crash when lowering a return by reference of a type with
an in-place initializing representation. We previously misinterpreted
this as an in-place initializing return.

This is addressed by changing lowering to interpret a `ReturnExpr` of a
reference expression as a reference return. However, that exposes
another issue: `return var;` produces a `ReturnExpr` of a reference
expression in the case where it returns in place! To fix that, we switch
`return var;` to producing a `ReturnExpr` of a value expression
regardless of whether the function has a return slot. This makes the
representation of `return var;` more uniform:

* If the expression is a reference, we're performing a `ref` return.
* If the expression is an initializing expression, we're performing a
normal by-initialization return.
* If the expression is a value expression, we're performing a `return
var;`.
2026-06-04 15:51:28 +00:00
Richard Smith 88c191146d Support for float <-> float conversions. (#7279)
Implement support for floating-point <-> floating-point type conversions
as described in https://github.com/carbon-language/carbon-lang/pull/820
and https://github.com/carbon-language/carbon-lang/pull/845.
Value-preserving conversions are implicit; narrowing conversions require
explicit `as`.

Assisted-by: Gemini via Antigravity
2026-06-04 00:33:33 +00:00
Richard Smith 7fe3e35aec Support for float <-> int conversions. (#7275)
Implement support for floating-point <-> integer type conversions as
described in #820 and #845, extended to support `unsafe as` conversions
for the conversions that can't be expressed as either implicit
conversions or `as` conversions.

One tricky part here is conversions from floating-point literals to
integer types. Such literals may have both a very large mantissa and a
corresponding somewhat large negative exponent, and still produce a
result that is in the range of values that a small integer type can
represent. In order to support that while avoiding building very large
2^N or 10^N constants in general, we first compute a conservative
approximation of the number of bits necessary to represent the integer
result, with an early exit if the number is either definitely too large
or definitely zero. The remaining cases have a reasonable bound on the
size of integer necessary to compute the base^exponent multiplicand.

Assisted-by: Gemini via Antigravity
2026-06-03 23:41:20 +00:00
Nicholas Bishop f2d0c4d0ae Export Carbon global variables and static vars to C++ (#7298)
Add `ExportVarToCpp`. This checks the `clang_decls` mapping and returns
an existing decl if found. Otherwise, it creates a new `VarDecl` and
adds it to the `clang_decls` mapping.

When lowering, in `FileContext::BuildGlobalVariableDecl`, the
`clang_decls` mapping is used to lookup an existing
`llvm::GlobalVariable` for the instruction. If found, use that rather
than creating a new one to avoid an unwanted second definition in the
llvm IR.
2026-06-03 20:47:54 +00:00
Chandler Carruth 76dd872ab4 Switch to prek rather than pre-commit (#7244)
This provides a native harness with several advantages over
`pre-commit`:

- Faster when initializing the cache
- Smaller cache sizes: under 43mb compared to over 62mb
- Better integration with `uv` for Python usage

Steps for migrating for existing contributors:

1.  Install `prek` following instructions in the updated docs.

2.  Replace hooks in an existing checkout with a special flag:

    ```sh
    prek install --overwrite
    ```

    The `--overwrite` flag is what removes the old hooks.

    If you used the pre-push variant:

    ```sh
    prek install --hook-type pre-push --overwrite
    ```

3.  Optional cleanups:

    ```sh
    rm -rf ~/.cache/pre-commit  # reclaim the old hook-environment cache
pipx uninstall pre-commit # if installed via pipx; or `brew uninstall
pre-commit`
    ```

Assisted-by: Antigravity with Gemini
2026-06-03 19:19:49 +00:00
josh11bandJosh L 358df53c48 Add design doc for proposal #6668: C++ interop type mapping for integer and floating-point literals (#7295)
Assisted-by: Gemini via Antigravity

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-06-03 14:22:17 +00:00
Chandler Carruth b344f3af12 Switch a few stragglers to uv and update python to 3.12 (#7296)
Not sure how these got missed when moving other things to `uv`, but this
should clean them up.

The bump to Python 3.12 is so that we can use `@override` with the
simple import from `typing`. This is needed by the newest versions of
`ty` to do type checking. Added the relevant `@override` annotations.

Assisted-by: Antigravity with Gemini
2026-06-03 05:34:44 +00:00
Christopher Di Bella 61ee4edd9c Implement Iterate for types that implement CppRangeForIterate (#7294)
This change adds rudimentary support for C++ ranges in Carbon range-for
loops. Since C++ ranges are exposed through `Core.Iterate`, C++ ranges
have the same limitations as Carbon ranges (e.g. can't return
references).

`Iterate.CursorType` now requires `Destroy`, since types that implement
`CppRangeForIterate` can't be used in range-for loops unless their
cursor type can be verifiably destructible.
2026-06-03 04:51:09 +00:00
Christopher Di Bella d578e4afe7 Remove ref pattern from CppUnsafeDeref (#7293)
Since we can't currently iterate over ranges as references, the
`CppUnsafeDeref` interface can't require types that implement it to take
or return references.
2026-06-03 01:22:07 +00:00
Dana Jansens 057ef0d458 Orphan rule for scopes (#7140)
Update the orphan rule to require a name to be defined within, or by,
the same scope as the impl declaration. Since libraries can not be
nested, this also enforces the old rule, but rejects more impl
declarations. In particular, it rejects an impl declaration in a generic
context which would have no way to provide a value for the generic
bindings it inherited from its enclosing scope, making the impl
unusable.

Discussed in open discussion
[2026-05-04](https://docs.google.com/document/d/1mjllGO3ZCL4qGt9uJHUtcxKoHAGEY7Y999ie4EtBWB8/edit?tab=t.3ifnhz83n73d#heading=h.p45zfugbmdih).
2026-06-02 22:33:15 +00:00
Richard Smith f5e9c61f11 Don't include the library name in most fingerprints. (#7292)
When we import from another library in the same package, its entities
end up with our library as their parent scope, resulting in cross-file
fingerprint mismatches. Instead, only include the library ID when
fingerprinting either a package-private entity or an `ImportIRId` that
refers to a particular `SemIR::File`.
2026-06-02 19:31:30 +00:00
Dana Jansens e7ed217d4e Require all constraints in where to have a designator (#7282)
Instead of requiring just one to have a designator, require each one.
You can't write `(type where A == B) & (type where C == .Self)` because
`A == B` has no designator. If the two facet types are combined into a
single `where` syntactically, their meaning does not change, and what we
allow should not change either. That is, `type where A == B and C ==
.Self` should be rejected since `A == B` does not contain a designator.

The design is also updated to make this clear.
2026-06-02 17:11:59 +00:00
antangelo 8e477cc2c6 Fix crash when calling local function in generic function (#6912)
Pass a function's self specific in `ScopeStack::PushForFunctionBody` and
remove assertion preventing lexical scopes from having specific IDs.
This allows lexical lookup within the function to find entities
associated with its self specific.

Closes #6793
2026-06-02 16:27:21 +00:00
Richard Smith b7f11e4c61 Propagate Carbon type alignments into LLVM IR. (#7290)
Use the Carbon-computed alignment for allocas, loads, stores, and
memcpys. Previously we used whatever LLVM felt like giving us, which
would result in ABI mismatches and runtime crashes due to misalignment
when creating objects of imported C++ class types, as well as resulting
in some surprising choices like `(i32, i32)` and `()` having 8-byte
alignment instead of 4 and 1, respectively.
2026-06-02 01:35:03 +00:00
Richard Smith 2952f61095 Support for mapping array types to/from C++. (#7285)
For now, disable the use of array types as by-var paramters and by-init
return types when exporting Carbon functions to C++, as C++ does not
support raw arrays being passed or returned by value.

Assisted-by: Gemini via Antigravity
2026-06-01 21:55:16 +00:00
d01e1d2d06 Update design docs for proposal #6710: char redesign (#7281)
Note that #7266 has already updated the toolchain for `char`, but not
`Core.CharLiteral`.

Assisted-by: Gemini via Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2026-06-01 19:34:35 +00:00
Richard Smith 49e5e15138 Fix mangling collisions for library-private entities. (#7283)
Include the library name in the fingerprint of an entity declared
`private` at namespace scope. Include the entity's fingerprint in the
mangling of a library-private entity.

This fixes miscompiles if two libraries in the same package declare
`private` entites with the same name. We can't fix this with internal
linkage because library-private entities can be reachable through
generics defined in the API file of the library.

Assisted-by: Gemini via Antigravity
2026-06-01 19:19:08 +00:00
Nicholas Bishop 682f9fef16 Add FieldStore and fix field initializer imports (#7287)
As suggested in [1], replace `FieldInitializerMap` with a `FieldStore`.
The corresponding `FieldId` is now stored in `FieldDecl`. To make room
for the `FieldId`, the `ElementIndex` is now stored in the `Field`,
along with the initializer.

In import_ref.cpp, resolving `FieldDecl` initializers is now supported,
and in convert.cpp `LoadImportRef` is called to do so. The
`field_initializer_import.carbon` test now passes.

Printing a `FieldDecl` instruction now prints the initializer as well,
if present. See field_initializer.carbon for an example.

[1]:
https://github.com/carbon-language/carbon-lang/pull/7238#discussion_r3283217158
2026-06-01 19:02:01 +00:00
Chandler CarruthandChristopher Di Bella 14a213d095 Apply the unused-without-definition check to implicit parameters (#7270)
The `unused` modifier is rejected on parameters of a function
declaration, but the check only covered the explicit parameter list, so
an implicit parameter (such as self or a compile-time binding) could
carry unused without a definition. Check the implicit parameter list
too.

The code changes and the test updates are split into two commits for
easier review.

Assisted-by: Claude Code with Claude Opus 4.7

---------

Co-authored-by: Christopher Di Bella <cjdb.ns@gmail.com>
2026-05-30 08:26:09 +00:00
Chandler CarruthandChristopher Di Bella 8a59f2a76b Fix mangling collision for C++ class template specializations (#7269)
Carbon-side thunks (for example the `Copy`/`Destroy` witness thunks
generated for imported C++ types) are mangled by Carbon, and their names
incorporate a fingerprint of the involved types. The instruction
fingerprinter identifies a class only by its name and parent scope,
which is sufficient for Carbon classes but not for imported C++ classes:
different specializations of one class template (and other cases such as
types in anonymous namespaces) share a Carbon name and parent scope. As
a result, the thunks for two distinct specializations could mangle to
the same name, producing a single LLVM function with two definitions and
failing `verifyModule` during lowering.

When fingerprinting a class imported from C++, also include the Clang
mangled name of its type.

Test: toolchain/lower/testdata/interop/cpp/thunks.carbon gains a split
with two specializations of one class template, each requiring a thunk;
their thunks now get distinct mangled names instead of colliding.

Assisted-by: Claude Code

---------

Co-authored-by: Christopher Di Bella <cjdb.ns@gmail.com>
2026-05-30 08:13:00 +00:00
Chandler Carruth 3ef128ac91 Switch to Astral Python tools: ruff and ty (#7243)
This replaces black, flake8, and mypy with the more modern and efficient
tools `ruff` and `ty` from Astral.

Assisted-by: Antigravity with Gemini
2026-05-29 22:56:27 +00:00
Richard Smith 1a8f2f3b8c Add Core.Destroy support for enums imported from C++ (#7267)
We previously only supported values of enum type, as we did not find a
suitable `Core.Destroy` implementation for enums.
2026-05-29 22:42:12 +00:00
Chandler Carruth 59e0f95a10 Fix Linux AArch64 build and add CI for that platform (#7273)
The `--dump-cpp-ast` file tests strip references to Clang builtins so
that the expected output is target-independent. The filter anchored a
`__`-prefixed builtin identifier on a preceding space or quote, which
matches the x86-64 `__va_list_tag` spelling but not the AArch64
`std::__va_list`, where `__` is preceded by the `::` namespace
qualifier. That left a single `RecordType 'std::__va_list'` line
unfiltered on AArch64, producing a spurious autoupdate diff for
`thunk_ast.carbon`.

Anchor the match on a preceding `:` as well so namespace-qualified
builtins are also filtered.

Carbon's test workflow covered Linux on x86-64 and macOS on AArch64, but
had no Linux AArch64 coverage, so AArch64-specific issues that don't
reproduce on macOS could land unnoticed. Add an `ubuntu-22.04-arm`
runner to the matrix.

The release used for Linux does not publish the monolithic
`LLVM-*-Linux-ARM64` package, only a `clang+llvm-*-aarch64-linux-gnu`
community build with a smaller tool set, so the Ubuntu setup now selects
the tarball by `runner.arch`. The prune step uses `rm -f` since the two
packages do not ship an identical set of tools to remove.

Assisted-by: Claude Code with Claude Opus 4.7
2026-05-29 15:32:18 +00:00
Chandler CarruthandRichard Smith 94d2c1c6d4 Make proposal filenames use 6 digits and include the title (#7245)
We've talked about adding the title to the filename several times over
the years and it seems really valuable. This requires us to compute a
"slug" for the title spelling that can be part of the filename.

Beyond that, we crossed 7000 recently, and so it seems likely that we
will need to add digits sooner rather than later here, so this goes
ahead and moves us to 6 digits so we don't have to adjust again for a
reasonable length of time.

To implement this and ensure we can sustain it going forward this adds a
tool to our pre-commit that validates (and corrects if needed) the
filename.

In order to update everything and keep links working, there are a _lot_
of changes, but the most interesting for direct review are in
`proposals/scripts`.

Assisted-by: Antigravity with Gemini

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-05-29 00:55:04 +00:00
Richard Smith 1cb0eecc1e Add skills for diagnostics and builtin functions. (#7277)
Also make some updates and improvements to fine-tune existing skills.

Simplify AGENTS.md to remove redundant instructions that duplicate
information that's already in skill files -- skills should be loaded
automatically and should not need to be redundantly specified in
AGENTS.md.

Assisted-by: Gemini via Antigravity
2026-05-28 23:58:37 +00:00
Chandler Carruth 1028538d05 Add the uv release endpoint (#7276) 2026-05-28 20:35:01 +00:00
Chandler Carruth b79ce84f33 Switch to uv for all of our Python scripts (#7242)
This removes the need to install any specific version of Python or
figure out how to configure it by instead asking users to install `uv`
and letting it manage Python. Among other advantages, `uv` is designed
to be fast enough to embed directly into our scripts.

We were already using this in `bench_runner.py` so that the script could
import non standard library dependencies. Moving to it for the rest of
our Python unifies the approach and will also enable dependencies
whenever needed.

I've left `github_tools` alone as it has special handling with its own
Bazel setup.

I've updated the contributing tools to explain the approach here.
2026-05-28 18:03:52 +00:00
dependabot[bot] 6aee1280e9 Bump tmp from 0.2.5 to 0.2.7 in /utils/vscode in the npm_and_yarn group across 1 directory (#7274)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [tmp](https://github.com/raszi/node-tmp).

Updates `tmp` from 0.2.5 to 0.2.7
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/raszi/node-tmp/commit/8ea1f37d75c67569e0f151448330d52f7babf211"><code>8ea1f37</code></a>
Bump up the version</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/8f24f788a356b5d45c9bec894632bd4931338153"><code>8f24f78</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/ce787f37aaacccad921ae90990c9da33481fe59c"><code>ce787f3</code></a>
Reject non-string prefix, postfix, template</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/41f71598d03f104a67e0448a7cb9bd4efcdd5980"><code>41f7159</code></a>
Bump up the version</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/efa4a06f24374797ae32ab2b6ae39b7a611ae429"><code>efa4a06</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/7ef2728ce0211b8110b2033dfe62eaf030341acf"><code>7ef2728</code></a>
Check for relative values</li>
<li>See full diff in <a
href="https://github.com/raszi/node-tmp/compare/v0.2.5...v0.2.7">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=tmp&package-manager=npm_and_yarn&previous-version=0.2.5&new-version=0.2.7)](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-05-28 05:16:54 +00:00
Richard Smith e45045d63b Implement char operations from #6710 (#7266)
This only covers `char`, and does not include the `CharLiteral`
operations.

Assisted-by: Gemini via Antigravity
2026-05-27 23:18:27 +00:00
Richard Smith 9986d0da69 Only propagate .Self dependence in facet types from extended constraints (#7253)
When forming the constant value of a `where` expression, don't consider
it to be `.Self`-dependent if the dependence only comes from the RHS of
the `where`. More generally, ignore `.Self` dependence when evaluating a
facet type unless it comes from an extended interface or named
constraint. While we can get other kinds of constraint from the
left-hand side of a `where`, such constraints must either come from the
right-hand side of other `where` expressions or be extend constraints.

This fixes a crash in lowering caused by a concrete function containing
a `.Self`-symbolic `where` constant.

Assisted-by: Gemini via Antigravity
2026-05-27 22:04:48 +00:00
Richard Smith 7569aff619 Don't convert runtime arguments during deduction. (#7265)
When performing deduction for a call to a generic function, we would
previously convert runtime arguments to match the parameter type, then
throw away the result. Instead, track whether deduction needs the value
of the argument, which will be the case only within compile-time
contexts such as generic bindings and types of instructions, and only
perform conversions during deduction for those contexts.

Fixes miscompiles when passing an argument requiring a runtime
conversion with side-effects to a generic function, where previously the
side-effects would have happened twice! (Once from deduction and once
from the real call argument conversion.)

Assisted-by: Gemini via Antigravity
2026-05-27 21:44:29 +00:00
Richard Smith 09d1331e85 Make Optional(T) copyable. (#7268)
`Optional` is already restricted to only be able to store copyable
types, so it should always implement `Core.Copy`.
2026-05-27 18:13:26 +00:00
DavidLoftus de381bded1 Fix off-by-one errors in LanguageServer's GetRange (#7251)
LSP assumes lines are index 0 to n-1, but Carbon Locs are index from 1
to n. We had the logic for this correct for the start of range but not
for the end of range (inclusive range).

Before this was the diagnostic span we would produce:

```carbon
fn F() {
  return ();
  <~~~~~~~~>
}
<~~~~~~~~~~~>
```

after:

```carbon
fn F() {
  return ();
  <~~~~~~~~>
}
```
2026-05-27 17:37:56 +00:00
Dana Jansens 518704608e Handle errors and non-constant instructions when substituting non-canonical instructions (#7262)
Subst is typically used for constant values, in which case an
`ErrorInst` anywhere results in a final `ErrorInst`. However there are
some use cases for substituting non-canonical instructions. And in that
case we need to take care in two ways:
- Some instructions have no constant value, such as the requirements in
a (non-canonical) `WhereExpr` instruction. When we rebuild them, we
can't do so by building a constant value and getting the canonical inst
id, since the constant value will be "runtime". For rebuilding a
non-canonical instruction, we should `AddInst` instead.
- When substituting something in a non-canonical instruction with an
`ErrorInst` inside it, we want to preserve the structure of the
non-canonical instruction, and leave the `ErrorInst` in place. As such,
we remove the early out in Subst so that we keep substituting after
encountering an error.

However the rewrite constraint resolution was relying on the `ErrorInst`
early out to correctly stop recursing when it found a cycle. So now we
do the checks for a cycle in its `SubstCallbacks` subclass, and avoid
substituting and rebuilding instructions once we have encountered a
cycle.
2026-05-27 15:43:41 +00:00
Chandler Carruth d313fd0b11 Add a skill file for creating proposals (#7257)
A lot of this is based on a few experiments using tools to help
synthesize a cohesive proposal or improve them. Likely more that can be
done here to get the most out of our tools in this space.

Assisted-by: Antigravity with Gemini
2026-05-27 03:15:14 +00:00
Christopher Di Bella bd7f89b1ad Remove lookup_result and function (#7264)
PR #7230 was automerged before
https://github.com/carbon-language/carbon-lang/pull/7230#pullrequestreview-4348841410
could be applied. This commit actions that feedback.
2026-05-26 22:57:03 +00:00
Richard Smith a779cc37a0 Support converted ref arguments. (#7258)
Allow a `ref`-tagged expression to be converted to match a reference
parameter. Move the `ref` checks to the start of `Convert`. Remove the
diagnostic for applying `ref` to a non-reference expression so that
non-reference expressions that convert to a reference would be accepted
(although we don't currently have any such conversions).

Assisted-by: Gemini via Antigravity
2026-05-26 20:38:49 +00:00
Dana Jansens bbca8668ae Allow witnesses to come from a facet with partially identified type in the lookup target (#7260)
We allow impl lookup to use `Self` which is partially identified, but we
were only allowing this for the `Self` facet appearing in the impl
lookup query self. We should also allow it when `Self` appears in the
impl lookup query target facet type.

But demonstrate that `Self` appearing in the interface of an
ImplWitnessAccess (a compound member access) is not sufficient at this
time, as it does not put `Self` into the type structure.
2026-05-25 23:02:06 +00:00
Dana Jansens 58b135235c Use earlier C(.Self) impls ... and .Self impls ... constraints in a facet type (#7246)
The `.Self` needs to be canonicalized when recording the witness, since
it will be a FacetAccessType in the `impls` clause.

Todo tests are also added for `C impls Y(.Self)`. The `.Self` in the
interface specific breaks everything as we end up replacing the `.Self`
with `C` in later `C as Y(.Self)` lookups, which then does not find the
witness.

Pull all the witnesses from `impls` constraints so that we capture
witnesses coming from named constraints on different self types, as `C
impls N(.Self)` may give witnesses for `C` or for other self types.
2026-05-25 15:13:20 +00:00
Chandler Carruth 4aacf2e2a5 Fix new-proposal script to correctly get GitHub username (#7255)
Assisted-by: Antigravity with Gemini
2026-05-24 23:26:28 +00:00
dependabot[bot] a49e1d94b8 Bump qs from 6.15.1 to 6.15.2 in /utils/vscode in the npm_and_yarn group across 1 directory (#7256)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [qs](https://github.com/ljharb/qs).

Updates `qs` from 6.15.1 to 6.15.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.15.2</strong></h2>
<ul>
<li>[Fix] <code>stringify</code>: skip null/undefined entries in
<code>arrayFormat: 'comma'</code> + <code>encodeValuesOnly</code>
instead of crashing in <code>encoder</code></li>
<li>[Fix] <code>stringify</code>: use configured <code>delimiter</code>
after <code>charsetSentinel</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/555">#555</a>)</li>
<li>[Fix] <code>stringify</code>: apply <code>formatter</code> to
encoded key under <code>strictNullHandling</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/554">#554</a>)</li>
<li>[Fix] <code>stringify</code>: skip null/undefined filter-array
entries instead of crashing in <code>encoder</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/551">#551</a>)</li>
<li>[Fix] <code>parse</code>: handle nested bracket groups and add
regression tests (<a
href="https://redirect.github.com/ljharb/qs/issues/530">#530</a>)</li>
<li>[readme] fix grammar (<a
href="https://redirect.github.com/ljharb/qs/issues/550">#550</a>)</li>
<li>[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li>[Tests] add regression tests for keys containing percent-encoded
bracket text</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ljharb/qs/commit/9aca4076fe788338c67cf7e115f0be6bc58d85a8"><code>9aca407</code></a>
v6.15.2</li>
<li><a
href="https://github.com/ljharb/qs/commit/5e33d33447ed0bf1ddab9abc41d27dea4687d992"><code>5e33d33</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/21f80b33e5c8b3f7eba1034fff0da4a4a37a1d41"><code>21f80b3</code></a>
[Fix] <code>stringify</code>: skip null/undefined entries in
<code>arrayFormat: 'comma'</code> + `e...</li>
<li><a
href="https://github.com/ljharb/qs/commit/a0a81ea2071acce3eff41a040f719ac8f5c4f64c"><code>a0a81ea</code></a>
[Fix] <code>stringify</code>: use configured <code>delimiter</code>
after <code>charsetSentinel</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/e3062f78f5233b338ceeb8e8dfa5a07dea4b32a8"><code>e3062f7</code></a>
[Fix] <code>stringify</code>: apply <code>formatter</code> to encoded
key under <code>strictNullHandling</code></li>
<li><a
href="https://github.com/ljharb/qs/commit/0c180a40adb8c6703fffc85b2ff06ca209f5c1e0"><code>0c180a4</code></a>
[Fix] <code>stringify</code>: skip null/undefined filter-array entries
instead of crashi...</li>
<li><a
href="https://github.com/ljharb/qs/commit/3a8b94aec19bd664720f6f6b1e66c4a0dfe4b656"><code>3a8b94a</code></a>
[Tests] add regression tests for keys containing percent-encoded bracket
text</li>
<li><a
href="https://github.com/ljharb/qs/commit/96755abd357c0e534dd3442a84a04d08864bfe0d"><code>96755ab</code></a>
[readme] fix grammar</li>
<li><a
href="https://github.com/ljharb/qs/commit/a419ce5bbfcdb98a299f1a0bb47ea055baef20e6"><code>a419ce5</code></a>
[Fix] <code>parse</code>: handle nested bracket groups and add
regression tests</li>
<li>See full diff in <a
href="https://github.com/ljharb/qs/compare/v6.15.1...v6.15.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.15.1&new-version=6.15.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-05-24 09:59:14 +00:00
Richard Smith 52b45a66a3 Convert TokenInfo::ResetAs... functions to return new TokenInfos. (#7252)
As requested in #7249.
2026-05-23 01:22:22 +00:00
Richard Smith 49024c8d83 Improve diagnostics and error recovery for invalid identifiers. (#7249)
If a keyword or a sized type literal (eg, `f2`) is used in a context
where we are confident that we are expecting an identifier -- either
before a `:` in a binding pattern or after a `.` in a member access or
designator -- then recover as if a raw identifier was used.

This appears to be a particular stumbling block for coding agents, so
seems worth paying special attention to.

Add a mechanism to the tokenized buffer to track additional tokens
synthesized for error recovery so that we can keep the lexed token
sequence immutable and still satisfy the invariants throughout the rest
of the toolchain for recovery tokens. Thanks to chandlerc for suggesting
this approach!
2026-05-22 23:53:19 +00:00
Christopher Di Bella 64e890c246 Extend CppRangeForIterate to support ADL begin/end (#7230)
`CppRangeForIterate` needs to support finding `begin()`/`end()` as a
pair of methods and as a pair of ADL-findable functions. This change
adds the ADL component, which lets us also diagnose types that don't
implement the interface.

Unlike methods, we apparently have support for overloads when using ADL.
2026-05-22 21:12:06 +00:00
Nicholas Bishop e6b1679552 Add support for field initializers (#7238)
In handle_let_and_var.cpp, field initializers are now handled like
regular `var` initializers, by calling `LocalPatternMatch`.

In pattern_match.cpp, `FieldDecl`s with initializers are handled by
storing a value in `SemIR::File::field_initializers()`. This is a new
map where the keys are `FieldDecl` `InstId`s and the map values are
`InstId`s representing the initializer value.

In convert.cpp, `ConvertStructToStructOrClass` now has a `get_default`
function parameter that callers can use to provide a field default.
`ConvertStructToClass` uses this to provide a default from field
initializers.
2026-05-22 02:48:07 +00:00
Richard Smith 862b1c91f8 Fix GetTokenText for raw identifiers. (#7250)
Include the `r#` in the spelling of the identifier.
2026-05-22 01:57:13 +00:00
Richard Smith 805b3eebce Fix crash if initializing Clang fails. (#7248)
Flush diagnostics before destroying Clang. If we see an `inline Cpp` and
`Cpp` initialization failed, recover by skipping the inline code rather
than CHECK-failing.
2026-05-21 21:21:50 +00:00
Richard Smith ad97b9e3a5 Basic support for use of C++ modules via interop. (#7241)
Create a multiplex source to pull information from both the AST reader
and from our custom source.

Assisted-by: Gemini via Antigravity
2026-05-21 00:21:54 +00:00
dependabot[bot] 022995e412 Bump idna from 3.7 to 3.15 in /github_tools in the pip group across 1 directory (#7234)
Bumps the pip group with 1 update in the /github_tools directory:
[idna](https://github.com/kjd/idna).

Updates `idna` from 3.7 to 3.15
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/kjd/idna/releases">idna's
releases</a>.</em></p>
<blockquote>
<h2>v3.15</h2>
<p>No release notes provided.</p>
<h2>v3.14</h2>
<p>No release notes provided.</p>
<h2>v3.13</h2>
<p>No release notes provided.</p>
<h2>v3.12</h2>
<p>No release notes provided.</p>
<h2>v3.11</h2>
<p>No release notes provided.</p>
<h2>v3.10</h2>
<p>No release notes provided.</p>
<h2>v3.9</h2>
<p>No release notes provided.</p>
<h2>v3.8</h2>
<h2>What's Changed</h2>
<ul>
<li>Fix regression where IDNAError exception was not being produced for
certain inputs.</li>
<li>Add support for Python 3.13, drop support for Python 3.5 as it is no
longer testable.</li>
<li>Documentation improvements</li>
<li>Updates to package testing using Github actions</li>
</ul>
<p>Thanks to Hugo van Kemenade for contributions to this release.</p>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/kjd/idna/compare/v3.7...v3.8">https://github.com/kjd/idna/compare/v3.7...v3.8</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/kjd/idna/blob/master/HISTORY.md">idna's
changelog</a>.</em></p>
<blockquote>
<h2>3.15 (2026-05-12)</h2>
<ul>
<li>Enforce DNS-length cap on individual labels early in
<code>check_label</code>,
short-circuiting contextual-rule processing for oversized input
while staying compatible with UTS 46 usage.</li>
<li>Tidy core helpers: hoist bidi category sets to module-level
frozensets (avoiding per-codepoint list construction), simplify
length checks, and reuse the shared <code>_unicode_dots_re</code> from
<code>idna.core</code> in the codec module.</li>
<li>Use <code>raise ... from err</code> for proper exception chaining
and
switch internal string formatting to f-strings.</li>
<li>Allow <code>flit_core</code> 4.x in the build backend.</li>
<li>Expand the ruff lint set (flake8-bugbear, flake8-simplify,
pyupgrade, perflint) and apply the surfaced fixes; pin lint CI
to Python 3.14.</li>
<li>Add Dependabot configuration for GitHub Actions.</li>
<li>Convert README and HISTORY from reStructuredText to Markdown.</li>
<li>Reference CVE-2026-45409 for the 3.14 advisory in place of the
initial GHSA identifier.</li>
</ul>
<p>Thanks to Felix Yan, Stan Ulbrych, and metsw24-max for
contributions to this release.</p>
<h2>3.14 (2026-05-10)</h2>
<ul>
<li>Removed opportunity to process long inputs into quadratic
time by rejecting oversize inputs up-front. Closes a bypass
of the CVE-2024-3651 mitigation. [CVE-2026-45409]</li>
</ul>
<p>Thanks to Stan Ulbrych for reporting the issue.</p>
<h2>3.13 (2026-04-22)</h2>
<ul>
<li>Correct classification error for codepoint U+A7F1</li>
</ul>
<h2>3.12 (2026-04-21)</h2>
<ul>
<li>Update to Unicode 17.0.0.</li>
<li>Issue a deprecation warning for the transitional argument.</li>
<li>Added lazy-loading to provide some performance improvements.</li>
<li>Removed vestiges of code related to Python 2 support, including
segmentation of data structures specific to Jython.</li>
</ul>
<p>Thanks to Rodrigo Nogueira for contributions to this release.</p>
<h2>3.11 (2025-10-12)</h2>
<ul>
<li>Update to Unicode 16.0.0, including significant changes to UTS46
processing. As a result of Unicode ending support for it, transitional
processing no longer has an effect and returns the same result.</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/kjd/idna/commit/af30a092e158181d0b35ac66dfa813788126bdd8"><code>af30a09</code></a>
Release 3.15</li>
<li><a
href="https://github.com/kjd/idna/commit/30314d4628744ca14cf2b5820564e5127a9f86f2"><code>30314d4</code></a>
Pre-release 3.15rc0</li>
<li><a
href="https://github.com/kjd/idna/commit/05d4b219aa9eddc47371fcbd2000f0301016f3e9"><code>05d4b21</code></a>
Merge pull request <a
href="https://redirect.github.com/kjd/idna/issues/237">#237</a> from
kjd/convert-docs-to-markdown</li>
<li><a
href="https://github.com/kjd/idna/commit/2987fdba1962bbb2358399e0084ba062b98a0bee"><code>2987fdb</code></a>
Convert README and HISTORY from reStructuredText to Markdown</li>
<li><a
href="https://github.com/kjd/idna/commit/59fa8002d514bf4a5ce7b58f67b9ec587d53fa9c"><code>59fa800</code></a>
Merge pull request <a
href="https://redirect.github.com/kjd/idna/issues/236">#236</a> from
kjd/dependabot/github_actions/actions-f3e34333ea</li>
<li><a
href="https://github.com/kjd/idna/commit/def69834ced5d4b3c50439d8b99c4c856ec19ca2"><code>def6983</code></a>
Merge branch 'master' into
dependabot/github_actions/actions-f3e34333ea</li>
<li><a
href="https://github.com/kjd/idna/commit/bbd8004a797185d8c56bb555cd5c88fde05e0631"><code>bbd8004</code></a>
Merge pull request <a
href="https://redirect.github.com/kjd/idna/issues/234">#234</a> from
StanFromIreland/patch-1</li>
<li><a
href="https://github.com/kjd/idna/commit/edd07c05024344a6ccb517414ccb36683aee99fc"><code>edd07c0</code></a>
Bump github/codeql-action from 3.35.2 to 4.35.2 in the actions
group</li>
<li><a
href="https://github.com/kjd/idna/commit/5557db030c11bdec50d62aa5f631d705d33ba123"><code>5557db0</code></a>
Merge branch 'master' into patch-1</li>
<li><a
href="https://github.com/kjd/idna/commit/f11746cf4981d25123ef7830d3ee60f07de8ae3d"><code>f11746c</code></a>
Merge pull request <a
href="https://redirect.github.com/kjd/idna/issues/235">#235</a> from
StanFromIreland/patch-2</li>
<li>Additional commits viewable in <a
href="https://github.com/kjd/idna/compare/v3.7...v3.15">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=idna&package-manager=pip&previous-version=3.7&new-version=3.15)](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-05-21 00:07:56 +00:00
Richard Smith 05cc09daca Fix cross-package signature mismatches. (#7232)
Fixes link failures when referencing a symbol involving a fingerprint
from a different package.

Previously we included the `Namespace`'s `import_id` as part of its
fingerprint, which caused local and imported namespaces to get different
fingerprints. We now store the `import_id` on the `NameScope` instead of
on the `Namespace` inst to avoid this problem.

Also, when we reach a package-level `NameScopeId`, consistently
fingerprint it as a (package name, library name) pair. Previously the
fingerprinting depended on whether it was imported or not, as an
imported `NameScopeId` had a parent scope (the current package). We need
to include the library name here so that private entities with the same
name in different libraries have different fingerprints.
2026-05-21 00:02:29 +00:00
Richard Smith 1231098c14 Fix crash in indirect template instantiation. (#7240)
Provide a source location to the member expression used when a thunk
calls a member function. This ends up being used as the point of
instantiation when the return type triggers a template instantiation;
the absence of this location previously caused assertion failures within
clang.

Assisted-by: Gemini via Antigravity
2026-05-20 23:18:15 +00:00
Richard Smith f31c553e65 Add a failing test for Clang modules support. (#7233)
Rearrange the file_test infrastructure so that we can customize the
mapping of file names to command line arguments. Map `module.modulemap`
files to corresponding Clang driver flags. In passing, also clean up the
interface for specifying custom argument replacements so that we don't
build a string map for each file we process, and stop using
`SmallVector::insert`.

Assisted-by: Gemini via Antigravity
2026-05-20 20:26:36 +00:00
Richard Smith be70c092fa Add a text mode for fingerprinting. (#7231)
The intent is to add visibility into how the fingerprint is computed, so
that fingerprinting issues and mangling collisions can be more readily
understood and fixed.

Assisted-by: Gemini via Antigravity
2026-05-19 23:16:51 +00:00
Richard Smith ce080b3549 Support unqualified lookup into extended interfaces from classes and impls (#7217)
When a class extends an interface, referring to a member name of the
interface as an unqualified name should refer to the class's
corresponding associated entity value, not to the associated entity
itself. Similarly, in an `impl`, unqualified names of associated
entities should refer to the `impl`'s corresponding value for that
entity.

To support this, we treat `impl`s as `extend`ing their implemented facet
type, and we make lookups into an extended facet type use the `Self`
type of the extending `impl` or `class` if lookup finds an associated
entity. We already did the latter if the extending entity was an
interface; this extends the existing support for these other cases.
2026-05-19 18:01:54 +00:00
Chandler Carruth 0d7c4a99eb Explicitly escape leading - (#7226)
Previously, this relied on the subtlety that `-- ` (with the trailing
space) didn't get parsed as a flag. But there is support already for
escaping a leading `-` in a format argument, so use that to make the
code more obviously correct.

Assisted-by: Antigravity with Gemini
2026-05-19 17:32:17 +00:00
Chandler Carruth bb59a0b1d8 Optimize pre-commit checks (#7229)
First, this makes the Bazel invocations not try to uses curses which
prevents running them with `pre-commit run ... -v` showing the timings
for each check. The curses display overwrote the output.

Second, this fixes the main slowdown I was seeing. Because we passed
_all_ files to the check-build-graph hook and there are large number of
files, pre-commit would run the tool over and over on a subset of the
files. This is especially wasteful as the build graph check already
doesn't do anything with the files, it just checks `//...` on each
invocation. So this just added a (large) constant factor of cost.

Third, this tries to reduce the cost of `fix_cc_deps.py` in the case of
large numbers of files. This still isn't _super_ fast -- but the rest of
the cost is in running the `bazel query` and parsing the output. I tried
switching it to jsonproto and it wasn't any faster. I think this would
need to be in a non-Python language and use `proto` directly to
significantly improve the cost here.

Assisted-by: Antigravity with Gemini
2026-05-19 15:51:33 +00:00
Richard Smith 9c277fd820 Add missing library line to test. (#7227) 2026-05-19 03:05:31 +00:00
Chandler Carruth 22d09f7f25 Add C++ compile benchmarking (#7220)
We had source generation support for some time, but needed to get all
the runtimes set up correctly so that standard library headers are
available. Now that this is in place, we can benchmark both languages.

Also fixes a bug in the C++ source generation causing compile failures.

Assisted-by: Antigravity with Gemini
2026-05-18 23:31:14 +00:00
Richard Smith 76f7025d68 Support use of Carbon toolchain as a bazel module (#7223)
Use `Label` to mark labels that are local to this module. Remove
workspace root when forming manifest. Add explicit import for name that
is not available implicitly in an imported module.

Assisted-by: Gemini via Antigravity
2026-05-18 20:46:46 +00:00
Richard Smith b87f848db4 Fix passing mode computation for methods. (#7225)
We were incorrectly computing the index of the Clang implicit conversion
corresponding to method arguments. This led to wrong code and a crash in
lowering due to a calling convention mismatch.

Fixes #7224.

Assisted-by: Gemini via Antigravity
2026-05-18 20:30:23 +00:00
Nicholas Bishop 773ecdfac6 Implement static var class fields (#7215)
This adds the `static` token to the lexer and parses it as a modifier.

In check, `FullPatternStack::Kind::FieldDecl` is now used for both
static and non-static vars. Static vars get treated basically the same
as `NameBindingDecl`s.

Global initialization is used for static var initializers. To make the
necessary stack information available to `pattern_match.cpp`, the
`full_pattern_stack` and `decl_introducer_state_stack` are now popped
later in `handle_let_and_var.cpp`.

In lowering, each class's body is checked for `VarStorage` insts and
lowered the same as global vars.
2026-05-18 20:09:17 +00:00
David Blaikie 31db4a0931 Export virtual/abstract/override functions as virtual (#7211)
This provides enough to Clang so it can include these new virtual
functions in the vtable of Carbon types derived from C++ types.
2026-05-18 19:04:33 +00:00
josh11bandJosh L 832d46f01b Update LLVM (#7221)
Assisted-by: Google Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-05-18 17:06:58 +00:00
josh11bandJosh L 4f2b3b644c Support jj workspaces in suggested jj abandon-untagged alias (#7222)
`@` refers to the current workspace's working copy, but if we want the
command to respect the working copies of other workspaces, we should use
`working_copies()` instead; see
https://docs.jj-vcs.dev/latest/revsets/#functions .

Also remove `all() &` while here, since it is always redundant.

Assisted-by: Google Antigravity

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2026-05-17 23:03:22 +00:00
f0aa561bd6 Support jj workspaces (#7219)
In particular, bazel builds would previously fail in
`workspace_status.py` if you didn't have a `.git` with this error:

> ```
> ERROR: <builtin>: BazelWorkspaceStatusAction stable-status.txt failed:
Failed to determine workspace status: Process exited with status 1
> fatal: not a git repository (or any of the parent directories): .git
> ```

Assisted-by: Google Antigravity

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-05-17 03:38:31 +00:00
David BlaikieandRichard Smith 843323b864 Export virtual functions when exporting a class definition (#7210)
This allows Clang to correctly generate the vtable for the exported
class.

There's still something wrong with new virtual functions in the Carbon
type (left a TODO) - I thought it might be related to not flagging
the CXXMethodDecl as virtual, but my initial experiments don't seem to
back that up, so I'll look into it further separately.

There's also a test regression due to an virtual (well, abstract
specifically, but I think it'd happen with a virtual one too) function
in an abstract class taking `self` by value being rejected since
the abstract class can't be instantiated. Not sure if this is a correct
change - the test's behavior could be preserved by using `ref self`
instnead of `self` in this function. Is that reasonable/expected? Should
we not require a type to be complete when passing by value if we can
compute the value representation without such completeness?

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-05-15 23:53:12 +00:00
Geoff Romer 6d5a883d6d Restructure scrutinee type handling (#7216)
This change avoids situations where a variable might be either a pattern
type or a scrutinee type, depending on the pattern matching state, and
makes it clear that the state only affects which specific is selected.
2026-05-15 21:10:40 +00:00
Dana Jansens ed1a949b47 Resolve nested ImplWitnessAccesses in rewrite constraints (#7213)
We were assuming that a nested access meant that we'd resolve the outer
one, then the inner one. But it may be that we can just resolve the
entire nested access together. Previously if we encountered this, it led
to a CHECK failure. Now we correctly resolve it.
2026-05-15 20:31:28 +00:00
Chandler Carruth e041afd98d Centralize benchmarking infrastructure and the toolchain-wide benchmarks (#7212)
The benchmarks themselves aren't really specific to `driver`.

Keeping the source generation near to the primary use case of
benchmarking also seems like a more discoverable location.

I feel a little bad doing this reorganization right after I gave a talk
with links to a bunch of this code, but seems good to reorganize a bit
before doing some work to extend things now that we have full standard
library support for C++ benchmarking and other improvements.

Assisted-by: Antigravity with Gemini
2026-05-15 20:17:23 +00:00
Dana Jansens 42a4dba9fd Makes impls constraints available to use in later constraints within a facet type (#7209)
If a facet type contains `.X impls Y` then later references to `.X`
should know that it impls `Y`. This is done through a stack on the
context like for rewrites, where impl lookup can find constraints from
the current `where` expression being checked.

Similarly, if a facet type contains `.X impls (Y where .Z = T)`, then
`.X.(Y.Z) = T` should be available to later constraints in the facet
type for early application of rewrite rules. We add these rewrites to
the rewrite stack when handling the `impls` constraint
2026-05-15 18:53:51 +00:00
Dana Jansens 835a61c385 Gracefully handle a concrete ImplWitnessAccess in the type structure (#7214)
While this can only happen when some other error is taking place, we
should handle it gracefully and report a concrete (but unmatchable)
value in the type structure instead of CHECK-failing.
2026-05-15 14:53:51 +00:00
Richard Smith dd47e41da6 Fix calls to functions with const T&& parameters. (#7208)
This also fixes passing a value expression to a forwarding reference,
since we currently deduce a `const T&&` parameter in that case.

We were accidentally looking at the type of the thunk parameter (which
is never an rvalue reference) rather than the type of the callee
parameter.
2026-05-14 20:22:32 +00:00
Dana Jansens 8e371c380a Use impl's interface to get the specific interface from the identified facet type (#7201)
Instead of doing a lookup for the identified facet type from the impl's
self+constraint, we can use `impl.interface` to get the specific
interface being implemented by the impl declaration. This is already the
specific interface returned from the identified facet type. And that
means we no longer have to identify the self+constraint for imported
impls.

This is split out from
https://github.com/carbon-language/carbon-lang/pull/7183#discussion_r3230571153
2026-05-14 19:34:23 +00:00
Dana Jansens 417531f484 Use early rewrites in compound member access (#7207)
We replace the non-canonical ImplWitnessAccess instruction with an
ImplWitnessAccessSubstituted instruction containing the RHS of a prior
rewrite constraint in the same facet type when possible, in order to
access the value of the prior constraint. We were doing this only in the
designator access path though, not in the compound member access. Join
these two code paths when they construct the ImplWitnessAccess, and
perform the early access there for both.
2026-05-14 16:37:50 +00:00
Chandler Carruth d010d52f37 Switch the ValueStore-related templates to use explicit instantiation (#7116)
As part of this, move functions that seem reasonable to make out-of-line
to a separate `_impl.h` header file that is only included where the
explicit instantiation _definition_ is provided.

By using explicit instantiation we can make these templates behave more
like non-template classes in terms of supporting out-of-line definitions
that don't need to be compiled by every translation unit. The set of
eventual instantiations here is fundamentally known, and there tend to
be headers that define a canonical "leaf" type where it makes sense to
trigger the explicit instantiation.

Where we already had a `.cpp` file to put the explicit instantiation
definition, use it. But in some places we didn't have such a `.cpp` file
so this PR adds those.

This also requires that we have precise constraints on APIs that _can't_
be instantiated for specific argument types, as now we don't do this
lazily.

Combined, this appears to reduce the sum of object file sizes in the
`check` directory by almost 40% (122mb -> 74mb) in my measurement.

My actual goal was to improve compile times, but so far I don't have a
great methodology for measuring these... But the object file size
reduction seems to confirm this is a net win and likely represents a
non-trivial improvement in compile time.

Assisted-by: Antigravity with Gemini
2026-05-14 08:29:17 +00:00
Richard Smith c9d8b59bbd Handle "gaps" in C++ vtables. (#7206)
Not every entry in a C++ vtable corresponds to a function that we want
to import. For the holes, leave a `SemIR::InstId::None` in the vtable.
Also mark vtables that extend a C++ vtable as being non-Carbon-native so
we don't try to lower them (and crash on the `None` entries).

In particular, we leave holes for destructors, since we don't have
destructor declarations on the Carbon side that need to override them.
2026-05-14 00:38:24 +00:00
Nicholas Bishop bd918fb33b Parse vars in classes the same as vars in other locations (#7188)
Class vars are still restricted to simple `name: type` bindings, not
full patterns. This is now handled in the check phase instead of during
parsing.

This is in preparation for supporting `static var`.
2026-05-13 21:22:46 +00:00
Dana Jansens 5706601096 Replace .Self in the self type of T(.Self) impls NamedConstraint when identifying a facet type (#7204)
Given this example function:

```carbon
fn F(T:! Z where .Self imps Y(.Self) and E(.Self) impls X(.Self)) {
  T as Y(T);
  E(T) as X(T);
}
```

When we identify the facet type of `T`, we replace `.Self` with `T`.
However in the initial loop, the self _is_ `T` so we don't want to
substitute `.Self` instances inside `T` with itself, as that creates
cycles.

When we see a `type impls...` constraint such as `E(.Self)` we now have
a different self-type so we can, and want to, substitute the `.Self` in
it with `T`. This was already being done, unless the RHS of the `impls`
was a named constraint. In that case we forgot that we were in a `type
impls...` constraint, and avoided replacing `.Self`. Now the algorithm
remembers and correctly replaces `.Self` for `type impls named
constraint` constraints in a facet type.
2026-05-13 18:49:02 +00:00
Chandler Carruth 2047e08635 Update examples throughout the design for p7016 (#7200)
Also updates a few spots with some subtle aspects changed in
`lambdas.md` and `namespace_cleanliness.md`.

Assisted-by: Antigravity with Gemini
2026-05-13 18:42:55 +00:00
Dana Jansens 77f1d93369 Avoid replacing .Self in designators more robustly in rewrite constraints (#7202)
When replacing `.Self` in a facet type we don't want to destroy the
structure of designators in rewrite constraints so that rewrite
constraint resolution and other similar code can still find them. We
were doing this only for the LHS, and for the RHS if it was a standalone
designator, like `.X = .Y` but we want to do this more robustly to also
avoid rewrite the `.Self` in `.Y` in the expression `.X = C(.Y)`. This
allows resolution, and ImplWitnessAccess to recognize the designator and
replace the `.Y` with the RHS value of another rewrite constraint
assigning to `.Y`.
2026-05-13 18:24:31 +00:00
Richard Smith 917856aff7 Export Carbon classes as base / final / abstract. (#7191)
* For Carbon `base class C`, export as a regular C++ class.
* For Carbon `class C`, export with the C++ `final` keyword attribute.
* For Carbon `abstract C`, mark the destructor as pure virtual in cases
where no member function is abstract, or emit an error if the destructor
is not virtual.

To support the final point, mark the destructor of an exported class as
virtual if it overrides a virtual destructor from the base class.

In passing, fix a crash exporting fields if the class has an invalid
base type.
2026-05-13 17:48:55 +00:00
Richard Smith c33fb9fc48 Support signature mismatch between virtual fn and override fn. (#7198)
For now, hide `override fn`s from name lookup, so that the base class
version is always used, as the derived-class version does not have its
own vptr entry and so would not do the right thing if a further-derived
class adds a new override. This is implemented via a new access kind of
`Hidden`.

When checking the overriding function, pass in the expected `Self` type
and check the `self` parameter against that; the signature that we
generate for the thunk in the derived class is the base class signature
with the `self` parameter's type changed to the derived class.

When we generate a thunk for a virtual function, the thunk is assigned a
`virtual_index`, and the virtual function itself is not. When the thunk
makes a direct call to the virtual function, recognize this situation by
checking for a `virtual_index`, and perform a non-virtual call if there
isn't one.

Assisted-by: Gemini via Antigravity
2026-05-13 17:40:45 +00:00
Dana Jansens 0b47efa57a Don't re-require complete types for extended scopes (#7194)
When an outer type defines an `extend` relationship to an inner type, we
require that inner type to be complete so that we can know that name
lookup can search both scopes as soon as the outer type is complete.

When doing name lookup, we require the type in which we are looking to
be complete. Then, we recursively add extended scopes, but then also
require each of them to be complete again, which inserts
RequireCompleteType instructions into the block doing lookup.

While these new instructions may differ in terms of their specifics,
they are redundant since we already required the type to be complete,
and specifics can not change the completeness of a type. They are also
problematic because a named constraint or interface can extend a scope
with a symbolic specific, by using `Self` as an argument. This inserts a
symbolic instruction into the block doing name lookup, even though that
block may not be generic.
2026-05-13 17:16:02 +00:00
Dana JansensandRichard Smith 6326bbdbe1 Resolve cycles in .Self replacement in nested designators (#7183)
A nested designator like `.(X.X1).(Y.Y1)` results in nested
ImplWitnessAccess instructions, which can produce cycles in the
toolchain easily when replacing `.Self`.

First, when constructing a facet type like `V:! Z where .Z1 impls (Y
where .Y1 = U)` we substitute replace `.Self` in the nested facet type,
and in this case we replace `.Self` with `.Z1` which contains a `.Self`
of its own. This was coming from us being lazy about replacing `.Self`
in an `impl as` declaration, such as `impl C as Z where .Z1 = .Self`.
The self type is known there, so we can more eagerly replace `.Self` as
we do in a `require impls` declaration. Then the replacement for `.Self`
never comes with a `.Self` that needs to also be replaced. Any resulting
`.Self` would always be the top-level one.

Second, when evaluating ImplWitnessAccess, we were replacing .Self in
the LHS of rewrite constraints, but the `.Self` may itself have a type
that contains rewrite constraints. If one of those rewrite constraints
has nested ImplWitnessAccess instructions, we evaluate the new
ImplWitnessAccess, which again finds rewrite constraints to replace
`.Self` in, and we repeat forever. For this one we just stop replacing
.Self in the LHS of rewrite constraints. Since they are always against
.Self, we can always look in the access facet's type for a value.

While fixing ImplWitness access, also correct the lookup to search
through the types of nested ImplWitnessAccess instructions to find a
rewrite value, since it may find it at any level up to the eventual
`.Self`.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-05-13 16:11:20 +00:00
Richard Smith 798b177fc0 Tidy up virtual method tests. (#7196)
Move the tests from `class/` to `class/method` and add SemIR dump
ranges.
2026-05-13 13:58:14 +00:00
Richard Smith 71ba07239f Support pass-by-move when calling a C++ function taking by value. (#7135)
Previously, we picked a single Carbon parameter pattern for each C++
parameter pattern. This doesn't work well in cases where the Carbon
semantics and the C++ semantics are not perfectly aligned. In
particular, when a parameter is passed by value in C++, that might mean
either pass-by-move (which in Carbon would best be modeled by a `var`
pattern, as no other form of parameter would perform a move) or
pass-by-copy (which in Carbon would best be modeled by a value
parameter, as a `var` parameter would force an extra copy).

After this change, we compute a passing mode for each parameter based on
the implicit conversion sequence from the argument to the parameter as
determined by C++ overload resolution, and use that to determine the
Carbon pattern corresponding to each C++ parameter. This results in
potentially generating multiple different thunks for the same C++
function if it's called in different ways, but we already did that to
handle default arguments and list-initialization. The passing modes are
included in the thunk mangling.

Add a new value store for clang decl signatures, which capture the
information about parameter passing mode as well as the other existing
information about different ways that a C++ function might be imported
to Carbon.

Most of the rules for computing passing modes are the same as before:
const references use pass by value, non-const lvalue references use
pass-by-ref, non-const rvalue references use pass-by-var. But for C++
non-reference parameters, pick between pass-by-value and pass-by-var
based on whether the implicit conversion sequence was effectively
performing a copy. Prefer pass-by-value if either would work and they'd
do the same thing. We still use pass-by-value for const references, even
when the argument is an lvalue and we could pass a reference; we may
want to change this in future.

For virtual functions, we try to pick a worst-case passing mode, as we
can only pick a single signature for what goes in the vtable. Calls to
virtual functions will still use a thunk to C++, allowing variance in
the calling convention at call sites. We don't allow variance in the
overriders as we don't implement support for thunks for virtual
functions yet. We currently use pass-by-value for const reference
parameters here, but that should probably change at some point.

Assisted-by: Gemini via Antigravity
2026-05-13 01:44:07 +00:00
10b2b71847 Updating self syntax and adding static member variables (#7016)
Update the syntax for class (and interface/`impl`) methods to move
`self` into
the parameter parentheses `()` and make the type in its binding optional
(defaulting to `Self`). Introduce the `static` keyword for non-instance
member
variables to indicate static storage. Reflects the decision in leads
issue
[#6931](https://github.com/carbon-language/carbon-lang/issues/6931).

Updates the directly relevant design, but leaves a systematic update of
examples
to a future PR.

Assisted-by: Antigravity with Gemini

---------

Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-05-13 01:30:44 +00:00
Dana Jansens 71eed5b04a Add tests that demonstrate missing diagnostics for impl as a named constraint (#7195)
Any non-extend require decls must be satisfied when the impl definition
starts, but they are not checked. We only check for require decls in the
target interface being impld.
2026-05-12 22:15:09 +00:00
Christopher Di BellaandRichard Smith 2aaa061688 Support detecting begin()/end() methods for range-for loops (#7185)
This commit adds support for range-based for loops using C++ types. It's
currently limited to detecting that `r.begin()` and `r.end()` are
available. We should be able to add full support for methods after #7181
is merged.

Support for ADL is still a work-in-progress, and will be added at a
later time.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-05-12 19:03:55 +00:00
Richard Smith dd7cfdb149 Relax alias restrictions. (#7190)
Implement the alias rules from proposal #5389, wherein an alias is
permitted so long as the target has a constant value. While that
proposal is not yet accepted, this seems like a reasonable basis for
further iteration, and will be useful for the examples we're currently
pursuing.
2026-05-12 17:22:44 +00:00
Dana Jansens d4063cad65 Remove completed TODO in import test (#7193)
The generic args are now in the stringified name
2026-05-12 17:02:57 +00:00
dependabot[bot] f9ac672b8f Bump urllib3 from 2.6.3 to 2.7.0 in /github_tools in the pip group across 1 directory (#7187)
Bumps the pip group with 1 update in the /github_tools directory:
[urllib3](https://github.com/urllib3/urllib3).

Updates `urllib3` from 2.6.3 to 2.7.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.7.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>
<p>Addressed high-severity security issues. Impact was limited to
specific use cases detailed in the accompanying advisories; overall user
exposure was estimated to be marginal.</p>
<ul>
<li>
<p>Decompression-bomb safeguards of the streaming API were bypassed:</p>
<ol>
<li>When <code>HTTPResponse.drain_conn()</code> was called after the
response had been read and decompressed partially. (Reported by <a
href="https://github.com/Cycloctane"><code>@​Cycloctane</code></a>)</li>
<li>During the second <code>HTTPResponse.read(amt=N)</code> or
<code>HTTPResponse.stream(amt=N)</code> call when the response was
decompressed using the official <a
href="https://pypi.org/project/brotli/">Brotli</a> library. (Reported by
<a
href="https://github.com/kimkou2024"><code>@​kimkou2024</code></a>)</li>
</ol>
<p>See GHSA-mf9v-mfxr-j63j for details.</p>
</li>
<li>
<p>HTTP pools created using
<code>ProxyManager.connection_from_url</code> did not strip sensitive
headers specified in <code>Retry.remove_headers_on_redirect</code> when
redirecting to a different host. (GHSA-qccp-gfcp-xxvc reported by <a
href="https://github.com/christos-spearbit"><code>@​christos-spearbit</code></a>)</p>
</li>
</ul>
<h2>Deprecations and Removals</h2>
<ul>
<li>Used <code>FutureWarning</code> instead of
<code>DeprecationWarning</code> for better visibility of existing
deprecation notices. Rescheduled the removal of deprecated features to
version 3.0. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3763">urllib3/urllib3#3763</a>)</li>
<li>Removed support for end-of-life Python 3.9. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3720">urllib3/urllib3#3720</a>)</li>
<li>Removed support for end-of-life PyPy3.10. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4979">urllib3/urllib3#4979</a>)</li>
<li>Bumped the minimum supported pyOpenSSL version to 19.0.0. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3777">urllib3/urllib3#3777</a>)</li>
</ul>
<h2>Bugfixes</h2>
<ul>
<li>Fixed a bug where <code>HTTPResponse.read(amt=None)</code> was
ignoring decompressed data buffered from previous partial reads. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3636">urllib3/urllib3#3636</a>)</li>
<li>Fixed a bug where <code>HTTPResponse.read()</code> could cache only
part of the response after a partial read when
<code>cache_content=True</code>. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4967">urllib3/urllib3#4967</a>)</li>
<li>Fixed <code>HTTPResponse.stream()</code> and
<code>HTTPResponse.read_chunked()</code> to handle <code>amt=0</code>.
(<a
href="https://redirect.github.com/urllib3/urllib3/issues/3793">urllib3/urllib3#3793</a>)</li>
<li>Updated <code>_TYPE_BODY</code> type alias to include missing
<code>Iterable[str]</code>, matching the documented and runtime behavior
of chunked request bodies. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3798">urllib3/urllib3#3798</a>)</li>
<li>Fixed <code>LocationParseError</code> when paths resembling
schemeless URIs were passed to
<code>HTTPConnectionPool.urlopen()</code>. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3352">urllib3/urllib3#3352</a>)</li>
<li>Fixed <code>BaseHTTPResponse.readinto()</code> type annotation to
accept <code>memoryview</code> in addition to <code>bytearray</code>,
matching the <code>io.RawIOBase.readinto</code> contract and enabling
use with <code>io.BufferedReader</code> without type errors. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3764">urllib3/urllib3#3764</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.7.0 (2026-05-07)</h1>
<h2>Security</h2>
<p>Addressed high-severity security issues.
Impact was limited to specific use cases detailed in the accompanying
advisories; overall user exposure was estimated to be marginal.</p>
<ul>
<li>
<p>Decompression-bomb safeguards of the streaming API were bypassed:</p>
<ol>
<li>When <code>HTTPResponse.drain_conn()</code> was called after the
response had been
read and decompressed partially.</li>
<li>During the second <code>HTTPResponse.read(amt=N)</code> or
<code>HTTPResponse.stream(amt=N)</code> call when the response was
decompressed
using the official <code>Brotli
&lt;https://pypi.org/project/brotli/&gt;</code>__ library.</li>
</ol>
<p>See <code>GHSA-mf9v-mfxr-j63j
&lt;https://github.com/urllib3/urllib3/security/advisories/GHSA-mf9v-mfxr-j63j&gt;</code>__
for details.</p>
</li>
<li>
<p>HTTP pools created using
<code>ProxyManager.connection_from_url</code> did not strip
sensitive headers specified in
<code>Retry.remove_headers_on_redirect</code> when
redirecting to a different host.
(<code>GHSA-qccp-gfcp-xxvc
&lt;https://github.com/urllib3/urllib3/security/advisories/GHSA-qccp-gfcp-xxvc&gt;</code>__)</p>
</li>
</ul>
<h2>Deprecations and Removals</h2>
<ul>
<li>Used <code>FutureWarning</code> instead of
<code>DeprecationWarning</code> for better
visibility of existing deprecation notices. Rescheduled the removal of
deprecated features to version 3.0.
(<code>[#3763](https://github.com/urllib3/urllib3/issues/3763)
&lt;https://github.com/urllib3/urllib3/issues/3763&gt;</code>__)</li>
<li>Removed support for end-of-life Python 3.9.
(<code>[#3720](https://github.com/urllib3/urllib3/issues/3720)
&lt;https://github.com/urllib3/urllib3/issues/3720&gt;</code>__)</li>
<li>Removed support for end-of-life PyPy3.10.
(<code>[#4979](https://github.com/urllib3/urllib3/issues/4979)
&lt;https://github.com/urllib3/urllib3/issues/4979&gt;</code>__)</li>
<li>Bumped the minimum supported pyOpenSSL version to 19.0.0.
(<code>[#3777](https://github.com/urllib3/urllib3/issues/3777)
&lt;https://github.com/urllib3/urllib3/issues/3777&gt;</code>__)</li>
</ul>
<h2>Bugfixes</h2>
<ul>
<li>Fixed a bug where <code>HTTPResponse.read(amt=None)</code> was
ignoring decompressed
data buffered from previous partial reads.
(<code>[#3636](https://github.com/urllib3/urllib3/issues/3636)
&lt;https://github.com/urllib3/urllib3/issues/3636&gt;</code>__)</li>
<li>Fixed a bug where <code>HTTPResponse.read()</code> could cache only
part of the
response after a partial read when <code>cache_content=True</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/9a950b92d999f906b6020bb2d1076ee56cddd5d2"><code>9a950b9</code></a>
Release 2.7.0</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/5ec0de499b9166ca71c65ab04f2a7e4eb0d66fcc"><code>5ec0de4</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/2bdcc44d1e163fb5cc48a8662425e35e15adfe6a"><code>2bdcc44</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/f45b0df09d8620ac6ed0491eb9362c8c87b7bc2c"><code>f45b0df</code></a>
Fix a misleading example for <code>ProxyManager</code> (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4970">#4970</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/577193ca029872384f82c133449e0935f6d8a64b"><code>577193c</code></a>
Switch to nightly PyPy3.11 in CI for now (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4984">#4984</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/e90af45bb006c3a452a3a21644a2681523f5c7fc"><code>e90af45</code></a>
Avoid infinite loop in <code>HTTPResponse.read_chunked</code> when
<code>amt=0</code> (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4974">#4974</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/67ed74fdaec6659a6534621ec8e3aaaa6f976210"><code>67ed74f</code></a>
Bump dev dependencies (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4972">#4972</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/3abd481097b54d87b574ac7ea593c3f40938a84d"><code>3abd481</code></a>
Upgrade mypy to version 1.20.2 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4978">#4978</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/2b8725dfcac4f21d4d93cc0cc3a64a33af08f890"><code>2b8725d</code></a>
Drop support for EOL PyPy3.10 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4979">#4979</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/2944b2a0a6c573f5548a39cfd17196f98ee21b33"><code>2944b2a</code></a>
Upgrade <code>setup-chrome</code> and <code>setup-firefox</code> to fix
warnings (<a
href="https://redirect.github.com/urllib3/urllib3/issues/4973">#4973</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/urllib3/urllib3/compare/2.6.3...2.7.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.6.3&new-version=2.7.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-05-12 05:29:46 +00:00
Chandler Carruth 5347a865f8 Remove some more checks that are noisy in our codebase. (#7189)
Assisted-by: Antigravity with Gemini
2026-05-11 19:01:24 +00:00
Chandler CarruthandDana Jansens b5a1688c85 Add check/dump.cpp functions for the new ones in sem_ir (#7126)
Also cleans up redundant code in the `sem_ir` dump methods that I missed
initially. Now we share as much logic as we can for dumping the non-ID
and ID components.

Assisted-by: Antigravity with Gemini

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-05-11 18:22:31 +00:00
David Blaikie df8b25522e Import C++ vtables (#7174)
This correctly renders the vtable in SemIR, including allowing overrides
in
Carbon-derived-from-C++ classes.

It doesn't work in lowering because clang walks the methods of the
CXXRecordDecl - and we currently don't export anything into the
CXXRecordDecl's methods (we do export the fields) - so that's next.

This also doesn't teach Clang to affirmatively emit the vtable
regardless of the types use in C++ code - or to have Carbon use the
vtable in an object's initialization.
2026-05-11 17:33:08 +00:00
David Blaikie 0f5de499d6 Roundtrip (export/reimport) class declarations (#7182)
Roundtrip (export/reimport) class declarations

The remapping was previously implemented using name_scopes, which aren't
created for class declarations, only definitions - causing the reimport
to import a fresh copy of the type that mismatched with the original (as
seen in the test baseline).

By changing the mapping to use the reverse part of the clang_decls
mapping this should generalize better (& we probably should further
migrate to that mapping). Though it did trip over some issue with
exactly which instruction is used as the key in the clang_decls map -
this change moves towards standardizing on the first decl id of the
class as its map key.
2026-05-11 16:35:47 +00:00
Dana Jansens eea1e58376 Correctly handle ImplWitnessAccess in impl lookup (#7181)
We were treating ImplWitnessAccess as a concrete type, but that is
incorrect if its accessing a symbolic type value. This results in
concrete impl lookup queries failing to match a generic impl that is
built with a symbolic ImplWitnessAccess in its type structure, when the
query does not have the equivalent ImplWitnessAccess in its own type
structure.

We need to look in the top level facet being accessed through
ImplWitnessAccess for witnesses, such as in `T:! Z where .Z1 impls Y`
where `T` provides the witness for `T.Z1 as Y`. But we also need to look
in the facet type of the ImplWitnessAccess for witnesses, such as in
`T:! Z` for `interface Z { let Z1:! Y }`, where `T.Z1` provides the
witness for `T.Z1 as Y`.

To support that we give TypeIterator an iteration step for
ImplWitnessAccess before recursing into it, like we do for FacetValue.

While doing this, we make TypeIterator more recursive, by making less
special casing around the step from one inst into the next. Instead of
eagerly finding a SymbolicType, we consistently recurse back into the
big switch statement and have it decide the next iteration step. This
allows it to recurse into instructions like ImplWitnessAccess and
FacetValue in a consistent manner.
2026-05-11 14:17:18 +00:00
Christopher Di Bella 219d1cdee1 Teach comparison interfaces about C++ operators (#7163) 2026-05-10 21:54:50 +00:00
dependabot[bot] 7c44c4dfb0 Bump fast-uri from 3.1.0 to 3.1.2 in /utils/vscode in the npm_and_yarn group across 1 directory (#7184)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [fast-uri](https://github.com/fastify/fast-uri).

Updates `fast-uri` from 3.1.0 to 3.1.2
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/fastify/fast-uri/releases">fast-uri's
releases</a>.</em></p>
<blockquote>
<h2>v3.1.2</h2>
<h2>⚠️ Security Release</h2>
<ul>
<li>Fix for <a
href="https://github.com/fastify/fast-uri/security/advisories/GHSA-v39h-62p7-jpjc">https://github.com/fastify/fast-uri/security/advisories/GHSA-v39h-62p7-jpjc</a></li>
</ul>
<h2>What's Changed</h2>
<ul>
<li>Handle malformed fragment decoding as a parse error by <a
href="https://github.com/mcollina"><code>@​mcollina</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/171">fastify/fast-uri#171</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/fastify/fast-uri/compare/v3.1.1...v3.1.2">https://github.com/fastify/fast-uri/compare/v3.1.1...v3.1.2</a></p>
<h2>v3.1.1</h2>
<h2>⚠️ Security Release</h2>
<ul>
<li>Fix for <a
href="https://github.com/fastify/fast-uri/security/advisories/GHSA-q3j6-qgpj-74h6">https://github.com/fastify/fast-uri/security/advisories/GHSA-q3j6-qgpj-74h6</a></li>
</ul>
<h2>What's Changed</h2>
<ul>
<li>build(deps-dev): bump tsd from 0.32.0 to 0.33.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/148">fastify/fast-uri#148</a></li>
<li>build(deps): bump actions/checkout from 4 to 5 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/149">fastify/fast-uri#149</a></li>
<li>chore(.npmrc): ignore scripts by <a
href="https://github.com/Fdawgs"><code>@​Fdawgs</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/150">fastify/fast-uri#150</a></li>
<li>build(deps-dev): remove <code>@​fastify/pre-commit</code> by <a
href="https://github.com/Fdawgs"><code>@​Fdawgs</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/151">fastify/fast-uri#151</a></li>
<li>build(deps): bump actions/setup-node from 4 to 5 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/152">fastify/fast-uri#152</a></li>
<li>ci(ci): add concurrency config by <a
href="https://github.com/Fdawgs"><code>@​Fdawgs</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/153">fastify/fast-uri#153</a></li>
<li>build(deps): bump actions/setup-node from 5 to 6 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/154">fastify/fast-uri#154</a></li>
<li>build(deps): bump actions/checkout from 5 to 6 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/156">fastify/fast-uri#156</a></li>
<li>chore(license): standardise license notice by <a
href="https://github.com/Fdawgs"><code>@​Fdawgs</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/159">fastify/fast-uri#159</a></li>
<li>style: remove trailing whitespace by <a
href="https://github.com/Fdawgs"><code>@​Fdawgs</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/161">fastify/fast-uri#161</a></li>
<li>ci: remove unused github files by <a
href="https://github.com/Tony133"><code>@​Tony133</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/162">fastify/fast-uri#162</a></li>
<li>chore: update readme by <a
href="https://github.com/Tony133"><code>@​Tony133</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/164">fastify/fast-uri#164</a></li>
<li>build(deps): bump
fastify/workflows/.github/workflows/plugins-ci-package-manager.yml from
5 to 6 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/165">fastify/fast-uri#165</a></li>
<li>build(deps): bump fastify/workflows/.github/workflows/plugins-ci.yml
from 5 to 6 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/166">fastify/fast-uri#166</a></li>
<li>build(deps-dev): bump neostandard from 0.12.2 to 0.13.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot]
in <a
href="https://redirect.github.com/fastify/fast-uri/pull/167">fastify/fast-uri#167</a></li>
<li>ci: add lock-threads workflow by <a
href="https://github.com/Fdawgs"><code>@​Fdawgs</code></a> in <a
href="https://redirect.github.com/fastify/fast-uri/pull/169">fastify/fast-uri#169</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/Tony133"><code>@​Tony133</code></a> made
their first contribution in <a
href="https://redirect.github.com/fastify/fast-uri/pull/162">fastify/fast-uri#162</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/fastify/fast-uri/compare/v3.1.0...v3.1.1">https://github.com/fastify/fast-uri/compare/v3.1.0...v3.1.1</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/fastify/fast-uri/commit/919dd8ea7689fcc220d0d9b71307f5095e723ef9"><code>919dd8e</code></a>
Bumped v3.1.2</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/c65ba573714af6b8e19e481d9444c27bc4355d07"><code>c65ba57</code></a>
fixup: linting</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/6c86c17c3d76fb93aa3700ec6c0fa00faeb97293"><code>6c86c17</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/a95158ad308df4d92bbde4eba699ce5165e9f796"><code>a95158a</code></a>
Handle malformed fragment decoding without throwing (<a
href="https://redirect.github.com/fastify/fast-uri/issues/171">#171</a>)</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/cea547c91c6aae610041b17b75792ca4aa035a6d"><code>cea547c</code></a>
Bumped v3.1.1</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/876ce79b662c3e5015e4e7dffe6f37752ad34f35"><code>876ce79</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/dcdf690b71a7bb3a19887ada65a9ab160d83bcc0"><code>dcdf690</code></a>
ci: add lock-threads workflow (<a
href="https://redirect.github.com/fastify/fast-uri/issues/169">#169</a>)</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/c860e6589b1ac346f66e114b4eadb9613768108c"><code>c860e65</code></a>
build(deps-dev): bump neostandard from 0.12.2 to 0.13.0 (<a
href="https://redirect.github.com/fastify/fast-uri/issues/167">#167</a>)</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/9b4c6dc82fde0ca44e674403ece9185d85bb6d5f"><code>9b4c6dc</code></a>
build(deps): bump fastify/workflows/.github/workflows/plugins-ci.yml (<a
href="https://redirect.github.com/fastify/fast-uri/issues/166">#166</a>)</li>
<li><a
href="https://github.com/fastify/fast-uri/commit/85d09a9f7aa76b32c2bb005a90a71e144c361d24"><code>85d09a9</code></a>
build(deps): bump
fastify/workflows/.github/workflows/plugins-ci-package-mana...</li>
<li>Additional commits viewable in <a
href="https://github.com/fastify/fast-uri/compare/v3.1.0...v3.1.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=fast-uri&package-manager=npm_and_yarn&previous-version=3.1.0&new-version=3.1.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-05-09 05:56:05 +00:00
9fb0e4a7ae Add sufficiency of declaration to the information accumulation principle (#7179)
Adding to the information accumulation principle instead of creating new
principle #5990.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2026-05-08 22:38:34 +00:00
Viktor 8d907e857e Add regression test for var parameter cleanup from struct literals (#7175)
`param.carbon` already tests cleanup when passing a class value produced
by
`C.Make()` to a `var` parameter. Add the corresponding struct literal
case,
`F({})`, matching the repro from #7168

The issue appears to already be fixed on main so this adds a test to
make sure
the compiler keeps calling `Core.Destroy` for the temporary value after
`F({})`
returns

Closes #7168

Assisted-by: Qwen 3.6
2026-05-08 19:13:52 +00:00
Lucile Rose Nihlen bc1ae703c3 return 0 from Run when it doesn't specify a return value (#7180)
https://carbon.compiler-explorer.com/z/88K9Kh5Wo shows the program
exiting with a garbage value copied from uninitialized memory.

This PR modifies `lower` to detect if the function lowered is the
entry point and doesn't specify a return type. If so, it emits
different LLVM IR to return int32 0, and modifies the lowered
function signature to match the int32 return type.
2026-05-08 19:00:47 +00:00
Christopher Di Bella 3e36f7d43c Replace manual CoreInterface tables with x-macros (#7176)
Manually filling out tables involving `CoreInterface` is error-prone,
especially when switching on strings, which the compiler can't warn on.
2026-05-08 05:47:38 +00:00
Dana Jansens a19a6ab6d1 Search all facets in the impl lookup query for witnesses (#7178)
This enables searching facets like `T:! Z where .Z1 impls Y` for queries
like `T.Z1 as Y`, etc.

Any facet in the query self or the query target type may provide a
witness for the requirements of the impl lookup, so search through them
all.

We accept partially identified facet types in the query self, since
`Self` can be used inside a named constraint before it's fully
identified. But any use of `Self` being converted would put it in the
query self, not the query target, which would be some generic parameter
facet type that a type involving `Self` is being converted to.

TypeIterator is expanded to support this use case, by giving it the
ability to walk through FacetType's extend/impls constraints. We return
the facet values that we find in the iterator instead of a type id. And
we also include FacetValue instructions as an iterator step for clients
that want them, while also recursing through them.
2026-05-07 22:33:47 +00:00
Richard Smith bc06f6c5ec Mangle the signature decl when mangling a thunk. (#7177)
Fixes mangling collisions when two thunks with the same name (eg, `Op`)
are created in the same context, which in turn would lead to LLVM
verifier failures and miscompiles.

To support this, add a new value store to track a little more
information about thunks beyond what's in the `Function`.
2026-05-07 21:58:29 +00:00
Geoff Romer 031ec0a140 Implement BundleStore (#7173)
See
[here](https://docs.google.com/document/d/1eWW8MTko3PIqxZ32-GhsdaRSYqoDicxMB1VeessMTOg/edit?tab=t.0#heading=h.igl2myxbaf58)
for the background and design. The only usage of `BundleStore` in this
PR is artificial, but I'm working on a PR involving an action inst with
3 arguments, which requires something like `BundleStore`.
2026-05-07 19:42:23 +00:00
Dana Jansens 6776e2b804 Detect impl redecls in non-declarative scopes (#7170)
Avoid crashing on the fact that block scopes have no related InstId. So
we can't push the InstId of the current scope in the ImplIntroducer
node, as it can be None. Instead we have to find the parent InstId when
we're building the ImplDecl, because the ImplDecl has a node at the top
of the scope stack for the DeclNameStack.

Impls are allowed in sequential (non-declarative) scopes (functions,
blocks), but [redeclarations are not
allowed](https://github.com/carbon-language/carbon-lang/blob/db24042fe56d22275aa801696e2f8f5c4171e35b/proposals/p3763.md?plain=1#L279).
We now diagnose these redecls as invalid.
2026-05-07 13:44:40 +00:00
Geoff Romer daebbf32fa Restructure ArgAndKind as a type-safe generic ID. (#7172)
The key changes here are:
- Relocating and renaming it to align with `IdKind` (and relocating
`ToRaw` and `FromRaw` to follow it).
- Adding a `Dispatch` method that provides a generic overload-based API
for expressing per-ID-kind dispatch, and rewriting existing code to use
it.

Note in particular that using overloads instead of switch cases makes it
possible to generically handle all specializations of a templated ID
type, e.g. `SomeIdType<T>` for all `T`. We have no such templated ID
types yet, but I'm introducing one in a follow-up PR that needs this
capability.
2026-05-07 00:13:52 +00:00
Dana Jansens db24042fe5 Diagnose overlapping impls in the api/impl files of the same library (#7164)
An `impl` decl in an impl file can refer only to things defined in the
api file, without the orphan rule rejecting it. If they are in different
scopes (such as one being in a class and one not), then they are treated
as separate `impl` decls. But if they have the same type structure, then
they fully overlap which is an error unless they are in a match_first
block.

This catches the overlap when two `impl` decls are in the same library
but are split between the api and the impl file of the library.
Previously we only diagnosed if they were in the same _file_ but now we
diagnose if they are in the same _library_.
2026-05-06 14:17:54 +00:00
Richard Smith 341901e337 Fix crash if an inst in a pending block needs a cleanup. (#7166)
Insert the cleanup if and when the pending block is inserted, not
eagerly. And if the pending block is inserted by overwriting an existing
instruction, create a cleanup for that instruction rather than for the
instruction in the pending block that we are discarding.

Assisted-by: Gemini via Antigravity
2026-05-04 21:50:13 +00:00
Nicholas Bishop 1bc329af14 Support calling Carbon destructors from C++ (#7143)
A destructor is added to the C++ class definition in
`CarbonExternalASTSource::CompleteType`. The destructor calls a Carbon
function that calls the `Destroy` operator.
2026-05-04 20:28:58 +00:00
Dana Jansens f8dd4d85bf Do not treat impls in different scopes as redeclarations (#7161)
An impl in a different scope, with the same parameters, will overlap and
get diagnosed for that later by the [prioritization
rule](https://docs.carbon-lang.dev/docs/design/generics/details.html#prioritization-rule),
if they are not in a match_first block. But they are not considered as
redeclarations.

See [proposal
p5366](https://github.com/carbon-language/carbon-lang/blob/62b94f79322039acc3fc8e175896a64a32df470e/proposals/p5366.md)
for the rule.
2026-05-04 19:11:51 +00:00
Dana Jansens 4d1a61de29 Don't consider designators in a nested facet type as constraining the current type (#7139)
The design says:
> 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

A nested facet type in a constraint does not constrain the current type,
with the exception of the LHS of a nested `where` in an impls
constraint. Diagnose this appropriately by not recursing into unrelated
parts of nested facet types to look for designators.

Before this change, this facet type is accepted:
```carbon
fn F(unused T:! Z where C impls (Y where .Y1 = .Y2)) {}
```

But then no calls to `F` work, since the `.Y1` and `.Y2` designators are
never resolved to anything from the caller, as they do not depend on `T`
in any way.
2026-05-04 16:42:06 +00:00
Dana Jansens 4819e68dac Make choice to replace only implicit .Self or all into a parameter of SubstPeriodSelfCallbacks (#7133)
This avoids the need for a virtual method, and a class overriding it in
eval.
2026-05-04 14:52:00 +00:00
Dana Jansens 88931a4196 Give the .Self instruction a location (#7147)
This lets us stop eliding it in textual semir tests with dump ranges.
Previously it would always get elided, even though it was part of the
range being dumped, and was referred to by other instructions in the
dump range.

Since each `.Self` is unique (can change its type if not its value) in a
facet type, having each one distinct by location also aids
understanding.
2026-05-04 14:45:06 +00:00
Richard Smith c6253b93f9 Don't identify sibling PRs as dependencies. (#7145)
Also, when constructing the diff link, make sure we pick a commit that's
on the current PR's branch as the starting point. github wasn't able to
properly process the links we were creating before, if the last
dependency PR had commits that weren't on the current PR.

Fix a couple of tests that were broken by a prior change.

Assisted-by: Gemini via Antigravity
2026-05-02 01:12:04 +00:00
Richard Smith b784900305 Simplify struct literal pop loop. (#7158)
Assisted-by: Gemini via Antigravity
2026-05-02 01:09:50 +00:00
David Blaikie 071ab9f532 Import dynamic-ness of a C++ class (#7141) 2026-05-01 22:53:44 +00:00
Richard Smith b5877d8afa Factor out definition merging logic. (#7154)
Move logic to merge class and function definitions onto Class and
Function, matching how we handle merging for EntityWithParamsBase.

Assisted-by: Gemini via Antigravity
2026-05-01 22:45:22 +00:00
Dana Jansens 46bb0fecd4 Properly diagnose ambiguous .Self in T impls X where... (#7132)
A `where` expression nested inside a `T impls X` constraint makes
`.Self` ambiguous on the right-hand side of the `where` if `T` is
anything other than `.Self`. After the `where`, the value of a `.Self`
could be `T` or could be the value of `.Self` before the `impls`
constraint: the so-called top-level value of `.Self`.

Implicit use of `.Self` in designators is always allowed, and they are
bound (and replaced by a reference) to the inner-most possible value of
`.Self`. On the right-hand side of the nested `where` above, they have
the value `T as X`.

`.Self impls ...` is also always allowed, since it acts more as a
keyword here, and it always refers to the inner-most possible value of
`.Self`.

Any other explicit use of `.Self` is diagnosed when ambiguous, in any
kind of constraint. This is done in the handling of `WhereExpr` since it
has enough context to allow `.Self impls` (which is an explicit use)
while disallowing other explicit uses. And because it has non-canonical
instructions to work with, so it is able to diagnose errors with precise
locations.

Since `.Self` is no longer going to be marked with depth modifiers, the
eval of `WhereExpr` does not need an input facet value instruction
representing `.Self` to compare with, as they are now going to all be
equivalent. So revert it back to just looking for the `PeriodSelf` name
id, through a shared helper being introduced as `IsPeriodSelf`. And drop
the period self InstId from the `WhereExpr` instruction. This causes
most of the formatted SemIR changes.

Move helpers for working with and replacing `.Self` to their own file,
out of the `facet_type.h` header/cpp files. These are working with
`.Self` facet values more than facet types, though `.Self` is a name
that only exists inside the scope of a facet type.
2026-05-01 21:22:32 +00:00
Richard Smith 0fcbe7c6b5 Remove redundant call. (#7156)
Assisted-by: Gemini via Antigravity
2026-05-01 19:53:16 +00:00
Dana Jansens 63c1f1e44e Add a colon to the dump output for IdentifiedFacetType (#7150)
Put a colon after `impls` to make it a bit easier to read.

Before:
```
identified_facet_type50000000
  - self: concrete_constant(inst50000023): {kind: ClassType, arg0: class50000004, arg1: specific<none>, type: type(TypeType)}
    impls interface50000000: {name: name0, parent_scope: name_scope0, require_impls_block_id: require_block_empty} `Z`
```

After:
```
identified_facet_type50000000
  - self: concrete_constant(inst50000023): {kind: ClassType, arg0: class50000004, arg1: specific<none>, type: type(TypeType)}
    impls: interface50000000: {name: name0, parent_scope: name_scope0, require_impls_block_id: require_block_empty} `Z`
```
2026-05-01 18:48:59 +00:00
Richard Smith ab409a6a71 Simplify type check. (#7155)
Assisted-by: Gemini via Antigravity
2026-05-01 18:46:52 +00:00
Richard Smith aebd7f9d7f Simplify logic a little. (#7153)
Also preserve the error state rather than overriding it, though this
doesn't seem to make a difference in practice.

Assisted-by: Gemini via Antigravity
2026-05-01 18:41:33 +00:00
Dana Jansens 364aa4d1ea Split arguments ignoring extra whitespace in lldb dump (#7149)
The `split(" ")` function will split two consecutive spaces apart,
giving an empty string in its output. So `dump context inst5` was
mis-parsed to have arguments `["context", "", "inst5"]`. If `split()` is
called with no arguments, it splits on whitespace but ignores
consecutive whitespace, so we correctly parse the args to be
`["context", "inst5"]`.
2026-05-01 17:36:57 +00:00
Dana Jansens 110adf15c2 Let lldb dump display a variable when its name matches an id type name (#7148)
`dump context facet_type` was an error before since we expected that to
be followed with an id value. While `dump context facet_type 5` still
works, if there's no id value, try to use `facet_type` as a variable
name. This allows us to dump an inst id if it happens to be named
`inst`, etc, without having to use `--` to disambiguate.
2026-05-01 15:09:45 +00:00
Christopher Di BellaandDana Jansens 62b94f7932 reduces how many SpecificIds a custom witness generates (#6961)
The removed TODO warned that we'd end up with O(n^2) witness table
entries per specific. This isn't a problem for a single associated
function but will cause issues for larger custom witnesses.

This commit generates at most two `SpecificId`s with an inner `Self`:
one for associated constants and one for associated functions.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-04-30 20:27:20 +00:00
Nicholas Bishop 2445ad9703 Prevent ref self methods from being called from C++ with an rvalue (#7130)
If the Carbon method takes a `ref self`, give the C++ thunk an lvalue
ref-qualifier.
2026-04-30 00:50:28 +00:00
Nicholas Bishop f3f039516e Support accessing Carbon class fields from C++ (#7119)
When any field of a Carbon class is access from C++ for the first time,
all fields are exported as `clang::FieldDecl`s (this is necessary
because clang fields have an internal index that is initialized on first
use).

`ClangDeclStore` now provides bidirectional mapping. This allows looking
up a `ClangDeclId` by `InstId`, so when Carbon class fields are exported
they can be looked up that way.
2026-04-29 20:07:10 +00:00
Geoff Romer bd6aeae9d4 Don't require ref tags in thunks (#7115)
This enables thunking to work when the function has `ref` parameters,
without jumping through hoops to add `ref` tags in the desugared
function body.

This also renames `is_operator_syntax` to `is_desugared`, which is more
general and more accurate.
2026-04-29 18:33:53 +00:00
Geoff Romer 4c9049346d Replace form insts with actions (#7100)
See
[here](https://docs.google.com/document/d/1rWcueFwIfZox6GKVGxiUG4cBzjrZ6djXiIDGyJDtrE4/edit?tab=t.0)
for the design doc.

This also removes the default value of the `result_type_inst_id`
parameter of `HandleAction`, moves it before the action in the parameter
list, and documents it. This solves two problems:
- The default made it easy to forget, leading to unnecessary
`TypeOfInst` instructions.
- When it was present, putting it after the fairly "bulky" action
argument tended to make the callsite harder to read.
2026-04-29 18:13:42 +00:00
Richard Smith 0124aae041 Import non-const rvalue references as var parameters. (#7125)
When importing a C++ function with an rvalue reference parameter, we
previously produced a Carbon value parameter. This would lead to the
toolchain believing it could pass the address of a non-expiring object
to the function, which would lead to a use-after-move.

Instead, we now map non-const rvalue reference parameters to Carbon
`var` parameters. This forces the object passed into C++ to be unique
and owned by the call. While that's not an exact match for C++ rvalue
reference parameters, given that it provides "always move" not
"conditionally move", it's the closest match we have at the moment.
2026-04-29 00:28:00 +00:00
Richard Smith ab0aff91b8 Support indirect imports of namespaces. (#7122)
When a namespace that was imported from C++ is indirectly imported, find
the corresponding namespace in the current C++ AST and return that
instead. This namespace may have completely different contents than the
one we found before; that's fine. The current file's view of a namespace
depends on what it imported.

Assisted-by: Gemini via Antigravity
2026-04-28 23:55:18 +00:00
Richard Smith 7bb86bad66 Dependent PR workflow: don't crash if first_commit is null. (#7137)
Example crash:
https://github.com/carbon-language/carbon-lang/actions/runs/25071912124/job/73454186818?pr=7122

Assisted-by: Gemini via Antigravity
2026-04-28 23:54:04 +00:00
Richard Smith bb5a9f3747 Fix dependent PR changes link. (#7136)
Use A..HEAD, where A is the head commit of the most recent dependency
PR. This should list all commits that are in the current PR that are not
part of that dependency commit. Produce the "warning" message if that
diff will include any commits that are in any other dependency PR.

Assisted-by: Gemini via Antigravity
2026-04-28 21:51:04 +00:00
Richard Smith 23339bc810 Fix initialization of var parameters. (#7023)
When an initializing expression is used to initialize a var parameter,
we need to create the storage earlier in SemIR than the initializing
expression. To do so, pass a pending block to initialization containing
the var storage.

Also stop using `temporary` for this purpose, since we treat temporaries
as potentially-constant and immutable, but `var` parameters can be
mutated by the callee. We should ideally introduce a new kind of
instruction for this purpose but for now we just use `var_storage`.
2026-04-28 20:10:13 +00:00
Richard Smith 51e843d904 Suppress some clang-tidy false positives (#7131)
This gets us back to being mostly clang-tidy clean. This turns out to be
important for agentic coding agents, which otherwise sometimes try to
"fix" these false-positive lints.

Assisted-by: Gemini via Antigravity
2026-04-28 18:20:37 +00:00
Chandler Carruth bb228dbcfb Fix computing the maximum merged PR (#7127)
Assisted-by: Antigravity with Gemini
2026-04-28 18:15:43 +00:00
Geoff Romer a8c6a7f88d Remove uses of -Oz flag (#7128)
The `-Oz` flag has been [removed from
LLVM](https://github.com/llvm/llvm-project/pull/191363). The documented
replacement is to use `-O2` in conjunction with the `optsize` or
`minsize` attributes, which we already apply in lowering.
2026-04-28 17:39:09 +00:00
Richard Smith 73adc479e3 Limited support for indirect import of template specializations. (#7121)
When a class template specialization is indirectly imported, map the
template arguments into the importing File and find the corresponding
local class template specialization. This is a short-term fix:
eventually we should import the C++ AST from the imported file into the
C++ AST for the current file, but we're not ready to do that yet.

So far we only support very simple template arguments: just classes and
builtin types. Unfortunately we can't just map the C++ template
arguments to Carbon types, then import the Carbon types, then map them
back, because mapping from C++ template arguments to Carbon types would
require a `Check::Context` for the imported code, which we don't have.
As this is only a temporary workaround, directly mapping from one C++
AST to another will do for now.

Assisted-by: Gemini via Antigravity
2026-04-28 02:36:44 +00:00
Chandler Carruth 0e308e0739 Switch to a manual check status for dependent PRs (#7117)
The labeling script will now directly set a check status for the PR as
`pending` when it marks something as dependent, and clear it when it no
longer is. This emulates a check that starts when marked as dependent
and runs until the last dependency lands, allowing automerge and other
workflows to work cleanly.

The branch protection rule will have to be updated to the new spelling.

This should do the same key thing as #7113, but integrated to the new
script.

Assisted-by: Antigravity with Gemini
2026-04-28 02:01:57 +00:00
Christopher Di Bella 9480c10ecf teaches arithmetic interfaces about C++ operators (#7123) 2026-04-28 01:00:21 +00:00
Richard Smith aa8f9d8c00 For a dependent PR, include a link to changes to review. (#7124)
Instead of linking to the first commit to be reviewed, link to the
complete series of commits to review. Include a warning if not all the
commits in that range should be reviewed due to non-linear history.

Assisted-by: Gemini via Antigravity
2026-04-28 00:27:12 +00:00
Dana Jansens 554b1b8d10 Remove SymbolicBindingType (#7114)
This inst was meant to support tracking the depth of a `.Self` facet,
but we have now implemented substitution of `.Self` in facet type
identification, and in eval of where expressions, without needing to
track the depth.

See history here:
-
[2025-06-30](https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.4qd5dkyfn2k3)
-
[2025-07-07](https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.7urbxcq23olv)
- #6026
2026-04-27 19:04:59 +00:00
Chandler Carruth df6a5a50dc Remove the Dump method from Printable (#7118)
Because this is an `__attribute__((used))` method in a templated base
class it forces a _huge_ amount of template instantiation in every
translation unit.

Often this was just printing the members of the type, which is still
useful in some cases (such as test output), but adds no value in the
debugger.

A more successful pattern for dumping has been namespace level
functions, and particularly static ones that more transparently don't
expand the non-debugger API surface. Add the few missing functions there
that cover `Printable` types with more interesting contents.

For several of these, it just gives us a "dump the whole thing" function
as a compliment to "dump this entity in the thing". These probably
aren't especially high value, but moving them here they become cheap, so
I've left them in.

For a couple, this expands the rich dumping support of SemIR constructs,
which should be substantially more useful than the previous `Dump`
behavior.

This reduces `check` cumulative object file size by another 14%.

Assisted-by: Antigravity with Gemini
2026-04-26 16:21:07 +00:00
Dana Jansens 235267680b Subst .Self in impl as rewrites (#7105)
This makes rewrites of a constraint that requires a generic `I(Self)`
work. The `Self` there is replaced in the identified facet type by the
impl-as self type. But the rewrite is for the interface `.I(.Self)`, so
they don't match. Once `.Self` is replaced with the impl-as self type,
then they match and the rewrite is applied.
2026-04-24 20:51:20 +00:00
Chandler Carruth 824d7e3c83 Create a GitHub action to automatically handle dependent PRs (#7101)
This should detect when a PR has a dependency of another open PR and add
a comment and label describing it. The comment will even do a
best-effort to compute the best starting commit for review.

Whenever PRs are closed, it will also scan the open depnedent PRs and
try to either remove the PRs in the comment or if it reaches zero the
label.

It works to update a single comment on a PR rather than adding more
comments.

Assisted-by: Antigravity with Gemini
2026-04-24 19:52:07 +00:00
Richard SmithandDavid Blaikie 2a059366a7 Require imported C++ types to be complete before creating a Core.Copy witness (#7112)
Fixes a crash that would occur due to `scope_id` of the class being
unset.

Relands #7106 that was reverted by #7103 due to a github infrastructure
bug.

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2026-04-24 19:30:02 +00:00
Dana Jansens d9841992cb Replace .Self in facet types (#7097)
This allows `T impls X` constraints to function, since they must contain
some reference to `.Self` in order to be valid. This should be
sufficient to support the interfaces we need for for loops over C++
range-for-compatible types.

We replace `.Self` in the following places:
- In a require decl, as we have a specific self facet to replace it with
from the declaration, either a user-specified facet or the symbolic
`Self`.
- When identifying a facet type, as we have a specific self that we are
identifying the facet type with. That self gets used for all `.Self`
references.
- Implicit `.Self` references on the RHS of an `impls` constraint when
building a facet type. The `.Self` references there no longer refer to
the top level self facet, so replace them with the facet that we now
know they refer to, which is found on the LHS of the `where` before the
`impls`.
- Rewrite constraints in impl lookup when validating them and comparing
them with constants from witnesses, which come from identifying a facet
type.
- Rewrite constraints in ImplWitnessAccess eval when comparing them with
constants from witnesses, which come from identifying a facet type.

Substitution is done through `SubstPeriodSelf`. It handles replacing
`.Self` and `.Self as type`, for a replacement facet that is either of
type FacetType or TypeType.

Eval currently diagnoses some ambiguous `.Self` references when doing
substitution of `.Self` but this is the incorrect place to do it, so
there are TODOs about moving this to name lookup. To support these
diagnostics there's some additional complexity in `SubstPeriodSelf` that
can go away once the TODOs are addressed, such as asking the caller if
they want to replace each `.Self`, in order for it to report a
diagnostic.

There are a number of follow-up work items here:
- Some TODO tests.
- Remove `SymbolicBindingType` since its intention was to support
`.Self` but we don't need it with this approach.
- Replace `.Self` in rewrite constraints of require decls.
- Replace `.Self` in rewrite constraints of impl as when constructing
the witness table.
- Reject explicit `.Self` in name lookup when it would be ambiguous.
- Officially disallow `.Self.A = B` in rewrite constraints in the design
docs, so that we don't have the case where `.A` is allowed but `.Self.A`
is not due to ambiguity.
2026-04-24 19:08:11 +00:00
Chandler CarruthandDana Jansens 5da651032f Add a permissions restriction (#7108)
Assisted-by: Antigravity with Gemini

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2026-04-24 17:52:15 +00:00
Christopher Di Bella f0c4b37c63 adds a field to SemIR::Interface to indicate whether it is a core interface (#7091)
The existing `GetCoreInterface` has linear-time complexity and adds more
than the search criteria to the `CoreInterfaceCache`. Adding a new field
to `Interface` changes this operation when building packages other than
`Core`, as this should only be set for the core library.
2026-04-24 17:33:23 +00:00
Chandler Carruth 9532effeae Update to the latest Bazel 8 release and latest Bazel modules (#7111)
Assisted-by: Antigravity with Gemini
2026-04-24 17:14:23 +00:00
Dana Jansens 9c9f5cb52c Preserve named constraints across where (#7104)
We were not copying named constraints in the base facet type over to the
result of the WhereExpr eval.

Add tests that cover this by doing `impl as Constraint where ...` with
rewrite contraints either in the impl-as or in the named constraint.
When the interface is generic, these tests fail (as TODOs). When the
impl is used in impl lookup, we crash (with TODOs in the tests).

Part of #6991.
2026-04-24 14:56:48 +00:00
Chandler Carruth 680fa0c990 Force updating the uuid dependency of vscode (#7109)
There are dependencies that kept this from upgrading automatically, but
while the new version technically includes breaking changes, they aren't
ones that cause any problems for VSCode.

Upgrading this is helpful as the old version has an irrelevant (for us)
security issue. With this we should be able to avoid distracting
security scanners.

Also updates other packages where relevant, all those automatically.

Assisted-by: Antigravity with Gemini
2026-04-24 14:32:19 +00:00
Chandler Carruth 57b03f8a53 Do an auto-update to pre-commit versions (#7110)
Assisted-by: Antigravity with Gemini
2026-04-24 08:35:56 +00:00
Chandler Carruth 8cd659ee09 Switch to a "manual" tags and use them more pervasively (#7102)
Without this, basic `bazel test //...` style wildcards would build a
bunch of extra configurations because of gaps excluding things. With
this, the action count of a normal build should be much more reasonable.

The switch from `target_compatible_with` to tagging is based on looking
at what ends up being most idiomatic and easiest -- trying to articulate
the complex and convoluted compatible with restrictions that would avoid
extraneous build configurations was really painful and this seems much
simpler and easier to deploy in a systematic way.

While here, also change the name of a rule that confused me to no end
while debugging this -- the rule that installs a `.bzl` file that
happens to be spelled `carbon_runtimes` is very different from all of
the other "installed carbon runtimes" kind of things in the tree. Adding
the file extension helps make that (much) more obvious.

Note that this is essentially a re-do of #7088 but now without any
dependencies that can mess up the merge.

Assisted-by: Antigravity with Gemini
2026-04-24 01:59:45 +00:00
Richard Smith 12cdd406b0 Factor type lowering out of file_context.cpp. (#7099)
This file was getting too big. This seems like a nice, independent chunk
to move elsewhere.

Assisted-by: Gemini via Antigravity
2026-04-24 00:43:18 +00:00
Richard Smith 56bd35e7b3 Basic support for indirect import of C++ classes. (#7094)
When importing Carbon code that refers to a C++ class, look for a
corresponding C++ class in the current context and import that instead.
This is a workaround for not having proper cross-file C++ import
support. For now, we only support non-templated namespace-scope class
types.

Assisted-by: Gemini via Antigravity
2026-04-24 00:36:19 +00:00
Nicholas Bishop 3f63cf4b10 Support C++ calling Carbon functions with ref parameters (#7107)
When creating the C++ thunk, make the parameters references if the
corresponding callee parameters are `ref`s.

When creating the Carbon thunk, tag the call arguments as `ref` if the
corresponding callee parameters are `ref`s.
2026-04-23 23:45:26 +00:00
Richard Smith 709776ad1c Support for locations in transitively imported C++ code (#7093)
Instead of treating all C++ code as coming from a single synthetic
`CheckIRId`, track the `SemIR::File` associated with each C++ location.
This is necessary since each `SemIR::File` has a distinct `CppFile` and
therefore distinct `SourceLocation`s and `ClangSourceLocId`s.

Assisted-by: Gemini via Antigravity
2026-04-23 20:11:04 +00:00
dependabot[bot] ab12932e56 Bump the npm_and_yarn group across 1 directory with 2 updates (#7103)
Bumps the npm_and_yarn group with 2 updates in the /utils/vscode
directory:
[brace-expansion](https://github.com/juliangruber/brace-expansion) and
[picomatch](https://github.com/micromatch/picomatch).

Updates `brace-expansion` from 1.1.12 to 1.1.14
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/10c05fcf3699b1a29ef5e611c011af3d3c97e6e3"><code>10c05fc</code></a>
1.1.14</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/1afa1b22ead12f6a7a02f25bf0f7d64c2439b007"><code>1afa1b2</code></a>
Add opt-in { max } mitigation to v1 legacy line (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/103">#103</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/2fbb6a2aa0f984bb2fb5f60252ca6cba3e1368ec"><code>2fbb6a2</code></a>
Revert &quot;Backport fix for GHSA-7h2j-956f-4vf2 to v1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/101">#101</a>)&quot;
(<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/102">#102</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/0d7652e3093d3273151729812f9b0b79a17ecba6"><code>0d7652e</code></a>
Backport fix for GHSA-7h2j-956f-4vf2 to v1 (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/101">#101</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/6c353caf23beb9644f858eb3fe38d43a68b82898"><code>6c353ca</code></a>
1.1.13</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/7fd684f89fdde3549563d0a6522226a9189472a2"><code>7fd684f</code></a>
Backport fix for GHSA-f886-m6hf-6m8v (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/95">#95</a>)</li>
<li>See full diff in <a
href="https://github.com/juliangruber/brace-expansion/compare/v1.1.12...v1.1.14">compare
view</a></li>
</ul>
</details>
<br />

Updates `picomatch` from 4.0.3 to 4.0.4
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/micromatch/picomatch/releases">picomatch's
releases</a>.</em></p>
<blockquote>
<h2>4.0.4</h2>
<p>This is a security release fixing several security relevant
issues.</p>
<h2>What's Changed</h2>
<ul>
<li>Fix for <a
href="https://github.com/micromatch/picomatch/security/advisories/GHSA-c2c7-rcm5-vvqj">CVE-2026-33671</a></li>
<li>Fix for <a
href="https://github.com/micromatch/picomatch/security/advisories/GHSA-3v7f-55p6-f55p">CVE-2026-33672</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/micromatch/picomatch/compare/4.0.3...4.0.4">https://github.com/micromatch/picomatch/compare/4.0.3...4.0.4</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/micromatch/picomatch/commit/e5474fc1a4d7991870058170407dda8a42be5334"><code>e5474fc</code></a>
Publish 4.0.4</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/4516eb521f13a46b2fe1a1d2c9ef6b20ddc0e903"><code>4516eb5</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/5eceecd27543b8e056b9307d69e105ea03618a7d"><code>5eceecd</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/0db7dd70651ca7c8265601c0442a996ed32e3238"><code>0db7dd7</code></a>
Run benchmark again against latest minimatch version (<a
href="https://redirect.github.com/micromatch/picomatch/issues/161">#161</a>)</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/95003777eb1c60dec09495a8231fa2ba4054d76a"><code>9500377</code></a>
docs: clarify what brace expansion syntax is and isn't supported (<a
href="https://redirect.github.com/micromatch/picomatch/issues/134">#134</a>)</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/2661f23eca86c8b4a2b14815b9b2b3b74bd5a171"><code>2661f23</code></a>
fix typo in globstars.js test name (<a
href="https://redirect.github.com/micromatch/picomatch/issues/138">#138</a>)</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/1798b07e9df59500b9cf567294d44d559032f4c7"><code>1798b07</code></a>
docs: fix <code>makeRe</code> example (<a
href="https://redirect.github.com/micromatch/picomatch/issues/143">#143</a>)</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/9d76bc57a03b7f57cc4ca516c8071daf632bafd8"><code>9d76bc5</code></a>
chore: undocument removed options (<a
href="https://redirect.github.com/micromatch/picomatch/issues/146">#146</a>)</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/e4d718bbfb47e4f030ab2612b5b04a9297fe272d"><code>e4d718b</code></a>
Remove unused time-require (<a
href="https://redirect.github.com/micromatch/picomatch/issues/160">#160</a>)</li>
<li><a
href="https://github.com/micromatch/picomatch/commit/38dffeb16221cc8eb8981524fb6895dd2aaaba76"><code>38dffeb</code></a>
chore(deps): pin dependencies (<a
href="https://redirect.github.com/micromatch/picomatch/issues/158">#158</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/micromatch/picomatch/compare/4.0.3...4.0.4">compare
view</a></li>
</ul>
</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 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-23 18:23:45 +00:00
David Blaikie 8e32faba18 Require imported C++ types to be complete before creating a Core.Copy witness (#7106)
Fixes a crash that would occur due to `scope_id` of the class being
unset.
2026-04-23 17:54:21 +00:00
dependabot[bot] 8205c8e460 Bump undici from 7.22.0 to 7.24.5 in /utils/vscode in the npm_and_yarn group across 1 directory (#6951)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [undici](https://github.com/nodejs/undici).

Updates `undici` from 7.22.0 to 7.24.5
<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>v7.24.5</h2>
<h2>What's Changed</h2>
<ul>
<li>Formdata tests by <a
href="https://github.com/KhafraDev"><code>@​KhafraDev</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/4902">nodejs/undici#4902</a></li>
<li>test: add unexpected disconnect guards to more client test files by
<a href="https://github.com/samayer12"><code>@​samayer12</code></a> in
<a
href="https://redirect.github.com/nodejs/undici/pull/4844">nodejs/undici#4844</a></li>
<li>fix(cache): only apply 1-year deleteAt for immutable responses by <a
href="https://github.com/metalix2"><code>@​metalix2</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/4913">nodejs/undici#4913</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/metalix2"><code>@​metalix2</code></a>
made their first contribution in <a
href="https://redirect.github.com/nodejs/undici/pull/4913">nodejs/undici#4913</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v7.24.4...v7.24.5">https://github.com/nodejs/undici/compare/v7.24.4...v7.24.5</a></p>
<h2>v7.24.4</h2>
<h2>What's Changed</h2>
<ul>
<li>fix(fetch): handle URL credentials in dispatch path extraction by <a
href="https://github.com/mcollina"><code>@​mcollina</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/4892">nodejs/undici#4892</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v7.24.3...v7.24.4">https://github.com/nodejs/undici/compare/v7.24.3...v7.24.4</a></p>
<h2>v7.24.3</h2>
<h2>What's Changed</h2>
<ul>
<li>fix(h2): TypeError: Cannot read properties of null (reading 'push')
i… by <a href="https://github.com/hxinhan"><code>@​hxinhan</code></a> in
<a
href="https://redirect.github.com/nodejs/undici/pull/4881">nodejs/undici#4881</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v7.24.2...v7.24.3">https://github.com/nodejs/undici/compare/v7.24.2...v7.24.3</a></p>
<h2>v7.24.2</h2>
<h2>What's Changed</h2>
<ul>
<li>fix fetch path logic by <a
href="https://github.com/KhafraDev"><code>@​KhafraDev</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/4890">nodejs/undici#4890</a></li>
<li>remove maxDecompressedMessageSize by <a
href="https://github.com/KhafraDev"><code>@​KhafraDev</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/4891">nodejs/undici#4891</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v7.24.1...v7.24.2">https://github.com/nodejs/undici/compare/v7.24.1...v7.24.2</a></p>
<h2>v7.24.1</h2>
<h2>What's Changed</h2>
<ul>
<li>fix: <strong>proto</strong> pollution by <a
href="https://github.com/rahulyadav5524"><code>@​rahulyadav5524</code></a>
in <a
href="https://redirect.github.com/nodejs/undici/pull/4885">nodejs/undici#4885</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v7.24.0...v7.24.1">https://github.com/nodejs/undici/compare/v7.24.0...v7.24.1</a></p>
<h2>v7.24.0</h2>
<h1>Undici v7.24.0 Security Release Notes</h1>
<p>This release addresses multiple security vulnerabilities in
Undici.</p>
<h2>Upgrade guidance</h2>
<p>All users on v7 should upgrade to <strong>v7.24.0</strong> or
later.</p>
<h2>Fixed advisories</h2>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/nodejs/undici/commit/51fd6617e5b4bd6a605628b7a9d40510fc0a723e"><code>51fd661</code></a>
Bumped v7.24.5 (<a
href="https://redirect.github.com/nodejs/undici/issues/4915">#4915</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/90775009148e5956ac58ace0eb493001db8b2b7c"><code>9077500</code></a>
fix(cache): only apply 1-year deleteAt for immutable responses (<a
href="https://redirect.github.com/nodejs/undici/issues/4913">#4913</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/1c5dc1ad36c886aa11d025cf6381c5ea1fff0ca4"><code>1c5dc1a</code></a>
test: add unexpected disconnect guards to more client test files (<a
href="https://redirect.github.com/nodejs/undici/issues/4844">#4844</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/28853613a582b74315617ec44dde06bd3cee3c11"><code>2885361</code></a>
Formdata tests (<a
href="https://redirect.github.com/nodejs/undici/issues/4902">#4902</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/4991f3e1fbb93c8243fe072a69b08c47fd5d0e24"><code>4991f3e</code></a>
Bumped v7.24.4</li>
<li><a
href="https://github.com/nodejs/undici/commit/ea3a06d76e1b0b3e23c77ead15836474906fd635"><code>ea3a06d</code></a>
fix(fetch): preserve path for credentialed URLs (<a
href="https://redirect.github.com/nodejs/undici/issues/4892">#4892</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/9b96516c266ddf37f658179448a1a19479d8c204"><code>9b96516</code></a>
Bumped v7.24.3</li>
<li><a
href="https://github.com/nodejs/undici/commit/79266603db63492826382375a504c580d86845c8"><code>7926660</code></a>
Ignore .githuman</li>
<li><a
href="https://github.com/nodejs/undici/commit/9eaa5af23e8be069556af812a982bc7d59932bb7"><code>9eaa5af</code></a>
fix(h2): TypeError: Cannot read properties of null (reading 'push') in
Reques...</li>
<li><a
href="https://github.com/nodejs/undici/commit/a9bfe210b093366a5d11ce5315e56adbadfbb78d"><code>a9bfe21</code></a>
ignore .pi</li>
<li>Additional commits viewable in <a
href="https://github.com/nodejs/undici/compare/v7.22.0...v7.24.5">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=undici&package-manager=npm_and_yarn&previous-version=7.22.0&new-version=7.24.5)](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-23 04:49:23 +00:00
Richard Smith afb733f02a Don't allow merging PRs with the dependent label. (#7096)
This should reduce the chance of a dependent PR being merged before its
base PR is merged.

Assisted-by: Gemini via Antigravity
2026-04-23 01:58:36 +00:00
Geoff RomerandChandler Carruth 49c7288619 Restructure return declaration handling (#7076)
- A function with a return declaration always has exactly one
`ReturnSlotPattern`, representing the whole return declaration (whereas
previously that was omitted for value and reference returns).
- The `ReturnSlotPattern` always has a subpattern with the same form.
`OutParamPattern` already plays that role for initializing forms, and
`TuplePattern` will play that role for tuple forms. This change
introduces `ValueReturnPattern` and `RefReturnPattern` to represent
value and reference return forms.
- As before, the `ReturnSlotPattern` has a corresponding `ReturnSlot`
that represents the output that is initialized by a `return` statement.
Its structure parallels the structure of the `ReturnSlotPattern`, so we
need `ValueReturn` and `RefReturn` insts that correspond to
`ValueReturnPattern` and `RefReturnPattern`.

This is a step toward supporting generic return forms, where the
`ReturnSlotPattern`'s subpattern may be an action: this change ensures
that evaluating the action for a specific form produces the same SemIR
as if the form were concrete to begin with. More speculatively, this
should simplify the implementation of `return` statements with compound
return forms.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2026-04-22 23:38:21 +00:00
Richard Smith 3abc334c42 Disable precommit checks for package-lock.json (#7098)
This file contains base64 hashes that sometimes contain word-shaped
sequences like ...+nD+... that generate precommit false positives from
codespell.

MODULE.bazel.lock was already excluded from all precommit checks; it
seems consistent to do the same for package-lock.json too.

Assisted-by: Gemini via Antigravity
2026-04-22 22:48:35 +00:00
Chandler Carruth a5215c64ea Split the bootstrapping logic out of the toolchain construction logic (#7087)
This shouldn't change any functionality, but simplifies (significantly)
the logic in the installed toolchain, and also provides a better
conceptual balance between these.

I've tried to minimize the changes beyond a pure refactoring, but it was
a bit tricky to get everything working so some things have been mixed
in...

Assisted-by: Antigravity with Gemini
2026-04-22 20:57:16 +00:00
Chandler Carruth 1d19618f1b Revert "Switch to a "manual" tags and use them more pervasively (#7088)" (#7095)
This reverts commit 4babfdbf22.

This was a stacked PR that was merged by accident, losing the commit and
description of the base change. Reverting and will re-land
independently.
2026-04-22 20:23:31 +00:00
Chandler Carruth 4babfdbf22 Switch to a "manual" tags and use them more pervasively (#7088)
Without this, basic `bazel test //...` style wildcards would build
a bunch of extra configurations because of gaps excluding things. With
this, the action count of a normal build should be much more reasonable.

The switch from `target_compatible_with` to tagging is based on looking
at what ends up being most idiomatic and easiest -- trying to articulate
the complex and convoluted compatible with restrictions that would avoid
extraneous build configurations was really painful and this seems much
simpler and easier to deploy in a systematic way.

While here, also change the name of a rule that confused me to no end
while debugging this -- the rule that installs a `.bzl` file that
happens to be spelled `carbon_runtimes` is very different from all of
the other "installed carbon runtimes" kind of things in the tree. Adding
the file extension helps make that (much) more obvious.

Assisted-by: Antigravity with Gemini
2026-04-22 18:08:17 +00:00
Nicholas Bishop 67648b4d49 Remove "__cpp_thunk" from thunk name for exported functions (#7092)
This makes the behavior consistent between methods and regular
functions, and fixes the behavior with `using` aliases (see new
`using.carbon` test).

As requested in
https://github.com/carbon-language/carbon-lang/pull/7078#discussion_r3121104954.
2026-04-22 18:05:02 +00:00
Dana Jansens 790cb6e6fe Make ImplWitnessAccess inst have constant kind Conditional (#7090)
ImplWitnessAccess can contain a LookupImplWitness instruction as an
operand, which used to be SymbolicOnly but has now become Conditional in
#6915. This opens up the possibility for LookupImplWitness to have a
concrete value, without resolving to a different instruction kind. If
this occurs when it's the operand of an ImplWitnessAccess, and the
access is unable to find a different value to resolve to through the
witness' self type, then the ImplWitnessAccess can also become concrete.

This can happen in particular when:
- You have an ImplWitnessAccess into a `.Self` symbolic in a facet type.
- You convert a concrete type to the facet type.
- The `.Self` is replaced by a concrete type, causing the impl lookup to
be on that concrete type.
- The (now concrete) impl lookup fails to find any impl witness, so it
remains a concrete LookupImplWitness

This results in a diagnostic, as the incoming type does not satisfy the
facet type, but in the meantime we have a concrete ImplWitnessAccess,
which we do not want to crash.

For example in this test:
```carbon
interface I {
  let I1:! type;
}
interface J {}

fn F(T:! I where .I1 impls J) {}

fn G() {
  class C;

  // This identifies `C as (I where .I1 impls J)`, which replaces `.Self.I1`
  // with `C.(I.I1)`. This is a concrete lookup since C and I are both concrete,
  // but it doesn't find anything as there is no impl.
  //
  // As such, the call to F fails to deduce a value for T.
  F(C);
}
```

This PR splits out the change to ImplWitnessAccess from the larger
change of replacing `.Self` in identified facet types (and comparisons
with identified facet types).
2026-04-22 17:11:40 +00:00
Dana Jansens 744ab33484 Use auto for the CheckTypeOfConstantIsTypeType fn signature (#7089) 2026-04-22 16:42:27 +00:00
Nicholas Bishop 33d534ab31 Support calling Carbon methods from C++ (#7078)
The FunctionDecl created for calling the Carbon thunk now takes a `self`
parameter for non-static methods, and the C++ thunk now passes an extra
argument for that `self` parameter when needed.

The CXXMethodDecl thunk created for calling methods now sets the storage
class appropriate depending on whether the method is static or not.

To reduce the number of parameters being passed around to thunk-building
functions, added a `FunctionInfo` struct and pass that around instead.
2026-04-22 15:09:33 +00:00
Chandler Carruth b16cde9c53 Add a hack to support -cc1as. (#7083)
This is (far) from robust -- particularly with repeated compiles in the
same address space. But it appears to be sufficient in the short term,
and we already have the relevant TODOs to factor this upstream into
something that we can use here.

This also somehow uncovered a bug in how we were logging failed commands
-- the failed commands are destroyed when we destroy the driver object
(and its diagnostics object), so we simply cannot do the logging _after_
flushing diagnostics. That's probably ok, and just doing this in the
other order makes the code simpler.

Assisted-by: Antigravity with Gemini
2026-04-21 20:33:58 +00:00
Richard Smith 335d811b9f Add a bit more structure to interop/cpp tests. (#7085)
Add import/ and export/ under function/. Move most top-level tests to a
new basics/ with subdirectories for `import` directives and `inline
Cpp`. Add subdirectory for primitive type handling. Move all `reverse/`
tests to somewhere else, typically under an `export/` directory.

I split two test files up: constexpr.carbon got split into var/ and
function/ pieces, and reverse/simple.carbon was inlined into
namespace/export.carbon. The rest are just simple renames.
2026-04-21 20:22:21 +00:00
Chandler Carruth a1a9c02cdc Refactor Bazel toolchain to use rules_cc action groups (#7086)
Rather than defining our own action groups, work to re-use the
`rules_cc` ones, as they are (much) more comprehensive. Also, completely
eliminate the `codegen` action group as it was not well used. For
example, `-march` flags and `-O` flags change the preprocessor macros
defined. There isn't a really great "codegen" heuristic, so just pass
those flags to all compiles which is simpler anyways.

I'm tempted to do the same with preprocessor actions, but maybe it makes
sense to have that one stay separate.

Assisted-by: Antigravity with Gemini
2026-04-21 16:40:24 +00:00
Dana Jansens b8bc7bffd2 Rework validation of require constraints (#7081)
Use constant values in code that can work with a canonical value
(`TypeStructureReferencesSelf`).

Give explicit location ids for the full require decl and the constraint
to `ValidateRequire`.

Go directly from `InstId` to `TypeId` in `ValidateRequire`.
Correctly/explicitly handle constraint instructions which are not types
instead of calling `SemIR::TypeId::ForTypeConstant` and hoping for the
best.

Leave a clear spot where we will subst `.Self` out of the contraint.
2026-04-21 16:11:19 +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
3135 changed files with 421108 additions and 167780 deletions
+45
View File
@@ -0,0 +1,45 @@
---
name: Agent tools
description:
Guidelines and restrictions on shell commands and file manipulation tools
for AI assistants.
---
# Agent tools
<!--
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
-->
AI assistants working on the Carbon repository **MUST NOT** use legacy or
generic UNIX shell search/edit commands when specialized environment tools
exist.
## Command line tools restrictions
- **DO NOT USE**: `cat`, `less`, `grep`, `sed`, or other shell utilities for
viewing, searching, or modifying files.
- **DO NOT USE**: `patch` to write and apply patch files.
- **DO NOT USE**: Writing custom scripts in other languages to circumvent this
limitation.
- **DO USE**: High-fidelity semantic API tools:
- **Viewing**: Use `view_file` instead of `cat` / `less`.
- **Searching**: Use `grep_search` / `find_by_name` instead of `grep` /
`find`.
- **Modifying**: Use `replace_file_content`, `multi_replace_file_content`,
or `write_to_file` instead of `sed` / `patch` / `python` edits.
You may only write and run temporary programs to modify source code if no
semantic tool is applicable or when performing complex, systematic transforms
across many codebase directories simultaneously.
## Temporary files management
Temporary files and scratchpad test scripts created by the assistant during
analysis, experiments, or debugging:
- **MUST** reside within the `tmp/` subdirectory under the workspace root.
- **MUST** be periodically cleaned out and deleted before ending your turn to
preserve a clean git workspace.
+84
View File
@@ -0,0 +1,84 @@
---
name: Bazel usage
description:
Instructions that **MUST** be followed when 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.
+276
View File
@@ -0,0 +1,276 @@
---
name: Builtin functions
description:
Instructions for registering, mapping, constant evaluating, and lowering
builtin functions in the Carbon toolchain.
---
# Builtin Functions in the Carbon Toolchain
<!--
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
-->
Builtin functions are compiler-recognized primitives mapping directly from
Carbon code expressions (via standard prelude bindings) to optimized backend
execution. This document defines the complete structural workflow, C++ patterns,
constant evaluation logic, machine lowering mechanics, library bindings, and
validation strategies required to implement builtin functions in the Carbon
compiler.
---
## Technical Flow & Lifecycle
```mermaid
graph TD
Src[Carbon Source Code] -->|Prelude Map| Sem[Semantic Analysis / SemIR]
Sem -->|Signature Constraint| Sig[builtin_function_kind.cpp]
Sem -->|Phase Evaluation| Eval[eval.cpp Constant Interpreter]
Sem -->|Machine Codegen| Lower[handle_call.cpp LLVM Lowering]
Eval -->|Diagnostics| Diag[diagnostics/kind.def]
Lower -->|Native Instructions| LLVM[LLVM IR Generation]
```
Adding a builtin function involves a 5-step integration:
1. **Define the Builtin Kind**: Register the enum in
[builtin_function_kind.def](../../../toolchain/sem_ir/builtin_function_kind.def).
2. **Signature & Compile-Time Registry**: Declare the mapping name, parameter
constraints, and compile-time evaluation residency in
[builtin_function_kind.cpp](../../../toolchain/sem_ir/builtin_function_kind.cpp).
3. **Compile-Time Interpreter Support**: Wire constant evaluation hooks and
bounds/exception diagnostics in
[eval.cpp](../../../toolchain/check/eval.cpp).
4. **LLVM IR Lowering Support**: Connect target machine generation in
[handle_call.cpp](../../../toolchain/lower/handle_call.cpp).
5. **Prelude Library Mapping**: Bind primitive interfaces to named builtins
under [core/prelude/](../../../core/prelude/).
---
## Detailed Step-by-Step Implementation Guide
### Step 1: Kind Definition & Registration
Register your builtin function name using the X-macro in
[builtin_function_kind.def](../../../toolchain/sem_ir/builtin_function_kind.def):
```cpp
// toolchain/sem_ir/builtin_function_kind.def
// Converts an integer type to a floating-point type.
CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(IntConvertFloat)
```
### Step 2: Signature Validation & Compile-Time Residence
Inside
[builtin_function_kind.cpp](../../../toolchain/sem_ir/builtin_function_kind.cpp):
1. **Define Parameter Constraints**: If the parameter requires novel
constraints (e.g. "must be a float type"), define a template constraint
struct checking the matching `SemIR` type instruction (such as `FloatType`
or `FloatLiteralType`). Use pre-established semantic helpers:
- `TypeParam<I, T>`: Ensures different parameters resolve to identical
type structures (e.g., generic constraint matching).
- `AnyInt`, `AnyFloat`, `AnySizedInt`, `AnySizedFloat`, `CharCompatible`,
`StdInitializerList`, `NoReturn`.
2. **Map Literal Name & Register Constraint Signature**: Declare a
`BuiltinInfo` constant inside `namespace BuiltinFunctionInfo` matching the
macro-defined name:
```cpp
// toolchain/sem_ir/builtin_function_kind.cpp
constexpr BuiltinInfo IntConvertFloat = {
"int.convert_float", ValidateSignature<auto(AnyInt)->AnyFloat>};
```
3. **Establish Compile-Time Residency Status**: Update
`BuiltinFunctionKind::IsCompTimeOnly` to determine if a call requires
compile-time evaluation:
- **Checked/Diagnostics Primitives**: Return `true` immediately. Runtime
lowering of these is illegal (e.g. `IntConvertFloatChecked`).
- **Runtime Primitives**: Return
`AnyLiteralTypes(sem_ir, arg_ids, return_type_id)` to enforce that
expressions involving unsized literal values (like `IntLiteral` or
`FloatLiteral`) are evaluated exclusively at compile-time (as they lack
runtime representation).
---
### Step 3: Constant Evaluation Support
Wire the interpreter inside [eval.cpp](../../../toolchain/check/eval.cpp) to
execute compile-time computations:
1. **Implement Constant Evaluation Logic**:
- Handle the builtin case inside `MakeConstantForBuiltinCall` (which
processes the compile-time execution of the call).
- Confirm type validation phase is `Phase::Concrete` to reject incomplete
bindings:
```cpp
case SemIR::BuiltinFunctionKind::IntConvertFloat: {
if (phase != Phase::Concrete) {
return MakeConstantResult(context, call, phase);
}
return PerformIntToFloatConvert(context, loc_id, arg_ids[0], call.type_id,
/*require_exact=*/false);
}
```
- Extract inputs safely from local value stores (e.g.
`context.ints().Get(arg.int_id)` or
`context.floats().Get(arg.float_id)`).
- Leverage high-precision LLVM mathematical structures (`llvm::APInt`,
`llvm::APFloat`, `llvm::APSInt`) to handle custom bits and signedness
safely.
2. **Diagnose Invalid Parameters or Exceptions**:
- Define compile-time diagnostics inside
[kind.def](../../../toolchain/diagnostics/kind.def):
```cpp
// toolchain/diagnostics/kind.def
CARBON_DIAGNOSTIC_KIND(IntTooLargeForFloatType)
```
- Emplace localized diagnostic formatting messages where they are caught
in `eval.cpp`:
```cpp
CARBON_DIAGNOSTIC(IntTooLargeForFloatType, Error,
"integer value {0} too large for floating-point type {1}",
llvm::APSInt, SemIR::TypeId);
context.emitter().Emit(loc_id, IntTooLargeForFloatType, val, dest_type_id);
```
- Return `SemIR::ErrorInst::ConstantId` to gracefully abort invalid
constant generation rather than crashing the compiler.
3. **Fast-Path Range Limits**:
- Before evaluating expensive math operations on giant exponents (e.g.
`1.0e1000000`), executing range limits check against `dest_width + 64`
(sized) or `IntStore::MaxIntWidth` (unsized) is mandatory to prevent
out-of-bounds calculations and compile-time memory exhaustion.
---
### Step 4: Machine Code Generation (LLVM Lowering)
Inside [handle_call.cpp](../../../toolchain/lower/handle_call.cpp):
1. **Map to Native LLVM Instructions**: For runtime-eligible builtins, map the
call inside `HandleBuiltinCall` to native LLVM IR builder methods:
```cpp
case SemIR::BuiltinFunctionKind::IntConvertFloat: {
auto* operand = context.GetValue(arg_ids[0]);
auto* dest_type = context.GetTypeOfInst(inst_id);
bool is_signed = IsSignedInt(context, arg_ids[0]);
context.SetLocal(
inst_id, is_signed
? context.builder().CreateSIToFP(operand, dest_type)
: context.builder().CreateUIToFP(operand, dest_type));
return;
}
```
2. **Assert on Compile-Time-Only Builtins**: Throw a hard assertion on
lowering-cases for checked validator builtins that should never hit code
generation:
```cpp
case SemIR::BuiltinFunctionKind::IntConvertFloatChecked: {
CARBON_CHECK(builtin_kind.IsCompTimeOnly(
context.sem_ir(), arg_ids,
context.sem_ir().insts().Get(inst_id).type_id()));
CARBON_FATAL("Missing constant value for call to comptime-only function");
}
```
---
### Step 5: Standard Library Prelude Integration
Map the standard library primitive interfaces to your newly minted named
builtins under [core/prelude/](../../../core/prelude/):
- **Primitive Mappings**: Bind Carbon methods directly to string-literal
builtin equivalents:
```carbon
fn Convert[self: Self]() -> Float(To) = "int.convert_float";
```
- **Strict Orphan Rule Compliance**: Carbon's orphan rules prohibit
implementing interfaces where neither the type nor the interface is locally
defined in the backing source module.
- **Literal Conversions**: Literal types (like `FloatLiteral`,
`IntLiteral`) do not have backing Carbon source files. Therefore, an
`impl` of `UnsafeAs` (which is defined in `as.carbon`) between two
literal types must reside inside `as.carbon` itself.
- **Sized Conversions**: Implementations targeting sized primitives (e.g.
`Int(N)`, `Float(N)`) must reside in their respective type source files
(such as [int.carbon](../../../core/prelude/types/int.carbon) or
[float.carbon](../../../core/prelude/types/float.carbon)) where the
backing target type resides to prevent duplicate symbols and structural
recursion loops.
---
## High-Fidelity Validation & Test Authoring
Follow the [Toolchain tests](../toolchain_tests/SKILL.md) skill with specialized
patterns for builtins:
### 1. Checker Builtin File Splits
Create validation splits under
[toolchain/check/testdata/builtins/](../../../toolchain/check/testdata/builtins/):
- **Test Naming Convention**: All tests under
[toolchain/check/testdata/builtins/](../../../toolchain/check/testdata/builtins/)
must be named after the builtin they are testing, replacing `.` characters
in the builtin name with `/` (directories). For example, a test for the
builtin `"char_literal.convert"` must be located at
`toolchain/check/testdata/builtins/char_literal/convert.carbon`.
- **Minimal Prelude & Direct Call Isolation**: Builtin tests must **not** test
the prelude library or operators. They must use the minimal primitive
prelude (`// INCLUDE-FILE:
toolchain/testing/testdata/min_prelude/primitives.carbon`) or a smaller
prelude, and explicitly declare and call the builtin functions under test
directly (e.g., `fn Add(a: f64, b: f64) -> f64 = "float.add";`). This
isolates the testing of compiler builtins from the library prelude.
- **Min-Prelude Limitations**: Standard operators (like `+`, `-`, `/`, `<`,
etc.) are **not** available in minimized preludes because the core operators
library isn't imported. To write tests with a minimal footprint, call
primitive builtins directly (e.g. `float.negate`, `float.div`) inside your
test code to build expressions.
- **Canonicalized Float Comparison**: In SemIR, real literal representations
with identical mathematical values can result in mismatched `RealId` objects
based on spelling variations. Verify compile-time constant conversions using
canonicalized comparison functions (e.g. passing converted results through
`Expect(X as f64)`) to completely avoid spelling mismatches in expected
outputs.
- **Locals Bypass**: If validating generic implicit conversions, compile-time
arguments cannot take local runtime variable parameters. Validate
compile-time conversions by passing literal constants directly, and sized
variable implicit conversions at runtime.
### 2. Machine Codegen Lowering Splits
Create testing splits under
[toolchain/lower/testdata/builtins/](../../../toolchain/lower/testdata/builtins/):
- Emplace a simple carbon binding to the tested builtin.
- Confirm matching LLVM metadata target definitions are mapped precisely
(e.g., matching `sitofp i32 %a to float`, `fptosi float %a to i32`).
+126
View File
@@ -0,0 +1,126 @@
---
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.
## Comments
- **Describe the code that is there.** A comment should explain what the
current code does or why it is the way it is, not narrate what the code used
to be. Do not add a comment to justify a deletion or explain that something
is no longer necessary; a reader of the new code has no idea what is being
contrasted against, and the comment rots as soon as the old shape is
forgotten. Put that reasoning in the commit message instead.
- **Do not introduce a local variable just to host a comment.** If a call
argument reads clearly on its own, inline it rather than naming it so that a
comment has somewhere to attach.
- **Lead with a plain summary.** Start a doc comment with a direct statement
of what the function does or returns, such as "Returns true if the InstKind
is a singleton." Put nuance in a following sentence rather than qualifying
the summary into something harder to read.
- **Re-read a comment before updating it.** When a symbol is renamed or
changes meaning, a comment that mentions it is not automatically stale. Work
out what the comment actually asserts first: it may be describing what the
code _uses_, which is still true, and rewriting it loses information.
## Documentation
This covers standalone prose: `/docs`, `README.md` files, and the skill files
under `.agents/skills`.
- **Be true of the tree it lands in.** Documentation shipping in the same
commit as the code it describes should name that code freely. Documentation
that lands separately must not: a reader who greps for an identifier from an
unlanded change finds nothing, and a claim that only holds after that change
is false until it lands. This is easy to get wrong when writing up a lesson
while the change that taught it is still in flight.
- **Use placeholders for illustrations.** When an example only needs to show a
shape, name it `Foo` rather than reaching for a real symbol. Save real
identifiers for documenting that identifier, where going stale is at least
detectable.
- **Make each point stand alone.** A reader has none of the discussion that
produced it. State the rule, and enough of the reason to apply it, without
assuming knowledge of the change that motivated it.
## Naming
- **A name is a claim, so keep it true.** When a change invalidates the
invariant a name describes, rename it in the same change. A factory called
`MakeSingletonFooId` has to be renamed once `Foo` is no longer a singleton,
even though nothing forces you to.
- **Types in a signature are part of the claim.** A function returning the id
of a namespace should return `InstId`, not `TypeInstId`, because a namespace
is not a type. Do not let a convenient wider or narrower id type imply
something false.
- **Delete a predicate whose name stops distinguishing anything.** If a change
widens a test so that it no longer says what its name implies, remove it and
let callers use the underlying test, rather than keeping a wrapper that
sounds meaningful. What callers actually want is often the inverse, and is
worth adding under its own name.
- **Name a variable for its role, not its representation.** If the role a
value plays is unchanged, keep its name even when a change means it is now
held or spelled differently.
## Commit descriptions
- **Say what the change is, not how you made it.** Describe the resulting
code. Only describe process when the process is more interesting than the
change, as with a large mechanical transformation.
- **Do not narrate your own work.** Statements like "each such site was
audited" or "we investigated every caller" describe effort, not the change.
- **Omit routine mechanical steps.** Do not mention running the testdata
autoupdater or the formatter. Every change is expected to include those.
- **Do not enumerate each edit.** Describe the change as a whole rather than
listing every function or file touched; the diff already lists them.
- **Use the project's terms precisely.** Reach for the term of art the
codebase uses. Calling something a "type alias" or a "namespace" when it is
a named scope misleads, and is worse than a vaguer but accurate word.
- **Scope claims to what changed.** Say the specific thing that is now true,
rather than a broader statement that happens to contain it.
## Design
- **Do not distort the data model to improve output.** If printed or golden
output is undesirable, change the printer, not the data structures that
feed it.
## 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.
+261
View File
@@ -0,0 +1,261 @@
---
name: Diagnostics
description:
Instructions for declaring, formatting, emitting, testing, and styling
diagnostic messages (errors, warnings, notes) in the Carbon toolchain.
---
# Diagnostics in the Carbon Toolchain
<!--
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
-->
The Carbon compiler features a highly-engineered, context-aware diagnostics
framework designed to deliver precise, readable, and highly targetable
diagnostic output (errors, warnings, notes). This document establishes strict
rules for declaring, formatting, emitting, testing, and styling compiler
diagnostics.
---
## Architecture Overview
```mermaid
graph TD
Kind[kind.def Registry] -->|Registration| Enum[Kind Enum ID]
Enum -->|Build/Emit| Emitter[Emitter LocT]
Emitter -->|ConvertLoc| Loc[Converted Physical Loc]
Emitter -->|formatv serialization| Formatting[format_providers.h / Custom Types]
Emitter -->|Emit Messages| Consumer[Console / Sorting Consumer]
Consumer -->|stable sort| StdErr[Compiler Standard Error]
```
Diagnostics are handled via three decoupled core components:
1. **Registry**: Globally enumerated kinds inside
[kind.def](../../../toolchain/diagnostics/kind.def).
2. **Emitters**: Specialized formatting pipelines (parameterized on custom
phase location types `LocT` like `Token` or `LocId`) that convert raw tokens
to standardized physical source locations (file, line, column, and text
snippet).
3. **Consumers**: Pipelines that process, track, filter, and sort diagnostics.
The default `SortingConsumer` buffers and stable-sorts diagnostics based on
their `last_byte_offset` matching compiler traversal order to ensure perfect
causal ordering.
---
## 1. Declaring and Registering Diagnostics
All diagnostic types must pass structural uniqueness and coverage verifications.
### The Diagnostic Registry
Every diagnostic kind must be registered globally as an enum option under
[kind.def](../../../toolchain/diagnostics/kind.def):
```cpp
// toolchain/diagnostics/kind.def
CARBON_DIAGNOSTIC_KIND(RealLiteralTooLargeForUnsizedInt)
```
### The Uniqueness Rule
To ensure optimal compile-time and analysis integrity, every diagnostic kind
declared in `kind.def` **MUST** be mapped to **one and only one** C++ macro
declaration (`CARBON_DIAGNOSTIC` or `CARBON_DIAGNOSTIC_ON_SCOPE`).
- **DO NOT** duplicate diagnostic definitions across different locations.
- The C++ representation of the diagnostic is a static/global constant of type
`DiagnosticBase<Args...>`.
- **Local Scope (Recommended)**: If the diagnostic is unique to a single
block/function body, declare it **locally** inside the function body
adjacent to its `Emit` trigger:
```cpp
void ConvertFloatValueToInt(...) {
CARBON_DIAGNOSTIC(FloatNaNConvertedToInt, Error,
"cannot convert NaN to integer type {0}", SemIR::TypeId);
context.emitter().Emit(loc_id, FloatNaNConvertedToInt, dest_type_id);
}
```
- **File Scope**: If the diagnostic is shared among multiple functions inside
the _same_ file, declare it at **file scope** inside the anonymous namespace
of the `.cpp` file.
- **Global Scope**: If a diagnostic (such as a shared helper note) is reused
_across different physical files_, define it in a shared header (e.g.
context/check helpers) and mark it `extern` where applicable, ensuring the
macro is only invoked once.
---
## 2. Formatting Diagnostic Arguments
Carbon diagnostics leverage LLVM's `formatv` engine. Parameters must be passed
using strongly-typed arguments to preserve translation capability.
### String Lifetimes & Pitfalls
- **`llvm::StringRef` is DISALLOWED**: Do not pass `StringRef` as a parameter
type to `CARBON_DIAGNOSTIC` due to unsafe lifetime and buffer-allocation
boundaries.
- **`llvm::StringLiteral` is DISALLOWED**: Do not use literal types as
arguments as they prevent future diagnostic localization and translations.
- **Use `std::string`**: If string formatting or custom allocations are
required, declare the parameter storage type as `std::string`.
### Format Selectors (`format_providers.h`)
Use specialized formatting wrappers under
[format_providers.h](../../../toolchain/diagnostics/format_providers.h) to
express clean inline options in format strings:
| Wrapper | Target Format Style | Example Usage | Output |
| :------------------------- | :------------------------------ | :----------------------------- | :------------------------------------------------------------------ |
| **`BoolAsSelect`** | `{Index:true\|false}` | `"{0:is signed\|is unsigned}"` | Maps bool to selection string. |
| **`IntAsSelect`** | `{Index:=Val:String\|:Default}` | `"{0:=1:is\|:are}"` | Matches exact options. |
| **`IntAsSelect` (Plural)** | `{Index:s}` | `"{0} argument{0:s}"` | Prints `"s"` if value != 1 (e.g., `"1 argument"`, `"3 arguments"`). |
### Custom Toolchain Type Mappings
Custom structures can define how they serialize inside diagnostics using the
`DiagnosticType` tag mapping to `Diagnostics::TypeInfo<StorageType>`:
- **Identifiers & Names** (declared in `check/diagnostic_helpers.h`):
- `NameId`: Formats raw identifier spelling, safely escaping keyword
conflicts under backticks automatically.
- `LibraryNameId`: Formats custom library descriptors cleanly (e.g.
`default library` or `library "foo"`).
- **Sized Primitives**:
- `TypedInt`: Formats an `APInt` constant exactly, extracting target
signedness representation automatically from its bound type
representation.
- **Type Formatter Hierarchy**: When choosing parameter types to print
compiler type representations, follow this priority list:
1. **`TypeOfInstId` (Preferred)**: Resolves the backing type of an
`InstId`, preserving programmatic aliasing, constraints, and source
spelling context. Enclosed under backticks automatically.
2. **`InstIdAsType`**: Converts an `InstId` for a type expression, printing
custom type layouts under backticks.
3. **`TypeId` (Fallback)**: Canonical description of the type. **Avoid when
possible** because type canonicalization loses intermediate source
program spelling and aliasing metadata.
4. **`*AsRawType` (e.g. `InstIdAsRawType`, `TypeIdAsRawType`)**: Formats
the type layout exactly like their counter-structures above, but
**omits** enclosing backticks (useful when inserting types inside larger
code snippets).
---
## 3. Fluent Emission Builders & RAII Scopes
### Fluent Builder Pattern
For compound diagnostics requiring multiple sub-notes, carets, or custom code
overrides, use `Build` to chain actions fluently:
```cpp
context.emitter()
.Build(second_node, ModifierRepeated, context.token_kind(second_node))
.Note(first_node, ModifierPrevious, context.token_kind(first_node))
.OverrideSnippet("custom snippet...")
.Emit();
```
> [!SAFETY] Emitter builders are marked `[[nodiscard]]`. To prevent a developer
> from creating a builder but failing to terminal-chain `.Emit()`, the builder
> uses an rvalue overload `Emit() &&` that triggers a compile-time
> `static_assert(false)`. You must save the builder to an lvalue or execute the
> chain exactly as `emitter.Build(...).Note(...).Emit()`.
### RAII Context & Annotation Scopes
Manage large checking structures requiring blanket note context using RAII block
scopes:
- `ContextScope`: Automatically converts any diagnostics emitted within its
scope into sub-notes under a high-level operation descriptor:
```cpp
ContextScope context_scope(&context.emitter(), [&](ContextBuilder& builder) {
builder.Context(eval_loc, InCallToEvalFn);
});
// any checker error emitted here will automatically append the 'InCallToEvalFn' note
```
- `AnnotationScope`: RAII block scope that automatically attaches blanket note
annotations to all scoped diagnostics.
---
## 4. Diagnostics Wording Style Guide
Refer to the official
[Diagnostic message style guide](../../../toolchain/docs/diagnostics.md#diagnostic-message-style-guide)
for complete details.
To maintain message consistency and integrate cleanly with Clang diagnostics in
interoperable code, adhere strictly to these rules:
- **Start with lowercase and omit periods**: Start diagnostic messages with a
lowercase letter or quoted code, and do **not** end them with a period
(e.g., `"cannot convert..."` or ``"`self` declared..."``).
- **Use backticks for quoted code**: Enclose identifiers, code constructs, and
types inside standard backticks (e.g., ``"`{0}` is bad"``).
- **Phrase as bullet points without articles**: Phrase diagnostics as
descriptive bullet points or sentence fragments rather than full sentences.
Leave out standard articles (`a`, `an`, `the`) unless necessary for logical
clarity. Semicolons can be used to separate fragments within a message.
- **Describe the situation and language rule**: Diagnostics should describe
the exact situation the toolchain observed. The language rule violated can
be mentioned if it wouldn't otherwise be clear:
- _Situation-only_: `"redeclaration of X"` (implies that redeclaration is
not permitted).
- _Rule-inclusion_: ``"`self` declared in invalid context; can only be
declared in implicit parameter list"``.
- **Wording Choice ("cannot" vs "allowed")**: Explicitly avoid `"allowed"`,
`"legal"`, `"permitted"`, `"valid"`, and related passive wording. You may
use `"cannot"` if needed, but try to use phrasing that does not require it:
- _Correct_: ``"`export` in `impl` file"`` (Avoids `"allowed"`)
- _Incorrect_: ``"`export` is only allowed in API files"``
- _Correct_: ``"`extern library` specifies current library"`` (Avoids
`"cannot"`)
- _Incorrect_: ``"`extern library` cannot specify the current library"``
- **Developer Intent Hints**: It is acceptable for a diagnostic to guess at
the developer's intent and provide a hint _after_ explaining the situation
and the rule, but never as a substitute for that:
- _Correct_: ``"cannot implicitly convert `i32` to `String`; add `as
String` for explicit conversion"``
- _Incorrect_: ``"add `as String` to convert `i32` to `String`"`` (Lacks
the core violation message).
- **Structure for Tooling API**: Try to structure diagnostics such that
parameter inputs can be programmatically extracted without string parsing
(prefer strongly-typed parameters over format placeholders where possible).
---
## 5. Diagnostics Testing & Coverage Verification
Carbon strictly enforces testing coverage at build-time.
1. **Tag Verification Requirement**: Every diagnostic kind declared in
`kind.def` (which is not blacklisted in the `UntestedKinds` array under
[coverage_test.cpp](../../../toolchain/diagnostics/coverage_test.cpp))
**MUST** be verified by at least one testcase file inside
`toolchain/*/testdata/`.
2. **Stderr Checklist Matchers**: The testcase split verifying the diagnostic
must catch it using standard CHECK matchers, explicitly tracking the
matching enum tag in standard error comments:
```carbon
// CHECK:STDERR: fail_bounds.carbon:[[@LINE+1]]:15: error: cannot convert NaN to integer type `i32` [FloatNaNConvertedToInt]
let a: i32 = Convert(nan_val);
```
3. **Build Enforcement**: Failing to provide a diagnostic test check matcher
triggers a build compilation error on the target test
`//toolchain/diagnostics:coverage_test`.
+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
```
+102
View File
@@ -0,0 +1,102 @@
---
name: Jujutsu (jj) usage
description:
Instructions for using Jujutsu (jj) for version control in the Carbon
repository.
---
# Jujutsu (jj) 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
-->
[Jujutsu](https://github.com/jj-vcs/jj) is a Git-compatible version control
system that may be used in Carbon checkouts.
> [!IMPORTANT] You can detect if Jujutsu is in use by checking for a `.jj`
> directory in the repository root. If present, you **must** use `jj` and **must
> not** use `git`. If absent, you **must not** use `jj`.
## General usage
Always use the `--no-pager` flag when invoking `jj` to prevent the command from
blocking or waiting for terminal paging.
## Common commands
### Syncing with remote
- **Fetch from remote**: `jj --no-pager git fetch`
- **Create a new change on top of trunk**: `jj --no-pager new trunk`
- **Show repository status**: `jj --no-pager status`
- **Show commit history**: `jj --no-pager log`
### Managing changes
- **View diff of current changes**: `jj --no-pager diff`
- **Commit changes**: `jj --no-pager commit`
- _Note_: Prefer using `jj commit` over the combination of `jj describe`
and `jj new`.
- **Abandon/discard current changes**: `jj --no-pager abandon`
- **Rebase current change onto trunk**: `jj --no-pager rebase -o trunk`
### Working with a stack of changes
A change is often built as a stack of commits sent up as a single pull request.
The stack is not necessarily based on `trunk`; it may be based on another change
that is itself still in flight.
> [!WARNING] **Never rewrite the history of a change that has been submitted as
> a pull request.** Reviewers track a PR by its commits, and squashing,
> reordering, or abandoning them discards review that is already in progress.
> This cannot be undone from their side.
>
> Before rewriting history in any other case, propose the exact command and wait
> for confirmation. This applies to `squash`, `rebase`, `abandon`, and
> `describe` on an existing change.
#### Finding the base of the stack
Bookmarks delimit the stack. List the bookmarks that are ancestors of the
working copy, nearest first:
```bash
jj --no-pager log -r '::@ & bookmarks()'
```
Reading the result takes care, because two situations produce similar output:
- **Editing an existing change.** The nearest bookmark names the change being
worked on, and the bookmark below it is the base.
- **Starting a new change.** The commits above the nearest bookmark have no
bookmark of their own yet, so the nearest bookmark is itself the base.
`trunk` is only ever a base. Finding `trunk` nearest means new work is being
built on top of it, never that `trunk` itself is being worked on.
The graph does not distinguish the two cases: an unbookmarked or empty commit
above a bookmark may be the next commit of that change or the start of a new
one. Ask which it is when it is not clear, and ask before choosing where a fix
should land rather than after. Guessing wrong means squashing into a change that
may already be under review.
Once the base is known, use it to scope commands to the current stack:
```bash
jj --no-pager log -r '<base-bookmark>..@'
```
#### Managing the stack
- **Fold a fix into an earlier change**:
`jj --no-pager squash --into <change-id> [path]`. Follow-up fixes and
formatter reflows belong in the change that introduced the code, not in a
trailing "fixes" commit, unless that change has already been submitted.
Naming a path squashes only that part of the working copy, leaving unrelated
work in place.
- **Descriptions**: only one change in the stack needs a long description, the
one used as the pull request description. Every other change gets a short
one-line summary. Do not repeat the long text across the stack.
+197
View File
@@ -0,0 +1,197 @@
---
name: Language server
description:
Instructions for working on Carbon's LSP language server, including its
architecture, its file_test-based tests, and the VS Code extension.
---
# Language server
<!--
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 covers [`toolchain/language_server/`](/toolchain/language_server/),
which implements `carbon language-server`, and
[`utils/vscode/`](/utils/vscode/), the VS Code extension that launches it.
## Architecture
The server is built on clangd's LSP transport (`clang::clangd`), not on a
Carbon-specific one. That means clangd's `Protocol.h` types (`Position`,
`Range`, `Location`, `Hover`, `MarkupContent`) are the interface currency.
- `server.cpp` / `incoming_messages.cpp`: message dispatch. A handler must be
registered in `incoming_messages.cpp` before it can be called.
- `handle_*.cpp`: one file per request family, each declaring its entry point
in `handle.h`.
- `handle_initialize.cpp`: the advertised capabilities. **Adding a capability
changes `Content-Length` in every test that calls `initialize`**, so expect
a large autoupdate diff.
- `context.h` / `context.cpp`: `Context::File` per open document, plus the
compile driver. `Context::File::unit()` has a `CARBON_CHECK` on the compile
driver, so any handler that reaches for the parse tree must first rule out
documents that were never compiled.
- `position.h`, `sem_ir_index.h`: mapping source positions to SemIR
instructions for real Carbon files.
- `sem_ir_text.h`, `handle_sem_ir_text.h`: navigation within the *formatted
SemIR* in a test file's `// CHECK:STDOUT:` lines. This is a heuristic text
index, deliberately independent of the real SemIR data structures. See
[the SemIR text reader](#the-semir-text-reader).
### Document kinds
The server handles two kinds of document, distinguished by the `languageId`
from `textDocument/didOpen`, with a content sniff as a fallback:
- `carbon`: a real Carbon file. Compiled; diagnostics published.
- `carbon-testdata`: a test file. **Not compiled**, because we lack logic to
split it into one file per `// ---` split marker.
> [!IMPORTANT]
> A handler that assumes every file was compiled will crash on a test file.
> When adding one, give the test-file path an explicit early return.
## Tests
There is **no language-server-specific test target**.
`toolchain/language_server/BUILD` only declares
`filegroup(name = "testdata")`, which is pulled into
`//toolchain/testing:all_testdata` and run by `//toolchain/testing:file_test`.
```bash
# Run just the language server tests (or any subset).
bazelisk test //toolchain/testing:file_test \
--test_arg=--file_tests=toolchain/language_server/testdata/position/hover_and_goto.carbon
# See the raw output, which is much easier to read than a test failure.
bazelisk run //toolchain/testing:file_test -- --dump_output \
--file_tests=toolchain/language_server/testdata/position/hover_and_goto.carbon
# Update expectations. Never hand-write CHECK lines.
./toolchain/autoupdate_testdata.py toolchain/language_server/testdata/...
```
These tests run serially, because clangd's logging is a global singleton.
### Test file shape
The request stream is a `// --- STDIN` split written with the `[[@LSP-*]]`
keywords, and the responses land in a trailing `// --- AUTOUPDATE-SPLIT`.
Documents come from other splits by way of `"text": "FROM_FILE_SPLIT"`, which
is substituted with the content of the split whose name matches the `uri`.
```carbon
// --- position.carbon
fn Abs(n: i32) -> i32 { return n; }
// --- STDIN
[[@LSP-CALL:initialize:"capabilities": {}]]
[[@LSP-NOTIFY:textDocument/didOpen:
"textDocument": {
"uri": "file:/position.carbon",
"languageId": "carbon",
"text": "FROM_FILE_SPLIT"
}
]]
[[@LSP-CALL:textDocument/hover:
"textDocument": {"uri": "file:/position.carbon"},
"position": {"line": 0, "character": 3}
]]
[[@LSP-CALL:shutdown]]
[[@LSP-NOTIFY:exit]]
// --- AUTOUPDATE-SPLIT
```
Full keyword documentation is in
[`testing/file_test/README.md`](/testing/file_test/README.md).
### Traps
> [!WARNING]
> **A blank line inside the `STDIN` split breaks the JSON transport.** It
> terminates a header block, so clangd logs a timestamped
> `Warning: Missing Content-Length header, or zero-length message.` The
> timestamp makes the test unreproducible, so it fails on the next run.
> Comment lines between messages are fine; blank lines are not. A single blank
> line immediately before `// --- AUTOUPDATE-SPLIT` is also fine.
Other things worth knowing:
- **`positionEncoding` is UTF-16.** A `character` is a UTF-16 code unit
offset, not a byte offset.
- **Line and character numbers in requests are 0-based**, while the `locN_M`
suffixes in SemIR output are 1-based. Off-by-ones here are silent: the
request succeeds and returns the wrong thing.
- **A split can hold a document that itself contains `// CHECK:STDOUT:`
lines**, because `CHECK` lines only form expectations inside the
`AUTOUPDATE-SPLIT`. Such a document still can't contain a literal `// ---`
line, which would split the enclosing test file; write it as
`[[@0x2f]]/ --- name.carbon`.
## The SemIR text reader
`sem_ir_text.cpp` indexes the formatted SemIR inside a test file's
`// CHECK:STDOUT:` lines so that hover and go-to-definition work on operand
names. It is a heuristic reader, not a parser, and its correctness rests on
facts about `toolchain/sem_ir/formatter.cpp` and
`toolchain/sem_ir/inst_namer.cpp`. Re-check these if the formatter changes:
- There are exactly four scope keywords: `file`, `generated`, `imports`, and
`constants` (`InstNamer::GetScopeName`). Everything else is `@entityname`.
- A reference is `%name` within its own scope and `scope.%name` otherwise
(`InstNamer::GetNameFor`). Names may contain `.` and may _start_ with one,
as in `%.Self.frozen`.
- **Type annotations are printed in the `constants` scope.**
`Formatter::FormatTypeOfInst` does
`llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants)`,
so in `%x: %foo = ...` a bare `%foo` means `constants.%foo`. This does not
apply to ordinary operands or to `[concrete = ...]` annotations.
- **`*_decl` braces hold the declared entity's scope.** The braces of
`%F.decl: ... = fn_decl @F [...] { ... } { ... }` are lexically inside
`file { }`, but their names belong to `@F`.
- **`!with Self:` switches scope without a brace**, until `!members:`
switches it back. Brace counting alone cannot see this.
- A `specific @F(args) { }` block uses `@F`'s scope and defines nothing; each
`%name => value` row references an instruction of the generic.
### Validating a change to the reader
The unit tests only cover a handful of cases. To check a change against the
real corpus, drive the server over a sample of check testdata, hovering on
every `%name`, and compare the resolved fraction before and after. Roughly 99%
of names resolve; the residue are names the formatter references but never
emits a definition line for, such as `%I.WithSelf.F`, which only ever appears
inside a `[symbolic = ...]` annotation.
Two things to get right in such a harness:
- Feed the request stream from a **file**, not a pipe. The server reads stdin
as a file and reports `error: Input/output error` on a pipe.
- Read the output as **bytes**. Python's `text=True` rewrites the `\r\n`
framing, and `Content-Length` counts bytes.
## VS Code extension
[`utils/vscode/`](/utils/vscode/) declares three languages in `package.json`:
| Language id | Applies to |
| ---------------- | --------------------------------- |
| `carbon` | `*.carbon` |
| `carbon-testdata`| `**/testdata/**/*.carbon` |
| `semir` | `*.semir` |
> [!NOTE]
> The TextMate _scope_ for SemIR is `source.carbon-semir`, but the
> _language id_ is `semir`. Markdown code fences in hover text resolve language
> ids, so a fence must say ` ```semir `.
`extension.ts` launches the server over stdio, using the `carbonPath` setting
(default `./bazel-bin/toolchain/carbon`). Its `documentSelector` controls which
files are sent to the server at all; a new document kind has to be added there
as well as in the server.
+66
View File
@@ -0,0 +1,66 @@
---
name: Prek
description:
Instructions for running prek, the Carbon pre-submit/style/lint checker,
that *MUST* be run before submitting an change.
---
# Prek
<!--
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
-->
`prek` is the Carbon pre-submit, style, and lint checker. Running it is
mandatory before submitting any changes.
## Running prek
To run `prek` on all files:
```bash
prek run -a
```
To validate a specific list of files:
```bash
prek run --files <files>
```
## Running prek in a Jujutsu (jj) workspace
If you are working in a Jujutsu workspace, running `prek` directly will fail
because it expects a standard Git repository structure. Instead, use the helper
script:
```bash
./scripts/jj_prek.sh
```
This script runs `prek` on all files that have changed between `trunk` and your
current Jujutsu `@` change.
Note that the script always compares against `trunk`. If your change is based on
another bookmark rather than on `trunk`, the script also checks the files
changed by that underlying change, so a reported failure may not be in your own
work.
## Hooks that rewrite files
Some hooks, notably `clang-format` and `rumdl`, fix problems in place rather
than only reporting them. When they do, `prek` reports a failure and exits
non-zero even though the tree is now correct.
Re-run `prek` after any failure that modified files, and treat the second, clean
run as the result. Review what it changed: a reflow is expected, but a content
change may not be what you intended.
## Prek dependency errors
> [!TIP] If `prek` fails with an error about resolving dependencies or security
> policy, you may be running in a restricted environment where the
> special-purpose `gpkg` tool is required. Prefix the command with `gpkg`, for
> example: `gpkg prek run -a` or `gpkg ./scripts/jj_prek.sh`.
+135
View File
@@ -0,0 +1,135 @@
---
name: Proposals
description:
Instructions for writing, submitting, and managing Carbon evolution
proposals.
---
# Proposals
<!--
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
-->
## Overview
This skill provides instructions and best practices for working with proposals.
Only create a proposal when explicitly directed as part of the task.
Make sure to confirm the desired title for the proposal as that will govern the
filename.
## Create a new proposal
1. **Use the helper script**: Run `./proposals/scripts/new_proposal.py "Title"`
to create a templated file and instructions for setting up the PR.
2. **Proposal file**: The file will be named `proposals/p######-title.md`,
where `######` is the 6-digit GitHub pull request number and `title` is a
slugified version of the proposal title.
3. **Template**: Follow the structure in `proposals/scripts/template.md`,
noting the specific `TODO` instructions in each section for the content that
should be included there.
4. **PR description**: Update the pull request description to match the
abstract section in the proposal document.
> [!IMPORTANT] Do _not_ mark the PR ready for review. The user must have the
> opportunity to review the proposal produced before asking for any review.
## Writing style and best practices
- **Skimmable**: Use
[BLUF](<https://en.wikipedia.org/wiki/BLUF_(communication)>) (Bottom Line Up
Front) or
[Inverted Pyramid](<https://en.wikipedia.org/wiki/Inverted_pyramid_(journalism)>)
style. Keep it brief, focused, and technical.
- **Match existing proposal style**: Review [existing proposals](/proposals)
(preferring more recent ones with higher numbers) to understand the expected
style, wording, and nature of content to include.
- **Connect to goals**: In the Rationale section, link to specific goals in
[`/docs/project/goals.md`](/docs/project/goals.md) and principles in
[`/docs/project/principles`](/docs/project/principles) (e.g.,
`error_handling.md`, `one_way.md`).
- **Living design**: If the proposal updates design documentation, include
those changes in the PR if possible. If deferred, add "TODO" comments
pointing to the proposal (e.g., `> **TODO:** Document ... adopted in
[p######](/proposals/p######-title.md)`). For pervasive changes, file a
GitHub issue instead of adding many TODOs.
## Alternatives considered and leads decisions
There are always alternatives to a proposal, and the proposal should carefully
include sections describing all of them and the rationale for not selecting
them. Any living design document updates should focus on fully describing the
end-state design, and the key motivating aspects of that design. The main
proposal should focus on _what is changing_ and _why it is changing_, and should
leave detailed description of the resulting design to the living design
document, and _why not_ rationale to the description of each alternative.
- **Cover all the alternatives**: Make sure to describe any alternatives
considered, even if minor or rejected early.
- **Be specific**: Don't be vague about any of the alternatives, or the
rationale for not choosing them.
- **Connect to goals or principles**: In addition to the rationale section,
one of the best rationale structures for rejecting an alternative connects
that choice back to the goals or principles relevant.
- **Always frame as a tradeoff**: Selecting the proposed direction instead of
an alternative is _always_ a tradeoff, with both advantages and
disadvantages.
- **Where relevant, cite the leads issue** that decides against an
alternative, in addition to summarizing the key points, tradeoffs, and
rationale for the decision.
> [!IMPORTANT] Don't just list the alternatives, create a sub-section for each
> alternative and carefully describe the alternative, the advantages,
> disadvantages and what the core of the decision is to reject each alternative.
> [!IMPORTANT] Carefully research each alternative in the leads issue in order
> to provide this clear and comprehensive explanation.
## Building from a leads issue
Sometimes a proposal is specifically documenting and formalizing a decided leads
issue. When this is the case, carefully research that leads issue, reading the
original issue text and every comment on the issue. Also read any linked Google
documents, linked issues, examples, gists, or other supplemental information
cited.
- **Summarize the leads issue**: Ensure you provide a high level summary of
the _decided_ direction of the leads issue as the proposal.
- **Capture and document** every key aspect of the decision made and factor
that led to the decision. It is important that the proposal stands alone,
and the leads issue is merely cited for context and history.
- **Stay grounded**: Only include alternatives, rationale, and arguments based
on what you find in the issue and related documents. No new information
should be in the proposal.
Use the `gh` command line tool to query leads issues in order to carefully
examine all of the comments. Follow any mentioned links to gather more data.
Refer to the [GitHub CLI usage skill](/.agents/skills/github_cli/SKILL.md) for
detailed instructions on using the `gh` tool.
Ask the user to clarify any aspects of the leads issue that are unclear rather
than continuing to edit the proposal. If there are questions that you don't find
an answer to in the issue, ask this to the user and let them provide an answer
that you use as the basis of what to include.
## Examples are golden
Heavily leverage examples to illustrate both the specifics of the design being
proposed, and the nature of the change being proposed. More examples to
illustrate more aspects, corner cases, or provide a more complete understanding
are almost always good. Comments in example code should focus on what that part
of the example illustrates from the proposal.
## Keep the PR description in sync with the abstract
Whenever you edit the abstract or notice differences from the PR description,
you should update the PR description to match the abstract. The only exception
is to retain any "Assisted-by" or other tags at the end of the description that
are only needed there and not in the abstract.
If you are creating or updating a proposal, make sure the PR description in
question contains an `Assisted-by:` tag that is appropriate for describing which
AI tool is being used.
@@ -0,0 +1,366 @@
---
name: Review testdata changes
description:
Instructions for judging whether changes to file test output
(`// CHECK:STDOUT:` and `// CHECK:STDERR:` lines) are correct, which
changes are acceptable churn, and which are regressions in disguise.
---
# Review 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
-->
## Introduction
Most toolchain work moves file test output. `./toolchain/autoupdate_testdata.py`
rewrites the `// CHECK:STDOUT:` and `// CHECK:STDERR:` lines in
`toolchain/*/testdata/` to match current behavior, so after running it the tests
pass again whether or not the new behavior is right. Deciding that the new
output is the output you wanted is a separate, manual step, and it is the step
this skill covers.
Three skills divide the work:
- [Toolchain tests](../toolchain_tests/SKILL.md): how to _author_ tests and
generate their output.
- This skill: how to _judge_ an output diff.
- [Summarize testdata changes](../summarize_testdata_changes/SKILL.md): how to
_report_ an output diff once you believe it is correct.
> [!IMPORTANT] Never hand-edit `// CHECK:STDOUT:` or `// CHECK:STDERR:` lines.
> Everything below is about changing the _code_ until the generated output is
> right, never about editing the output to match the code.
## The rule that generates all the others
**Every line of testdata churn must have a cause you can name.** Not "it is
similar to the other changes", not "the tests pass now" — an actual sentence
saying which code change produced it and why that is the intended result.
A diff you cannot narrate is a diff you have not reviewed. Changes you cannot
explain are where regressions hide, because a regression and an intended change
look exactly alike once the autoupdater has written them down.
> [!CAUTION] Autoupdating is destructive to your evidence. Once the autoupdater
> has run, the previous expectations are gone from the working copy. Read the
> diff after _every_ autoupdate run, and if something changed for a reason you
> cannot name, fix the code before autoupdating again. Recovering the old
> expectations later means reverting and re-running.
## STDERR and STDOUT are different kinds of evidence
Treat them separately; they have different standards of proof.
**STDERR is user-visible behavior.** These are the diagnostics a Carbon
programmer sees. A change here is a change to the language implementation as
users experience it, so each one needs an individual justification. For a
refactoring, the expected STDERR diff is empty.
**STDOUT is internal representation.** SemIR dumps, parse trees, LLVM IR. Users
never see it. Churn here is normal and often unavoidable, so the standard is not
"no change" but "no change I cannot account for".
For a change that is supposed to preserve behavior, write the list of accepted
STDERR changes down _before_ you autoupdate, and keep it current. Order matters
more than form: written first, the list is a prediction the diff can falsify;
written afterwards, it is a description of whatever happened, and describes a
regression exactly as well as an intended change.
The list does not have to be a deliverable. Scratch notes you never publish do
the job, because the work is in committing to the list, not in presenting it.
What a reader needs is not the list but its exceptions: diagnostics that changed
without being predicted, and predictions that did not occur. Both are findings.
The matches are not, and reporting them buries the two entries that matter.
## Judging STDOUT churn
Sort each STDOUT change into mechanical or structural.
### Mechanical churn
Expected, and cheap to accept in bulk once you have confirmed the pattern:
- **Renaming.** An instruction, type, or scope prints under a new name.
- **Positional name renumbering.** Names like `%x.loc18_46.3` embed a line,
column, and disambiguating index. Two different events move them:
- Adding or removing an instruction at a location renumbers the rest, so a
_single_ removed instruction can show up as many changed lines in the
same block. Confirm the cascade is a cascade before accepting it as one.
- Adding or removing a _diagnostic_ moves the source lines themselves, so
the line component changes everywhere below it in the file. See
[Autoupdate to a fixed point](#autoupdate-to-a-fixed-point).
- **Fingerprint-derived names.** Mangled names and some scope names are
derived from a hash of their inputs. If you changed a hashed input, these
move. Confirm that each such difference is _only_ the fingerprint, and not a
fingerprint difference concealing a structural one.
> [!TIP] Mechanical churn is usually wide and shallow: the same substitution,
> repeated across many files. If a "mechanical" pattern needs a different
> explanation in each file, it is not mechanical.
### Structural churn
Each of these needs its own explanation:
- Instructions appearing or disappearing.
- Changed `[concrete = ...]`, `[symbolic = ...]`, or other constant-value
annotations.
- Changed types on existing instructions.
- Changed control flow: new or removed blocks, changed branch targets.
- Raw instruction ids renumbering in `--dump-raw-sem-ir` output when you did
not intend to change the id layout.
## Fewer instructions is not automatically better
A diff that removes instructions looks like an optimization. Whether it is one
depends on what the changed function owes its caller, and two functions can
produce the same shrinking diff for opposite reasons:
- A function that only needs a constant value, but built instructions on the
way to it, was doing wasted work. Dropping them and using the constant
directly is correct, and the shorter output reflects that.
- A function whose caller needs a **non-canonical instruction** can be made
shorter the same way, by using the constant instead of creating an
instruction of its own — and that is wrong. The instruction carries location
information, and symbolic constant substitution operates on it; the constant
value alone loses both.
The instruction count is identical evidence in both cases, so it cannot be the
thing you judge. Decide what the function is required to produce; the count
follows from that.
The same reasoning runs in reverse: a diff that _adds_ instructions is not
automatically a regression.
## Judging STDERR churn
### A diagnostic's authority depends on the file's prefix
The `fail_` and `todo_` prefixes (see
[Toolchain tests](../toolchain_tests/SKILL.md)) say how much the recorded
diagnostics are worth:
- **`fail_...`** — the test should and does produce errors. The recorded
diagnostic **is the specification**. Changing it is a user-visible behavior
change and needs justification on its own merits.
- **`fail_todo_...`** — the test produces errors (or crashes) but shouldn't,
or produces the wrong errors. The recorded diagnostic is explicitly **not**
the specification; the file exists to record that today's behavior is wrong.
Changing it replaces one wrong answer with another. That is acceptable when
you can say why the new message follows from your change and why it is no
further from the intended eventual behavior — which, for many such files, is
no diagnostic at all.
- **`todo_fail_...`** — the test should produce errors but does not. Gaining a
diagnostic here may be _progress_, not a regression. Either way the file
must be renamed, since the framework requires a `fail_` prefix on any file
that errors: `fail_...` if it now produces the right error, `fail_todo_...`
if the error is the wrong one. Both renames make the test pass, so record
which case it is instead of letting the rename settle it.
- **`todo_...`** — behavior is wrong but produces no errors, and shouldn't.
Gaining a diagnostic here is a regression unless you can argue otherwise.
> [!IMPORTANT] This is a reason to look at the _filename_ before judging a
> diagnostic change, not a license to ignore `todo_` files. "It was already
> broken" does not excuse making it differently broken for no reason.
### Reclassifying tests
If your change moves a test between the states above, the prefix must move with
it: when the test is fixed, when it starts failing, and when it starts failing
differently. The correspondence between the `fail_` prefix and whether
compilation actually failed is enforced by the test framework, not by the
autoupdater, so it surfaces when you run `bazelisk test` and not when you
autoupdate. **Autoupdating is not a substitute for running the tests.**
Only that half of the name is checked. Nothing enforces `todo_`, so a file whose
behavior you have just fixed can keep its `todo_` prefix indefinitely and still
pass. A missing `fail_` stops the build; a stale `todo_` is silent, and is yours
to catch.
When a fix drops a file's prefix, also check that the file still belongs where
it is and that its comments do not still describe the old broken behavior.
### Vaguer diagnostics are a signal, not a verdict
When a diagnostic becomes less specific — a general "unsupported" message
replacing one that named the problem — that usually means a code path stopped
finding information it previously had. Sometimes that is correct: the
information was misleading, and the old message was confidently wrong.
Do not accept it silently and do not reject it reflexively. Say which direction
it moved and whether the new message is closer to or further from the eventual
intended behavior.
## Signals in the shape of the diff
### Zero churn is a result
If you removed something you believed was doing work and _no_ testdata moved,
that is not a missing test run — it is the proof that the thing was a no-op.
Say so explicitly; it is one of the strongest pieces of evidence a refactoring
can produce.
The converse is also informative. If you expected a path to churn and it didn't,
either your model of the code is wrong or that path is untested. Find out which,
and consider adding a test before continuing.
### Churn should be proportional to the change
- **Wide churn from a narrow change** means your model of the code is wrong.
Do not autoupdate over it. Find the structural mistake first.
- **Narrow churn from a sweeping change** means the affected paths are
probably untested.
Set a rough expectation for the size of the diff before you run the autoupdater,
and treat a large mismatch in either direction as a finding.
### Never make the diff smaller by weakening the test
Editing test _input_ (the Carbon source, not the CHECK lines) to make a diff
look better is a behavior change in disguise. Deleting a test that now produces
awkward output is worse. If a test's input has to change, that is a separate,
explicitly-justified change, not diff cleanup.
## What the autoupdater will not fix for you
- **`NOAUTOUPDATE` files.** Their expectations are maintained by hand. They
fail under `bazelisk test` rather than being silently rewritten.
- **Hand-written C++ expectations**, for example golden output asserted in a
`_test.cpp`. When several assertions in one of these break together, often
only the first failure is reported, so fixing it can reveal another. Re-run
until clean rather than assuming one fix was the whole repair.
- **Golden files outside `testdata/`**, and documentation that quotes compiler
output.
## Review loop
### Run the autoupdater
Autoupdate everything, then read the diff a directory at a time. Passing no
paths is the default and updates every file test in the toolchain:
```bash
./toolchain/autoupdate_testdata.py
```
Narrow the scope only while iterating on one subdirectory you know you are not
done with, where each round would otherwise regenerate output you have already
read:
```bash
./toolchain/autoupdate_testdata.py toolchain/check/testdata/SUBDIR/**/*
```
The globs are expanded by the shell; the script filters its arguments to
`.carbon` files under a `testdata/` directory.
> [!TIP] If intermediate states crash on `CARBON_CHECK` failures, pass
> `--non-fatal-checks` so you can see the full set of downstream damage in one
> run instead of one crash at a time.
> [!IMPORTANT] Return to the full scope before judging the diff. Whether churn
> is proportional to the change, and whether a change to one phase moved another
> phase's testdata, are only visible across everything.
### Autoupdate to a fixed point
One pass is not always enough, because the autoupdater's output is part of its
own input. `// CHECK:STDERR:` lines sit inline, immediately above the source
line they describe, and the compiler reads them as comments in the file.
Gaining or losing a diagnostic therefore moves every source line below it.
Within a single run, the compiler has already read the file as it was, so the
two kinds of output end up in different states:
- **STDERR is correct after one pass.** These lines locate themselves
relatively, as `[[@LINE+N]]`, and the autoupdater recomputes `N` as it
places them.
- **STDOUT is stale after one pass.** SemIR names like `%x.loc18_46.3` embed
an absolute line and column with no filename attached, and the autoupdater
only remaps `file.carbon:18`-style references. Nothing rewrites the `loc`,
so it still describes where the instruction was _before_ the diagnostic
lines moved it.
Running again compiles the shifted file and the names catch up. The diagnostic
set does not change this time, so nothing shifts again and a third run is a
no-op. Keep running the autoupdater until it stops changing files: one pass when
the diagnostics held still, two when they didn't.
> [!WARNING] The intermediate state is self-inconsistent, not just unfinished:
> its `loc` names describe a file layout that no longer exists. Keep reading the
> diff after every run — that rule does not change — but do not chase positional
> churn to a cause until the file has converged, and do not present the diff
> until then either.
The converging pass should be positional renumbering and nothing else. If it
moves an instruction, a type, or a constant value, then something other than a
`loc` name is sensitive to where lines fall in the file. Find out what before
accepting it.
The file tests do catch a file left unconverged, since each test re-runs the
autoupdate in memory and fails with
`Autoupdate would make changes to the file content` when the result differs. But
that arrives at `bazelisk test` time, after you have already read a diff that
was describing a file which had moved out from under it.
### Inspect the diff
Inspect the diagnostics first, since that is the acceptance criterion:
```bash
# STDERR-only view, with jj.
jj --no-pager diff --git 'glob:toolchain/*/testdata/**' \
| grep -E '^[-+].*CHECK:STDERR'
# The same, with git.
git diff -- 'toolchain/*/testdata/*' \
| grep -E '^[-+].*CHECK:STDERR'
```
For a structured view separating test input, STDERR, and STDOUT changes, use the
helper from the
[Summarize testdata changes](../summarize_testdata_changes/SKILL.md) skill:
```bash
jj --no-pager diff --git 'glob:toolchain/*/testdata/**' \
| python3 .agents/skills/summarize_testdata_changes/scripts/parse_diff.py
git diff -- 'toolchain/*/testdata/*' \
| python3 .agents/skills/summarize_testdata_changes/scripts/parse_diff.py
```
The argument after the tool name is not interchangeable: `glob:...` is a jj
fileset, `-- ...` is a git pathspec. `--git` and `--no-pager` are jj flags; git
already emits this format and skips the pager when piped.
### Run the tests
Then run the tests, which is what catches prefix mismatches and non-autoupdated
expectations:
```bash
bazelisk test //toolchain/...
```
See the [Bazel usage](../bazel/SKILL.md) skill.
## Checklist
Before presenting a testdata diff as finished:
- [ ] The autoupdater was run until it made no further changes, so no `loc`
name describes a stale line numbering.
- [ ] The list of accepted STDERR changes was written before autoupdating, and
every change either matches it or is reported as an exception.
- [ ] Every STDOUT change is either an instance of a named mechanical pattern
or has its own explanation.
- [ ] Instructions that appeared or disappeared are justified by what the
changed function owes its caller, not by the instruction count.
- [ ] Files whose prefix no longer matches their behavior have been renamed.
- [ ] No test input was changed, and no test was deleted, to make the diff
smaller.
- [ ] The size of the diff is proportional to the size of the change.
@@ -0,0 +1,209 @@
---
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.
This skill is about _reporting_ a diff. For deciding whether the diff is correct
in the first place, see the
[Review testdata changes](../review_testdata_changes/SKILL.md) skill.
## 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 Dict, List, TextIO
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)
@@ -0,0 +1,169 @@
---
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.
- **Builtin Functions**: Refer to the **Builtin functions** skill
([SKILL.md](../builtins/SKILL.md)) for guidelines on registering, mapping,
constant evaluating, and lowering compiler builtin primitives (e.g.
`"int.convert_float"`).
- **Language server**: Refer to the **Language server** skill
([SKILL.md](../language_server/SKILL.md)) before working on
`toolchain/language_server/` or `utils/vscode/`. Neither follows the
patterns described here.
- **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
- **Compiler Diagnostics**: Refer to the **Diagnostics** skill
([SKILL.md](../diagnostics/SKILL.md)) for strict rules on declaring,
formatting, emitting, testing, and styling compiler diagnostic messages
(errors, warnings, notes).
- **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.
### Context-Aware Diagnostics
When declaring and emitting errors, ensure semantic wording matches the exact
context:
- **Semantic Precision**: Do not reference "types" when raising errors for
unsized expressions like `IntLiteral` or `FloatLiteral`. For example, use
`RealLiteralTooLargeForUnsizedInt` instead of a diagnostic referencing an
"integer type".
- **Wording Consistency**: Before declaring a new diagnostic in
[kind.def](../../../toolchain/diagnostics/kind.def), search for existing
diagnostics in the targeted implementation files (for example, other uses of
`MaxIntWidth`) to align message structures and parameter expectations.
### 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.
### Leverage LLVM APIs
Before implementing custom algorithms for mathematical, logical, or bitwise
operations, inspect target LLVM ADT class APIs:
- **Builtin APIs**: Verify if LLVM classes (such as `APInt`, `APFloat`, or
`APSInt`) already offer native equivalents (for example, `.pow()`,
`ilogb()`, `.changeSign()`, `convertFromAPInt()`). Avoid duplicate, naive,
or inefficient custom loops.
### 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.
6. **Builtin implementation gaps**: If adding a primitive builtin function,
make sure you address all phases of the lifecycle: macro definition
registration, signature validation, compile-time constant evaluation
(interpreter), LLVM IR lowering, and prelude modular implementation bindings
(avoiding orphan rules). Refer to the **Builtin functions** skill
([SKILL.md](../builtins/SKILL.md)) for details.
7. **Premature helper abstraction**: Avoid extracting tiny helper functions
that are called from exactly one place and do not significantly modularize
complex code. Prefer inlining directly to keep the implementation compact,
readable, and localized.
8. **Redundant bounds calculations**: Avoid repeating calculations of complex
boundary estimations (such as lower and upper bound estimations). Refactor
the logic to calculate unified values once, preserving compactness.
9. **Trusting stale `clangd` diagnostics**: In-editor diagnostics are only as
good as `compile_commands.json`. If it predates a newly added file, `clangd`
falls back to a default command and reports nonsense, such as missing
standard headers or "no member named `None`". Regenerate it with
`./scripts/create_compdb.py`, which only takes a few seconds.
+193
View File
@@ -0,0 +1,193 @@
---
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.
Language server tests also use `file_test`, but with quite different
conventions (an LSP message stream, `AUTOUPDATE-SPLIT`, `FROM_FILE_SPLIT`).
Refer to the **Language server** skill
([SKILL.md](../language_server/SKILL.md)) for those.
## 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.
- **Builtin Primitive Testing**: Standard operators (such as `+`, `-`, `/`,
`<`, etc.) are **not** imported or available inside minimized preludes. To
write tests with a minimal prelude footprint, call primitive builtins
directly (e.g., `float.negate`, `float.div`) inside your test code to build
expressions.
### 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]]";
// ...
```
- **Always** use `library "[[@TEST_NAME]]";` in each split rather than
hardcoding the library name. This prevents name conflicts, avoids redefining
the default library, and keeps the test code clean and templateable.
- Exactly `[[@TEST_NAME]]` (including the brackets) must 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]]`.
### Constant Evaluation Validation
When testing constant evaluation in semantic checker tests, follow these
conventions to ensure diagnostic stability and accuracy:
- **Literal Spelling Canonicalization**: In Semantic IR, real literals
(floating-point constants) with identical mathematical values can be
assigned distinct internal representation identifiers based on spelling
variations in source code. To completely prevent literal spelling mismatches
in expected output checks, validation tests must be performed using
canonical comparison methods (for example, passing converted values through
an `Expect(X as f64)` function).
- **Generic Parameters Validation**: To bypass compile-time constraints where
local runtime variables are rejected as generic function arguments, test
generic type conversions at runtime, and validate compile-time conversions
by passing static literal values directly into primitive builtin calls.
- **Exhaustive Edge Case Verification**: For complex mathematical algorithms
(such as floating-point to integer truncation and rounding), map and execute
test constraints covering every code branch, conditional exit, and fallback
evaluation path.
- **Rounding Threshold Boundaries**: Test cases that land extremely close to
mathematical boundaries (for example, floating-point literals representing a
tiny fraction above 1.0, such as $2^{30} \times 2^{-30}$ or
$10^{10} \times 10^{-10}$, verifying correct exact truncation down to 1 or
0).
- **Precise Float Literal Spelling**: Spell floating-point literals in test
code with exact mathematical precision targeting target thresholds. For
example, if testing the smallest fractional increment above 1.0, use the
exact hex fractional representation (e.g. `0x1.0000000000001p0`) or a highly
precise decimal fractional spelling (e.g. `1.0000000000000001`) instead of
coarse fractions like `1.1` to ensure correct boundary assertions.
- **Representation Capacity Boundaries**: Explicitly target edge cases near
representation limits of target types. Test combinations of mantissas and
exponents that yield values exactly on, just below, or just above the
capacity limits of fixed-size destination types (e.g. signed/unsigned
targets like `i32` or `u32`).
- **Zero-Value Sizing Bounds**: Verify boundary inputs of `0` and `0.0`
explicitly. Assert that zero inputs are sized and simplified correctly
without triggering calculation underflows, division-by-zero errors, or
underestimating required bit allocations.
### 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.
Autoupdating makes the tests pass whether or not the new behavior is correct, so
deciding that the new output is the output you wanted is a separate step. See
the [Review testdata changes](../review_testdata_changes/SKILL.md) skill.
+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
+21 -10
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.
@@ -42,7 +45,11 @@ build --use_target_config_carbon_rules
# Default to using a disk cache to minimize re-building LLVM and Clang which we
# try to avoid updating too frequently to minimize rebuild cost. The location
# here can be overridden in the user configuration where needed.
common --disk_cache=~/.cache/carbon-lang-build-cache
#
# We avoid the disk cache on MacOS because it breaks debugging. When the cache
# is used, the separate debug symbol files are not perserved.
common:linux --disk_cache=~/.cache/carbon-lang-build-cache
common:windows --disk_cache=~/.cache/carbon-lang-build-cache
# If you'd like a different disk cache size, override it by copying this
# line to `user.bazelrc` in the repository root and modify the number there.
common --experimental_disk_cache_gc_max_size=100G
@@ -82,12 +89,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 +125,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
@@ -168,7 +180,6 @@ common --incompatible_disallow_empty_glob
common --incompatible_disallow_legacy_py_provider
common --incompatible_disallow_sdk_frameworks_attributes
common --incompatible_disallow_struct_provider_syntax
common --incompatible_do_not_split_linking_cmdline
common --incompatible_dont_enable_host_nonhost_crosstool_features
common --incompatible_dont_use_javasourceinfoprovider
common --incompatible_enable_apple_toolchain_resolution
+1 -1
View File
@@ -1 +1 @@
8.3.1
8.6.0
+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
+61
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'
@@ -34,22 +35,48 @@ Checks:
- '-readability-make-member-function-const'
- '-readability-math-missing-parentheses'
- '-readability-static-definition-in-anonymous-namespace'
- '-readability-trailing-comma'
- '-readability-use-anyofallof'
# These are copies of older google- prefixed rules that have been moved
# out of that prefix, but the google- prefix names still exist as aliases to
# these. We enable the google- prefix rules and use those in our NOLINT
# expressions, so we disable the newer aliased rules.
#
# Alias for google-explicit-constructor.
- '-misc-explicit-constructor'
# Alias for google-readability-casting.
- '-modernize-avoid-c-style-cast'
# Warns when we have multiple empty cases in switches, which we do for comment
# reasons.
- '-bugprone-branch-clone'
# We use CRTP inheritence widely and across distant areas of the codebase,
# which makes maintaining friend lists for the constructors frustrating.
- '-bugprone-crtp-constructor-accessibility'
# We shadow methods with CRTP, instead of using virtual, such as for Print().
- '-bugprone-derived-method-shadowing-base-method'
# Frequently warns on multiple parameters of the same type.
- '-bugprone-easily-swappable-parameters'
# Finds issues like out-of-memory in main(). We don't use exceptions, so it's
# unlikely to find real issues.
- '-bugprone-exception-escape'
# We have File class types in different namespaces and we forward declare it,
# but don't find this to be problematic.
- '-bugprone-forward-declaration-namespace'
# Doesn't respect `[[clang::enum_extensibility(open)]]`.
- '-bugprone-invalid-enum-default-initialization'
# Has false positives in places such as using an argument to declare a name,
# which cannot have parentheses. For our limited use of macros, this is a
# common conflict.
- '-bugprone-macro-parentheses'
# Conflicts with integer type C++ style.
- '-bugprone-narrowing-conversions'
# We return const references from value stores.
- '-bugprone-return-const-ref-from-parameter'
# Complains about reasonable code like `1 << 20` and would push us away from
# our integer type C++ style rules.
- '-bugprone-signed-bitwise'
# Has false positives for `enum_base.h`. Clang's built-in switch warnings
# cover most of our risk of bugs here.
- '-bugprone-switch-missing-default-case'
@@ -66,6 +93,8 @@ Checks:
# Extremely slow. TODO: Re-enable once
# https://github.com/llvm/llvm-project/issues/128797 is fixed.
- '-misc-confusable-identifiers'
# We use multiple inheritence without virtual extensively.
- '-misc-multiple-inheritance'
# Overlaps with `-Wno-missing-prototypes`.
- '-misc-use-internal-linkage'
# Suggests `std::array`, which we could migrate to, but conflicts with the
@@ -88,13 +117,32 @@ Checks:
- '-readability-enum-initial-value'
# Warns too frequently.
- '-readability-function-cognitive-complexity'
# Allows naming styles we don't use, and has errors on our use of `_1`, `_2`
# to have multiple unnamed vars in a destructuring declaration.
- '-readability-identifier-naming'
# Warns on use of CARBON_KIND() and can't use NOLINT effectively inside a
# macro.
- '-readability-inconsistent-ifelse-braces'
# Warns in reasonably documented situations.
- '-readability-magic-numbers'
# Warns on `= {}` which is also used to indicate which fields do not need to
# be explicitly initialized in aggregate initialization.
- '-readability-redundant-member-init'
# We generally do want to collapse if statements, and ask for it in review.
# But this check ignores when ifs are nested to place comments above/below
# the nested if block. And when the outer if block is also initializing a
# variable. There are more than a handful of cases where we want to do this,
# especially working with LLVM apis like dyn_cast.
- '-readability-redundant-nested-if'
# Broken, wants to remove parens from `*(p + 1)` and `("Foo" + s).str()`.
# TODO: Re-enable once https://github.com/llvm/llvm-project/issues/192435 and
# related bugs are fixed.
- '-readability-redundant-parentheses'
# Warns when callers use similar names as different parameters.
- '-readability-suspicious-call-argument'
# Low value check, and it's a stylistic choice to use `#if defined(...)` when
# paired with `#elif defined(...)`.
- '-readability-use-concise-preprocessor-directives'
CheckOptions:
# Don't warn on structs; done by ignoring when there are only public members.
@@ -110,6 +158,10 @@ CheckOptions:
value: CamelCase
- key: readability-identifier-naming.NamespaceCase
value: CamelCase
# Headers re-open LLVM and Clang namespaces to forward-declare their types,
# which is much cheaper to compile than including their headers.
- key: readability-identifier-naming.NamespaceIgnoredRegexp
value: '^(clang|llvm)$'
- key: readability-identifier-naming.StructCase
value: CamelCase
- key: readability-identifier-naming.TemplateParameterCase
@@ -142,3 +194,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
+14 -3
View File
@@ -6,9 +6,11 @@ CompileFlags:
# Workaround for https://github.com/clangd/clangd/issues/1582
Remove: [-march=*]
Diagnostics:
# `unused-includes`: has false positives, reporting includes unused when
# they are used.
Suppress: [unused-includes]
# `unneeded-internal-declaration`, `unused-function`, `unused-includes`,
# `unused-template`: These all have false positives due to not performing
# template instantiation. We get a more reliable version of these warnings
# from the compiler.
Suppress: [unneeded-internal-declaration, unused-function, unused-includes, unused-template]
---
@@ -19,3 +21,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
AnyOther
ArchType
atleast
circularly
@@ -16,6 +18,7 @@ groupt
indext
inout
isELF
iterm
parameteras
pullrequest
rightt
+16 -9
View File
@@ -11,13 +11,12 @@ inputs:
runs:
using: composite
steps:
# Setup Python and related tools.
- uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
# Setup Python and related tools with uv.
- name: Set up uv and Python
uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.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' }}
enable-cache: true
version: '0.11.15'
- uses: ./.github/actions/build-setup-macos
if: startsWith(inputs.matrix_runner, 'macos')
@@ -38,9 +37,10 @@ runs:
bazelisk --version
echo '*** run_bazel.py'
./scripts/run_bazel.py --version
echo '*** python'
which python
python --version
echo '*** uv'
which uv
uv --version
uv python list --only-installed
echo '*** clang'
which clang
clang --version
@@ -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
+8 -8
View File
@@ -23,12 +23,12 @@ runs:
xcrun simctl delete all
sudo rm -rf ~/Library/Developer/CoreSimulator/Caches/*
# Install and cache LLVM 19 from Homebrew. Some runners may have LLVM 19,
# Install and cache LLVM 21 from Homebrew. Some runners may have LLVM 21,
# but this is reliable (including with libc++), and gives us testing at the
# 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
@@ -46,7 +46,7 @@ runs:
}}
# Note the key needs to include all the packages we're adding.
key:
Homebrew-Cache-${{ inputs.matrix_runner }}-${{ runner.arch }}-llvm@19
Homebrew-Cache-${{ inputs.matrix_runner }}-${{ runner.arch }}-llvm@21
- name: Install LLVM and Clang with Homebrew
if: steps.cache-homebrew-macos.outputs.cache-hit != 'true'
@@ -60,11 +60,11 @@ runs:
LEAVES=$(brew leaves | egrep -v '^(bazelisk|gh|git|git-lfs|gnu-tar|go@.*|jq|pipx|node@.*|openssl@.*|wget|yq|zlib)$')
brew uninstall -f --ignore-dependencies $LEAVES
echo '*** Installing LLVM deps'
brew install --force-bottle --only-dependencies llvm@19
brew install --force-bottle --only-dependencies llvm@21
echo '*** Installing LLVM itself'
brew install --force-bottle --force --verbose llvm@19
echo '*** brew info llvm@19'
brew info llvm@19
brew install --force-bottle --force --verbose llvm@21
echo '*** brew info llvm@21'
brew info llvm@21
echo '*** brew autoremove'
brew autoremove
echo '*** brew info'
@@ -77,7 +77,7 @@ runs:
- name: Setup LLVM and Clang
shell: bash
run: |
LLVM_PATH="$(brew --prefix llvm@19)"
LLVM_PATH="$(brew --prefix llvm@21)"
echo "Using ${LLVM_PATH}"
echo "${LLVM_PATH}/bin" >> $GITHUB_PATH
echo '*** ls "${LLVM_PATH}"'
+20 -7
View File
@@ -22,23 +22,34 @@ runs:
# to save time.
large-packages: false
# Select the LLVM release - by the cache key and the download.
- name: Select LLVM release
shell: bash
run: |
if [[ "${{ runner.arch }}" == "ARM64" ]]; then
echo "LLVM_RELEASE=21.1.8" >> "$GITHUB_ENV"
else
echo "LLVM_RELEASE=21.1.8" >> "$GITHUB_ENV"
fi
# Cache and install a recent version of LLVM. This uses the GitHub action
# cache to avoid directly downloading on each iteration and improve
# 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 }}
key: LLVM-${{ env.LLVM_RELEASE }}-Cache-ubuntu-${{ runner.arch }}
- name: Download LLVM and Clang installation
if: steps.cache-llvm-ubuntu.outputs.cache-hit != 'true'
shell: bash
run: |
cd ~
LLVM_RELEASE=19.1.7
LLVM_TARBALL_NAME=LLVM-$LLVM_RELEASE-Linux-X64
# `LLVM_RELEASE` comes from the "Select LLVM release" step; `runner.arch`
# (`X64`/`ARM64`) matches the package's arch suffix.
LLVM_TARBALL_NAME=LLVM-$LLVM_RELEASE-Linux-${{ runner.arch }}
LLVM_PATH=~/llvm
echo "*** Downloading $LLVM_RELEASE"
wget --show-progress=off "https://github.com/llvm/llvm-project/releases/download/llvmorg-$LLVM_RELEASE/$LLVM_TARBALL_NAME.tar.xz"
@@ -50,10 +61,12 @@ runs:
echo "*** Testing `clang++ --version`"
$LLVM_PATH/bin/clang++ --version
# The installation contains *huge* parts of LLVM we don't need for the
# toolchain. Prune them here to keep our cache small.
# toolchain. Prune them here to keep our cache small. x86-64 and
# AArch64 use different LLVM releases whose tool sets differ, so `-f`
# ignores entries that are absent from a given package.
echo "*** Cleaning the 'llvm' directory"
rm $LLVM_PATH/lib/{*.a,*.so,*.so.*}
rm $LLVM_PATH/bin/{flang-*,mlir-*,clang-{scan-deps,check,repl},*-test,llvm-{lto*,reduce,bolt*,exegesis,jitlink},bugpoint,opt,llc}
rm -f $LLVM_PATH/lib/{*.a,*.so,*.so.*}
rm -f $LLVM_PATH/bin/{flang-*,mlir-*,clang-{scan-deps,check,repl},*-test,llvm-{lto*,reduce,bolt*,exegesis,jitlink},bugpoint,opt,llc}
echo "*** Size of the 'llvm' directory"
du -hs $LLVM_PATH
+2 -1
View File
@@ -18,7 +18,8 @@ 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:
- pre_commit.yaml (Bazel, pre-commit)
- clangd_tidy.yaml (Bazel)
- prek.yaml (Bazel, prek)
- 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
+56
View File
@@ -0,0 +1,56 @@
# 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 PRs'
on:
pull_request_target:
types: [opened, synchronize, ready_for_review, closed]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
statuses: write
jobs:
check_dependent_prs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
allowed-endpoints: >
api.github.com:443 github.com:443 pypi.org:443
files.pythonhosted.org:443 raw.githubusercontent.com:443
releases.astral.sh:443
# Note: pull_request_target checks out the base branch by default.
# This is safe as it avoids running untrusted code from the PR branch.
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Set up uv
uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with:
enable-cache: true
version: '0.11.15'
- name: Check Dependent PR
run: |
if [ "$EVENT_ACTION" = "closed" ]; then
./github_tools/check_dependent_pr.py --scan
else
./github_tools/check_dependent_pr.py --pr-number "${PR_NUMBER}"
fi
env:
GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_ACTION: ${{ github.event.action }}
-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
+21 -11
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,34 +26,49 @@ 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
raw.githubusercontent.com:443
registry.npmjs.org:443
release-assets.githubusercontent.com:443
releases.astral.sh: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
with:
persist-credentials: false
- id: filter
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
with:
predicate-quantifier: 'every'
filters: |
has_cpp:
- added|modified: '{**/*.cpp,**/*.h}'
- '!**/*.tpl.h'
list-files: 'shell'
- uses: ./.github/actions/build-setup-common
@@ -67,13 +81,9 @@ jobs:
if: steps.filter.outputs.has_cpp == 'true'
run: ./scripts/create_compdb.py
- name: Install clangd-tidy
if: steps.filter.outputs.has_cpp == 'true'
run: pip install clangd-tidy==1.1.0.post2
- name: Run clangd-tidy
if: steps.filter.outputs.has_cpp == 'true'
env:
FILTER_FILES: ${{ steps.filter.outputs.has_cpp_files }}
run: |
clangd-tidy -p . -j 10 $FILTER_FILES
uvx --with clangd-tidy==1.1.0.post2 clangd-tidy -p . -j 10 $FILTER_FILES
+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
+12 -3
View File
@@ -22,16 +22,25 @@ 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
with:
persist-credentials: false
- name: Set up uv
uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with:
enable-cache: true
version: '0.11.15'
- 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
+23 -11
View File
@@ -18,29 +18,36 @@ concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages.
permissions:
contents: read
pages: write
id-token: write
permissions: {}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
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
with:
persist-credentials: false
- name: Set up uv
uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with:
enable-cache: true
version: '0.11.15'
- 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
@@ -49,15 +56,16 @@ jobs:
- name: Build with Jekyll
env:
JEKYLL_ENV: production
STEPS_PAGES_OUTPUTS_BASE_PATH: ${{ steps.pages.outputs.base_path }}
run: |
bundle exec jekyll build --verbose \
--source ./ \
--destination ./_site \
--baseurl "${{ steps.pages.outputs.base_path }}"
--baseurl "${STEPS_PAGES_OUTPUTS_BASE_PATH}"
- 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:
@@ -65,9 +73,13 @@ jobs:
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages.
permissions:
pages: write
id-token: write
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
+24 -10
View File
@@ -37,26 +37,40 @@ 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
raw.githubusercontent.com: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
with:
persist-credentials: false
- name: Set up remote cache access
env:
@@ -79,10 +93,10 @@ jobs:
run: |
./scripts/run_bazel.py \
--attempts=5 --jobs-on-last-attempt=4 \
test -c opt --remote_download_toplevel \
--pre_release=nightly --nightly_date=${{ env.nightly_date }} \
test -c opt --stamp --remote_download_toplevel \
--pre_release=nightly --nightly_date=${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
@@ -101,8 +115,8 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create \
--title "Nightly build ${{ env.nightly_date }}" \
--title "Nightly build ${nightly_date}" \
--generate-notes \
--prerelease \
v${{ env.release_version }} \
"bazel-bin/toolchain/install/carbon_toolchain-${{ env.release_version }}.tar.gz"
v${release_version} \
"bazel-bin/toolchain/install/carbon_toolchain-${release_version}.tar.gz"
@@ -2,7 +2,7 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: pre-commit
name: prek
on:
pull_request:
@@ -14,34 +14,44 @@ permissions:
contents: read # For actions/checkout.
jobs:
pre-commit:
prek:
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
raw.githubusercontent.com:443
registry.npmjs.org:443
release-assets.githubusercontent.com:443
releases.astral.sh: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
with:
persist-credentials: false
# Ensure LLVM is set up consistently.
- uses: ./.github/actions/build-setup-common
@@ -49,22 +59,22 @@ jobs:
matrix_runner: ubuntu-22.04
remote_cache_upload: '--remote_upload_local_results=false'
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
- uses: j178/prek-action@01345c78b7de7d79edf368729212760396ba9345 # v2
# We want to automatically create github suggestions for pre-commit file
# We want to automatically create github suggestions for prek file
# changes for a pull request. But `pull_request` actions never have write
# permissions to the repository, so we create the suggestions in a separate
# privileged `workflow_run` action in pre_commit_suggestions.yaml. Here,
# privileged `workflow_run` action in prek_suggestions.yaml. Here,
# we upload the diffs and event configuration to an artifact for use by
# that action.
- name: Collect pre-commit output
- name: Collect prek output
if: failure()
run: |
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
mkdir -p prek-output
git diff > prek-output/diff
cp $GITHUB_EVENT_PATH prek-output/event
- uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
if: failure()
with:
name: pre-commit output
path: pre-commit-output/*
name: prek output
path: prek-output/*
@@ -2,11 +2,11 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# Create PR suggestions based on problems found by pre-commit action.
name: 'Add pre-commit suggestions'
# Create PR suggestions based on problems found by prek action.
name: 'Add prek suggestions'
# This action is run whenever the `pre-commit` action finishes. Because the
# `pre-commit` action is an unprivileged action running on (for example) the
# This action is run whenever the `prek` action finishes. Because the
# `prek` action is an unprivileged action running on (for example) the
# `pull_request` event, it's run without write permissions to the repository, so
# we use a separate privileged `workflow_run` action here to pick up its results
# and convert them into suggestion comments.
@@ -15,7 +15,7 @@ name: 'Add pre-commit suggestions'
# this file will not take effect until they are merged to trunk.
on:
workflow_run:
workflows: [pre-commit]
workflows: [prek]
types:
- completed
@@ -25,15 +25,14 @@ permissions:
jobs:
pull-request-suggestions:
# Only generate suggestions if pre-commit for a PR failed.
# Only generate suggestions if prek 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,17 +47,19 @@ jobs:
with:
reviewdog_version: latest
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Download pre-commit output
uses: actions/download-artifact@c850b930e6ba138125429b7e5c93fc707a7f8427 # v4.1.4
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
name: pre-commit output
persist-credentials: false
- name: Download prek output
uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0
with:
name: prek output
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ github.event.workflow_run.id }}
# Use https://github.com/reviewdog/reviewdog to create PR suggestions
# matching the diff that pre-commit created.
# matching the diff that prek created.
- name: Create suggestions
env:
REVIEWDOG_GITHUB_API_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
+4 -2
View File
@@ -25,13 +25,15 @@ 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
with:
persist-credentials: false
# Run the sync script.
- name: Sync to other repositories
+43 -11
View File
@@ -22,36 +22,67 @@ 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]
# Test a recent version of each supported OS, covering both x86-64 and
# AArch64: Linux on x86-64 and AArch64, and macOS on AArch64.
runner: ['ubuntu-22.04', 'ubuntu-22.04-arm', 'macos-14']
# 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
raw.githubusercontent.com:443
registry.npmjs.org:443
release-assets.githubusercontent.com:443
releases.astral.sh: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
with:
persist-credentials: false
- id: test-setup
uses: ./.github/actions/test-setup
@@ -65,7 +96,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 +107,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
+15 -1
View File
@@ -9,7 +9,13 @@
/github_tools/bazel-*
/github_tools/MODULE.bazel.lock
# Directories created by python.
# We also have example Bazel projects that shouldn't have their implementation
# details committed.
/examples/**/bazel-*
/examples/**/MODULE.bazel.lock
# Files and directories created by python.
uv.lock
**/__pycache__/
# Ignore the user's VSCode settings and debug setup.
@@ -34,6 +40,7 @@
# vim temporary files
.*.sw[a-p]
.swp
# generated by utils/tree_sitter/helix.sh
/.helix/
@@ -43,3 +50,10 @@
# Ignore the .gdb_history that's created next to the project-specific .gdbinit
.gdb_history
# Generated by scripts/create_compdb.py
/external
# Linux perftools output
perf.data
perf.data.old
+73 -38
View File
@@ -11,8 +11,7 @@ default_language_version:
python: python3 # Defaults to python2, so override it.
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: cef0300fd0fc4d2a87a85fa2093c6b283ea36f4b # frozen: v5.0.0
- repo: builtin
hooks:
- id: check-added-large-files
- id: check-case-conflict
@@ -29,11 +28,34 @@ repos:
exclude: '^(.*/fuzzer_corpus/.*|.*\.svg)$'
- id: trailing-whitespace
exclude: '^(.*/fuzzer_corpus/.*|.*/testdata/.*\.golden|.*\.svg)$'
# Run markdown linting early so that doc style and table-of-contents see the
# linted state.
- repo: https://github.com/rvben/rumdl-pre-commit
rev: v0.2.58
hooks:
- id: rumdl
args: [--fix]
- repo: https://github.com/google/pre-commit-tool-hooks
rev: efaea7c61c774c0b1a9805fd999e754a2d19dbd1 # frozen: v1.2.5
hooks:
- id: check-google-doc-style
exclude: |
(?x)^(
.*\.agents/.*|
.*AGENTS.md
)$
- id: markdown-toc
# Re-run markdown linting to fix any issues caused by doc style and TOC. This
# is very fast, so it shouldn't be problematic to run twice.
- repo: https://github.com/rvben/rumdl-pre-commit
rev: v0.2.58
hooks:
- id: rumdl
args: [--fix]
- repo: local
hooks:
- id: fix-cc-deps
@@ -44,10 +66,29 @@ repos:
pass_filenames: false
# 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
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 0c7b6c989466a93942def1f84baf36ddfcd60c83 # frozen: v0.15.14
hooks:
- id: black
- id: ruff-check
args: [--fix]
- id: ruff-format
- repo: local
hooks:
- id: ty
name: ty
entry: ty check --no-progress
language: python
additional_dependencies:
- ty==0.0.46
- rich
- 'gql>=2.0.0,<3.0.0'
- PyGitHub
- types-requests
- requests
types: [python]
pass_filenames: false
- repo: local
hooks:
- id: prettier
@@ -56,7 +97,7 @@ repos:
# TODO: Not upgrading to/past 3.4.0 due to list indent changes that may
# get fixed. See: https://github.com/prettier/prettier/issues/16929
additional_dependencies: ['prettier@3.3.3']
types_or: [html, javascript, json, markdown, yaml]
types_or: [html, javascript, json, yaml]
entry: npx prettier@3.3.3 --write --log-level=warn
- repo: local
hooks:
@@ -64,7 +105,7 @@ repos:
name: Bazel buildifier
entry: scripts/run_buildifier.py
# Beyond just formatting, explicitly fix lint warnings.
args: ['--lint=fix', '--warnings=all', '-r', '.']
args: ['--lint=fix', '--warnings=all']
language: python
files: |
(?x)^(
@@ -90,7 +131,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:
@@ -107,6 +148,23 @@ repos:
entry: scripts/check_sha_filenames.py
language: python
files: ^.*/fuzzer_corpus/.*$
- id: check-proposal-names
name: Check proposal names
entry: proposals/scripts/check_proposal_names.py
language: python
files: ^proposals/p.*\.md$
# This edits files other than the ones passed to it, so we need each
# chunk of files to be run through the script serially.
require_serial: true
# This also renames files, invalidating the list of files provided to
# subsequent checks so we fail-fast if this makes changes.
fail_fast: true
- id: build-textmate-grammar
name: Build TextMate grammar
entry: scripts/update_tm_language.py
language: system
files: ^utils/vscode/carbon\.tmLanguage\.json$
pass_filenames: false
- id: check-toolchain-diagnostics
name: Check toolchain diagnostics
entry: toolchain/diagnostics/check_diagnostics.py
@@ -129,35 +187,8 @@ repos:
language: python
files: ^.*/BUILD$
pass_filenames: false
- repo: https://github.com/PyCQA/flake8
rev: d93590f5be797aabb60e3b09f2f52dddb02f349f # frozen: 7.3.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: '850d8bf806620ef89a99381c5cf5ea2c1ea826dd' # frozen: v1.17.0
hooks:
- id: mypy
# Use setup.cfg to match the command line.
args:
- --config-file=setup.cfg
# This should match the requirements added in the WORKSPACE pip_install.
additional_dependencies:
- gql >= 2.0.0, < 3.0.0
- PyGitHub
- rich
# Exclusions are:
# - p#### scripts because they're not tested or maintained.
# - lit.cfg.py because it has multiple copies, breaking mypy.
# - Unit tests because they sometimes violate typing, such as by
# assigning a mock to a function.
exclude: |
(?x)^(
proposals/(?!scripts/).*|
.*/lit\.cfg\.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', '*']
@@ -195,7 +226,7 @@ repos:
- ''
- '*/'
- --custom_format
- '\.(plist)$'
- '\.(plist|tmLanguage)$'
- '<!--'
- ''
- '\-->'
@@ -212,13 +243,14 @@ repos:
- --custom_format
- '\.lua$'
- ''
- '-- '
- '\-- '
- ''
exclude: |
(?x)^(
.bazelversion|
.github/pull_request_template.md|
.python-version|
LICENSE.*|
compile_flags.txt|
github_tools/requirements.txt|
third_party/.*|
@@ -238,6 +270,7 @@ repos:
name: Check build graph
entry: scripts/check_build_graph.py
language: python
pass_filenames: false
files: |
(?x)^(
.*BUILD.*|
@@ -249,7 +282,9 @@ repos:
# This excludes third-party code, and patches to third-party code.
exclude: |
(?x)^(
\.jj/.*|
MODULE.bazel.lock|
.*package-lock\.json|
bazel/bazel_clang_tidy/.*\.patch|
bazel/google_benchmark/.*\.patch|
bazel/libpfm/.*\.patch|
+1 -1
View File
@@ -1 +1 @@
3.10
3.12
+83
View File
@@ -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
[global]
exclude = [
".clang-tidy",
".git",
".jj",
"CHANGELOG.md",
"LICENSE.md",
".github/pull_request_template.md",
]
respect-gitignore = true
# Disable rules that produce the most noise initially. Some of these might make
# sense to re-enable.
disable = [
"MD033", # Inline HTML - commonly used in real-world markdown
"MD036", # Emphasis used instead of heading
"MD040", # Code blocks should have a language specified
"MD014", # Commands in code blocks should show output
"MD034", # Bare URLs
"MD059", # Link text should be descriptive
"MD028", # Blank line inside blockquote
]
# Line wrapping
[MD013]
reflow = true
# Note that we might want to use the "normalize" reflow mode to have more
# consistent line wrapping, however this mode is currently deeply incompatible
# with inline HTML that we use reasonably often. For now, we go with the default
# mode that doesn't try to normalize wrapping.
reflow-mode = "default"
ignore-link-urls = false
code-blocks = false
code-spans = false
atomic-spans = false
headings = false
stern = true
# Heading style
[MD003]
style = "atx"
# Narrow restriction on trailing punctuation in headings -- allows ':' and '!'.
[MD026]
punctuation = ".,;"
# Unordered list marker style
[MD004]
style = "dash"
# Ordered list numbering
[MD029]
style = "one-or-ordered"
# Unordered list indentation
[MD007]
style = "fixed"
indent = 4
[MD077]
style = "aligned"
# Spaces after list markers
[MD030]
ul-single = 3
ul-multi = 3
ol-align-column = 4
# Code block style
[MD046]
style = "fenced"
# Emphasis style
[MD049]
style = "underscore"
# Strong style
[MD050]
style = "asterisk"
+3 -2
View File
@@ -4,8 +4,9 @@
"bierner.github-markdown-preview",
"carbon-lang.carbon-vscode",
"esbenp.prettier-vscode",
"rvben.rumdl",
"llvm-vs-code-extensions.vscode-clangd",
"ms-python.black-formatter",
"ms-python.python"
"charliermarsh.ruff",
"astral-sh.ty"
]
}
+20
View File
@@ -10,6 +10,25 @@
"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",
"settings set target.max-string-summary-length 10000",
"env TEST_TARGET=//toolchain/testing:file_test",
"env TEST_TMPDIR=/tmp"
]
},
{
"type": "lldb-dap",
"request": "launch",
"name": "file_test (all files) (lldb)",
"program": "bazel-bin/toolchain/testing/file_test",
"args": [],
"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 +52,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",
+30
View File
@@ -0,0 +1,30 @@
# 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
contributing to the Carbon Language project.
## General instructions
- **Communication**: Be concise, professional, and technical. Use GitHub-style
markdown.
- **Verification**: Always run relevant tests.
## 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.
## Version control
> [!IMPORTANT] Never rewrite the history of a change that has been submitted as
> a pull request. Reviewers track a PR by its commits, and rewriting them
> discards their in-progress review. Ask before rewriting history in any case.
> Refer to the [Jujutsu (jj) usage skill](/.agents/skills/jj/SKILL.md) for
> details.
+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
+54 -19
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
@@ -226,27 +227,54 @@ trying to write proposals, both types of contributor access will help.
Please see our [contribution tool](/docs/project/contribution_tools.md)
documentation for information on setting up a git client for Carbon development,
as well as helpful tooling that will ease the contribution process. For example,
[pre-commit](https://pre-commit.com) is used to simplify
[prek](https://github.com/j178/prek) is used to simplify
[code review](/docs/project/code_review.md).
#### 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.
@@ -378,9 +405,9 @@ respectful, and don't drown out other discussion.
Changes to Carbon documentation follow the
[Google developer documentation style guide](https://developers.google.com/style).
Markdown files should additionally use [Prettier](https://prettier.io) for
formatting, which we automate with
[pre-commit](/docs/project/contribution_tools.md#main-tools).
Markdown files should additionally use [rumdl](https://github.com/rvben/rumdl)
for formatting, which we automate with
[prek](/docs/project/contribution_tools.md#running-prek).
Other style points to be aware of are:
@@ -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.
+75 -70
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.18")
bazel_dep(name = "rules_pkg", version = "1.2.0")
bazel_dep(name = "rules_shell", version = "0.8.0")
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,52 +64,38 @@ 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.3.3", 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-08-09.
llvm_project_version = "fc44a4fcd3c54be927c15ddd9211aca1501633e7"
# 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",
integrity = "sha256-0iiuvlWDxpxOSP16jhSePSLuba+urpQAlGcUPTLZv8Q=",
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-09-08.
commit = "7024b9e1b423b3c3c6ac76ab6a73cb2c9e4ef842",
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",
"@carbon//bazel/llvm_project:0004_Introduce_filegroups_for_compiler_rt_builtins_runtime.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:0006_Add_more_libc_math_excludes.patch",
"//bazel/llvm_project:0011_Temporarily_remove_reference_to_hermetic_toolchain.patch",
],
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.
@@ -133,10 +109,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",
python_version = "3.12",
)
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",
)
+645 -271
View File
File diff suppressed because it is too large Load Diff
+28 -4
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">
@@ -248,10 +251,10 @@ 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.
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:
@@ -362,6 +365,27 @@ Learn more about the Carbon project:
Carbon focused talks from the community:
### 2026
- Carbon memory safety: a first deep dive (July 10,
[video](https://drive.google.com/file/d/1tQlzpnbWZfn2WtTFMoJgF93QteByBBwm/view?usp=sharing),
[transcript](https://docs.google.com/document/d/1JB9H3KzVixAPC5WIytS4AMyrvjwzC7TXqp596veLT34/edit?usp=sharing),
[slides](https://chandlerc.blog/slides/2026-memory-safety-deep-3/))
- Benchmarking and optimizing the Carbon compiler, NDC {Toronto} (May 5-8)
([video](https://www.youtube.com/watch?v=hN6KcAKfTN0),
[slides](https://chandlerc.blog/slides/2026-ndc-toronto-carbon-benchmarking))
- Carbon: graduating from the experiment, NDC {Toronto} (May 5-8)
([video](https://www.youtube.com/watch?v=WJl4ftb5Fxg),
[slides](https://chandlerc.blog/slides/2026-ndc-toronto-carbon-update/))
### 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))
-1
View File
@@ -1 +0,0 @@
bazel-out/../../_main
+303 -41
View File
@@ -4,22 +4,61 @@
"""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_api_files = []
dep_link_inputs = []
deps = ctx.attr.deps + ctx.attr._default_deps
for dep in 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()
if CarbonLibraryInfo in dep:
carbon_info = dep[CarbonLibraryInfo]
dep_link_inputs += carbon_info.objs.to_list()
dep_api_files += carbon_info.apis
# 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, []),
]
srcs_and_flags = [(ctx.files.srcs, dep_flags)]
objs = []
for (srcs, extra_flags) in srcs_and_flags:
for src in srcs:
@@ -32,44 +71,189 @@ 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,
src.short_path.removeprefix(ctx.label.package).removesuffix(src.extension),
))
objs.append(out)
srcs_reordered = [s for s in srcs if s != src] + [src]
srcs_reordered = dep_api_files + [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"] +
["--no-include-carbon-core"] +
[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 = depset(direct = objs + dep_link_inputs),
executable = toolchain_driver,
tools = depset(toolchain_data),
arguments = ["link", "--output=" + bin.path] + [o.path for o in objs],
tools = depset(direct = toolchain_data + prebuilt_runtimes),
arguments = full_link_flags,
mnemonic = "CarbonLink",
progress_message = "Linking " + bin.short_path,
)
return [DefaultInfo(files = depset([bin]), executable = bin)]
CarbonLibraryInfo = provider(
doc = "Contains information about a linkage unit of one or more compiled Carbon libraries.",
fields = {
"apis": "The api source files to provide to library consumers.",
"objs": "A depset of one or more compiled library files, including impl and api.",
},
)
def _carbon_library_impl(ctx):
toolchain_driver = ctx.executable.internal_exec_toolchain_driver
toolchain_data = ctx.files.internal_exec_toolchain_data
# 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
# Pass any C++ flags from our dependencies onto Carbon.
dep_flags = []
dep_hdrs = []
dep_api_srcs = []
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)
if CarbonLibraryInfo in dep:
carbon_info = dep[CarbonLibraryInfo]
dep_api_srcs += carbon_info.apis.to_list()
# Build object files for the library impls and api file
srcs_and_flags = [(ctx.files.srcs + ctx.files.hdrs, dep_flags)]
objs = []
for (srcs, extra_flags) in srcs_and_flags:
for src in srcs:
# Build each source file. For now, we pass all sources to each compile
# because we don't have visibility into dependencies and have no way to
# specify multiple output files. Object code for each input is written
# into the output file in turn, so the final carbon source file
# specified ends up determining the contents of the object file.
#
# TODO: This is a hack; replace with something better once the toolchain
# supports doing so.
#
# 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,
src.short_path.removeprefix(ctx.label.package).removesuffix(src.extension),
))
objs.append(out)
srcs_reordered = dep_api_srcs + [s for s in srcs if s != src] + [src]
ctx.actions.run(
outputs = [out],
inputs = depset(direct = srcs_reordered, transitive = dep_hdrs),
executable = toolchain_driver,
tools = depset(toolchain_data),
arguments = ["compile", "--output=" + out.path, "--output-last-input-only"] +
["--no-include-carbon-core"] +
extra_flags + ctx.attr.flags + [s.path for s in srcs_reordered],
mnemonic = "CarbonCompile",
progress_message = "Compiling " + src.short_path,
)
return [CarbonLibraryInfo(apis = ctx.files.hdrs, objs = depset(objs))]
# We synthesize two sets of attributes from mirrored `select`s here
# because we want to select on an internal property of these attributes
# but that isn't `select`-able. Instead, we have both attributes and
# `select` which one we use.
_select_internal_exec_toolchain_driver = select({
Label("//bazel/carbon_rules:use_target_config_carbon_rules_config"): None,
"//conditions:default": Label("//toolchain/install:carbon-busybox"),
})
_select_internal_exec_toolchain_data = select({
Label("//bazel/carbon_rules:use_target_config_carbon_rules_config"): None,
"//conditions:default": Label("//toolchain/install:install_data"),
})
_select_internal_exec_prebuilt_runtimes = select({
Label("//bazel/carbon_rules:use_target_config_carbon_rules_config"): None,
"//conditions:default": Label("//toolchain/install:built_runtimes"),
})
_select_internal_target_toolchain_driver = select({
Label(
"//bazel/carbon_rules:use_target_config_carbon_rules_config",
): Label("//toolchain/install:carbon-busybox"),
"//conditions:default": None,
})
_select_internal_target_toolchain_data = select({
Label(
"//bazel/carbon_rules:use_target_config_carbon_rules_config",
): Label("//toolchain/install:install_data"),
"//conditions:default": None,
})
_select_internal_target_prebuilt_runtimes = select({
Label(
"//bazel/carbon_rules:use_target_config_carbon_rules_config",
): Label("//toolchain/install:built_runtimes"),
"//conditions:default": None,
})
_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], [CarbonLibraryInfo]]),
"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 +263,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",
),
@@ -92,42 +279,117 @@ _carbon_binary_internal = rule(
executable = True,
cfg = "target",
),
"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"),
"_default_deps": attr.label_list(default = [Label("//core:io")]),
},
executable = True,
fragments = ["cpp"],
)
def carbon_binary(name, srcs):
_carbon_library_internal = rule(
implementation = _carbon_library_impl,
attrs = {
"deps": attr.label_list(allow_files = True),
"flags": attr.string_list(),
"hdrs": attr.label_list(allow_files = [".carbon"]),
# 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",
),
"internal_exec_toolchain_driver": attr.label(
allow_single_file = True,
executable = True,
cfg = "exec",
),
# 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",
),
"internal_target_toolchain_driver": attr.label(
allow_single_file = True,
executable = True,
cfg = "target",
),
"srcs": attr.label_list(allow_files = [".carbon"]),
"_cc_toolchain": attr.label(default = "//toolchain/install:carbon_stage1_cc_toolchain"),
},
executable = False,
fragments = ["cpp"],
)
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,
internal_exec_toolchain_driver = _select_internal_exec_toolchain_driver,
internal_exec_toolchain_data = _select_internal_exec_toolchain_data,
internal_exec_prebuilt_runtimes = _select_internal_exec_prebuilt_runtimes,
internal_target_toolchain_driver = _select_internal_target_toolchain_driver,
internal_target_toolchain_data = _select_internal_target_toolchain_data,
internal_target_prebuilt_runtimes = _select_internal_target_prebuilt_runtimes,
)
# We synthesize two sets of attributes from mirrored `select`s here
# because we want to select on an internal property of these attributes
# but that isn't `select`-able. Instead, we have both attributes and
# `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",
}),
internal_exec_toolchain_data = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": None,
"//conditions:default": "//toolchain/install:install_data",
}),
internal_target_toolchain_driver = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:prefix_root/bin/carbon",
"//conditions:default": None,
}),
internal_target_toolchain_data = select({
"//bazel/carbon_rules:use_target_config_carbon_rules_config": "//toolchain/install:install_data",
"//conditions:default": None,
}),
def carbon_library(name, hdrs = [], srcs = [], deps = [], flags = [], tags = [], visibility = []):
"""Compiles a Carbon library.
Note: This carbon_library is designed as a _linkage_unit_, and does not necessarily
have to correlate the Carbon language library concept. As such it is designed to
accommodate more than one api file.
The arguments `hdrs` and `srcs` are kept for reasons of convention and compatibility
with C++ toolchains, particularly build aspects that folks might want to reuse on
mixed projects.
Args:
name: The name of the build target.
hdrs: List of one or more api files.
srcs: List of zero or more implementation files.
deps: List of dependencies.
flags: Extra flags to pass to the Carbon compile command.
tags: Tags to apply to the rule.
visibility: Visibility rules for the library.
"""
_carbon_library_internal(
name = name,
hdrs = hdrs,
srcs = srcs,
deps = deps,
flags = flags,
tags = tags,
visibility = visibility,
internal_exec_toolchain_driver = _select_internal_exec_toolchain_driver,
internal_exec_toolchain_data = _select_internal_exec_toolchain_data,
internal_exec_prebuilt_runtimes = _select_internal_exec_prebuilt_runtimes,
internal_target_toolchain_driver = _select_internal_target_toolchain_driver,
internal_target_toolchain_data = _select_internal_target_toolchain_data,
internal_target_prebuilt_runtimes = _select_internal_target_prebuilt_runtimes,
)
+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_bootstrapping.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,219 @@
# 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 rules for bootstrapping the Carbon toolchain."""
load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
load("//toolchain/runtimes:carbon_runtimes.bzl", "carbon_runtimes_build")
load(
":carbon_cc_toolchain_config.bzl",
"carbon_cc_toolchain",
)
def _bootstrap_transition_impl(_, attr):
return {
"//:bootstrap_stage": attr.stage,
# Note that we need to either set or clear the runtimes build flag each
# time we transition to a different bootstarp stage or we can
# incorrectly inherit an unexpected state.
"//:runtimes_build": attr.enable_runtimes_build,
}
_bootstrap_transition = transition(
inputs = [],
outputs = [
"//:bootstrap_stage",
"//:runtimes_build",
],
implementation = _bootstrap_transition_impl,
)
def _filegroup_with_stage_impl(ctx):
return [DefaultInfo(files = depset(ctx.files.srcs))]
filegroup_with_stage = rule(
implementation = _filegroup_with_stage_impl,
attrs = {
"enable_runtimes_build": attr.bool(default = False),
"srcs": attr.label_list(mandatory = True, cfg = _bootstrap_transition),
"stage": attr.int(mandatory = True),
"_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.",
)
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.
"""
impl_tags = tags if "manual" in tags else tags + ["manual"]
filegroup_with_stage(
name = name + "_stage_only",
srcs = srcs,
stage = stage,
tags = impl_tags,
)
_exec_filegroup(
name = name + "_with_exec",
srcs = [":" + name + "_stage_only"],
tags = impl_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 = _bootstrap_transition,
)
def carbon_bootstrapped_cc_toolchain(
name,
all_hdrs,
base_files,
clang_hdrs,
platforms,
runtimes_cfg,
build_stage = 1,
base_stage = 0,
tags = []):
"""Create a bootstrapped Carbon `cc_toolchain` for the current target.
This builds on `carbon_cc_toolchain`, but enables bootstrapping the produced
toolchain from a base stage's toolchain.
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.
"""
impl_tags = tags if "manual" in tags else tags + ["manual"]
filegroup_with_stage_and_exec(
name = "{}_clang_hdrs".format(name),
srcs = clang_hdrs,
stage = base_stage,
tags = impl_tags,
)
filegroup_with_stage_and_exec(
name = "{}_base_files".format(name),
srcs = base_files,
stage = base_stage,
tags = impl_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 = impl_tags,
)
filegroup_with_stage_and_exec(
name = "{}_compile_files".format(name),
srcs = [":{}_base_files".format(name)] + all_hdrs,
stage = base_stage,
tags = impl_tags,
)
# The runtimes build for this stage of the bootstrap is only compatible with
# both the build stage and the runtimes build. We'll induce those below, and
# constrain them here to avoid any other usage.
carbon_runtimes_build(
name = "{}_runtimes_build".format(name),
config = runtimes_cfg,
clang_hdrs = ["{}_clang_hdrs".format(name)],
tags = impl_tags,
)
# Wrap the runtimes build in a filegroup that both sets the stage to the
# build stage as well as enabling runtimes building. Note that this is _not_
# the base stage -- runtimes should be built by the same stage, simply using
# the runtimes build setting.
filegroup_with_stage(
name = "{}_runtimes".format(name),
srcs = [":{}_runtimes_build".format(name)],
stage = build_stage,
enable_runtimes_build = True,
tags = impl_tags,
)
carbon_cc_toolchain(
name = name,
platforms = platforms,
base_files_target = ":{}_base_files".format(name),
runtimes_compile_files_target = ":{}_runtimes_compile_files".format(name),
compile_files_target = ":{}_compile_files".format(name),
runtimes_target = ":{}_runtimes".format(name),
extra_toolchain_settings = [":is_bootstrap_stage_{}".format(build_stage)],
tags = tags,
)
@@ -0,0 +1,380 @@
# 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("@rules_cc//cc:action_names.bzl", "ACTION_NAMES", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"action_config",
"flag_group",
"flag_set",
"tool",
"tool_path",
)
load(
"@rules_cc//cc:defs.bzl",
"CcToolchainConfigInfo",
"cc_toolchain",
)
load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
load(
"carbon_clang_variables.bzl",
"clang_include_dirs",
"clang_resource_dir",
"clang_sysroot",
)
load(
"cc_toolchain_actions.bzl",
"all_c_compile_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 ACTION_NAME_GROUPS.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 ACTION_NAME_GROUPS.all_cc_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 = []
sdk_settings = []
if clang_sysroot != "None" and clang_sysroot != "/":
builtin_sysroot = clang_sysroot
sysroot_include_search = ["%sysroot%/usr/include"]
# On MacOS, the compiler depends on this file at the root of the SDK,
# and it ends up in the `.d` files.
sdk_settings = ["%sysroot%/SDKSettings.json"]
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 + sdk_settings,
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) + [tool_path(name = "carbon-busybox", path = "carbon-busybox")],
)
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 _runtimes_transition_impl(_, attr):
return {
"//:runtimes_build": True,
}
_runtimes_transition = transition(
inputs = [],
outputs = [
"//:runtimes_build",
],
implementation = _runtimes_transition_impl,
)
def _filegroup_with_runtimes_build_impl(ctx):
return [DefaultInfo(files = depset(ctx.files.srcs))]
filegroup_with_runtimes_build = rule(
implementation = _filegroup_with_runtimes_build_impl,
attrs = {
"srcs": attr.label_list(mandatory = True, cfg = _runtimes_transition),
"_allowlist_function_transition": attr.label(
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
),
},
doc = "A filegroup whose sources are built with or without runtimes building enabled.",
)
def carbon_cc_toolchain(
name,
platforms,
base_files_target,
runtimes_compile_files_target,
compile_files_target,
runtimes_target,
extra_toolchain_settings = [],
tags = []):
"""Create a Carbon `cc_toolchain` for the current target.
This macro constructs the configuration and toolchain rules for a baseline
Carbon toolchain, including building its own runtimes on demand.
Args:
name: The base name for the toolchain targets.
platforms: Supported platforms.
base_files_target: Target for base files.
runtimes_compile_files_target: Target for runtimes compile files.
compile_files_target: Target for compile files.
runtimes_target: Target for runtimes.
extra_toolchain_settings: Extra toolchain settings.
tags: Tags to apply to the toolchain.
"""
impl_tags = tags if "manual" in tags else tags + ["manual"]
carbon_cc_toolchain_config(
name = "{}_runtimes_toolchain_config".format(name),
identifier_prefix = "{}_runtimes".format(name),
target_cpu = select({
":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_target,
tags = impl_tags,
)
cc_toolchain(
name = "{}_runtimes_cc_toolchain".format(name),
all_files = runtimes_compile_files_target,
ar_files = base_files_target,
as_files = runtimes_compile_files_target,
compiler_files = runtimes_compile_files_target,
dwp_files = base_files_target,
linker_files = base_files_target,
objcopy_files = base_files_target,
strip_files = base_files_target,
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 = impl_tags,
)
native.toolchain(
name = "{}_runtimes_toolchain".format(name),
target_settings = [":is_runtimes_build"] + extra_toolchain_settings,
use_target_platform_constraints = True,
toolchain = ":{}_runtimes_cc_toolchain".format(name),
toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
tags = tags,
)
carbon_cc_toolchain_config(
name = "{}_toolchain_config".format(name),
identifier_prefix = name,
target_cpu = select({
":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_target,
bins = base_files_target,
tags = impl_tags,
)
native.filegroup(
name = "{}_linker_files".format(name),
srcs = [
base_files_target,
runtimes_target,
],
tags = impl_tags,
)
native.filegroup(
name = "{}_all_files".format(name),
srcs = [
compile_files_target,
":{}_linker_files".format(name),
],
tags = impl_tags,
)
cc_toolchain(
name = "{}_cc_toolchain".format(name),
all_files = ":{}_all_files".format(name),
ar_files = base_files_target,
as_files = compile_files_target,
compiler_files = compile_files_target,
dwp_files = ":{}_linker_files".format(name),
linker_files = ":{}_linker_files".format(name),
objcopy_files = base_files_target,
strip_files = base_files_target,
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 = impl_tags,
)
native.toolchain(
name = name + "_toolchain",
target_settings = [":not_runtimes_build"] + extra_toolchain_settings,
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,21 @@
# 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", "ACTION_NAME_GROUPS")
# all_c_compile_actions includes actions that compile C or assembly.
all_c_compile_actions = [
x
for x in ACTION_NAME_GROUPS.all_cc_compile_actions
if x not in ACTION_NAME_GROUPS.all_cpp_compile_actions
]
# preprocessor_compile_actions includes actions that run the preprocessor.
preprocessor_compile_actions = [
x
for x in ACTION_NAME_GROUPS.all_cc_compile_actions
if x not in [ACTION_NAMES.assemble, ACTION_NAMES.cpp_module_codegen]
]
@@ -0,0 +1,129 @@
# 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", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
)
# 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 = ACTION_NAME_GROUPS.all_cc_compile_actions,
flag_groups = [flag_group(
expand_if_available = "user_compile_flags",
flags = ["%{user_compile_flags}"],
iterate_over = "user_compile_flags",
)],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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,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
"""Defines `cc_toolchain_config` features specific to the Carbon project."""
load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
"with_feature_set",
)
load(
":cc_toolchain_actions.bzl",
"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 = ACTION_NAME_GROUPS.all_cc_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,344 @@
# 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", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"with_feature_set",
)
load(
":cc_toolchain_actions.bzl",
"preprocessor_compile_actions",
)
# Sysroots and MacOS are complicated:
#
# On Darwin/MacOS, the `-isysroot` flag is used for includes *and* libraries,
# and if specified it wins over `--sysroot` which would be used for libraries
# on other platforms.
# https://discourse.llvm.org/t/silly-what-is-the-difference-between-sysroot-and-isysroot/55788/2
#
# Additionally, on a MacOS build of clang, the sysroot defaults to `/`, which
# is incorrect and it needs to be pointed to the SDK root. However, as a
# convenience, homebrew builds of clang automatically add `-isysroot` to the
# command line, so that the user doesn't have to. But the SDK it chooses does
# not always match the one returned from `xcrun --show-sdk-path`, which is the
# SDK that we want to use. So we need to override homebrew's choice and specify
# `-isysroot`. This will also supersede anything given to `--sysroot` (on
# Darwin) so we don't need to specify both. For non-homebrew clang builds on
# MacOS, specifying `-isysroot` will also work to point the compiler to the
# correct SDK instead of `--sysroot`.
_sysroot_flag_sets = [
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_link_actions,
flag_groups = [
flag_group(
expand_if_available = "sysroot",
flags = ["--sysroot=%{sysroot}"],
),
],
with_features = [with_feature_set(not_features = ["macos_target"])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_link_actions,
flag_groups = [
flag_group(
flags = ["-isysroot", "%{sysroot}"],
),
],
with_features = [with_feature_set(["macos_target"])],
),
]
clang_feature = feature(
name = "clang",
enabled = True,
flag_sets = _sysroot_flag_sets + [
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_link_actions,
flag_groups = [
flag_group(flags = [
"-no-canonical-prefixes",
"-fcolor-diagnostics",
]),
],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cpp_compile_actions,
flag_groups = [flag_group(flags = [
"-fno-exceptions",
"-fno-rtti",
"-std=c++20",
])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_compile_actions,
flag_groups = [flag_group(flags = [
"-ffunction-sections",
"-fdata-sections",
])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cpp_compile_actions + ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cpp_compile_actions,
flag_groups = [flag_group(flags = _libcpp_debug_flags)],
with_features = [with_feature_set(not_features = ["opt"])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cpp_compile_actions,
flag_groups = [flag_group(flags = _libcpp_release_flags)],
with_features = [with_feature_set(features = ["opt"])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_link_actions,
flag_groups = [flag_group(flags = [
"-unwindlib=libunwind",
])],
with_features = [
# libc++ is only used on non-Windows platforms, and macOS
# doesn't support a custom unwinding library (or need one)
# even when using libc++.
with_feature_set(not_features = [
"macos_target",
"windows_target",
]),
],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_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,135 @@
# 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:action_names.bzl", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
)
# 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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_compile_actions,
flag_groups = [flag_group(flags = [
"-ggdb",
"-ggnu-pubnames",
])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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,284 @@
# 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", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"flag_group",
"flag_set",
"variable_with_value",
"with_feature_set",
)
link_libraries_feature = feature(
name = "link_libraries",
enabled = True,
flag_sets = [
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_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,66 @@
# 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:action_names.bzl", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
"with_feature_set",
)
# 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 = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_compile_actions,
flag_groups = [flag_group(flags = ["-DNDEBUG"])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_compile_actions,
flag_groups = [flag_group(flags = ["-O3"])],
),
],
)
cpu_flags = feature(
name = "aarch64_cpu_flags",
enabled = True,
flag_sets = [
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_link_actions,
flag_groups = [flag_group(flags = ["-march=armv8.2-a"])],
with_features = [with_feature_set(["aarch64_target"])],
),
flag_set(
actions = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_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,109 @@
# 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:action_names.bzl", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"feature",
"feature_set",
"flag_group",
"flag_set",
"with_feature_set",
)
sanitizer_common_flags = feature(
name = "sanitizer_common_flags",
implies = ["minimal_debug_info_flags", "preserve_call_stacks"],
flag_sets = [flag_set(
actions = ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_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 = ACTION_NAME_GROUPS.all_cc_compile_actions + ACTION_NAME_GROUPS.all_cc_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,79 @@
# 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", "ACTION_NAME_GROUPS")
load(
"@rules_cc//cc:cc_toolchain_config_lib.bzl",
"action_config",
"tool",
"tool_path",
)
load(
":cc_toolchain_actions.bzl",
"all_c_compile_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 ACTION_NAME_GROUPS.all_cpp_compile_actions
] + [
action_config(
action_name = name,
enabled = True,
tools = [tool(path = clang_bindir + "/clang++")],
)
for name in ACTION_NAME_GROUPS.all_cc_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]
]
+60
View File
@@ -0,0 +1,60 @@
"""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
+27 -5
View File
@@ -83,7 +83,11 @@ def _compute_clang_resource_dir(repository_ctx, clang):
).stdout
# The only line printed is this path.
return output.splitlines()[0]
dir_path = repository_ctx.path(output.splitlines()[0])
# Canonicalize the path to help ensure string matching succeeds
# even with clang installs returning a non-canonical path.
return str(dir_path.realpath)
def _compute_mac_os_sysroot(repository_ctx):
"""Runs `xcrun` to extract the correct sysroot."""
@@ -148,7 +152,7 @@ def _compute_clang_cpp_include_search_paths(repository_ctx, clang, sysroot):
if repository_ctx.os.name.lower().startswith("mac os"):
if not sysroot:
fail("Must provide a sysroot on macOS!")
cmd.append("--sysroot=" + sysroot)
cmd += ["-isysroot", sysroot]
# Note that verbose output is on stderr, not stdout!
output = _run(repository_ctx, cmd).stderr.splitlines()
@@ -174,6 +178,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
@@ -182,9 +188,9 @@ def _configure_clang_toolchain_impl(repository_ctx):
(clang, clang_version, clang_version_for_cache) = _detect_system_clang(
repository_ctx,
)
if clang_version and clang_version < 19:
if clang_version and clang_version < 21:
fail("Found clang {0}. ".format(clang_version) +
"Carbon requires clang >=19. See " +
"Carbon requires clang >=21. See " +
"https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/contribution_tools.md#old-llvm-versions")
clang_cpp = clang.dirname.get_child("clang++")
@@ -224,7 +230,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 +264,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}"
+1 -1
View File
@@ -41,6 +41,6 @@ def cc_env():
macos_env = {"MallocNanoZone": "0"}
return common_env | select({
"//bazel/cc_toolchains:macos_asan": macos_env,
Label("//bazel/cc_toolchains:macos_asan"): macos_env,
"//conditions:default": {},
})
+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"],
)
+20 -5
View File
@@ -41,14 +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
@@ -68,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
+6 -1
View File
@@ -1,4 +1,9 @@
#!/usr/bin/env python3
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# ///
"""Update the roots of the Carbon build used for dependency checking.
@@ -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++",
+]
@@ -1,194 +0,0 @@
From 19d5d9913778ca95da272f41c5916907154a5e73 Mon Sep 17 00:00:00 2001
From: Chandler Carruth <chandlerc@gmail.com>
Date: Thu, 24 Apr 2025 05:03:43 +0000
Subject: [PATCH] Introduce filegroups for compiler-rt builtins runtimes
These filegroups allow downstream projects to package and build
customized runtime libraries.
The filegroups work hard to use globs and a careful structuring to
create the structured breakdown of sources needed to target different
architectures and platforms without having to maintain a complete
parallel list of sources from CMake.
---
.../compiler-rt/BUILD.bazel | 167 ++++++++++++++++++
1 file changed, 167 insertions(+)
diff --git a/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel b/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
index 6a5a89fdee40..7d158f0c13f2 100644
--- a/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
@@ -128,3 +128,170 @@ cc_library(
],
includes = ["lib/fuzzer"],
)
+
+BUILTINS_CRTBEGIN_SRCS = ["lib/builtins/crtbegin.c"]
+
+filegroup(
+ name = "builtins_crtbegin_src",
+ srcs = BUILTINS_CRTBEGIN_SRCS,
+)
+
+BUILTINS_CRTEND_SRCS = ["lib/builtins/crtend.c"]
+
+filegroup(
+ name = "builtins_crtend_src",
+ srcs = BUILTINS_CRTEND_SRCS,
+)
+
+# Note that while LLVM's CompilerRT provides a few hosted sources, we don't
+# currently build them:
+#
+# - `emutls.c`: Unclear we need to support targets with software emulated
+# TLS rather than hardware support.
+# - `enable_execute_stack.c`: Used to implement support for a builtin that
+# marks part of the stack as *executable* to support the GCC extension of
+# nested functions. This extension was never implemented in Clang, and is
+# generally considered a security issue to include. We expect to be able
+# to avoid even linking the support code for this into binaries at this
+# point.
+# - `eprintf.c`: This provided a legacy `__eprintf` builtin used by old
+# versions of `assert.h` in its macros, but does not appear to be needed
+# when building with modern versions of this header.
+BUILTINS_HOSTED_SRCS = [
+ "lib/builtins/emutls.c",
+ "lib/builtins/enable_execute_stack.c",
+ "lib/builtins/eprintf.c",
+]
+
+filegroup(
+ name = "builtins_hosted_srcs",
+ srcs = BUILTINS_HOSTED_SRCS,
+)
+
+BUILTINS_BF16_SRCS_PATTERNS = [
+ # `bf` marks 16-bit Brain floating-point number builtins.
+ "lib/builtins/*bf*.c",
+]
+
+filegroup(
+ name = "builtins_bf16_srcs",
+ srcs = glob(BUILTINS_BF16_SRCS_PATTERNS),
+)
+
+BUILTINS_X86_FP80_SRCS_PATTERNS = [
+ # `xc` marks 80-bit complex number builtins.
+ "lib/builtins/*xc*.c",
+
+ # `xf` marks 80-bit floating-point builtins.
+ "lib/builtins/*xf*.c",
+]
+
+filegroup(
+ name = "builtins_x86_fp80_srcs",
+ srcs = glob(
+ BUILTINS_X86_FP80_SRCS_PATTERNS,
+ exclude = BUILTINS_BF16_SRCS_PATTERNS,
+ ),
+)
+
+BUILTINS_TF_SRCS_PATTERNS = [
+ # `tc` marks 128-bit complex number builtins.
+ "lib/builtins/*tc*.c",
+
+ # `tf` marks 128-bit floating-point builtins.
+ "lib/builtins/*tf*.c",
+]
+
+BUILTINS_TF_EXCLUDES = (
+ BUILTINS_HOSTED_SRCS +
+ BUILTINS_BF16_SRCS_PATTERNS +
+ BUILTINS_X86_FP80_SRCS_PATTERNS
+)
+
+filegroup(
+ name = "builtins_tf_srcs",
+ srcs = glob(
+ BUILTINS_TF_SRCS_PATTERNS,
+ exclude = BUILTINS_TF_EXCLUDES,
+ ),
+)
+
+BUILTINS_MACOS_ATOMIC_SRCS_PATTERNS = [
+ "lib/builtins/atomic_*.c",
+]
+
+filegroup(
+ name = "builtins_macos_atomic_srcs",
+ srcs = glob(BUILTINS_MACOS_ATOMIC_SRCS_PATTERNS),
+)
+
+filegroup(
+ name = "builtins_aarch64_srcs",
+ srcs = [
+ "lib/builtins/cpu_model/aarch64.c",
+ "lib/builtins/cpu_model/aarch64.h",
+ ] + glob(
+ [
+ "lib/builtins/cpu_model/AArch64*.inc",
+ "lib/builtins/cpu_model/aarch64/**/*.inc",
+ "lib/builtins/aarch64/*.S",
+ "lib/builtins/aarch64/*.c",
+ ],
+ exclude = [
+ # This file isn't intended to directly compile, but to be used to
+ # generate a collection of outline atomic helpers.
+ # TODO: Add support for generating the sources for these helpers if
+ # there are users that need this functionality from the builtins
+ # library.
+ "lib/builtins/aarch64/lse.S",
+ ],
+ ),
+)
+
+filegroup(
+ name = "builtins_x86_arch_srcs",
+ srcs = [
+ "lib/builtins/cpu_model/x86.c",
+ "lib/builtins/i386/fp_mode.c",
+ ],
+)
+
+filegroup(
+ name = "builtins_x86_64_srcs",
+ srcs = glob([
+ "lib/builtins/x86_64/*.c",
+ "lib/builtins/x86_64/*.S",
+ ]),
+)
+
+filegroup(
+ name = "builtins_i386_srcs",
+ srcs = glob(
+ [
+ "lib/builtins/i386/*.c",
+ "lib/builtins/i386/*.S",
+ ],
+ exclude = [
+ # This file is used for both i386 and x86_64.
+ "lib/builtins/i386/fp_mode.c",
+ ],
+ ),
+)
+
+filegroup(
+ name = "builtins_generic_srcs",
+ srcs = ["lib/builtins/cpu_model/cpu_model.h"] + glob(
+ [
+ "lib/builtins/*.c",
+ "lib/builtins/*.h",
+ "lib/builtins/*.inc",
+ ],
+ exclude = (
+ BUILTINS_CRTBEGIN_SRCS +
+ BUILTINS_CRTEND_SRCS +
+ BUILTINS_TF_EXCLUDES +
+ BUILTINS_TF_SRCS_PATTERNS +
+ BUILTINS_MACOS_ATOMIC_SRCS_PATTERNS
+ ),
+ ),
+)
--
2.49.0.850.g28803427d3-goog
@@ -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,37 @@
Removes additional libc-backed arithmetic builtins added
by https://github.com/llvm/llvm-project/pull/207092
and https://github.com/llvm/llvm-project/pull/209984
---
--- a/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/compiler-rt/BUILD.bazel
@@ -303,6 +303,30 @@
"lib/builtins/extendsfdf2.cpp",
"lib/builtins/extendsftf2.cpp",
"lib/builtins/extendxftf2.cpp",
+ "lib/builtins/fixdfdi.cpp",
+ "lib/builtins/fixdfsi.cpp",
+ "lib/builtins/fixdfti.cpp",
+ "lib/builtins/fixsfdi.cpp",
+ "lib/builtins/fixsfsi.cpp",
+ "lib/builtins/fixsfti.cpp",
+ "lib/builtins/fixunsdfdi.cpp",
+ "lib/builtins/fixunsdfsi.cpp",
+ "lib/builtins/fixunsdfti.cpp",
+ "lib/builtins/fixunssfdi.cpp",
+ "lib/builtins/fixunssfsi.cpp",
+ "lib/builtins/fixunssfti.cpp",
+ "lib/builtins/floatdidf.cpp",
+ "lib/builtins/floatdisf.cpp",
+ "lib/builtins/floatsidf.cpp",
+ "lib/builtins/floatsisf.cpp",
+ "lib/builtins/floattidf.cpp",
+ "lib/builtins/floattisf.cpp",
+ "lib/builtins/floatundidf.cpp",
+ "lib/builtins/floatundisf.cpp",
+ "lib/builtins/floatunsidf.cpp",
+ "lib/builtins/floatunsisf.cpp",
+ "lib/builtins/floatuntidf.cpp",
+ "lib/builtins/floatuntisf.cpp",
"lib/builtins/muldf3.cpp",
"lib/builtins/mulsf3.cpp",
"lib/builtins/multf3.cpp",
@@ -0,0 +1,24 @@
Temporarily undo
https://github.com/llvm/llvm-project/pull/207295
Which introduces a dependency on the hermetic llvm
toolchain. A fix-forward is in progress, at which
point we can remove this patch.
---
--- a/utils/bazel/llvm-project-overlay/llvm/config.bzl
+++ b/utils/bazel/llvm-project-overlay/llvm/config.bzl
@@ -72,7 +72,6 @@
backtrace_defines = select({
"@platforms//os:emscripten": [],
"@platforms//os:windows": [],
- "@llvm//platforms/config:musl": [],
"//conditions:default": [
"HAVE_BACKTRACE=1",
"BACKTRACE_HEADER=<execinfo.h>",
@@ -80,7 +79,6 @@
})
mallinfo_defines = select({
- "@llvm//platforms/config:gnu": ["HAVE_MALLINFO=1"],
"//conditions:default": [],
})
+9 -5
View File
@@ -8,17 +8,21 @@ 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
# may or may not be prefixed with the package directory. Strip both.
bin_dir = ctx.bin_dir.path + "/"
workspace_root = (
ctx.label.workspace_root + "/" if ctx.label.workspace_root else ""
)
package_dir = ctx.label.package + "/"
files_stripped = [f.removeprefix(bin_dir).removeprefix(package_dir) for f in files]
files_stripped = [
f.removeprefix(bin_dir)
.removeprefix(workspace_root)
.removeprefix(package_dir)
for f in files
]
else:
files_stripped = files
+11 -2
View File
@@ -1,4 +1,13 @@
#!/usr/bin/env python3
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# ///
# NOTE: The `uv` shebang and inline metadata above are only used for direct
# execution of this script outside of Bazel. When executed by Bazel (e.g., as a
# tool in a rule or as a test), Bazel uses its own hermetic Python toolchain
# and ignores this metadata.
"""Generate a file from a template, substituting the provided key/value pairs.
@@ -88,7 +97,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:
+2 -2
View File
@@ -134,8 +134,8 @@ 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({
"//bazel/version:internal_stamp_flag_detect": True,
internal_stamp_flag_detect = False if kwargs.get("stamp") == 0 else select({
Label("//bazel/version:internal_stamp_flag_detect"): True,
"//conditions:default": False,
}),
**kwargs
+82 -10
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",
],
)
@@ -262,10 +286,10 @@ sh_test(
size = "small",
srcs = [":filesystem_benchmark"],
args = [
"--benchmark_min_time=1x",
# Restrict the sizes to 4-digit ones or smaller to keep test times low.
"--benchmark_dry_run",
# Restrict the sizes to 2-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$$",
"--benchmark_filter=^[^/]+(/[0-9]{1,2}(/[0-9]+)?)?/real_time$$",
],
)
@@ -318,12 +342,22 @@ cc_library(
],
)
cc_library(
name = "hashing_llvm",
hdrs = ["hashing_llvm.h"],
deps = [
":hashing",
"@llvm-project//llvm:Support",
],
)
cc_test(
name = "hashing_test",
size = "small",
srcs = ["hashing_test.cpp"],
deps = [
":hashing",
":hashing_llvm",
":raw_string_ostream",
"//testing/base:gtest_main",
"@googletest//:gtest",
@@ -360,6 +394,7 @@ cc_test(
size = "small",
srcs = ["hashtable_key_context_test.cpp"],
deps = [
":hashing_llvm",
":hashtable_key_context",
"//testing/base:gtest_main",
"@googletest//:gtest",
@@ -393,6 +428,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"],
@@ -414,6 +471,7 @@ cc_test(
":raw_hashtable_test_helpers",
"//testing/base:gtest_main",
"@googletest//:gtest",
"@llvm-project//llvm:Support",
],
)
@@ -427,7 +485,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",
],
@@ -441,9 +499,9 @@ 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]+)?$$",
"--benchmark_filter=^[^/]*/[1-9][0-9]{0,2}(/[0-9]+)?$$",
],
)
@@ -460,6 +518,19 @@ cc_library(
],
)
cc_test(
name = "ostream_test",
size = "small",
srcs = ["ostream_test.cpp"],
deps = [
":ostream",
":raw_string_ostream",
"//testing/base:gtest_main",
"@googletest//:gtest",
"@llvm-project//llvm:Support",
],
)
cc_library(
name = "pretty_stack_trace_function",
hdrs = ["pretty_stack_trace_function.h"],
@@ -511,7 +582,7 @@ sh_test(
size = "small",
srcs = ["raw_hashtable_metadata_group_benchmark"],
args = [
"--benchmark_min_time=1x",
"--benchmark_dry_run",
],
)
@@ -531,7 +602,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",
],
@@ -589,6 +660,7 @@ cc_test(
":set",
"//testing/base:gtest_main",
"@googletest//:gtest",
"@llvm-project//llvm:Support",
],
)
@@ -614,9 +686,9 @@ 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]+)?$$",
"--benchmark_filter=^[^/]*/[1-9][0-9]{0,2}(/[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
+50 -7
View File
@@ -8,18 +8,61 @@
#include <string>
#include "common/ostream.h"
#include "llvm/Support/FormatCommon.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
namespace Carbon::Internal {
auto CheckFailImpl(const char* kind, const char* file, int line,
const char* condition_str, llvm::StringRef extra_message)
namespace {
// Renders `fmt` over the externally-built, type-erased `adapters` into `out`,
// with the same semantics as `llvm::formatv` (including runtime format-string
// validation).
//
// TODO: We should add a type-erased helper to upstream LLVM instead of rolling
// our own type-erased version of `format` here.
auto FormatvInto(
llvm::raw_ostream& out, llvm::StringRef format_str,
llvm::ArrayRef<llvm::support::detail::FormatFunctorRef> adapters) -> void {
for (const llvm::ReplacementItem& replacement :
llvm::formatv_object_base::parseFormatString(format_str, adapters.size(),
/*Validate=*/true)) {
if (replacement.Type == llvm::ReplacementType::Literal ||
replacement.Index >= adapters.size()) {
out << replacement.Spec;
continue;
}
llvm::FmtAlign(adapters[replacement.Index], replacement.Where,
replacement.Width, replacement.Pad)
.format(out, replacement.Options);
}
}
} // namespace
auto CheckFailImpl(
const char* kind, const char* file, int line, const char* condition_str,
const char* extra_format,
llvm::ArrayRef<llvm::support::detail::FormatFunctorRef> extra_adapters)
-> void {
// Render the final check string here.
std::string message = llvm::formatv(
"{0} failure at {1}:{2}{3}{4}{5}{6}\n", kind, file, line,
llvm::StringRef(condition_str).empty() ? "" : ": ", condition_str,
extra_message.empty() ? "" : ": ", extra_message);
// Render the final check string directly into one stream. The extra message
// is rendered in place from its format string and type-erased adapters, so
// we never materialize a separate string just for it.
//
// `llvm::raw_string_ostream` (rather than `common/raw_string_ostream.h`) is
// used to avoid a dependency cycle: `RawStringOstream` itself uses
// `CARBON_CHECK`. It is unbuffered, so `message` is populated directly.
std::string message;
llvm::raw_string_ostream message_stream(message);
message_stream << kind << " failure at " << file << ":" << line;
if (*condition_str != '\0') {
message_stream << ": " << condition_str;
}
if (*extra_format != '\0') {
message_stream << ": ";
FormatvInto(message_stream, extra_format, extra_adapters);
}
message_stream << "\n";
// This macro is defined by `--config=non-fatal-checks`.
#ifdef CARBON_NON_FATAL_CHECKS
+60 -38
View File
@@ -31,25 +31,29 @@ CheckCondition(bool condition)
// Implements the check failure message printing.
//
// This is out-of-line and will arrange to stop the program, print any debugging
// information and this string. In `!NDEBUG` mode (`dbg` and `fastbuild`), check
// failures can be made non-fatal by a build flag, so this is not `[[noreturn]]`
// in that case.
// information and the failure message. In `!NDEBUG` mode (`dbg` and
// `fastbuild`), check failures can be made non-fatal by a build flag, so this
// is not `[[noreturn]]` in that case.
//
// This API uses `const char*` C string arguments rather than `llvm::StringRef`
// because we know that these are available as C strings and passing them that
// way lets the code size of calling it be smaller: it only needs to materialize
// a single pointer argument for each. The runtime cost of re-computing the size
// should be minimal. The extra message however might not be compile-time
// guaranteed to be a C string so we use a normal `StringRef` there.
// should be minimal.
//
// The user can provide an extra format string along with an array of
// type-erased format adapters. This will be rendered into the final message.
#ifdef NDEBUG
[[noreturn]]
#endif
auto CheckFailImpl(const char* kind, const char* file, int line,
const char* condition_str, llvm::StringRef extra_message)
auto CheckFailImpl(
const char* kind, const char* file, int line, const char* condition_str,
const char* extra_format,
llvm::ArrayRef<llvm::support::detail::FormatFunctorRef> extra_adapters)
-> void;
// Allow converting format values; the default behaviour is to just pass them
// through.
// Allow custom conversion of format values; the default behaviour is to just
// pass them through.
template <typename T>
auto ConvertFormatValue(T&& t) -> T&& {
return std::forward<T>(t);
@@ -70,37 +74,53 @@ auto ConvertFormatValue(T&& t) -> auto {
}
}
// Builds one type-erased format functor per value -- forwarding each value
// through the conversion machinery. References to each of these functors are
// then collected into an init list that can be accessed with an `ArrayRef`. All
// of this is then passed to the out-of-line rendering function `CheckFailImpl`.
//
// This is templated only on the value types, not on the per-check-site
// metadata (file, line, etc., which are passed as ordinary arguments), so the
// adapter-building is instantiated once per distinct sequence of value types in
// the TU.
template <typename... Ts>
#ifdef NDEBUG
[[noreturn]]
#endif
auto CheckFailFormat(const char* kind, const char* file, int line,
const char* condition_str, const char* extra_format,
Ts&&... values) -> void {
CheckFailImpl(kind, file, line, condition_str, extra_format,
{llvm::support::detail::FormatFunctor(
ConvertFormatValue(std::forward<Ts>(values)))...});
}
// Prints a check failure, including rendering any user-provided message using
// a format string.
//
// Most of the parameters are passed as compile-time template strings to avoid
// runtime cost of parameter setup in optimized builds. Each of these are passed
// along to the underlying implementation to include in the final printed
// message.
//
// Any user-provided format string and values are directly passed to
// `llvm::formatv` which handles all of the formatting of output.
// The check-site metadata is passed as compile-time template strings to avoid
// runtime cost of parameter setup in optimized builds. This function is
// instantiated once per check site (its template arguments are unique to the
// site), so it is kept trivial: it just lowers those template strings to
// ordinary arguments and forwards everything to `CheckFailFormat`, where the
// adapter-building is shared across sites with the same value types.
template <TemplateString Kind, TemplateString File, int Line,
TemplateString ConditionStr, TemplateString FormatStr, typename... Ts>
#ifdef NDEBUG
[[noreturn]]
#endif
[[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
// `{}`s in the format string. This case is about when there is no message
// at all, just the condition.
CheckFailImpl(Kind.c_str(), File.c_str(), Line, ConditionStr.c_str(), "");
} else {
CheckFailImpl(Kind.c_str(), File.c_str(), Line, ConditionStr.c_str(),
llvm::formatv(FormatStr.c_str(),
ConvertFormatValue(std::forward<Ts>(values))...)
.str());
}
[[gnu::cold, clang::noinline]] auto CheckFail(Ts&&... values) -> void {
CheckFailFormat(Kind.c_str(), File.c_str(), Line, ConditionStr.c_str(),
FormatStr.c_str(), std::forward<Ts>(values)...);
}
// Type-checks the arguments of a `DCHECK` in optimized builds, where the check
// itself is dead code, without instantiating any formatting machinery for them
// and without provoking unused-variable warnings. It is only ever named from
// dead code, so it is never actually called.
template <typename... Ts>
auto IgnoreDeadCheckArgs(Ts&&... /*values*/) -> void {}
} // namespace Carbon::Internal
// Evaluates the condition of a CHECK as a boolean value.
@@ -149,21 +169,23 @@ CheckFail(Ts&&... values) -> void {
CARBON_INTERNAL_FATAL_NORETURN_SUFFIX())
#ifdef NDEBUG
// For `DCHECK` in optimized builds we have a dead check that we want to
// potentially "use" arguments, but otherwise have the minimal overhead. We
// avoid forming interesting format strings here so that we don't have to
// repeatedly instantiate the `Check` function above. This format string would
// be an error if actually used.
// For `DCHECK` in optimized builds the check is dead code, but we still want to
// type-check its arguments so they can't bitrot. We route them through
// `IgnoreDeadCheckArgs`, which uses the arguments (avoiding unused-variable
// warnings) but builds no format adapters, so the dead check doesn't pull in
// the formatting machinery -- in particular not the per-value-type adapters
// that the live `CheckFail` path would. The format string is a literal, so it
// needs no type-checking and is dropped.
#define CARBON_INTERNAL_DEAD_DCHECK(condition, ...) \
CARBON_INTERNAL_DEAD_DCHECK_IMPL##__VA_OPT__(_FORMAT)(__VA_ARGS__)
#define CARBON_INTERNAL_DEAD_DCHECK_IMPL() \
Carbon::Internal::CheckFail<"", "", 0, "", "">()
Carbon::Internal::IgnoreDeadCheckArgs()
#define CARBON_INTERNAL_DEAD_DCHECK_IMPL_FORMAT(format_str, ...) \
Carbon::Internal::CheckFail<"", "", 0, "", "">(__VA_ARGS__)
Carbon::Internal::IgnoreDeadCheckArgs(__VA_ARGS__)
// The CheckFail function itself is noreturn in NDEBUG.
// The `CheckFail` function itself is noreturn in NDEBUG.
#define CARBON_INTERNAL_FATAL_NORETURN_SUFFIX() void()
#else
#define CARBON_INTERNAL_FATAL_NORETURN_SUFFIX() std::abort()

Some files were not shown because too many files have changed in this diff Show More