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
Boaz Brickner 8adb3570ac C++ Interop: Add support for char (#5988)
Added tests for different character types.
`char` is currently not in primitives prelude, so had to use full
prelude.

C++ Interop Demo:

```carbon
// main.carbon

library "Main";

import Cpp inline '''
auto output_char(char c) -> void {
  printf("%c", c);
}
''';

fn Run() -> i32 {
  let msg: array(Core.Char, 13) =
      ('H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n');
  for (c: Core.Char in msg) {
    Cpp.output_char(c);
  }
  return 0;
}
```

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o --output=demo
$ ./demo
Hello world!
```

Part of https://github.com/carbon-language/carbon-lang/issues/5263.
2025-08-29 01:11:24 +00:00
Richard Smith 50e5476ee3 Add support for unsafe as operator to the toolchain. (#5993)
Following the direction of #5913, add support for parsing an `unsafe as`
operator. For now, we allow one additional conversion using `unsafe as`
beyond the conversions supported by `as`: we permit pointer conversions
that remove qualifiers, such as `const T*` -> `T*`.
2025-08-28 23:00:53 +00:00
David Blaikie 1d0f30df3a Fix a use of an imported InstId used where a local InstId is required (#5998)
Found by WIP validation for this type of issue ongoing in #5997

I'm not entirely sure how the one test update falls out of this change -
but it is from the same test that I originally reduced the problem from,
which is reassuring.

The reduced test case I investigated the issue with was this:
`a.carbon`:
```
library "lib";
interface I1(Other:! type) {
   let Result:! type;
}
```
`b.carbon`:
```
import library "lib";
class T1 { }
impl T1 as I1(Self) where .Result = Self { }
```
The SemIR dump diff looked like this:
```
89c89
<   %Main.import_ref.b6f = import_ref Main//lib, inst28 [no loc], unloaded
---
>   %Main.import_ref.b6f = import_ref Main//lib, inst27 [no loc], unloaded
96c96
<   %Main.import_ref.f7b: @I1.%I1.type (%I1.type.e87) = import_ref Main//lib, inst28 [no loc], loaded [symbolic = @I1.%Self (constants.%Self.c47)]
---
>   %Main.import_ref.f7b: @I1.%I1.type (%I1.type.e87) = import_ref Main//lib, inst27 [no loc], loaded [symbolic = @I1.%Self (constants.%Self.c47)]
```
Which is a difference, but given the `inst28`/`inst27` don't appear
anywhere else than these two lines, it doesn't give a terribly
meaningful diff/story about what changed - but perhaps it's
sufficient...

Not sure if this test ^ is sufficiently more interesting than the diff
update already in this patch. If so, happy to add the above as a new
test case.

Open to ideas.
2025-08-28 20:02:26 +00:00
pascal754 9cfbe9eac9 Fix a typo in README.md (#5994) 2025-08-28 16:25:53 +00:00
Richard SmithandChandler Carruth bd90fe1d9b Interop: map C++ std::string_view into Carbon str when importing. (#5985)
We assume these types have the same representation. For now, that will
only be the case for libc++ on 64-bit targets, because libc++ puts the
size field first, and `Core.String` always uses a 64-bit size field even
on 32-bit targets.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-08-27 01:02:39 +00:00
Richard Smith 82ba1a43a1 Support for importing C++ enum types. (#5978)
We import C++ enum types as Carbon class types as adapters for the
corresponding builtin integer type, and we import enumerator constants
as integer constants of that class type.

No operators are supported on such values for now; eventually once we
start asking Clang to implement operators on C++-owned types, these
types should be handled in the same way. However, they can be converted
to the corresponding integer type with `as` via adapter conversion, and
integer builtin functions can operate on them.
2025-08-26 23:11:35 +00:00
Boaz Brickner 6ba900ab97 Update comment to not be specific for signed integers (#5987)
Following the change in #5980.
2025-08-26 21:49:31 +00:00
Richard Smith 742017c475 Widen integer loads and stores to a multiple of 8 bits. (#5986)
This makes Carbon's loads and stores ABI-compatible with Clang's for
`bool` and `_BitInt(N)`.
2025-08-26 21:49:24 +00:00
Richard Smith 3533668186 Support for building thunks for C++ constructors. (#5977) 2025-08-26 21:49:11 +00:00
Richard Smith d37f1ae6b5 Add return value support to C++ thunks. (#5976)
Based on #5948. A couple of tricky parts:

* When generating the C++ side of the thunk, we are given a pointer to
the location to emplace the return value. The only mechanism C++
provides to perform this emplacement is using placement `operator new`,
which requires a library function in the `<new>` header. We handle this
by declaring that library function ourselves, and rely on Clang not
actually needing a definition for it (which the standard library owns).

* On the Carbon side of the thunk, we want to form an initializing
expression as the result of the call. We don't have a way of expressing
in SemIR that an initializing expression performs its initialization by
storing through a pointer, so this PR adds a new initializing
instruction, `InPlaceInit`, to model an initialization that's performed
opaquely in-place.
2025-08-26 02:23:38 +00:00
Richard Smith 1331ade57f Attempt to complete the source type in a conversion. (#5984)
This is necessary if the source type is an adapter, as we would not
otherwise be able to determine what type it adapts and hence could be
converted to.
2025-08-26 00:33:12 +00:00
Richard Smith 8c9080801c Support for building thunks for C++ methods. (#5972)
Also tweak how we import C++ methods to properly handle C++23's explicit
object parameters.
2025-08-25 22:33:51 +00:00
Richard Smith ddafbc9331 Use direct passing for 32- and 64-bit unsigned integers. (#5980)
Previously we only avoided creating a thunk for signed integers. But the
same logic also applies to the unsigned 32-bit and 64-bit types.
2025-08-25 21:49:03 +00:00
Chandler Carruth 74016d47f9 Rework the IsSuccess matcher to be fully polymorphic (#5981)
Previously, this matcher mostly worked, but the `DescribeTo` functions
wouldn't compile when another polymorphic matcher was nested to match
the value.

The updated code uses the same polymorphic matcher design as used by
`Not` and others in Google Test itself.

I've added a test that uses `VariantWith` to nest matchers more deeply
with `IsSuccess`. This test doesn't compile prior to this change.
2025-08-25 16:28:11 +00:00
d49cb3ecfb Start building Clang runtimes on-demand (#5338)
This is the first step to having Clang's runtime libraries fully
available for the Carbon toolchain. This PR focuses on the lowest level
runtimes, the CRT files and the builtins library.

The goal is to intercept Clang runs where it needs these
target-dependent pieces to be available, and build them on demand using
our Clang-running infrastructure. This avoids most of the subprocess
overhead, but there is still some due to missing features in Clang.

This requires exporting the sources for these runtimes from the Bazel
build, and installing them in our target-independent resource directory.
We then build a simplified "build" of these sources within the
`ClangRunner` itself to produce the specific artifacts and layout
expected by Clang.

It also required fixing our use of Clang on macOS to have a default
system root in order to successfully compile or link.

It also required cleaning up how the `ClangRunner` used target
information more generally -- instead of taking the target as
a constructor parameter, it manages its target internally and relies on
the Clang target-specifying command line flags.

I looked at whether we could split this into another layer separate from
the `ClangRunner`, but that proved frustratingly difficult to manage.
While we support building these on-demand as part of a detected link,
that doesn't seem feasible as we don't have the necessary separation
between compilation runs of Clang and link runs of Clang. However,
I have tried to factor the internals to provide as clear of separation
as I could across these.

I have also created a stand-alone subcommand to directly build the
runtimes which allows for easy testing. It also supports building them
into a specific directory, and that directory can in turn be passed to
a Clang invocation. This is designed to work both at the API level with
`ClangRunner` and at the subcommand level.

Currently, the only part of the commandline that is detected and
forwarded to the runtimes build is the target. Eventually, the plan is
to expand this so that we can build a maximally tailored set of runtimes
for a given compilation.

The other big TODO here is to actually implement caching storage of
these runtimes so they aren't built on every execution. Right now, this
uses a somewhat hack-y build of a temporary directory, but this isn't
expected to be suitable long-term. Building these runtimes on *every*
link makes those commands take approximately 15 seconds with an ASan
build like our default development build, and just over 2 seconds in an
optimized build. Because of this, I've kept all of this disabled by
default for now. The goal is that once caching and some other
improvements land, we can enable this by default.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-22 03:05:21 +00:00
Richard Smith 816d4589cd Make use of new ArrayRef::consume_* functions. (#5975)
Minor code simplifications.
2025-08-21 21:41:53 +00:00
Chandler Carruth 046fbbcb29 Tweak the name for the function that diagnoses when fuzzing external libraries (#5974)
The old function name caused some confusion during the review of #5338,
sending this to see if it provides a less surprising function name and
boolean result. Happy to try other names / approaches as well.
2025-08-21 19:36:44 +00:00
223d0397c0 Updating Carbon's safety strategy (#5914)
Carbon is accelerating and adjusting its safety strategy, specifically
to flesh out its memory safety strategy and reflect simplifying
developments in the safety space.

This proposal replaces the previous directional safety strategy with a
new concrete and updated framework for the safety design. It includes a
specific framework for memory safety, simplified build modes, specific
"safety modes", and terminology.

This proposal also provides a _directional_ suggestion for temporal and
data-race safety specifically.

In addition to fully building out the above directional component, there
are several other aspects of our safety design that will follow in
subsequent proposals. The hope is to establish the initial framework
here.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Mike Forster <michael@forster.pro>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-20 23:31:30 +00:00
Richard Smithandjosh11b 30b8a93fde Support conversion from T* to const T*. (#5971)
Also support conversion from Derived* to const Base*.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-08-20 23:27:03 +00:00
Richard Smith ad84e71acd Avoid non-UTF8-encoded test files. (#5965)
Add a content keyword to file_test, `[[@0xAB]]`, that expands to the
code unit 0xAB, and use that instead of putting raw malformed code units
in test files.

Instead of printing the raw input bytes in snippets in diagnostics,
replace non-printable characters with <AB> in the output, being careful
to still compute the location of the caret and underscore properly.
2025-08-20 21:07:58 +00:00
Richard Smith 2352e93bb5 Remove now-unused StringType instruction. (#5964) 2025-08-20 18:30:11 +00:00
Richard Smith b72c11e94a Support importing nested types from C++. (#5955)
Fix the algorithm for importing declarations in dependency order to
properly walk the dependency graph. Add the parent declaration of a
declaration to the dependency set so that we have a parent declaration
context to import a declaration into.

Fixes a crash when attempting to import a class whose parent is not
imported.
2025-08-20 07:39:12 +00:00
Chandler Carruth 3c9b87ab54 Add some more operations to the filesystem library (#5968)
Specifically this adds `WriteStream` to get an LLVM-style
`raw_fd_ostream` for an open file, and `Rename` corresponding to
`rename` and `renameat` Unix-like system calls.

Some basic testing for both is added as well.

This was split out of work to switch the runtimes building to use the
new filesystem library.
2025-08-20 02:54:22 +00:00
Richard Smith 41ed82e033 Add basic support for strings to core, check, and lower. (#5963)
Add a `Core.String` class to the prelude representing a string view, and
rename the `String` keyword to `str` and make it evaluate to
`Core.String`.

`Core.String` is represented as a pair of a pointer to a character
(actually, to the first character of a string, but we don't have a way
of modeling that yet) and a size (which should be pointer-width, but is
currently always a `u64` as we don't have a `usize` equivalent yet).
`Core.String` values are generated directly by the toolchain for string
literal expressions.

This follows the direction established at the recent summit, but the
design implemented here has not been through the proposal process yet.
2025-08-20 00:18:50 +00:00
Jon Ross-Perkins 8d08e774fc Add a feature to explicitly include a file's SemIR (#5961)
Trying to figure out an easy way to debug semir in the prelude, #5703
removed an option to set `--exclude-dump-file-prefix` to empty. But,
this is probably an improvement over that flow... With this change, it's
possible to add `//@dump-sem-ir-file` to a specific prelude file, and
its full IR will be printed. Additionally, it becomes an option with the
default `--dump-sem-ir-ranges=only` to add `//@dump-sem-ir-file` and get
the full file's IR.
2025-08-15 18:53:43 +00:00
David BlaikieandRichard Smith 3f9fc633fe Add a vtableDecl inst and use that in classes instead of VtablePtr (#5945)
This addresses/avoids the duplicate import of vtables.

I went through a few iterations/etc along the way and left them in the
commit
history for the PR in case any of them are useful to illustrate how I
got here,
or worth revisiting.

Essentially I ended up with a circularity in importing - importing the
class
imported the vtable_decl which imported the virtual functions - and then
pending
specifics of the virtual functions needed the self specific of the
enclosing
class which wasn't ready yet.

Adding ImportRef to the vtable_decl to break the cycle caused me trouble
when
naming the vtable_decl instructions - so I tried making the functions in
the
vtable unloaded ImportRefs instead. That worked, but meant that
importing a
class still was doing O(number of vtable entries) even if the vtable
wasn't
used.

So I revisited the lazy vtable_decl - figured out how to make the naming
work
(when building the vtable_ptr, even though the vtable_decl doesn't have
to be
loaded for the vtable_ptr, I force it to be loaded anyway, to load the
vtable so
it's usable by lowering, etc). And then I could go back to the old
non-lazy
loaded vtable entries (using some loaded ImportRefs in the cases where
we needed
them/had already adopted them).

Then thinking about the VtablePtr instruction, went back/forth on
exactly what
it needed - went from VtablePtr's member being a VtableDecl InstId, to a
ClassId, then back to a VtableId as it was before this patch.

Naming the instructions has one oddity, that the VtableDecl and
VtablePtr
instructions seem to need to add the pending name for the VtableId -
despite not
using the VtableId in their own name - should the inst namer be doing
this work
for parameters of instructions rather than requiring the inst to do it
deliberately? (or am I holding it wrong in some way?)

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-15 18:36:54 +00:00
Richard Smith 7727c62880 Enforce a couple of char literal restrictions from #1964: (#5960)
* `\x` escapes are not permitted in character literals
* ASCII control characters (U+0000 .. U+001F) are not permitted in
character literals unless specified with escape sequences.
2025-08-15 00:45:16 +00:00
Richard Smith ae54873441 Change tests in check/testdata/builtins/char to be tests for the builtin char functions. (#5956)
Follow the pattern used by other tests in check/testdata/builtins.
2025-08-14 20:58:09 +00:00
Chandler Carruth 0a679504a5 Update LLVM again to 2025-08-09 (#5958)
This lets us pick up another API update to creating lifetimes, as well
as the consequent test updates.
2025-08-14 19:19:27 +00:00
Dana Jansens 9feb493680 Add instructions for including CARBON_VLOG output when running a file_test (#5959) 2025-08-14 18:12:54 +00:00
Richard Smith b851e8c423 Add support for f16, f64, f128. (#5952)
Generalize the f64 support to support other sizes. Also provide interop
support for `float`, `_Float16`, and `__float128`.

Also lay some groundwork for non-standard floating-point types, though
we don't have any syntax to name them yet.
2025-08-14 01:14:40 +00:00
Jon Ross-Perkins cfe5599144 Support imports of more literal values (#5954)
I noticed while trying to set up an associated constant in the prelude
that we weren't supporting bool value imports; this goes through and
addresses support for simple builtin types.

Array initialization fails on declaration, which seems like a bug but
I'm only documenting it here.

Also fix missing export of `Core.FloatLiteral`

I checked and this doesn't seem to affect #5952, which is doing more
float changes.
2025-08-13 23:36:40 +00:00
Richard SmithandJon Ross-Perkins b2b0b4a73f Improve recovery from bad type imports. (#5953)
The main change here is that a bad type appearing somewhere within a
field or base class of a class shouldn't cause an import of that class
to fail. Instead, only that field or base class becomes inaccessible
from Carbon.

Also improve the way that type importing errors are diagnosed. While we
lose the precision of a diagnostic saying why a type is not supported,
we gain a useful source location for where the type was mentioned in C++
code.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-08-13 22:07:54 +00:00
Dana Jansens 2140a57294 Remove todo in facet_type.cpp after exploration (#5950)
We looked at it in
https://github.com/carbon-language/carbon-lang/pull/5947 and decided not
to proceed with it.
2025-08-13 16:01:31 +00:00
Chandler Carruth 52972ea83d Update LLVM to head on 2025-08-01 (#5951)
This pulls in updated LLVM IR features in our thunk test, and needs us
to adapt the dependency tests, but otherwise seems to work easily.
2025-08-13 01:12:40 +00:00
Richard Smith 629f77eb61 Switch to representing FloatLiteralType as a RealId. (#5944)
Don't convert to f64 until we know that's the type that we actually
want. Also reimplement the conversion from RealId to FloatId to perform
an exact conversion with a real check for overflow, rather than
performing an approximate conversion via the host `double` type.

Unfortunately, LLVM doesn't expose its integer mantissa and exponent to
APFloat conversion, so we convert the RealId back to a string for now.

The LLVM conversion also detects overflow only if the literal would
round to having an out-of-range exponent, not if the literal is outside
the range of values of the type as the Carbon design expects. It's not
clear to me which rule we actually want here, so for simplicitly I'm
using the LLVM rule for now.

In preparation for adding other floating-point types beyond f64.
2025-08-12 22:08:07 +00:00
Chandler Carruth 969abfe814 Follow-up fixes to filesystem code (#5949)
Tidies up extraneous move, unnecessary function style type cast, and
simplifies the temporary directory string construction. These were
noticed during another PR review.

Also corrects support for older glibc versions, including the
GNU-specific quirks of `strerror_r`. Restricts the fancier formatting
with the name of the error number to when a recent glibc is available.

Lastly, filters the benchmarks in the benchmark test down to smaller
ones to avoid test timeout flakiness.
2025-08-12 21:51:44 +00:00
Richard Smith 28103b8f2e Convert LegacyFloatType into FloatLiteralType. (#5939)
* Rename the type.
* Change lowering to lower FloatLiteralType values as the placeholder
  `{}` value we use for literals instead of as an LLVM f64.
* Change eval to convert the type as part of a floating point
  conversion, so that lowering can lower converted constants properly.

For now we still represent a value of FloatLiteralType as a
double-precision APFloat. (That will need to change so that we can
losslessly convert literals to f80 / f128 values, and so that we can
convert literals to f32 values without double-rounding.)
2025-08-12 18:55:38 +00:00
Dana JansensandJon Ross-Perkins 4b0e2b03b6 Add the .Self name for the type expression of a compile time binding (#5937)
We add a virtual node (`CompileTimeBindingPatternStart`) as the first
child of `CompileTimeBindingPattern` which holds the identifier
underneath it, so that it is checked just before the type expression of
the `CompileTimeBindingPattern`. When we reach this virtual node during
check, we add `.Self` as a name in the current scope, and when we reach
`CompileTimeBindingPattern` we remove it from scope, which ensures it's
present during only the checking of the type expression for the compile
time pattern.

At the moment the `.Self` has a different type (it's a `TypeType`) than
other `.Self` in the facet type (which are a single `FacetType`), but
the intention is to immediately substitute it out of the facet type
entirely, replacing it with a reference to the compile time binding (a
`BindSymbolicName`) itself. A TODO has been added for this.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-08-12 16:27:07 +00:00
Chandler Carruth 2e509e9103 Port //toolchain/install to new filesystem library (#5905)
This removes a bunch of manual filesystem helpers and complexity that
are directly provided by the new library.

It also moves all of the install paths detection to use
`std::filesystem::path` instead of the LLVM path library. The goal is to
consolidate all our logic onto a single stack, and the standard one
seems the best for that purpose. This does give up some of the
optimizations of this code to avoid memory allocation, but in practice
that likely isn't a critical issue. And with the new filesystem library
we can likely do more to avoid that by using directory-object-relative
filesystem access. However, that will have to wait for moving more parts
of the toolchain over to use this set of filesystem abstractions. There
is a related TODO left in the manifest handling code.
2025-08-12 02:20:22 +00:00
Chandler CarruthandDana Jansens 42d29764c0 Introduce a custom filesystem library (#5888)
The standard filesystem API lacks significant functionality, ranging
from correct and secure creation of directories and files within them by
using `openat` and avoiding [TOCTOU] issues, to support for filesystem
locking.

[TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use

The LLVM filesystem library has more functionality, but uses an API that
is increasingly diverging from the standard, and also fails to defend
against TOCTOU.

This library is designed to carefully model the Unix or POSIX filesystem
concepts of `openat` to avoid TOCTOU. However, it also tries to limit
itself to an API subset that LLVM's filesystem library has also
implemneted and so we have a strong reason to expect to be possible to
port to Windows reasonably.

This PR included several benchmarks that show that this implementation
is also faster for the majority of operations than the C++ standard
library. The only places where there is a consistent regression is in
recursively creating directories, and this is directly connected to the
approach of using `openat` as the basis. Even there, while the wall time
regresses, the cycles and instructions are significantly improved.

There are a number of operations not yet included here, I've focused on
a core set of opening, closing, creating, and removing, and then adding
those that I saw the current toolchain code using actively. I'll plan to
expand the operations as needed going forward.

A follow-up PR that I'll finish polishing and send next ports
`//toolchain/install` to consistently use this library and
`std::filesystem::path` to both exercise the library and showcase its
use. I'll be working systematically across the toolchain to converge all
the code, extending this library as needed.

For reference, benchmark results on my macOS laptop:
https://gist.github.com/chandlerc/29d1f4d465a835b8be5174a48dad2e8f

Benchmark results on a Asahi Linux M1 Mac Mini:
https://gist.github.com/chandlerc/c42d43dd6b9b91746ab314b2afa152f7

Benchmark results on a Linux server with weirdly slow FS operations:
https://gist.github.com/chandlerc/48301a7383eb3972d53351b7e35e0561

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-08-12 01:38:31 +00:00
Jon Ross-Perkins b410ebd088 Fix destruction of generic types (#5943)
The self access is important; for the test `generic_class.carbon` being
added to `toolchain/check/testdata/class/destroy_calls.carbon`, it was
using `%T.as.Destroy` instead of `%D.as.Destroy`, indicating the default
blank impl was being used instead of the type-specific version. That
test is trying to focus on the issue, but the delta is visible in a
couple other files in this PR, for example
`toolchain/check/testdata/class/generic/init.carbon`.

I'm separately working on getting rid of the default impl, which is how
I noticed this.
2025-08-12 00:10:43 +00:00
694c00c7eb Make Core.Float a class. Add missing builtins for float support. (#5932)
Add missing builtins for float compound assignment, for building a
FloatType, and for converting a float literal to FloatType. Switch
`Core.Float` to being a class and add impls for the various
floating-point operators.

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-08-11 21:01:34 +00:00
Richard Smith f616817b71 Improve autoupdate diagnostic CHECK line positioning. (#5942)
When an error diagnostic has an unattached location, for example because
the diagnostic points into a file that's in the prelude, use the next
attached location to position the error diagnostic's CHECK line. In
particular, if the error is followed by a note, use the position of the
note to determine where to place the error.

This exposes a general mechanism to do final fixups of the CHECK lines
to individual file_test binaries, which the toolchain's binary uses to
special-case error / warning CHECK lines.
2025-08-11 19:30:57 +00:00
David Blaikie efbc9f7c9c Create LoadedImportRefs for vtable entries with import insts instead of local insts (#5931)
With help from Richard Smith debugging/identifying this.

Hmm - looks like maybe the Self type import ref may have the same
problem? (or at least it seems to have the same quirk in the semir dump,
where the inst id is mentioned in the `import_ref` insts, but is not
defined elsewhere, has no name, and says `[no loc]`. I'll look into that
separately. (hmm, maybe this is just an unloaded ImportRef, actually)
2025-08-11 19:29:59 +00:00
Boaz Brickner 5b328da0aa Avoid creating a vector of bools to mark which C++ thunk parameter types were modified (#5941)
Instead, check which types were modified.
This simplifies the logic and could make it easier to add return value
support.

Part of #5514.
2025-08-11 15:01:51 +00:00
Boaz Brickner fd3eb136af Use llvm::zip() to iterate over callee_function_params, thunk_function_params and callee_arg_ids (#5940) 2025-08-11 14:57:42 +00:00
Richard Smith e0de9ddf05 Implement initialization for C++ thunk parameters. (#5938)
When initializing a C++ thunk parameter:

* If we have an initializing expression, materialize a temporary and
pass its address.
* If we have a reference expression, pass its address directly.
* If we have a value expression with a pointer value representation,
pass the pointer.
* Otherwise, create a new temporary and initialize it with a copy of the
argument, and pass its address.
2025-08-08 23:38:47 +00:00
Dana Jansens 2e22733372 Use canonical constant values as the keys for ImplWitnessAccess in AccessRewriteValues (#5912)
Instead of a bespoke structure based on the `EntityName` in the
`ImplWitnessAccess`' `.Self` type, use the constant value of the
`ImplWitnessAccess` as the map key in `AccessRewriteValues`. This is
okay after #5883 makes the `ImplWitnessAccess` to `.Self` canonically
the same regardless of how it's constructed with nested `where`
expressions.

Introduce `KnownInstId` which tracks in the type system that an `InstId`
is known to refer to a specific typed inst structure. This avoids
writing CHECKs and comments and allows compiler enforcement.
2025-08-08 23:17:54 +00:00
Dana Jansens f6b98261e1 Allow dumping with a Parse::Context (#5936)
Don't make the debugging user have to get the `.tree()` off of the
context (which takes a bit of work to find).
2025-08-08 20:32:16 +00:00
Dana Jansens 3d77c4441b Compare ImplWitnessAccess into Self as canonical constants (#5883)
This makes all `.Self` references in a facet type canonically the same
(which will remain true iff they refer to the same `Self` type in the
future), removing the need to do more complex comparisons between them
using the EntityName, interface, and index. This allows the comparison
of types containing `.Self` references to be done correctly regardless
of where the `.Self` appears, as such type expressions will all be
canonically equal if they otherwise equal now, regardless of whether
they are written in the context where `.Self` could have seen different
`Self` facet types.

In order to retain access to constraints on a base `.Self` facet type,
in the case of applying `where` to an existing facet type, we:
- Give the base facet type as a `RequirementBaseFacetType` constraint so
that eval of `WhereExpr` can find and copy all the constraints off of
it.
- Introduce eager/early rewrite constraint resolution, which allows a
constraint to eagerly resolve access to earlier rewrite constraints
(`where .A = () and .B = .A` is eagerly transformed into `where .A = ()
and .B = ()`) before the full constraint resolution step. This allows
use of rewrite constraints in larger type expressions, such as `where .A
= () and .B = C(.A)` and `C` will know that the argument is `()`.
2025-08-08 18:36:39 +00:00
Dana Jansens edcc24ecf7 Don't require writing a return type on lambdas (#5935)
clang-tidy/clangd has started warning on lambdas without an explicit
return type
2025-08-08 17:28:30 +00:00
Boaz Brickner de3148c966 Avoid readability-function-size clang-tidy checks on Stringify() (#5933)
This currently triggers due to preprocessing.
2025-08-08 14:14:21 +00:00
Boaz Brickner 9f108bad6e Rename cpp_ast to clang_ast_unit (#5926)
Followup of #5924.
2025-08-08 08:11:49 +00:00
Dana Jansens d5cb9a7144 Simpler regex for a multi-line capture group (#5925) 2025-08-07 17:58:45 +00:00
Boaz Brickner 52ed26235d Add a flag to dump the C++ AST (#5918)
Use it to dump the AST that includes a generated C++ thunk.
Based on #5917.

Also added printing of the full actual text when check fails to make
debugging easier.
Changed line replacement to allow removing complete lines.

Part of #5514.
2025-08-07 17:09:30 +00:00
Boaz Brickner 0f171611d4 Create clang::MangleContext once per file instead of once per C++ thunk (#5924)
Part of #5514.
2025-08-07 14:50:46 +00:00
Jon Ross-Perkins 55085de6aa Use GetStructType when building object repr structs (#5923)
I was thinking about this for destruction, which I may not be able to
use it for, but still think this may be a good change to keep features
consistent.
2025-08-06 23:55:05 +00:00
37d5046ceb Support parse/check/lower for char (#5901)
toolchain/check/testdata/builtins/char/basics.carbon and
toolchain/lower/testdata/builtins/char.carbon are probably the most
interesting tests here. The parse tests is required because this adds a
new node kind, and we need coverage of it; but the attached info is
minor. There's a fair amount of test churn here because I'm adding the
Core.Char and Core.CharLiteral types as new singletons.

My intent here is that `CharId` is always a unicode code point, even
when the type is a `Char` and thus must be a single UTF-8 code unit
(single byte). This mainly means the stored value of a `CharValue` can
be printed internally without knowing the type.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-06 20:39:01 +00:00
Dana JansensandRichard Smith 9c7e0f6bd5 Add some tests for .Self in the interface params, and comments about implied constraints (#5919)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-06 20:14:49 +00:00
David Blaikie 545354a3b4 Import symbolic vtable entries as attached constants (#5871)
Similar to 26ec78ec00 - vtable entries
can't be unattached symbolic constants, because if they are they can't
be `GetValueInSpecific`d because they lack the context for their
generic/specific.

Importing mostly wants to make/import things as unattached constants -
but `ImportRef` supports attached constants, so use those - but we don't
need the laziness, so use `LoadedImportRef`.
2025-08-06 18:27:22 +00:00
dependabot[bot] 139bdf258e Bump tmp from 0.2.3 to 0.2.4 in /utils/vscode in the npm_and_yarn group across 1 directory (#5921)
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.3 to 0.2.4
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/raszi/node-tmp/commit/08fa3abac32b621506512724b28b56b9c4a95846"><code>08fa3ab</code></a>
Update version</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/1cf4ec54180a77a2a95dc1941efa1659774c8787"><code>1cf4ec5</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/188b25e529496e37adaf1a1d9dccb40019a08b1b"><code>188b25e</code></a>
Fix GHSA-52f5-9888-hmc6</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/73b9fe45bbb40157acdfab8126dd0911de91c8fa"><code>73b9fe4</code></a>
Add test case for GHSA-52f5-9888-hmc6</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/b8e2f29a7575352e49e4882a836aab4bd2ec927f"><code>b8e2f29</code></a>
Remove broken tests</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/2892a027b4d2d3a25d1d08a398bc108a0200857f"><code>2892a02</code></a>
Remove outdated URL</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/f5923182461a89e9de5a7a09c75f410a76979ae7"><code>f592318</code></a>
Reformat package.json</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/995ac8cc45867b44babdf232a1ab0a3bb1d25d95"><code>995ac8c</code></a>
Merge pull request <a
href="https://redirect.github.com/raszi/node-tmp/issues/301">#301</a>
from raszi/dependabot/npm_and_yarn/braces-3.0.3</li>
<li><a
href="https://github.com/raszi/node-tmp/commit/caa758d7b55783c1e9abcb34695fdb9a812c30b7"><code>caa758d</code></a>
Bump braces from 3.0.2 to 3.0.3</li>
<li>See full diff in <a
href="https://github.com/raszi/node-tmp/compare/v0.2.3...v0.2.4">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.3&new-version=0.2.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-08-06 17:28:55 +00:00
Boaz Brickner 1d314c7c4d Import C++ constructors of class Type fn Type(...) -> Type (#5879)
Only supports classes with a single (non copy non move) constructor
(without default values), until overloading is supported.

Based on #5878.

C++ Interop Demo:

```c++
// hello_world.h

#include <cstdio>

class C {
 public:
  C(int x, int y) : x_(x), y_(y) {}

  int x() const { return x_;}
  int y() const { return y_;}

 private:
  int x_;
  int y_;
};

void hello_world(C* _Nonnull c);
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

void hello_world(C* _Nonnull c) {
  printf("C.x = %d. C.y = %d\n", c->x(), c->y());
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  var c : Cpp.C = Cpp.C.C(1, 2);
  Cpp.hello_world(&c);
  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
C.x = 1. C.y = 2
```

Part of #5880.
2025-08-06 12:02:38 +00:00
Boaz Brickner 3c9d267388 Generate and use a C++ thunk to call non simple ABI C++ functions (#5850)
When the C++ function has a parameter that is not a pointer and not a
signed integer of 32 or 64 bits, generate a thunk.

Terminology:
* Callee function: The C++ function we actually want to call.
* Thunk function: The C++ function we generated that calls the callee
function.
* A simple ABI type, for now, is one of:
  * A pointer
  * signed integer with 32 bits
  * signed integer with 64 bits

The thunk function is marked `always_inline` and uses the `asm`
attribute to set its mangled to the callee function mangled name
suffixed with `".carbon_thunk"`.

When importing a C++ function, we decide whether calling it requires a
thunk and if so we generate it and import it as well, which is currently
a recursive call.

When calling the thunk function, we initialize a temporary storage for
each non simple ABI parameter type and take its address. This can be
optimized when the variable is already in storage.

Not supported yet:
* Functions with non void return values.
* Member methods.

Moved unsigned int param test from `arithmetic_types_direct.carbon` to
`arithmetic_types_bridged.carbon`, since only signed integers aren't
bridged using a thunk.

C++ Interop Demo:

```c++
// hello_world.h

struct S {
  S() {}
  S(const S&) { x = 1; }
  int x;
};

void hello_world(S s);
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

void hello_world2(S s) { printf("hello_world2: %d\n", s.x); }

void hello_world(S s) {
  printf("hello_world: %d\n", s.x);
  hello_world2(s);
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  var s : Cpp.S;
  Cpp.hello_world(s);
  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
hello_world: 1
hello_world2: 1
```

Before this change (no thunk - copy constructor not called when calling
`hello_world()`):
```shell
$ ./demo
hello_world: -1219172304
hello_world2: 1
```
2025-08-06 10:27:33 +00:00
Richard SmithandJon Ross-Perkins 7cac77119c Support import Cpp inline "some code";. (#5904)
This adds support for importing C++ code directly from source rather
than via a `#include`.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-08-05 23:03:32 +00:00
Richard Smithandgoogle-labs-jules[bot] 4685890d63 Rename FloatLiteral to FloatValue. (#5911)
In preparation for `FloatValue` being used more generally, and not only
for literals.

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
2025-08-05 22:34:34 +00:00
Richard Smith bd2483b553 Don't use Check::Context when emitting C++ diagnostics. (#5910)
Diagnostics can get flushed after the context is destroyed. Should fix
an issue found by msan.
2025-08-05 21:21:30 +00:00
Jon Ross-Perkins fd4dbc5b6f Remove clang prefixes from isa/cast when optional (#5909)
This is from a quick discussion with zygoloid. There's a mix of uses,
we're both comfortable with a "minimum syntax" decision here to use ADL.

Note this doesn't touch llvm::cast uses in yaml_test_helpers, but ADL
doesn't work there (because the objects are in a `llvm::yaml`
namespace). This gets to another choice made here: if we specify a
namespace, prefer `llvm::` because it's shorter. `clang` has a using of
them, but it's probably better to point at the canonical version if
we're being explicit about it.
2025-08-05 20:04:51 +00:00
Dana Jansens 905c964278 Remove two todos in facet_type.cpp (#5908)
The first TODO is done/under development. The second is no longer
relevant now that we don't ever invalidate pointers into ValueStores.
2025-08-05 19:27:54 +00:00
Boaz Brickner 720c77f6e7 Don't use struct literals in tests (#5906)
The first version of C++ overload resolution would not support struct
literals, so we prepare the tests for that.
2025-08-05 18:57:03 +00:00
Boaz Brickner 29c102bd15 Add missing Cpp. to unsupported decl type test (#5907)
Followup of #5787.
2025-08-05 18:30:42 +00:00
Jon Ross-PerkinsandGeoff Romer 7209ad7c9f Generate Destroy impls for classes (#5873)
Although this focused on `Destroy` support, some choices here around
`implicit_type_impls` are because copy/move will likely follow a similar
approach. I'm trying not to predict too much about how we'll structure
those, but I'm putting `Destroy` impl logic in a file that could perhaps
be shared with those. They'd likely be interested in similar things,
e.g. traversing members of types (particularly class, struct literal,
tuple literal).

At present this sets the destroy function as `no_op` which is consistent
with current logic, but has a TODO to correctly define.

Constant importing for functions changes slightly due to some issues I
was having with `GetFunctionType`. zygoloid suggested this approach to
avoid `EvalInst` logic.

Adds a flag for controlling whether to generating these impls. While
this does generation for `class`, as noted above this'll also need to be
done for tuples and struct literals, which would leave the `none.carbon`
min_prelude unable to use any types. Note if destruction *would* occur,
it'll still look up `Core.Destroy` for that and fail, but that's already
true of any test using `none.carbon`. I'm trying to use the flag to see
if we can keep `none.carbon` working mostly-consistently.

I'd tried separating out the flag to #5852, but that got a lot of
pushback over whether the behavior was appropriate. I'm hoping that the
interactions here make it clearer why the particular approach -- the
goal is not to enable advanced testing, or create some new end-user
behavior that we really support, it's just to keep no-prelude tests
functional. The main question raised there was why not just keep
generating `impl T as Core.Destroy` if `fn destroy` is present -- but I
think here it should be apparent that would require additional
complexity, as the generation of `impl T as Core.Destroy` is not
currently conditioned based on the implementation of `fn destroy`. I'd
rather add complexity to this flag only if it's enabling interesting
test functionality.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-08-04 19:39:22 +00:00
Dana Jansens a5a5e381be More tests for early rewrite application and implied constraints (#5892)
Attempting to capture all the use cases described in [open discussion
2025-07-31](https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.lup43xycic7t).
2025-08-01 21:38:49 +00:00
Alina Sbirlea 7198050573 Docs for specific coalescing. (#5886)
Add documentation describing the problem and algorithm for coalescing
the LLVM functions generated from Carbon generic functions into fewer
LLVM functions, where the LLVM types permit it.
2025-08-01 19:01:20 +00:00
Geoff RomerandJon Ross-Perkins 48e75892bf Document pattern-matching implementation (#5846)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-08-01 18:42:40 +00:00
Jon Ross-PerkinsandRichard Smith cae8aa3adf Support lexing characters (#5893)
Adapts `StringLiteral` to lex characters. Adds a `CharLiteral` token,
which contains a `CharLiteralValue` which is a straight unicode code
point (suggested by zygoloid).

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-08-01 18:24:03 +00:00
Dana Jansens c707a6deaa Verify rewrite constraints in impl lookup (#5617)
In order to verify rewrite constraints at the end of
`LookupImplWitness()` we need to replace references to associated
constants in the query facet type with values that come from the query's
self. To do this, we find any `ImplWitnessAccess` that is a reference to
`.Self` and replace its witness with the witness found through the impl
lookup process, if the interfaces match. This allows the
`ImplWitnessAccess` to resolve to a concrete value if that witness was
concrete. Then we just need to compare that for each rewrite constraint
the lhs and rhs are the same constant value. If they differ, the self
provided a different value for one side (either through its own facet
value constraints or through an associated impl), or the self did not
provide a value at all.

For now, only .Self references in the top-level facet type are
rewritten. Nested facet types are not, even if they contain a .Self
reference up to the top level facet value. This will be addressed by
adding numbering to the EntityName of of .Self in a BindSymbolicName.
See the third model in
https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0
for the plan. For now, there is a TODO addressing this.
2025-08-01 18:04:20 +00:00
ac98870e67 ref parameters, arguments, returns and val returns (#5434)
- A parameter binding can be marked `ref` instead of `var` or the
default. It will bind to reference argument expressions in the caller
and produces a reference expression in the callee.
- Unlike pointers, a `ref` binding can't be rebound to a different
object.
- This replaces `addr`, and is not restricted to the `self` parameter.
- A `ref` binding, like a value binding, can't be used in fields of
classes or structs.
- When calling functions, arguments to non-`self` `ref` parameters are
also marked with `ref`.
- The return of a function can optionally be marked `ref`, `val`, or
`var`. These control the category of the call expression invoking the
function, and how the return expression is returned.
- These may be mixed for functions returning tuple or struct forms.
-   The address of a `ref` binding is `nocapture` and `noalias`.
- We mark parameters of a function that may be referenced by the return
value with `bound`.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-08-01 17:43:41 +00:00
Richard Smith e3a366f1c3 Add prelude impl of Iterate for array types. (#5895)
Iterate over arrays by producing their elements in the obvious way. We
use `i32` as the cursor type because that's the type that check converts
array indexes to. This may need revisiting if we support arrays with
more than 2Bi elements.

Also includes a fix for an import crash bug that's triggered by this
change, borrowed from #5873.
2025-08-01 16:13:22 +00:00
Boaz Brickner 7de86a0b10 Move and deduplicate testing access when a Carbon class extends a C++ record to access.carbon (#5897)
Followup of #5858.
Part of #5859.
2025-08-01 13:44:08 +00:00
Richard Smith 25681901bd Improve mapping of Clang diagnostics into Carbon diagnostics (#5894)
Instead of taking the complete text of the Clang diagnostic and using it
as the message portion of a Carbon diagnostic, generate the individual
pieces separately and pass them into the Carbon diagnostic
infrastructure.

* Clang's context lines are generated by running a custom "diagnostic
renderer" and tracking which lines it wants to print as context for a
given source location. When mapping from a C++ source location back to a
Carbon location, the Carbon `Loc` structure is now fully populated,
including filling in the context line and the column number.
* Clang's snippet is generated by running a custom diagnostic renderer
that is a cut-down version of the full text diagnostic renderer that
only prints a snippet. This is then attached to the Carbon diagnostic
manually as an override for the snippet we'd usually create.

We no longer repeat the file location twice on each diagnostic, and no
longer produce a bogus "in import" line for all locations coming from
clang that point arbitrarily to the first C++ import in the Carbon file.
The `[diagnostic kind]` marker is now displayed at the end of the
diagnostic message, not on a line of its own after the snippet.
2025-08-01 01:24:31 +00:00
Richard SmithandChandler Carruth b320ea77ec Improve source location in an import error. (#5887)
When attempting to import a definition of a class with virtual bases,
diagnose the point of use instead of the point of definition of the
class.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-07-31 00:45:38 +00:00
Dana Jansens 7f96069b95 Add some tests for constraints depending on resolving other constraints (#5885)
Questions of what should be possible are raised in
https://github.com/carbon-language/carbon-lang/issues/5884

This provides the examples from the issue as test cases.
2025-07-31 00:14:31 +00:00
Richard Smith ae16014df8 Don't import a C++ class definition until the class is required to be complete. (#5865)
When importing a class definition, ask Clang to complete it first. This
causes class template specializations to get instantiated as needed when
the type-checking of Carbon requires a C++ class to be complete. It also
allows Clang to implement things like modules-aware definition
visibility checking.

Don't reject importing a class with a virtual base if it's never
required to be complete. Instead, defer diagnosing until the definition
is required.

This also removes the recursion from `MapType`, as mapping a class type
no longer maps its definition.

In order to get diagnostics from instantiation failures, fix a bug that
caused any Clang diagnostics produced after the initial building of the
`ASTUnit` to get discarded. This exposed some duplicate diagnostic
issues in `ImportNameFromCpp` which are fixed here too.
2025-07-30 23:34:18 +00:00
14f51d70c2 Emit diagnostics produced by Clang after the ASTUnit is constructed. (#5876)
Previously we would drop these diagnostics; now periodically flush them
to Carbon's diagnostics emitter. We flush them at the end of checking,
and also immediately before changing the set of diagnostic annotation
scopes, so that Clang diagnostics get properly annotated.

This exposes some double diagnostics being produced in situations where
Clang's name lookup logic would produce a diagnostic and we also
produced one. For access control issues, use the Carbon diagnostic, in
order to properly handle protected access. For ambiguity issues, use the
Clang diagnostic that produces helpful notes.

Also fix rendering of note diagnostics produced by Clang, by attaching
them to the prior error / warning diagnostic.

---------

Co-authored-by: Boaz Brickner <brickner@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-07-30 21:01:12 +00:00
Jon Ross-PerkinsandDana Jansens 19a7fb08b7 Switch handling of errors in impls to not build a type structure (#5881)
Per discussion at
https://github.com/carbon-language/carbon-lang/pull/5875#issuecomment-3137288037,
a different approach to the same solution.

A key difference is that whereas #5875 would build a `TypeStructure`
containing `ConcreteType{error}`, this instead just returns nothing.
This means impls with errors can't be compared in the same way, though
I'm not sure how much impact that'll really have (I've added a test here
to show a case where it seemed interesting to see what effect it'd have,
and it seems to have none).

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-07-30 20:24:38 +00:00
Boaz Brickner a905f15bf9 Fix the tests for forward declared union pointer as return type by making the return type pointer _Nonnull (#5878)
Followup of #5773.
Part of #5772.
2025-07-30 20:20:30 +00:00
Jon Ross-Perkins 800e8fd55a Add braces for CARBON_KIND uses that lack them (#5882)
Also document why these are expected on `CARBON_KIND`. In
`kind_switch_test.cpp`, drop the `str` variable.

My recollection of the original discussion of `CARBON_KIND` is that it
should always have braces due to the risk of confusion for statement
interpretation, similar to a typical `if`/`else` but more subtle due to
the macro.

For example:

```
      case CARBON_KIND(int n):
        str << "int = " << n;
        return str.TakeStr();
```

is equivalent to:

```
      case CARBON_KIND(int n): {
          str << "int = " << n;
        }
        return str.TakeStr();
```

This happens to work in context because `str` isn't scoped, but a
trivial refactoring to move `RawStringOstream str;` the first statement
of the `case` would probably have non-obvious results. For example:

```
      case CARBON_KIND(int n):
        RawStringOstream str; // Valid name shadowing, destructed without use.
        str << "int = " << n; // Name lookup error on `n`.
        return str.TakeStr();
```
2025-07-30 18:56:39 +00:00
Jon Ross-Perkins 4c0979fc10 Fix crash when importing an invalid impl (#5875)
Dropping this in with basic.carbon as an aspirational way to encourage
more tests there.

This currently crashes because `CollectCandidateImplsForQuery` tries
building a type structure which cannot contain `ErrorInst`.
2025-07-30 17:43:40 +00:00
Boaz Brickner 6a3e222fb7 Don't ignore SemIR ranges in C++ interop tests (#5877)
The non failing tests already define ranges.
2025-07-30 17:17:37 +00:00
Richard Smith a6f5143f22 Fix diagnostic for access of protected/private base member. (#5874)
When importing the member, import the access level for the lookup
result, not the declared access of the member declaration.
2025-07-30 17:17:09 +00:00
Dana Jansens 105618ecb1 Resolve nested accesses in rewrite constraints (#5872)
A rewrite constraint like `.X = .Y.Z and .Y = .Self and .Z = ()` has a
nested `ImplWitnessAccess` `.Y.Z` (technically `(.Self.Y).Z`). The inner
access `.Self.Y` needs to be resolved (in this case to `.Self`) before
the outer `???.Z` can be resolved as `.Self.Z` which is `()`.
2025-07-30 14:34:24 +00:00
Boaz Brickner f0cff612eb Add support for using C++ double type in imported function declarations (#5868)
Carbon only supports f64, so only double can be mapped.

https://github.com/carbon-language/carbon-lang/blob/30f0ddab71bda71f8789080962b1fe8a5938e327/toolchain/check/type.cpp#L54

C++ Interop Demo:

```c++
// hello_world.h

auto hello_world(double x) -> void;
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

auto hello_world(double x) -> void {
  printf("double: %f\n", x);
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  Cpp.hello_world(0.25);
  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
double: 0.250000
```

Before this change:

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
main.carbon:8:3: error: semantics TODO: `Unsupported: parameter type: double`
  Cpp.hello_world(0.25);
  ^~~~~~~~~~~~~~~
main.carbon:8:3: note: in `Cpp` name lookup for `hello_world`
  Cpp.hello_world(0.25);
  ^~~~~~~~~~~~~~~
```

Part of #5263.
2025-07-30 07:13:59 +00:00
Richard Smith ef475d8197 Import C++ class A final as Carbon final class. (#5866)
Also import unions as final classes, and abstract classes as `abstract
class`es.
2025-07-30 00:41:42 +00:00
Dana Jansens 6b83414ee8 Dedupe rewrite constraints without sorting (#5864)
Dedupe rewrite constraints by consuming them by their LHS from the map
of rewrite values, and dropping any LHS that we see more than once. This
essentially uses the map to track which LHS we have seen in place of
sorting the rewrite constraints by the LHS.
2025-07-29 21:34:18 +00:00
Jon Ross-Perkins 64c31a6b9f Adjust ordering of EXTRA-ARGS to allow tests to override includes (#5870) 2025-07-29 20:22:51 +00:00
Dana Jansens 3d6395b75a Remove outdated piece of comment on SubstInst (#5869)
The comment on `Subst` explains what is going on with the possible
return values now, and the return type is no longer bool.
2025-07-29 18:18:32 +00:00
Dana Jansens b36a987e73 Find cycles in rewrite constraints without performing the full exponential expansion of the RHS (#5673)
Make Subst perform "recursion" on the RHS instructions as they are
replaced, effectively doing a depth-first traversal through the rewrite
constraints doing replacements. This allows us to fully compute
individual associated constants in the minimal amount of work, and cache
the results so they can be reused cheaply in cases where the rewrite
constraints generate an exponential number of references to associated
constants.

Fixes https://github.com/carbon-language/carbon-lang/issues/5672
2025-07-29 16:31:28 +00:00
Kazu Hirata 0bba03ce71 Migrate away from llvm::ArrayRef(std::nullopt_t) (#5867)
The upstream LLVM has deprecated ArrayRef(std::nullopt_t).  This CL
migrates away from that.
2025-07-29 15:31:11 +00:00
Richard Smith 63b441390c Avoid vector copies when building dependent declarations list. (#5862)
Plus a few cleanups for uses of clang APIs.
2025-07-29 14:55:43 +00:00
Boaz Brickner 30f0ddab71 Add support for importing access from C++ to Carbon (#5858)
Better access control with inheritance should come with better
inheritance support (actually importing inheritance).

C++ Interop Demo:

```c++
// hello_world.h

class HelloWorld {
 public:
  static auto Pub() -> void;

 protected:
  static auto Pro() -> void;

 private:
  static auto Pri() -> void;
};
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

auto HelloWorld::Pub() -> void { printf("Public!\n"); }
auto HelloWorld::Pro() -> void { printf("Protected!\n"); }
auto HelloWorld::Pri() -> void { printf("Private!\n"); }
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  Cpp.HelloWorld.Pub();
  Cpp.HelloWorld.Pro();
  Cpp.HelloWorld.Pri();
  return 0;
}
```

```shell
$ clang -c hello_world.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
main.carbon:9:3: error: cannot access protected member `Pro` of type `Cpp.HelloWorld`
  Cpp.HelloWorld.Pro();
  ^~~~~~~~~~~~~~~~~~
main.carbon: note: declared here

main.carbon:10:3: error: cannot access private member `Pri` of type `Cpp.HelloWorld`
  Cpp.HelloWorld.Pri();
  ^~~~~~~~~~~~~~~~~~
main.carbon: note: declared here
```

Before this change (no access checks):
```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link hello_world.o main.o --output=demo
$ ./demo
Public!
Protected!
Private!
```

Part of #5859.
2025-07-29 08:25:15 +00:00
Boaz Brickner 6d6e0d0418 Add support for using C++ bool type in imported function declarations. (#5860)
C++ in

C++ Interop Demo:

```c++
// hello_world.h

auto hello_world(bool x) -> bool;
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

auto hello_world(bool x) -> bool {
  printf("bool: %d\n", x);
  return !x;
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  let x: bool = Cpp.hello_world(false);
  if (x) {
    return 0;
  } else {
    return 1;
  }
}
```

```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
bool: 0
```

Before this change (bool is interpreted as a 1 bit integer):
```shell
$ bazel-bin/toolchain/carbon compile main.carbon
... CRASH! ...
clang/include/clang/AST/Type.h:952: const ExtQualsTypeCommonBase *clang::QualType::getCommonPtr() const: Assertion `!isNull() && "Cannot retrieve a NULL type pointer"' failed.
```

Part of #5263.
2025-07-29 06:56:45 +00:00
432ee89dda Semantic Identity and Order-Dependent Resolution for Rewrite Constraints (#5689)
In open discussion[1] we decided that "identical" rewrites would mean
that for a given LHS value, all RHS have the same value (after
evaluation), rather than requiring the RHS to all have the same
syntactic value. This means the following is valid, since the value of
`.Y` is known to be `()` while resolving the rewrite constraints of `T`.
So both rewrites of `.X` are resolved to `.X = ()`:
```
fn Identical(T:! I where .X = () and .X = .Y and .Y = ()) {}
```

The implementation of this clarification, along with test cases encoding
it, is done in https://github.com/carbon-language/carbon-lang/pull/5686.

Clarify this in the language design documents, and improve some other
clarity while we're there:
- The prose talks about a facet `T`, but the examples were using `A` as
its name. Change the facet to be `T`. This means changing the `.T`
associated constant (and `.U` and `.V`) to be `.X` (and `.Y` and `.Z`).
While doing this, use `I` for the interface name instead of `C`, which
we use more commonly for a class type name.
- Correct the comments in the cycle example that claim we find `.Y then
.Y* then .Y**`. In this example `.Y = .Z* and .Z = .Y*` which adds _two_
levels of pointers when evaluating `.Y`: `.Y => .Z* => (.Y*)* => .Y**`

[1]
https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.qti4vn50zwy

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-07-29 02:01:45 +00:00
David BlaikieandDana Jansens 26ec78ec00 Ensure vtable entries for generics are attached constants (#5853)
Otherwise these end up as unattached constants (see the baseline test
changes) and can't be resolved by `GetConstantValueInSpecific` in
lowering or in further derived vtables.

If the class is non-generic, then it's fine for the vtable entry for
some function inherited from a generic base is represented as an
unattached constant, since the specific in that specific_function is
already fully resolved.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-07-28 21:06:57 +00:00
Richard Smith 5de47962b0 Support for importing C++ base classes. (#5856)
For now, provide no support for virtual base classes and only minimal
support for multiple inheritance.
2025-07-28 20:56:06 +00:00
Richard Smith 0d74162e2a Support C++ import for anonymous struct and union members. (#5855) 2025-07-28 20:26:24 +00:00
Dana JansensandJon Ross-Perkins 5dc299f58b Note we are using Clang 16+ in the contribution tools docs (#5861)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-07-28 18:25:04 +00:00
Chandler Carruth eeea9dc9e5 Make minor improvements to ErrorOr based on usage (#5857)
When using this with filesystem errors, a few issues came up that I'm
fixing here. They're small enough and near enough in code that it didn't
seem worth splitting part.

- It's nice to forward declare custom error types and an API using them
and then define both later. That doesn't work with `requires` but works
fine with `static_assert`, so go back to that pattern here. A test is
added that checks this pattern compiles.

- The `operator*` didn't support moving out of `ErrorOr`, which is
especially important when writing code that is happy with just
`CARBON_CHECK`-failing on any errors. For example, we have a lot of
filesystem code in tests that is made *much* more concise by just using
`*` on a function return and letting the built-in checking ensure no
errors were present. But when the value is move-only, this requires
special overloading. Add that and add a test with a move-only value.

- There wasn't an idiomatic way to do something like `operator*` for
`ErrorOr<Success, ...>`. This PR factors out the checking for `ok()`
into a `Check()` method that can be used to make code more readable that
is intentionally just verifying no error. Also makes the result of
`operator*` `[[nodiscard]]` to improve error messages and help void
accidental bugs.

- The `IsError` and `IsSuccess` test helpers required printable values
which isn't always realistic. Teach the printing logic to be conditional
on some indication of a printable value and gracefully fall back to a
generic string otherwise for testing output.

- The use of the `listener` in `IsError` and `IsSuccess` assumed a
non-null stream. Instead, streaming should go directly to the `listener`
as it is configured to only actually do the output when a stream is
installed. When a stream isn't installed, the previous code would crash
if the `MatchAndExplain` method ended up called without an 'interesting'
stream attached to the listener.

- When doing a `CARBON_CHECK` that there isn't an error, print the error
out as the check failure message. Without this, all the nice error
message work doesn't end up helping the debugging of test code that hits
these errors, etc.
2025-07-28 17:42:36 +00:00
Dana Jansens 13e2268783 Add a dump command in lldb for dumping from ids (#5824)
The command is:
```
dump <context> [<ID>|<TYPE><ID>|<TYPE> <ID>|-- <ID>]

TYPE can be "inst", "entity_name", etc.
```

This saves a lot of typing of `SemIR::MakeInstId()` in a debugger, and
allows copy-pasting ids from dump output, as they take the form
`inst33`, etc.
2025-07-28 17:14:37 +00:00
Richard Smith 36f0a73092 Initial support for interop with class/struct/union fields. (#5849)
Add a new type, `custom_layout_type`, representing a struct type whose
size, alignment, and field offsets can be manually controlled. Use this
as the object representation type for imported C++ class types (which
also includes struct and union types), allowing us to model C++ class
type layouts. In passing, also add support for incomplete C++ class
types, mapping them into incomplete Carbon class types.

Map C++ fields into Carbon field declarations, allowing direct access to
C++ fields from Carbon. So far, no support is added for base classes nor
anonymous struct or union declarations; those will be added in
subsequent PRs. Also, we don't map C++ access control into Carbon yet,
so all C++ fields are accessible regardless of their access control.

For now we still use a `struct_type` as the object representation for
empty C++ classes, in order to continue to support our existing tests
that convert `{}` to empty C++ class types. This is temporary and should
be removed once we support interop with C++ class initialization.
2025-07-25 21:09:24 +00:00
Jon Ross-Perkins ef748ab36d Factor out an impl declaration helper function (#5851)
In trying to have types implicitly define `impl Self as Destroy`, I'm
wanting to use standard impl declaration support. For example, this
should produce more consistent errors if someone writes code that would
conflict with the generated impl. I'm also concerned, with the
complexity involved, that I'd get something wrong if I tried to write a
divergent implementation.

I'm only factoring out the start of the declaration. Right now the
finishing portion seems much simpler and lower risk to duplicate; I may
also factor it out separately. But either way, I think `StartImplDecl`
here is high churn risk due to its size (`CheckConstraintIsInterface` I
also expect to be used).
2025-07-25 18:34:07 +00:00
Jon Ross-Perkins bcfaf1044e Remove location support from error (#5837)
Location support was probably there for explorer, which is deleted.
Remove support as a simplification.
2025-07-25 15:00:33 +00:00
Jon Ross-Perkins 8ea92b728c Update prelude files to increase destroy dependencies (#5848)
This is in anticipation of having `class` depending on the `Destroy`
interface, in order to automatically generate implementations of it.

I'm doing some sorting of imports in the prelude too, which I hope will
be uncontroversial; clang-format would do similar in C++...
2025-07-24 23:57:25 +00:00
Jon Ross-Perkins d599023c19 Change CodeGen to use a diagnostic consumer (#5847)
We've been trying to have errors/warnings all go through the diagnostics
consumers instead of straight to stderr.
2025-07-24 21:44:44 +00:00
Jon Ross-PerkinsandChandler Carruth 59619fa8eb Make driver fuzzing more robust for clang flags (#5845)
I'm not sure the target in use here will reliably crash over time, but
it does right now, and that seems reasonable...?

Example crash:

```
file_test: external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Darwin.h:505: bool clang::driver::toolchains::Darwin::isTargetWatchOSBased() const: Assertion `TargetInitialized && "Target not initialized!"' failed.
```

Stack fragment:

```
...
#10 0x0000562ba07dec33 isTargetWatchOSBased /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Darwin.h:505:5
#11 0x0000562ba07dec33 clang::driver::toolchains::DarwinClang::addClangWarningOptions(llvm::SmallVector<char const*, 16u>&) const /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp:1188:7
#12 0x0000562ba072afc7 clang::driver::tools::Clang::ConstructJob(clang::driver::Compilation&, clang::driver::JobAction const&, clang::driver::InputInfo const&, llvm::SmallVector<clang::driver::InputInfo, 4u> const&, llvm::opt::ArgList const&, char const*) const /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Clang.cpp:0:6
#13 0x0000562ba06306d8 clang::driver::Driver::BuildJobsForActionNoCache(clang::driver::Compilation&, clang::driver::Action const*, clang::driver::ToolChain const*, llvm::StringRef, bool, bool, char const*, std::__1::map<std::__1::pair<clang::driver::Action const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, llvm::SmallVector<clang::driver::InputInfo, 4u>, std::__1::less<std::__1::pair<clang::driver::Action const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>>, std::__1::allocator<std::__1::pair<std::__1::pair<clang::driver::Action const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>> const, llvm::SmallVector<clang::driver::InputInfo, 4u>>>>&, clang::driver::Action::OffloadKind) const /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/Driver.cpp:6083:10
...
#28 0x0000562b9e479d1f Carbon::BuildClangInvocation(Carbon::Diagnostics::Consumer&, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>, llvm::ArrayRef<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>) /proc/self/cwd/toolchain/base/clang_invocation.cpp:103:21
...
```

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-07-24 20:00:41 +00:00
Boaz Brickner a269c72e48 Fix variadic arguments test to use the format that is not deprecated in C++26 and fix the call site to be valid (#5842)
See https://en.cppreference.com/w/cpp/language/variadic_arguments.html.

Part of #5436.
2025-07-24 19:40:19 +00:00
Geoff RomerandRichard Smith cb6ca962d2 Update/clarify documentation of generic constants (#5473)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-07-24 19:39:43 +00:00
Jon Ross-Perkins 6bf335c309 Mark VtablePtr always constant (#5843) 2025-07-24 17:17:21 +00:00
Chandler CarruthandJon Ross-Perkins e99448eecf Add support for a custom error type in ErrorOr (#5834)
This doesn't split apart the current error type into one that tracks
location and one that doesn't, although that might be easier to do once
we have this.

Instead, this is primarily intended to support custom error types that
lazily materialize the error message in case that can be avoided by
completely handling the error. For example, many file system operations
are *expected* to produce errors even in the hot path and we don't want
to render `ENOENT` (for example) to a pretty string and instead will
directly query the error to understand and handle it in code.

The type parameter ordering isn't the most obvious, but helpfully allows
us to default the error type in a useful way.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-07-23 23:15:41 +00:00
Jon Ross-Perkins b8ca7bf18f Include the virtual modifier when importing functions (#5841) 2025-07-23 21:42:15 +00:00
Jon Ross-Perkins 192c3f1939 Add comment to FindAssociatedImportIRs (#5840)
This had come up during the summit, figured a brief comment may help
clarify in the future.
2025-07-23 16:55:13 +00:00
Jon Ross-Perkins fce98b7331 Allow formatting instructions with a missing name (#5839)
This is to make it easier to debug formatter issues. It means printing
can now result in things like:

```
<unexpected>.inst57.loc4_24: type = bind_symbolic_name ...
```

Where the "unexpected" reflects incorrect construction.
2025-07-22 22:46:58 +00:00
Jon Ross-Perkins fdd68dcbe6 Fix a crash when Core is poisoned (#5838)
There are probably other ways to reproduce this, but this is roughly how
I ran into it.
2025-07-22 22:31:41 +00:00
Richard Smith c90c6728fd Interop: support all C++ integer types that map to intN_t or uintN_t. (#5836)
Expand support for `int` and `short` to cover all the other `intN_t` and
`uintN_t` types too. We achieve this by asking Clang what the `intN_t` /
`uintN_t` type that it would use for the given bitwidth is, and checking
if that's the type we're trying to map.
2025-07-22 21:29:09 +00:00
dependabot[bot] b01767a5e4 Bump form-data from 4.0.1 to 4.0.4 in /utils/vscode in the npm_and_yarn group across 1 directory (#5835)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [form-data](https://github.com/form-data/form-data).

Updates `form-data` from 4.0.1 to 4.0.4
<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.3...v4.0.4">v4.0.4</a>
- 2025-07-16</h2>
<h3>Commits</h3>
<ul>
<li>[meta] add <code>auto-changelog</code> <a
href="https://github.com/form-data/form-data/commit/811f68282fab0315209d0e2d1c44b6c32ea0d479"><code>811f682</code></a></li>
<li>[Tests] handle predict-v8-randomness failures in node &lt; 17 and
node &gt; 23 <a
href="https://github.com/form-data/form-data/commit/1d11a76434d101f22fdb26b8aef8615f28b98402"><code>1d11a76</code></a></li>
<li>[Fix] Switch to using <code>crypto</code> random for boundary values
<a
href="https://github.com/form-data/form-data/commit/3d1723080e6577a66f17f163ecd345a21d8d0fd0"><code>3d17230</code></a></li>
<li>[Tests] fix linting errors <a
href="https://github.com/form-data/form-data/commit/5e340800b5f8914213e4e0378c084aae71cfd73a"><code>5e34080</code></a></li>
<li>[meta] actually ensure the readme backup isn’t published <a
href="https://github.com/form-data/form-data/commit/316c82ba93fd4985af757b771b9a1f26d3b709ef"><code>316c82b</code></a></li>
<li>[Dev Deps] update <code>@ljharb/eslint-config</code> <a
href="https://github.com/form-data/form-data/commit/58c25d76406a5b0dfdf54045cf252563f2bbda8d"><code>58c25d7</code></a></li>
<li>[meta] fix readme capitalization <a
href="https://github.com/form-data/form-data/commit/2300ca19595b0ee96431e868fe2a40db79e41c61"><code>2300ca1</code></a></li>
</ul>
<h2><a
href="https://github.com/form-data/form-data/compare/v4.0.2...v4.0.3">v4.0.3</a>
- 2025-06-05</h2>
<h3>Fixed</h3>
<ul>
<li>[Fix] <code>append</code>: avoid a crash on nullish values <a
href="https://redirect.github.com/form-data/form-data/issues/577"><code>[#577](https://github.com/form-data/form-data/issues/577)</code></a></li>
</ul>
<h3>Commits</h3>
<ul>
<li>[eslint] use a shared config <a
href="https://github.com/form-data/form-data/commit/426ba9ac440f95d1998dac9a5cd8d738043b048f"><code>426ba9a</code></a></li>
<li>[eslint] fix some spacing issues <a
href="https://github.com/form-data/form-data/commit/20941917f0e9487e68c564ebc3157e23609e2939"><code>2094191</code></a></li>
<li>[Refactor] use <code>hasown</code> <a
href="https://github.com/form-data/form-data/commit/81ab41b46fdf34f5d89d7ff30b513b0925febfaa"><code>81ab41b</code></a></li>
<li>[Fix] validate boundary type in <code>setBoundary()</code> method <a
href="https://github.com/form-data/form-data/commit/8d8e4693093519f7f18e3c597d1e8df8c493de9e"><code>8d8e469</code></a></li>
<li>[Tests] add tests to check the behavior of <code>getBoundary</code>
with non-strings <a
href="https://github.com/form-data/form-data/commit/837b8a1f7562bfb8bda74f3fc538adb7a5858995"><code>837b8a1</code></a></li>
<li>[Dev Deps] remove unused deps <a
href="https://github.com/form-data/form-data/commit/870e4e665935e701bf983a051244ab928e62d58e"><code>870e4e6</code></a></li>
<li>[meta] remove local commit hooks <a
href="https://github.com/form-data/form-data/commit/e6e83ccb545a5619ed6cd04f31d5c2f655eb633e"><code>e6e83cc</code></a></li>
<li>[Dev Deps] update <code>eslint</code> <a
href="https://github.com/form-data/form-data/commit/4066fd6f65992b62fa324a6474a9292a4f88c916"><code>4066fd6</code></a></li>
<li>[meta] fix scripts to use prepublishOnly <a
href="https://github.com/form-data/form-data/commit/c4bbb13c0ef669916657bc129341301b1d331d75"><code>c4bbb13</code></a></li>
</ul>
<h2><a
href="https://github.com/form-data/form-data/compare/v4.0.1...v4.0.2">v4.0.2</a>
- 2025-02-14</h2>
<h3>Merged</h3>
<ul>
<li>[Fix] set <code>Symbol.toStringTag</code> when available <a
href="https://redirect.github.com/form-data/form-data/pull/573"><code>[#573](https://github.com/form-data/form-data/issues/573)</code></a></li>
<li>[Fix] set <code>Symbol.toStringTag</code> when available <a
href="https://redirect.github.com/form-data/form-data/pull/573"><code>[#573](https://github.com/form-data/form-data/issues/573)</code></a></li>
<li>fix (npmignore): ignore temporary build files <a
href="https://redirect.github.com/form-data/form-data/pull/532"><code>[#532](https://github.com/form-data/form-data/issues/532)</code></a></li>
<li>fix (npmignore): ignore temporary build files <a
href="https://redirect.github.com/form-data/form-data/pull/532"><code>[#532](https://github.com/form-data/form-data/issues/532)</code></a></li>
</ul>
<h3>Fixed</h3>
<ul>
<li>[Fix] set <code>Symbol.toStringTag</code> when available (<a
href="https://redirect.github.com/form-data/form-data/issues/573">#573</a>)
<a
href="https://redirect.github.com/form-data/form-data/issues/396"><code>[#396](https://github.com/form-data/form-data/issues/396)</code></a></li>
<li>[Fix] set <code>Symbol.toStringTag</code> when available (<a
href="https://redirect.github.com/form-data/form-data/issues/573">#573</a>)
<a
href="https://redirect.github.com/form-data/form-data/issues/396"><code>[#396](https://github.com/form-data/form-data/issues/396)</code></a></li>
<li>[Fix] set <code>Symbol.toStringTag</code> when available <a
href="https://redirect.github.com/form-data/form-data/issues/396"><code>[#396](https://github.com/form-data/form-data/issues/396)</code></a></li>
</ul>
<h3>Commits</h3>
<ul>
<li>Merge tags v2.5.3 and v3.0.3 <a
href="https://github.com/form-data/form-data/commit/92613b9208556eb4ebc482fdf599fae111626fb6"><code>92613b9</code></a></li>
<li>[Tests] migrate from travis to GHA <a
href="https://github.com/form-data/form-data/commit/806eda77740e6e3c67c7815afb216f2e1f187ba5"><code>806eda7</code></a></li>
<li>[Tests] migrate from travis to GHA <a
href="https://github.com/form-data/form-data/commit/8fdb3bc6b5d001f8909a9fca391d1d1d97ef1d79"><code>8fdb3bc</code></a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/form-data/form-data/commit/41996f5ac73a867046d48512cab62e64fc846dad"><code>41996f5</code></a>
v4.0.4</li>
<li><a
href="https://github.com/form-data/form-data/commit/316c82ba93fd4985af757b771b9a1f26d3b709ef"><code>316c82b</code></a>
[meta] actually ensure the readme backup isn’t published</li>
<li><a
href="https://github.com/form-data/form-data/commit/2300ca19595b0ee96431e868fe2a40db79e41c61"><code>2300ca1</code></a>
[meta] fix readme capitalization</li>
<li><a
href="https://github.com/form-data/form-data/commit/811f68282fab0315209d0e2d1c44b6c32ea0d479"><code>811f682</code></a>
[meta] add <code>auto-changelog</code></li>
<li><a
href="https://github.com/form-data/form-data/commit/5e340800b5f8914213e4e0378c084aae71cfd73a"><code>5e34080</code></a>
[Tests] fix linting errors</li>
<li><a
href="https://github.com/form-data/form-data/commit/1d11a76434d101f22fdb26b8aef8615f28b98402"><code>1d11a76</code></a>
[Tests] handle predict-v8-randomness failures in node &lt; 17 and node
&gt; 23</li>
<li><a
href="https://github.com/form-data/form-data/commit/58c25d76406a5b0dfdf54045cf252563f2bbda8d"><code>58c25d7</code></a>
[Dev Deps] update <code>@ljharb/eslint-config</code></li>
<li><a
href="https://github.com/form-data/form-data/commit/3d1723080e6577a66f17f163ecd345a21d8d0fd0"><code>3d17230</code></a>
[Fix] Switch to using <code>crypto</code> random for boundary
values</li>
<li><a
href="https://github.com/form-data/form-data/commit/d8d67dc8ac79285154edf7d3f57dbab593b9a146"><code>d8d67dc</code></a>
v4.0.3</li>
<li><a
href="https://github.com/form-data/form-data/commit/e6e83ccb545a5619ed6cd04f31d5c2f655eb633e"><code>e6e83cc</code></a>
[meta] remove local commit hooks</li>
<li>Additional commits viewable in <a
href="https://github.com/form-data/form-data/compare/v4.0.1...v4.0.4">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=form-data&package-manager=npm_and_yarn&previous-version=4.0.1&new-version=4.0.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-07-22 13:53:19 +00:00
Jon Ross-Perkins bd4fbb4393 Expand use of CheckIRId stores (#5820)
This is trying to make it clearer when vectors are being indexed with
`CheckIRId`.

The only one that I still kind of want to change is the
`SmallVector<std::unique_ptr<CompilationUnit>>`, but because it's a
`unique_ptr` that's a little more complex. I may not bother.

Note, some of the changes around nuanced `SmallVector` interactions were
based on trying to copy the way `SmallVector` itself takes arguments,
like with range passing.
2025-07-21 20:02:27 +00:00
Jon Ross-Perkins 7ccc1e0144 Expand naming for impls and functions (#5808)
Change impls from `<interface>.impl` to `<self>.as.<interface>.impl`,
and *member* functions to `<parent scope>.<fn>` (non-member functions
exclude their parent scope). Stop special-casing builtin functions,
given the new naming scheme.

The purpose of this is to make it clearer when a member function is
being accessed and, if so, which member function. In particular, we
often access interface `Op` functions. The builtin function
special-casing was intended to help with that, but we still have lots of
`Op` functions. This particular approach should make the interactions
clearer.

This changes up queueing of block IDs a little because, in particular,
we need to process bodies of entities only after constants finish
processing. But, it should also result in less memory usage during
processing because it means we have less on the insts stack at any given
time, since we track a block rather than all instructions contained by
the block.
2025-07-21 18:45:07 +00:00
Jon Ross-PerkinsandGeoff Romer eae3491129 Switch inst namer to queue entities when reached (#5806)
This switches from the `CollectNamesInBlock` approach for entities, to
instead traversing entities as they're encountered. For example, when
traversing constants, when a type is found, the entity will have its
block queued for processing.

This leads to a change in the traversal order, which affects
disambiguation done by numeric sequencing (since that's just showing the
traversal order).

This will allow for simpler "name based on name" logic. This is
something I plan to use for:

- impls: `<type>.as.<interface>.impl`
- functions: `<entity>.<member function>`
  - Note an impl may be used as the entity for a bound function.

By naming the entities as they're encountered, I'll be able to rely on
the generated names rather than recalculating them.

To assist this, I'm also differentiating between the ambiguous and
disambiguated name. Otherwise, we could end up with things like
`<function>.<disambiguator>.<call>.<other disambiguator>`, where the
repeated disambiguator may not be necessary in order to get full
disambiguation. It's also a smaller delta from the current output.

Note, changing `Name` to a class felt appropriate given its shape. I was
also noticing that parts of its API were unused, and the class helps
detect unused private members.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-07-21 17:58:55 +00:00
Dana Jansens 9e9df7d14e Use a none prelude instead of needing int.carbon just to name a return type (#5819) 2025-07-19 16:03:34 +00:00
Dana Jansens 64c7e4eeb3 Add a comment on EntityName's CarbonHashtableEq about its requirements (#5828)
The entity name structure will grow at least one more field for symbolic
bindings (see [open
discussion](https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0)),
so we can just refer to the "following" fields to include them all.
2025-07-18 22:00:33 +00:00
Boaz Brickner 68ee3d5021 Use llvm::reverse() instead of pop_back_val() in ImportDeclAndDependencies() (#5831)
This is more explicit and similar to what we do in `MapType()`.
2025-07-18 21:11:12 +00:00
Boaz Brickner 977875ec20 Add C++ inline namespace tests (#5826)
Part of #5436.
2025-07-18 21:04:48 +00:00
Boaz Brickner 8cb01b54bd Avoid passing name scope id and name id through ImportCXXRecordDecl() and BuildClassDefinition() (#5829)
All this information is calculated based on the Clang declaration.
2025-07-18 20:58:59 +00:00
Richard Smith 2b9e110154 Don't unnecessarily create output files in a driver test. (#5830)
Make another driver test a little more permissive.
2025-07-18 20:55:19 +00:00
Dana Jansens 565f39480a Make the .Self entity name in a WhereExpr a canonical one (#5827)
This will allow reusing existing entity names when there are nested
.Self references in a facet type. They are canonical as the contents of
a .Self reference are all canonical.
2025-07-18 20:42:16 +00:00
Jon Ross-Perkins ec3a3eff99 Update bazel and module versions (#5822)
- Update bazel to 8.3.1, just to stay reasonably up to date.
- Bazel warned about the platforms version, so I generally updated
packages that have central registry versions.
- Note there's a newer re2 in the central registry, but I got a download
error with it.
- `--experimental_guard_against_concurrent_changes` is deprecated; I
wasn't sure it's worth explicitly setting
`--guard_against_concurrent_changes=full`, but figured it may be
consistent (it's not clear to me -- see
https://github.com/bazelbuild/bazel/pull/25874).
2025-07-18 20:24:02 +00:00
David Blaikie 37ac093f32 Diagnose impl method without matching virtual function in base class (#5817)
Also update `RequestVtableIfVirtual` to strip `impl` from functions in
classes without a base class - this avoids a duplicate diagnostic where
they're diagnosed as being in a class without a base class, then
diagnosed again because they don't have a matching function in a base
class.
2025-07-18 19:03:06 +00:00
Jon Ross-Perkins 8428b86cfb Update pre-commit clang-format version (#5825)
Versus #5823, this is manually updated (still verified with `pre-commit
run -a`).

I also looked at updating prettier; adding a note why I'm not doing
that.
2025-07-18 18:29:12 +00:00
Jon Ross-Perkins 8c0fee2a29 Include generate_llvm_tools_def in the list of file generators (#5815)
Trying to fix the error at:

https://github.com/carbon-language/carbon-lang/actions/runs/16349808015/job/46193321961?pr=5811

Also make it a little easier to debug which files are being built, I've
done this a few times now.
2025-07-18 18:05:03 +00:00
Boaz Brickner 52976c55fb When importing a declaration, first collect all dependent unimported declarations and import them first (#5821)
This fixes some tests since we now handle record name scopes correctly.

Part of #5533.
2025-07-18 18:01:27 +00:00
Jon Ross-Perkins 8d7fe8a04f pre-commit autoupdate (#5823)
Just a simple `pre-commit autoupdate --freeze && pre-commit run -a` with
no new issues.
2025-07-18 17:59:05 +00:00
Richard SmithandChandler Carruth 553dd6e531 Build the clang::CompilerInvocation in the driver. (#5784)
Add driver flags to specify clang driver arguments.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-07-18 16:30:47 +00:00
Dana Jansens bcba76aca7 Require file tests to specify a min-prelude (#5818)
Use `full.carbon` min-prelude for any tests using the full prelude. A
few tests were using it unnecessarily and are changed to a more minimal
one in the process.

Any test which does not include some min-prelude will now fail with an
error.
2025-07-18 16:26:12 +00:00
Jon Ross-PerkinsandDana Jansens 2658142f7b Add link for 'How we compile' talk (#5810)
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-07-18 15:02:52 +00:00
Boaz Brickner f4f521de7f Explicitly mark as unsupported instead of crashing mapping a parameter record type defined not in a namespace (#5777)
Before this change we crash in this case when trying to use the outer
type.
After this change we diagnose a TODO.
Will add the missing support for this in a separate PR.

Part of #5533.
2025-07-18 02:42:45 +00:00
Jon Ross-Perkins 61290fdee9 Make ConstantValueStore use ValueStore internally (#5811)
This changes ConstantValueStore to use ValueStore so that we get the
allocation flow that we're leaning towards there. This adds
`ConstantId::SymbolicId` to represent what was previously an int32
"symbolic_index" (although called an index, it's consistent with ID
usages).

I'm also changing Chunk::at/push to be consistent with the wrapping
Get/Add naming; the naming difference sticks out more with
UninitializedFill being added.
2025-07-17 20:44:15 +00:00
David Blaikie c25ea81320 Ignore abstract functions when checking for referenced functions requiring definitions (#5816)
Abstract functions can't be defined, so we shouldn't be checking for
definitions when the function is referenced from an abstract base's
vtable.
2025-07-17 20:25:59 +00:00
David Blaikie aeba878335 Clean up some TODO and other comments (#5813) 2025-07-17 18:58:34 +00:00
David Blaikie c2a0ee98c5 Remove outdated comment about generic vtable inst naming (#5814)
Since vtables are generic over the class's specific, they don't have
their own generic/specific ids and so there's no generic insts that need
naming.
2025-07-17 18:32:36 +00:00
Jon Ross-Perkins a842162424 Make NameScope move constructor noexcept (#5812) 2025-07-17 18:29:49 +00:00
David BlaikieandJon Ross-Perkins 3bf98e9bc2 Implement correctly overriding dependent virtual functions (#5804)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-07-17 16:14:50 +00:00
Richard Smith 9f67fa4b0f Allow interop with templated but non-template functions. (#5809)
For example, this would allow using `std::string::size`, which is
templated because it's a member of the class template
`std::basic_string`, but isn't itself a function template.
2025-07-17 15:04:19 +00:00
Boaz Brickner dd76c9bd13 Merge i16 and i32 param and return test files (#5760)
This is instead of having one test file that has different return types
and two test files for `i16` and `i32` param tests, which doesn't seem
consistent.
First commit does file renames for easier review.

Part of #5063.
2025-07-16 12:53:05 +00:00
Boaz Brickner 4f8d0649d5 When importing a looked up name, reuse previously imported declaration instead of importing the same declaration again (#5789)
Added test coverage to demonstrate name lookup following import of a
type of a function parameter.
SemIR changes show that the same decl isn't imported multiple times.

Part of #5533.
2025-07-16 11:21:49 +00:00
Richard Smith f204bdf094 Basic support for calling class methods imported from C++. (#5796)
Create a `self` parameter when importing a C++ non-static member
function. That seems to be all we need to get basic method calls
working! For now, `const` methods have by-value self parameters, and
non-`const` methods get an `addr self: Self*` parameter.
2025-07-15 16:05:01 +00:00
David BlaikieandDana Jansens 83b2924432 Support importing vtables for generic classes (#5802)
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-07-15 14:06:51 +00:00
David Blaikie e6214b946a Remove out of date comment (#5805)
Lazy vtable_ptrs were implemented in
967a98f845
2025-07-15 14:03:41 +00:00
Jon Ross-Perkins be487bbeda Use declaration locations for formatting entities (#5799)
This is just trying to address the location TODO.
2025-07-14 23:27:03 +00:00
David Blaikie 16ab0b313a Remove out-of-date comment now that generic vtables are implemented (#5803) 2025-07-14 20:56:00 +00:00
Richard Smith a6acba9eab Support for importing const-qualified types from C++. (#5794)
Incidentally also supports import of pointers-to-pointers.

Imported const-qualified types aren't especially useful just yet,
because on the Carbon side we don't yet permit conversions from
non-const to const types, so most of the tests still fail, but for
different reasons now.
2025-07-12 02:22:24 +00:00
David BlaikieandRichard Smith 27be0973e7 Vtable support for generics (#5793)
Some specific features:

* Use `SpecificFunction` for vtable entries for generic classes.
* Create specific constants for vtable entries in classes derived from
  generic classes to reference the appropriate specific of the function
  in the context of such a derived class.
* Create specific constants for vtable_ptrs for uses of specific generic
  classes.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-07-11 22:29:10 +00:00
Jon Ross-Perkins 8cd1307711 Include the interface name in impl names (#5798)
i.e., `impl` -> `<interface>.impl`
2025-07-11 19:52:53 +00:00
Chandler Carruth 1a97021875 Enhance benchmark runner args and defaults (#5797)
There are some very useful default arguments, so teach the runner script
to directly provide them. They can be easily overridden if needed. As
part of this, change the default run count to 10 which much more often
produces statistically significant error bars and results.

Also, tweak the processing of the results to provide a stable order
based on the source order, even when randomized interleaving is enabled.
The randomized interleaving improves the statistical strength of the
benchmarks significantly, but displaying the results in the source order
is much more understandable. This should give roughly the best of both
worlds.
2025-07-11 16:54:51 +00:00
Jon Ross-Perkins a7dbd4ef62 Improve handling of carbon-busybox symlinks in bazel (#5795)
Trying to make the handling of `bazel build //toolchain; bazel clean;
bazel build //toolchain; ./bazel-bin/toolchain/carbon` work more
consistently.
2025-07-10 23:51:44 +00:00
Jon Ross-Perkins 2bb8e98849 Change SemIR formed for 'as' errors (#5792)
Direct use of an error means we can delay looking at the actual type,
and also use the `self_id` of the stored `ImplInfo` directly.

Note, I'm assuming we should be okay with this not always being a
`NameRef`. In error cases though, it seems like we shouldn't mind it
being an error instead of a name reference to an error.
2025-07-10 21:56:03 +00:00
Jon Ross-Perkins e855f38b8c Tag destruction as desugaring (#5790)
In `BuildUnaryOperator`, `GetOperatorOpFunction` is treated as
desugaring, but `PerformCompoundMemberAccess` and `PerformCall` are not.
This treats all of destruction as desugaring.

This leads to some instructions being elided, because of `GetOrAddInst`
behaviors:

> // If the instruction has a desugared location and a constant value,
returns
> // the constant value's instruction ID. Otherwise, same as AddInst.

This changes instructions that previously had a non-desugared location
to instead have a desugared location, so if they also have a constant
value then the constant value can be used directly.
2025-07-10 21:21:19 +00:00
Richard Smith 26e23eac10 Support import of typedefs. (#5787)
Unify code paths for importing classes by name and importing them
indirectly when their type is referenced. Switch to using the general
type import machinery to import all type declarations, which allows
typedef declarations naming importable types to be used too.

Fix up handling of error cases to consistently only produce an Error
InstId after actually producing an error message, so that we can produce
exactly one diagnostic in failure cases.

Remove TODO error for unions that previously was only produced when
importing them indirectly, not when importing them by name. Import of
unions is exactly as complete / incomplete as import of other class
types, so treating them differently doesn't seem necessary.
2025-07-10 20:46:46 +00:00
Jon Ross-Perkins 6ca4e2e089 Fix a small implicit/desugared reference (#5791)
Implicit is the old term, and could be confusing now.
2025-07-10 18:27:28 +00:00
Jon Ross-Perkins 6a53947c5c Handle destruction for return statements (#5785)
This just catches uses equivalent to `return;` and `return <expr>;`.
Note it's just extending the current implicit return logic, not really
adding much unique here.

I'm still delaying break and continue because those require partial
destruction, which is more work and I want to be careful to get it
right.
2025-07-10 16:32:39 +00:00
Boaz Brickner a5ddc3e3cd Support importing C++ _Nonnull pointers as function parameters or return values (#5773)
We avoid using canonical type before knowing it's not a pointer because
we need the nullability attribute.
No support for pointers to pointers, yet.

C++ Interop Demo:

```c++
// hello_world.h

auto hello_world_param(int* _Nonnull i) -> void;
auto hello_world_return() -> int* _Nonnull;
```

```c++
// hello_world.cpp

#include "hello_world.h"
#include <cstdio>

auto hello_world_param(int* _Nonnull i) -> void {
  printf("hello_world: %d\n", *i);
}

static int x = 5;
auto hello_world_return() -> int* _Nonnull { return &x; }
```

```carbon
// main.carbon

library "Main";

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

fn Run() -> i32 {
  var i: i32 = 10;
  Cpp.hello_world_param(&i);

  let p: i32* = Cpp.hello_world_return();
  Core.Print(*p);

  return 0;
}
```

```shell
$ clang -c hello_world.cpp
$ ./bazel-bin/toolchain/install/prefix_root/bin/carbon compile main.carbon
$ ./bazel-bin/toolchain/install/prefix_root/bin/carbon link hello_world.o main.o --output=demo
$ ./demo
hello_world: 10
5
```

Part of #5772.
2025-07-10 08:00:37 +00:00
Jon Ross-Perkins 110af3bfe4 Set an explicit size for lexical lookup's vector (#5786) 2025-07-09 22:42:27 +00:00
Jon Ross-Perkins d64ec883d5 Move BlockValueStore from sem_ir to base (#5779)
The other generic `ValueStore` types are in base; this is for
consistency, to make it easier to find. I think it's only in sem_ir for
historical reasons, since it was probably the first bespoke ValueStore
variant added.
2025-07-09 16:25:23 +00:00
Richard SmithandChandler Carruth 3776e464e0 Properly set up C++ include paths and similar environment settings when parsing imported C++. (#5767)
Stop using the clang tooling library to build an ASTUnit; that library
is set up to process clang frontend arguments, assuming that something
has already built frontend arguments from the compiler arguments. It is
also too encapsulated and doesn't let us inspect and modify the compiler
invocation before it's executed.

Instead, build the AST unit directly in two phases:

* FIrst, take a list of clang driver arguments and convert them into a
list of compiler arguments, using `clang::createInvocation`. Internally,
this uses the clang driver to build a frontend invocation, including
building system-specific include paths as needed.
* Then, directly build an ASTUnit from this compiler invocation.

I've factored this so that we can split out the `createInvocation` step,
with the intention that we may want to move it out of check and into the
carbon driver with the rest of the driver-level argument handling, and
we may want to customize some of the clang options before we invoke the
clang frontend with that set of options.

In order to make the invocation reusable, it no longer depends on the
name of the carbon file importing the C++ code. In place of synthesizing
a header file name as `<foo.carbon>.generated.cpp_imports.h`, we now
insert line marker directives into the generated header so that errors
in that header cause Clang to point a diagnostic back at the Carbon
source file itself. This results in a minor improvement in the
diagnostic output: we no longer refer to a nonexistent generated file.
But the snippet still contains text that doesn't match the source code,
so it remains imperfect.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-07-09 03:09:43 +00:00
Jon Ross-Perkins da99b940f5 Fix clangd-tidy to avoid blocking merges while testing (#5782)
What I'm trying to fix is visible at:

- PR: https://github.com/carbon-language/carbon-lang/pull/5779
- clangd-tidy run on merge:
https://github.com/carbon-language/carbon-lang/actions/runs/16155546033/job/45597095935
- Merge attempt:
https://github.com/carbon-language/carbon-lang/pull/5779#event-18534768919

That PR deletes block_value_store, so excluding deleted files here
(`added|modified`). But also, I think this is blocking merge just
because it's set for merge_group. Or it may be because of the clang-tidy
job name overlap -- I'm just going to address both.

Also trying to remove the base commit; I think dorny/paths-filter should
actually be calculating this reasonably well, and it was holdover from
where we set the commit explicitly elsewhere. There's a warning about it
being ignored in pull_request, visible
[here](https://github.com/carbon-language/carbon-lang/actions/runs/16155814211/job/45597903684).
2025-07-09 01:11:28 +00:00
Richard Smith f987504614 Track the location of the Cpp import for use in Clang diagnostics. (#5783)
When diagnosing a problem with C++ code imported from Carbon, include
the location of the specific `import Cpp` statement that imported the
C++ code as part of the backtrace, rather than providing a location in a
generated file that doesn't exist on disk.

Also fix handling in autoupdate of check lines that contain multiple
file name and line number pairs to use the matched file name for
remapping of locations rather than the first file name in the line.
2025-07-09 00:47:21 +00:00
Jon Ross-Perkins 6db13532ca Try using clangd-tidy (#5763)
Run clangd-tidy in parallel with clang-tidy, to experimentally see
whether it works reasonably well. These may produce slightly different
results, and it's not clear that clangd-tidy will be better, so being
cautious about switching.

A real possibility here is this is slower in some cases (building
compile commands takes ~6m below), but faster in the extremely slow
cases (when clang-tidy takes >10m).

For contrast:

- clang-tidy:
https://github.com/carbon-language/carbon-lang/actions/runs/16038096026/job/45254162180?pr=5763
- clangd-tidy:
https://github.com/carbon-language/carbon-lang/actions/runs/16038096427/job/45254164217?pr=5763
2025-07-08 14:00:15 +00:00
Boaz Brickner 9d0aaa740b When adding an imported C++ name, make sure that its clang::Decl is mapped if import failed (#5769)
When mapping parameter types, we assume that if the `clang::Decl` isn't
mapped, the name wasn't added, so this fixes a bug that triggers a crash
otherwise.

Part of #5533.
2025-07-08 13:12:32 +00:00
Dana Jansens cd14dca749 Document and test that structs with different field orders are different types for impl lookup (#5778)
This encodes the decision of #5413 in our tests.
2025-07-07 20:59:11 +00:00
Boaz Brickner ff9154b978 Push a decl name scope before calling CalleePatternMatch() (#5771)
Otherwise the return values of different functions collide.

Part of #5063.
2025-07-07 15:02:47 +00:00
Boaz Brickner 3f5b04f777 Use Core.Print instead of Carbon.Print in documentation (#5770) 2025-07-04 08:05:11 +00:00
Jon Ross-Perkins b3866250db Remove prebuilt_binary from file_test rules (#5765)
Since explorer was removed, this is no longer in use.
2025-07-03 15:29:39 +00:00
Boaz Brickner 12d66be1cd Delete files that were moved in #5716 but got undeleted in #5678 (#5768) 2025-07-03 10:33:25 +00:00
Richard Smith c7886f4336 Ask Clang to mangle names, don't try to do it ourselves. (#5764)
Fixes mangling for `extern "C"` functions, as well as some other
uncommon cases like multi-version functions.
2025-07-02 23:25:52 +00:00
Jon Ross-Perkins 5b0ae6e784 Remove IdT from ValueStoreTypes (#5761)
`IdT` is no longer needed because `ValueT` is always supplied.
2025-07-02 22:09:09 +00:00
Jon Ross-PerkinsandRichard Smith b4b4d33789 Change CanonicalValueStore to take ValueT and KeyT as parameters (#5759)
`SpecificInterface` seems oddly placed. It appears to be in ids.h just
because it's used by typed_insts.h, but maybe that should be factored
differently? We typically aren't having typed_insts.h depend on non-ID
types. To that end, I'm splitting it out to its own file so that at
least I'm not adding a `ValueStore` dep inside ids.h

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-07-02 20:58:02 +00:00
David Blaikie 967a98f845 Import vtable_ptr lazily (#5762)
Ensure `vtable_ptr`s(and the vtables they refer to) aren't
imported if the type is imported but the vtable isn't
needed (no initialization of a value of that type is required).
2025-07-02 19:45:02 +00:00
Dana Jansens 6c6552ce57 Consistently return runtime phase if the operands contain a runtime (#5729)
Currently if the first operand contains an error, we will return error,
even though the second operands contains a runtime, and it has a
stronger priority (the phase always goes up if possible).

Import is only allowed on instructions with compile-time values, so we
crash if we ever try to import a runtime value. Importable instructions
must diagnose unexpected runtime values and produce errors in the semir
from which they would be imported so that runtime values are never
imported by another semir.

If we had an instruction where you had an error value from the first
operand, and runtime from the second, and we imported it:
- Before https://github.com/carbon-language/carbon-lang/pull/5728 we
would crash in import, but only because we treated errors as runtime
- After https://github.com/carbon-language/carbon-lang/pull/5728 we
would import ErrorInst because we propagate errors. This is desirable
for cases with compile-time values and errors present only.
- After this PR, we would crash again, cuz you're importing a runtime
thing.

This change means that instructions containing an
`InstConstantKind::Never` instruction like`ValueParam` will consistently
evaluate to a runtime value, even if there are errors present. This is
visible in the `BindName` instructions changing in the semir, where they
became constant `ErrorInst` values previously but no longer do.
2025-07-02 19:21:41 +00:00
Jon Ross-Perkins 002756b4cc Change BlockValueStore to take ElementT as a parameter (#5758)
Also modify CopyOnWriteBlock to just pull block type information from
the return type of the function it receives, rather than taking some as
a parameter.

I chose the `RefType`/`ConstRefType` names based on other similar
`ValueStore` uses which I think are equivalent.
2025-07-02 19:21:01 +00:00
Jon Ross-Perkins a65f4b89e2 Make ValueStore require a ValueT parameter (#5757)
This is reducing ValueStore inference of types from `using`, and removes
`using ValueType = ...` from affected id types.

I'm adding a number of `using FooStore = ValueStore<FooId, Foo>` because
I think it's a little repetitive otherwise; often 4 cases where I'm
doing this: getter, const getter, member, and getter on `Context`. Note
we also have a number of `-> decltype(auto)` that were added I think
mainly to avoid repeating the type, but I'm not sure whether there'll be
agreement on replacing those and so am not changing them here.

I'm placing these aliases with the value type in general, because I
think it's probably easier to view that way. An alternative would be to
put all the types on `File`, but:

- That would be inconsistent with things like `InstStore`, which are
very `ValueStore`-adjacent and put with their value type.
- `File` would have a _lot_ of using's, and the accessors are already
noisy -- I think it would just make the file harder to skim.

Note this is the heart of what I'd brought up [on
Discord](https://discord.com/channels/655572317891461132/655578254970716160/1388199282250613019).
This PR still leaves CanonicalValueStore and BlockValueStore as things
to also add parameters to, but I thought it best to try breaking the set
of changes apart by type. Both of those rely on ValueStore, so
ValueStore needs to change first.
2025-07-02 18:07:55 +00:00
Jon Ross-Perkins 839a7b7c96 Refactor ValueStoreChunk and ValueStoreRange into ValueStore (#5756)
ValueStoreChunk and ValueStoreRange are implemented in a way that's
closely tied to ValueStore, and the separation makes for a lot of
additional template parameter passing, which seems easy to make mistakes
on. Combine types in order to make the close association more implicit.

I also considered passing `ValueT` everywhere, as an additional template
parameter. Note I believe the simplification is important. I'll
highlight four notes that I think favor this approach:

- `ValueStore`, with the chunk type in the same file, now has more of
the closely related implementation features in the same file. I think we
probably will want any chunking to continue to be done by `ValueStore`
itself, with related types using the implementation on `ValueStore` and
never creating their own.
- Making `ValueT` a template parameter on `ValueStore` -- my next step
-- will only change a couple lines of code on this type, instead of
sweeping changes. That should make it easier to be confident of the
correctness of those changes.
- Simpler to verify correctness. For example, `ValueStoreChunk` takes a
`ValueType` parameter that it doesn't forward; other functions assume
they can use `IdT::ValueType`. With the changes, this also no longer
benefits from separating out `IdHasValueType`, which was inconsistently
applied to related types (e.g., `ValueStoreRange` didn't use it).
- Template parameters often lead to `sizeof`, where we can't rely on
type checking to catch mistakes.
- The reduction of code is significant, with 8 `template<...>` removed
(including 1 forward declaration for `ValueStoreRange`), and also the
related `requires`. Correspondingly, places specifying template
parameters also decreased.
2025-07-02 16:19:32 +00:00
Jon Ross-Perkins 864e9cb4a2 Add a ValueT to RelationalValueStore (#5755)
RelationalValueStore is only used in one spot, so starting there.
2025-07-01 20:09:00 +00:00
Ivana Ivanovska 44b2f60c90 Carbon/C++ Interop: Primitive Types proposal (#5448)
A proposal for Primitive Types mapping between Carbon and C++.

Part of #5263
2025-07-01 18:17:02 +00:00
Jon Ross-Perkins b97646a890 Split value store related types to separate files (#5754)
As I'm looking at splitting value type setting out, this is to make it a
bit easier to see what's part of each type. Note, I expect
`ValueStoreTypes` to remain because of the `StringRef` logic it does --
I'm giving that its own file.
2025-07-01 17:38:56 +00:00
Jon Ross-Perkins 57ef976802 Move dumping into the phase factory functions (#5747)
By moving dumping, we can have dumping occur before verification that
might CHECK-fail (e.g. parse tree and llvm IR verification).

I'm dropping vlogging of raw semir. It was only done when dumping, so
`-v` would print zero copies and `-v --dump-raw-sem-ir` would print two
copies. The lack of complaints about this suggests it's not needed.

I'm making a small change to drop newlines between textual and raw
semir. This is an edge case so I don't expect people to really notice in
general, but it seemed unusually aware of what's on a stream, and it
made it harder to do the dump_stream/raw_dump_stream approach, which I
felt would be decent in general, since check is the only phase that can
emit two different things (which I could also just drop -- we don't
really use raw semir anymore, it doesn't seem like a big need to be able
to print it with textual semir, but I'm assuming to just maintain
existing behavior).

In parse, we were previously dumping the tree on verification errors.
I'm removing that because now `--dump-parse-tree` should work fine,
where previously it wouldn't.
2025-07-01 15:51:41 +00:00
Richard Smith 11d5ee5f3e Add partial to the precedence diagram. (#5749)
Following the decision in #5010.
2025-06-30 22:44:54 +00:00
Jon Ross-Perkins 6966b1879d A few more mermaid newline fixes (#5752)
Akin to #5751, found in two other files.
2025-06-30 22:43:03 +00:00
David Blaikie 0b53217372 Diagnose partial applied to final types. (#5744)
Is it worth having a distinct diagnostic or phrasing for non-class types
(like tuples, structs, pointers, etc), also for declared-but-not-defined
class types (where we can't tell if they're final or not)? Happy to add
it, but not sure how much detail to put in here at this stage at least.

I chose "non-final type" as somewhat vague wording so it sort of applies
even to pointers/tuples/structs.
2025-06-30 20:35:19 +00:00
Jon Ross-Perkins 72c3f8a6b5 Fix repeated newlines in expression mermaid (#5751)
A newline adds a br. The br tag is redundant, unless you really want two
newlines. Might stem from a mistake in #1089

We have a couple spots using br to keep text on a single line; changing
those for consistency.

Before:

![Screenshot 2025-06-30 at 1 01
51 PM](https://github.com/user-attachments/assets/29c16b0f-1180-4e91-a2f8-3889db4dd311)

After:

![Screenshot 2025-06-30 at 1 01
18 PM](https://github.com/user-attachments/assets/1b69356e-92b7-4db5-8e0d-9e838035a9f5)
2025-06-30 20:10:16 +00:00
Geoff Romer 12fbf9c9c2 Progressive disclosure principle (#5661)
This proposal codifies our preference for designs that support
"progressive
disclosure", meaning that programmers can ignore a given language
concept (or
even be unaware of it) until it is directly relevant to the task they're
doing.
2025-06-30 19:02:01 +00:00
Chandler CarruthandJon Ross-Perkins b39c7c93aa Add hashtable benchmark coverage for integers with low zero bits (#5735)
These have unique challenges for our hashing scheme, and so its useful
to make sure the hash functions we use can handle them.

Some other work on Abseil's hash tables uncovered that this might be
risky and may have surfaced some improvements to reduce the impact here,
but the first step seems to try and start covering this path in the
benchmarks.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-28 00:52:58 +00:00
Jon Ross-Perkins 4aa62bf5cd Switch Destroy to addr self (#5748)
Pointed out by zygoloid on #toolchain, just taking care of this now.
2025-06-28 00:50:47 +00:00
dependabot[bot] 21762f4003 Bump webrick from 1.8.1 to 1.8.2 in /website in the bundler group across 1 directory (#5745)
Bumps the bundler group with 1 update in the /website directory:
[webrick](https://github.com/ruby/webrick).

Updates `webrick` from 1.8.1 to 1.8.2
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/ruby/webrick/releases">webrick's
releases</a>.</em></p>
<blockquote>
<h2>v1.8.2</h2>
<h2>What's Changed</h2>
<ul>
<li>Drop commented-out line by <a
href="https://github.com/olleolleolle"><code>@​olleolleolle</code></a>
in <a
href="https://redirect.github.com/ruby/webrick/pull/108">ruby/webrick#108</a></li>
<li>Add Ruby 3.1 &amp; 3.2 to CI matrix by <a
href="https://github.com/tricknotes"><code>@​tricknotes</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/109">ruby/webrick#109</a></li>
<li>Fix/redos by <a
href="https://github.com/ooooooo-q"><code>@​ooooooo-q</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/114">ruby/webrick#114</a></li>
<li>Raise HTTPStatus::BadRequest for requests with invalid/duplicate
content-length headers by <a
href="https://github.com/jeremyevans"><code>@​jeremyevans</code></a> in
<a
href="https://redirect.github.com/ruby/webrick/pull/120">ruby/webrick#120</a></li>
<li>Bump actions/checkout from 3 to 4 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/121">ruby/webrick#121</a></li>
<li>Improve CI by <a
href="https://github.com/hsbt"><code>@​hsbt</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/123">ruby/webrick#123</a></li>
<li>Fix WEBrick::TestFileHandler#test_short_filename test not working on
mswin by <a
href="https://github.com/KJTsanaktsidis"><code>@​KJTsanaktsidis</code></a>
in <a
href="https://redirect.github.com/ruby/webrick/pull/128">ruby/webrick#128</a></li>
<li>Fix bug chunk extension detection by <a
href="https://github.com/jeremyevans"><code>@​jeremyevans</code></a> in
<a
href="https://redirect.github.com/ruby/webrick/pull/125">ruby/webrick#125</a></li>
<li>Fix CI. by <a
href="https://github.com/ioquatix"><code>@​ioquatix</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/131">ruby/webrick#131</a></li>
<li>Merge multiple cookie headers, preserving semantic correctness. by
<a href="https://github.com/ioquatix"><code>@​ioquatix</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/130">ruby/webrick#130</a></li>
<li>Test on macos-latest by <a
href="https://github.com/byroot"><code>@​byroot</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/132">ruby/webrick#132</a></li>
<li>Require CRLF line endings in request line and headers by <a
href="https://github.com/jeremyevans"><code>@​jeremyevans</code></a> in
<a
href="https://redirect.github.com/ruby/webrick/pull/138">ruby/webrick#138</a></li>
<li>Prefer squigly heredocs. by <a
href="https://github.com/ioquatix"><code>@​ioquatix</code></a> in <a
href="https://redirect.github.com/ruby/webrick/pull/143">ruby/webrick#143</a></li>
<li>Only strip space and horizontal tab in headers by <a
href="https://github.com/jeremyevans"><code>@​jeremyevans</code></a> in
<a
href="https://redirect.github.com/ruby/webrick/pull/141">ruby/webrick#141</a></li>
<li>Treat missing CRLF separator after headers as an EOFError by <a
href="https://github.com/jeremyevans"><code>@​jeremyevans</code></a> in
<a
href="https://redirect.github.com/ruby/webrick/pull/142">ruby/webrick#142</a></li>
<li>Return 400 response for chunked requests with unexpected data after
chunk by <a
href="https://github.com/jeremyevans"><code>@​jeremyevans</code></a> in
<a
href="https://redirect.github.com/ruby/webrick/pull/136">ruby/webrick#136</a></li>
<li>Fix reference to URI::REGEXP::PATTERN::HOST by <a
href="https://github.com/casperisfine"><code>@​casperisfine</code></a>
in <a
href="https://redirect.github.com/ruby/webrick/pull/144">ruby/webrick#144</a></li>
<li>Prevent request smuggling by <a
href="https://github.com/jeremyevans"><code>@​jeremyevans</code></a> in
<a
href="https://redirect.github.com/ruby/webrick/pull/146">ruby/webrick#146</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a
href="https://github.com/tricknotes"><code>@​tricknotes</code></a> made
their first contribution in <a
href="https://redirect.github.com/ruby/webrick/pull/109">ruby/webrick#109</a></li>
<li><a href="https://github.com/ooooooo-q"><code>@​ooooooo-q</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby/webrick/pull/114">ruby/webrick#114</a></li>
<li><a
href="https://github.com/KJTsanaktsidis"><code>@​KJTsanaktsidis</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby/webrick/pull/128">ruby/webrick#128</a></li>
<li><a href="https://github.com/byroot"><code>@​byroot</code></a> made
their first contribution in <a
href="https://redirect.github.com/ruby/webrick/pull/132">ruby/webrick#132</a></li>
<li><a
href="https://github.com/casperisfine"><code>@​casperisfine</code></a>
made their first contribution in <a
href="https://redirect.github.com/ruby/webrick/pull/144">ruby/webrick#144</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/ruby/webrick/compare/v1.8.1...v1.8.2">https://github.com/ruby/webrick/compare/v1.8.1...v1.8.2</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ruby/webrick/commit/0fb9de6788a3ba5fe903e63d778a0fb8c1dce786"><code>0fb9de6</code></a>
Bump up v1.8.2</li>
<li><a
href="https://github.com/ruby/webrick/commit/b9a4c81ea94dec02a750c6b34092c55234519bf1"><code>b9a4c81</code></a>
Removed trailing spaces</li>
<li><a
href="https://github.com/ruby/webrick/commit/f5faca9222541591e1a7c3c97552ebb0c92733c7"><code>f5faca9</code></a>
Prevent request smuggling</li>
<li><a
href="https://github.com/ruby/webrick/commit/0c600e169bd4ae267cb5eeb6197277c848323bbe"><code>0c600e1</code></a>
Fix reference to URI::REGEXP::PATTERN::HOST</li>
<li><a
href="https://github.com/ruby/webrick/commit/15a93914782789520837c334e0c302702aec34e2"><code>15a9391</code></a>
Return 400 response for chunked requests with unexpected data after
chunk</li>
<li><a
href="https://github.com/ruby/webrick/commit/2b38d5614e876d313fe981e87c4e35b91556d226"><code>2b38d56</code></a>
Treat missing CRLF separator after headers as an EOFError</li>
<li><a
href="https://github.com/ruby/webrick/commit/e4efb4a2300540f14f93c09c06bf0357ac1597dc"><code>e4efb4a</code></a>
Remove unnecessary gsub calls in test_httprequest.rb</li>
<li><a
href="https://github.com/ruby/webrick/commit/426e214532bb0be5e4ab8b3c9cef328432012d0d"><code>426e214</code></a>
Only strip space and horizontal tab in headers</li>
<li><a
href="https://github.com/ruby/webrick/commit/e72cb697836e2ff201a4a74c108fdca9d3d2d0ed"><code>e72cb69</code></a>
Prefer squigly heredocs. (<a
href="https://redirect.github.com/ruby/webrick/issues/143">#143</a>)</li>
<li><a
href="https://github.com/ruby/webrick/commit/ee60354bcb84ec33b9245e1d1aa6e1f7e8132101"><code>ee60354</code></a>
Require CRLF line endings in request line and headers</li>
<li>Additional commits viewable in <a
href="https://github.com/ruby/webrick/compare/v1.8.1...v1.8.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=webrick&package-manager=bundler&previous-version=1.8.1&new-version=1.8.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-06-27 23:19:41 +00:00
Richard Smith 3a7a09dfab Use Core.Range from for lowering tests. (#5746)
Avoids duplicated test helper `EmptyRange`.
2025-06-27 23:19:20 +00:00
Jon Ross-Perkins 2de746e83c Switch compile functions to use options structs (#5742)
I've been mulling this mainly for the parameter complexity of
check/lower, but doing lex/parse for symmetry.

I'm motivated by the plan to move dumping for all of them into the
respective functions, because of discussion about llvm-verifier. That
basically would add another bool parameter (or more) to each of these.
My instinct is we're going to probably accrue a little more over time,
so I'm suggesting this as maybe adding the boundary a little simpler
and/or easier to read.

Note it may make sense to refactor a little further, e.g. maybe
Lower::Context could receive the full set of options and pick out what
it wants, but I figured creating the struct itself would be a decent
start.

I'm trying to put things into options when we can produce a reasonable
default if the user doesn't assign a value. I'm using an explicit
constructor so that values can be added without affecting every caller.

A different factoring would be to pass in everything through the param
struct, but that just felt weird when I was trying it out.

Removing `inst_namer` and `module_name` from `LowerToLLVM` params --
both of these can be inferred from `sem_ir`, and I'm not seeing a
particular reason to maintain them at the call site.
2025-06-27 22:08:47 +00:00
Jon Ross-Perkins 0722dab0ef Reimplement destroy as an interface (#5678)
This changes `Destroy` to use an interface for its implementation.

Note that this change includes a lot of test updates. Even when
`Destroy` is a no-op, it still causes code generation as part of
determining that.

Originally I was trying to use ranges to cut down the scope of this, and
to a degree I think they have. But a flipside here is that cases where
no destructors should be generated -- particularly globals -- would be
needed to completely remove destructor calls. Even for ranges, the range
can often include the destructor placement. So I've shifted
frame-of-thought a little: accept a bunch of destructor churn, because
destructors are needed and will be prevalent. The verbosity is a feature
of the design to make desugaring apparent in IR, not a bug.
2025-06-27 21:57:14 +00:00
Chandler CarruthandGeoff Romer bba037738d Key-type customization in CanonicalValueStore and ClangDecl cleanups (#5743)
The `ClangDecl` struct caused some confusion here -- it is embedding
extra data into a `CanonicalValueStore` that isn't used for lookups or
canonicalization, but is useful to store along side. This changes the
`CanonicalValueStore` to support customized key type for `Lookup` so
that we can provide the more direct API that only takes the relevant
key.

This in turn takes advantage of the support for heterogenous keys in the
underlying `Set` as long as hashing and equality are consistent. We do
need to add support for heterogenous equality comparison with
`clang::Decl*`, but that is fairly easily done now that the
argument-reversed form isn't needed as well.

Lastly, this cleans up the `ClangDecl` customization points to be more
idiomatic by using `operator==` and `CarbonHashValue`. While there, I've
added comments to make it unambiguous why we can use the pointer value
for the underlying `clang::Decl` due to the Clang AST's
address-as-identity model.

Resolves the immediate TODOs around this type.

Future work might involve changing from the current `Add` API to one
more like `Map` and `Set`'s API where a callback is used to create the
object, but that level of API complexity isn't necessarily motivated yet
and can easily be a follow-on if and when its worth doing. The `Add`
code paths *are* working with the `inst_id` in order to create an
instruction if we are importing the Clang declaration. It is the
`Lookup` code paths that never needed to know about the `inst_id` and
became more confusing for having to stub it out in the API.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-06-27 20:30:05 +00:00
124313269a Represent vtables as a top level SemIR construct (#5472)
The goal was/is to reduce the overhead for vtables in generics - the
previous representation/prior to this patch caused a new vtable to be
created in every specific which isn't generally what we want for Carbon
generics (the whole specific/generic thing is meant to avoid creating
specific versions for things that can be a generic form parameterized by
a specific instead of manifest as a unique entity per specific)

So this moves vtables to a top level object (like functions, classes,
etc). Each dynamic class will have a vtable in this list.

Classes have a `vtable_ptr` instruction in them that points to the
vtable.

The actual generic support hasn't been implemented in this patch, as
I've been struggling with just getting this part of the migration going
& wanted to get it flushed out before adding the additional
complications.

It's possible more laziness when doing cross-file importing would be
suitable - for instance if we only need to reference the vtable from
another file, but don't need to know its individual contents, it may be
beneficial for the functions in the vtable to be import_refs (or to add
another layer of indirection - so it can be a single import_ref
all-or-nothing for the functions in the vtable).

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-06-27 18:45:26 +00:00
David BlaikieandChandler Carruth b39a0f0c8c Basic SemIR partial support (#5736)
This adds something similar to the level of `const` support - that it's
a type, but not the conversions and limitations on usage that are
needed.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-06-26 23:55:48 +00:00
Jon Ross-Perkins 49212feac6 Allow repeated includes, particularly for min_prelude (#5741)
Make min_prelude parts include what they use, and remove the inclusions
which were for indirect uses from the main min_prelude files.
2025-06-26 21:59:55 +00:00
Jon Ross-PerkinsandDana Jansens c3b0c2e425 Use LLVM verifier in lowering (#5733)
Suggested by zygoloid while looking at #5678 

```
CHECK failure at toolchain/lower/context.cpp:62: !llvm::verifyModule(*llvm_module_, &errs): Verifier errors: Instruction does not dominate all uses!
  %.loc17_46.1.temp = alloca { i1, i32, i32 }, align 8, !dbg !13
  %tuple.elem0.loc17_46.2.tuple.elem = getelementptr inbounds nuw { i1, i32, i32 }, ptr %.loc17_46.1.temp, i32 0, i32 0, !dbg !13
Instruction does not dominate all uses!
  %.loc17_46.1.temp = alloca { i1, i32, i32 }, align 8, !dbg !13
  %tuple.elem1.loc17_46.2.tuple.elem = getelementptr inbounds nuw { i1, i32, i32 }, ptr %.loc17_46.1.temp, i32 0, i32 1, !dbg !13
Instruction does not dominate all uses!
  %.loc17_46.1.temp = alloca { i1, i32, i32 }, align 8, !dbg !13
  %tuple.elem2.loc17_46.2.tuple.elem = getelementptr inbounds nuw { i1, i32, i32 }, ptr %.loc17_46.1.temp, i32 0, i32 2, !dbg !13
```

Adds a `--llvm-verifier` flag to be able to turn this off easily,
particularly for debugging the LLVM IR.

The call workaround is due to a verifier requirement `inlinable function
call in a function with debug info must have a !dbg location`. It
specifically comes up for the `++x` case, with `%1 = call i32
@"_CConvert.8b3d5d6a6c17be04:ImplicitAs.Core.b88d1103f417c6d4"(i32
%other)`. I think #5397 is in the direction of a fix for that, but #5397
was set aside because it puts the debug info in too many places.
Instead, address this by adding a stub location for calls that don't
have a good location. I'm deliberately putting this next to the TODO so
that it's easier to understand the association.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-06-26 21:34:09 +00:00
Jon Ross-Perkins fcf445b517 Print captured stdout/stderr on test crashes (#5740)
Related to #5733, but as a general fix, this will hopefully make it a
little easier to debug test/autoupdate crashes.
2025-06-26 20:28:21 +00:00
Richard Smith c34d0c7adf Add Core.Range(N) facility to construct an integer range. (#5699)
Use it in examples where appropriate.

Depends on #5698.
2025-06-26 20:13:07 +00:00
Jon Ross-Perkins 9855818bb8 Move PrettyStackTraceFunction to common (#5739)
I'm looking at using this as part of file_test to dump streaming,
related to #5733
2025-06-26 18:39:54 +00:00
Boaz Brickner b90d3b7751 Use Decl::getAsFunction() to cast clang_decl to FunctionDecl (#5737)
This seems like a better practice though has no effect since we don't
support templates yet.

Part of #5436.
2025-06-26 17:14:02 +00:00
Dana Jansens 67b67af7a6 Add a test where impls requires things of another generic type (#5713)
From open discussion on 2025-06-23:
https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.5mygrwse32v5

The test does not pass yet, as we have not completed implementation of
`impls` constraints.
2025-06-26 15:45:46 +00:00
Geoff Romer 1893afe479 Tolerate incomplete interface when stringifying ImplWitnessAccess (#5730)
Closes #5727
2025-06-26 14:37:16 +00:00
Alina Sbirlea 78ef1678aa Adding additional test for specific coalescing. (#5732)
Adding additional test for specific coalescing.
2025-06-26 14:32:24 +00:00
Richard SmithandJon Ross-Perkins 866794b82a Check and lowering support for for loops. (#5698)
Add check support for `for` loops following #1885. This also adds a
basic `Optional` type to the prelude, as that's necessary to support the
new `Iterate` interface.

Depends on #5688, #5697. Those PRs aren't stacked here, but this change
will crash until they land.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-25 23:45:14 +00:00
Richard Smith a556cf41fc Use static allocas for temporaries. (#5734)
Previously we created allocas for temporaries at whatever point in the
output LLVM function we'd reached. This would result in these being
dynamic allocas (performing a dynamic stack allocation), which is
inefficent and can lead to a stack overflow if it happens in a loop.

Switch to putting the allocas in the entry block instead, and instead
generate a lifetime start marker when we reach the point where the
temporary is introduced. We already did this for local variables; this
is just factoring out and reusing that code.
2025-06-25 21:53:39 +00:00
Dana Jansens 3585b31813 Handle insts that resolve to type on the RHS of impls (#5712)
In a facet type constraint, you can write `where .Self impls T` for any
facet type `T`, or the constant `type`. It is possible to write `type`
in different ways though, with a `NameRef` instruction appearing on the
RHS instead of `TypeType`. In this case, the canonical constant value's
instruction will still be `TypeType`, so make eval look at the canonical
instruction to see this.

Add a test with an `alias Type = type` which hits this case.

After this change, we only will accept and find one of the following on
the RHS of `impls`:
- `TypeType`
- A facet type
- An error, if the source code had something else there, which will
already be diagnosed. Tested by `fail_right_of_impls_non_type.carbon`
and `fail_right_of_impls_non_facet_type.carbon`.

So we handle these three cases, and drop the implicit handling of other
things which will never appear there.
2025-06-25 21:45:23 +00:00
Alina Sbirlea dd0905ccbb Refactor coalescing logic out of the file context. (#5723)
Move coalescing logic outside of the file context.
This is intended to be pure refactoring / NFC.
2025-06-25 21:22:58 +00:00
Jon Ross-Perkins 70c94cb5b4 Clean up --no-prelude-import uses (#5722)
For some of these, it's just replacing with min_prelude/none.carbon.
Some had min_preludes specified, and I'm generally switching those to
none.carbon as well. The one exception is the destroy.carbon test, which
I noticed because of #5678
2025-06-25 21:03:15 +00:00
Dana Jansens fa6322dd8f Propagate errors in import (#5728)
`AddImportedInstruction` was turning errors in an instruction into a
Runtime constant value instead of an Error, which led to crashes when
importing an instruction that had an error inside it somewhere.

Fixes #5726
2025-06-25 20:41:07 +00:00
Dana Jansens 1d2cf1ddcb Remove the IsPeriodSelf function, use constant value comparison instead (#5731)
The `IsPeriodSelf` function is problematic, as it's possible for a
FacetType to contain multiple `.Self` bindings which refer to different
selves, when one FacetType is nested within another: `I where .Self.J =
(K where .Self impls type)`.

The `WhereExpr` instruction contains the instruction of the `.Self` of
that `where` clause, which is what `IsPeriodSelf` is looking for, so we
can compare with its constant value instead.
2025-06-25 20:05:49 +00:00
Jon Ross-PerkinsandRichard Smith 72cd8717e3 Helper to flag unexpected instructions on branches (#5721)
Context:
https://github.com/carbon-language/carbon-lang/pull/5698/files/450d938de98b52db3db36dbe77516f2f87edd143#r2162629599

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-06-24 20:17:34 +00:00
Alina Sbirlea b0be6619ef Optimize specific function coalescing in lowering. (#5684)
- Update all the llvm::Function pointers after function replacement.
Some were previously left in an inconsistent state.
- Only do function replacement once, after converging on the canonical
specific to use.
2025-06-24 18:59:04 +00:00
Dana Jansens badd544798 Add a full.carbon min-prelude that pulls in the full production prelude (#5703)
The `full.carbon` prelude just sets a flag indicating an explicit intent
to include the full prelude. Once all tests include some prelude file,
an error can be enabled (currently it's commented out) that requires an
`INCLUDE-FILE` of some min-prelude to be present in all `check/` and
`lower/` file tests.
2025-06-24 18:10:55 +00:00
Dana Jansens b91ad3be36 Add tests for accessing an aggregate member constant through an ImplWitnessAccess (#5702) 2025-06-24 17:37:55 +00:00
Richard SmithandGeoff Romer 7215302a27 Clean up and extend support for cross-file lowering of specific functions. (#5688)
Update remaining parts of lowering, in particular the lowering of
aggregates, to handle lowering within a specific from a different file
than its generic. Look up information about a type in the current
specific and in its file rather than performing lookups for the type in
the generic and its file.

Remove or fix all remaining uses of raw `TypeId` in
lower/function_context and lower/handle*, so that the type from the
specific is consistently always used when lowering a specific function.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-06-24 17:22:48 +00:00
Boaz Brickner 11a75d1de1 Move function_ test files to be in function dir and remove the function_ prefix (#5716)
Follow up of
https://github.com/carbon-language/carbon-lang/pull/5645#discussion_r2153064236
and #5607.
2025-06-24 12:53:33 +00:00
Chandler CarruthandDana Jansens 9a4a9a9730 Introduce a benchmark running script (#5706)
This script runs benchmarks written using Google Benchmark repeatedly,
and collects the results from JSON to render them nicely and provide
statistical information across the runs.

Because this runs the binaries repeatedly, this can help account for
run-to-run variations that are pervasive in many of Carbon's benchmarks,
such as ASLR and other process-specific differences.

It's most basic mode runs a benchmark multiple times and shows both
median and confidence intervals.

It also supports two comparison modes:

1) Regular expressions can be provided that describe collections of
   related benchmarks where one is the "main" benchmark and the others
   are comparable. For example, Carbon's data structure vs. data
   structures from LLVM or Abseil. These will be rendered with the main
   benchmark first, followed by a comparison relative to a "baseline" of
   each comparable benchmark.

2) A baseline benchmark binary, and potentially different command line
   flags, can be provided to run two benchmark binaries and compute
   a comparison for each benchmark within them.

Across all of these, the script works to present the best text UI it can
in the console. I may have gotten a bit obsessed with rendering the
benchmark results in a way that is really pretty. There are lots of
fancy color coding and progress bars, etc., when run in in the terminal.

For the basic mode without any comparisons, the results look like:

```
Computing statistically significant deltas only wherethe P-value < 𝛂 of 0.05
Metric key:
   BenchmarkName...  <median> ± <% at 95th conf>

 Benchmark                                             ┃        CPU Time         ┃    bytes_per_second
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━
 BM_LatencyHash<RandValues<uint8_t>, CarbonHashBench>. │    3.051 ns ±   2.721%  │  327.8   M ±   2.765%
 BM_LatencyHash<RandValues<uint8_t>, AbseilHashBench>. │    3.395 ns ±   4.377%  │  294.6   M ±   4.572%
 BM_LatencyHash<RandValues<uint8_t>, LLVMHashBench>... │    6.125 ns ±   2.662%  │  163.3   M ±   2.726%
 BM_LatencyHash<RandValues<uint16_t>, CarbonHashBench> │    3.105 ns ±   3.947%  │  644.1   M ±   4.109%
 BM_LatencyHash<RandValues<uint16_t>, AbseilHashBench> │    3.433 ns ±   4.308%  │  582.6   M ±   4.502%
 BM_LatencyHash<RandValues<uint16_t>, LLVMHashBench>.. │    6.127 ns ±   2.540%  │  326.5   M ±   2.587%
 BM_LatencyHash<RandValues<uint32_t>, CarbonHashBench> │    3.082 ns ±   2.846%  │    1.298 G ±   2.923%
 BM_LatencyHash<RandValues<uint32_t>, AbseilHashBench> │    3.401 ns ±   3.611%  │    1.176 G ±   3.739%
 BM_LatencyHash<RandValues<uint32_t>, LLVMHashBench>.. │    6.209 ns ±   4.064%  │  644.3   M ±   4.236%
 BM_LatencyHash<RandValues<uint64_t>, CarbonHashBench> │    3.122 ns ±   2.871%  │    2.563 G ±   2.956%
 BM_LatencyHash<RandValues<uint64_t>, AbseilHashBench> │    3.426 ns ±   2.811%  │    2.335 G ±   2.892%
 BM_LatencyHash<RandValues<uint64_t>, LLVMHashBench>.. │    6.497 ns ±   3.081%  │    1.231 G ±   3.179%
```

For the first comparison mode on one of Carbon's benchmarks, the results
look like:

```
Computing statistically significant deltas only wherethe P-value < 𝛂 of 0.05
Metric key:
   BenchmarkName...    <median> ± <% at 95th conf>
     vs Comparable: 👍 <delta>    p=<U-test P-value>
                       <median> ± <% at 95th conf>

 Benchmark                                             ┃          CPU Time          ┃     bytes_per_second
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━
 BM_LatencyHash<RandValues<uint8_t>, CarbonHashBench>. │      3.037 ns ±   1.781%   │    329.2   M ±   1.813%
                                            vs Abseil: │ 👍  -8.200%     p=0.000183 │ 👍   8.933%    p=0.000183
                                                       │      3.309 ns ±   2.064%   │    302.2   M ±   2.022%
                                              vs LLVM: │ 👍 -49.401%     p=0.000183 │ 👍  97.632%    p=0.000183
                                                       │      6.003 ns ±   1.502%   │    166.6   M ±   1.480%
                                                       │                            │
 BM_LatencyHash<RandValues<uint16_t>, CarbonHashBench> │      3.026 ns ±   1.816%   │    661     M ±   1.784%
                                            vs Abseil: │ 👍  -8.599%     p=0.000183 │ 👍   9.408%    p=0.000183
                                                       │      3.311 ns ±   1.873%   │    604.1   M ±   1.839%
                                              vs LLVM: │ 👍 -49.829%     p=0.000183 │ 👍  99.319%    p=0.000183
                                                       │      6.031 ns ±   2.806%   │    331.6   M ±   2.730%
                                                       │                            │
 BM_LatencyHash<RandValues<uint32_t>, CarbonHashBench> │      3.017 ns ±   2.696%   │      1.326 G ±   2.625%
                                            vs Abseil: │ 👍  -9.754%     p=0.000183 │ 👍  10.808%    p=0.000183
                                                       │      3.344 ns ±   1.537%   │      1.196 G ±   1.514%
                                              vs LLVM: │ 👍 -49.857%     p=0.000183 │ 👍  99.427%    p=0.000183
                                                       │      6.018 ns ±   3.269%   │    664.7   M ±   3.167%
                                                       │                            │
 BM_LatencyHash<RandValues<uint64_t>, CarbonHashBench> │      3.025 ns ±   3.395%   │      2.644 G ±   3.284%
                                            vs Abseil: │ 👍  -9.812%     p=0.000183 │ 👍  10.879%    p=0.000183
                                                       │      3.354 ns ±   2.640%   │      2.385 G ±   2.572%
                                              vs LLVM: │ 👍   0.476x     p=0.000183 │ 👍   2.101x    p=0.000183
                                                       │      6.357 ns ±   2.477%   │      1.258 G ±   2.418%
                                                       │                            │
```

For the second mode, in this case comparing a baseline build with `-Oz`
vs an experiment with `-Os`, the results look like:

```
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          ┃     bytes_per_second
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━
 BM_LatencyHash<RandValues<std::pair<uint32_t, uint32_t>>, CarbonHashBench> │ 👍 -35.870%     p=0.000557 │ 👍  55.930%    p=0.000557
                                                                  baseline: │      5.704 ns ±   1.877%   │      1.403 G ±   1.911%
                                                                experiment: │      3.658 ns ±   4.209%   │      2.187 G ±   4.039%
                                                                            │                            │
 BM_LatencyHash<RandValues<std::pair<uint32_t, uint64_t>>, CarbonHashBench> │ 👍 -19.475%     p=0.00119  │ 👍  24.186%    p=0.00119
                                                                  baseline: │      4.974 ns ±   3.029%   │      3.217 G ±   3.124%
                                                                experiment: │      4.005 ns ±   4.297%   │      3.995 G ±   4.120%
                                                                            │                            │
 BM_LatencyHash<RandValues<std::pair<uint32_t, int*>>, CarbonHashBench>.... │ 👍 -11.740%     p=0.00153  │ 👍  13.302%    p=0.00153
                                                                  baseline: │      4.634 ns ±   3.433%   │      3.453 G ±   3.555%
                                                                experiment: │      4.09  ns ±   2.999%   │      3.912 G ±   2.911%
                                                                            │                            │
```

The script itself uses a new tool for managing dependencies called `uv`:
https://docs.astral.sh/uv/ This tool allows for the script to contain an
inline set of dependencies that will be installed and cached for
subsequent runs. This seemed particularly important as dependencies like
SciPy and NumPy can be particularly difficult to manager or keep
installed in other ways, but are essential to this scripts statistical
analysis. So far, the `uv` system has been working remarkably well for
me and been a relatively pleasant experience on the whole.

I have included as much of the Python dependencies as have good type
information into the MyPy configuration to get good type checking in
pre-commit however.

Last but not least, this has been a pet project of mine for a quite a
while and so may be a bit rough around the edges as I added and tweaked
functionality based on specific benchmarks I was looking at. It feels
like its gotten useful enough to contribute somewhere, but totally open
to any refactoring or improvements needed. I tried to take a few passes
over it to organize and document the code before sending it, but I'm
sure there are still some things that could use improvement.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-06-24 12:47:32 +00:00
Dana JansensandJon Ross-Perkins d17188208c Apply min-preludes to more tests (part 7) (#5704)
This drops file_test runtime from about 3s to 2.5s on my machine, which
is now ~30% faster than before #5653 slowed things down by adding a lot
of stuff to the production prelude.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-24 12:43:08 +00:00
Boaz Brickner 4b8ac429a7 Replace isStruct() || isClass() with !isUnion() (#5715)
Follow up of
https://github.com/carbon-language/carbon-lang/pull/5709/files#r2162385549

Part of https://github.com/carbon-language/carbon-lang/issues/5533.
2025-06-24 07:42:51 +00:00
Dana Jansens ad4914b575 Avoid deducing errors as argument instructions after subst (#5710)
If convert fails after applying a substitution in deduce, fail deduction
rather than succeeding deduction with an ErrorInst in the deduced
argument.

For example, in
`toolchain/check/testdata/facet/fail_convert_class_type_to_generic_facet_value.carbon`
the `WrongGenericParam` is deduced for the first argument, then
substituted into the second parameter, but the argument can not convert
to the parameter after substitution. In this case, deduction fails
instead of producig a call with an error in the second argument. The
resulting semir drops the call with an error argument:
```
-// CHECK:STDOUT:   %CallGenericMethod.specific_fn: <specific function> = specific_function %CallGenericMethod.ref, @CallGenericMethod(constants.%WrongGenericParam, <error>) [concrete = <error>]
-// CHECK:STDOUT:   %CallGenericMethod.call: init %empty_tuple.type = call %CallGenericMethod.specific_fn() [concrete = <error>]
```
2025-06-23 23:10:33 +00:00
Richard Smith b21d0c4210 Fix tuple patterns matching expressions with atomic tuple form. (#5697)
Fixes #5696.
2025-06-23 22:09:29 +00:00
Dana Jansens ea227be0fe Apply min-preludes to more tests (part 6) (#5691)
This drops file_test runtime from about 3.5s to 3s on my machine.
2025-06-23 21:33:17 +00:00
Boaz Brickner 20f44e0a92 Support a C++ class as a parameter or return by value, similar to a C++ struct (#5709)
Add tests for C++ `union`.
Also fix some typos in `class` tests and remove SemIR ranges from tests
that should diagnose an error.

Part of #5533.
2025-06-23 19:30:56 +00:00
Boaz Brickner 8aedcbcabd Remove TODOs from the test of a declared but not defined struct as a by value parameter/return value (#5708)
These TODOs should have been removed in
https://github.com/carbon-language/carbon-lang/pull/5538 which adds
support for struct by value parameters and return values.

Part of #5533.
2025-06-23 14:45:06 +00:00
Boaz Brickner c025f96894 Replace EXTRA-ARGS: --no-prelude-import with INCLUDE-FILE: toolchain/testing/testdata/min_prelude/none.carbon (#5707)
Follow up https://github.com/carbon-language/carbon-lang/pull/5538 to be
consistent with the practice introduced in
https://github.com/carbon-language/carbon-lang/pull/5694.
2025-06-23 13:57:47 +00:00
Dana Jansens 0b022feb12 Apply min-preludes to more tests (part 8) (#5705)
This drops file_test runtime from about 2.5s to 2s on my machine, which
is now ~50% faster than before
https://github.com/carbon-language/carbon-lang/pull/5653 slowed things
down by adding a lot of stuff to the production prelude.
2025-06-23 13:50:03 +00:00
Boaz Brickner cc698d78f5 When using a C++ struct as a parameter, map its type to a Carbon class type (#5538)
This doesn't support actually passing the value of the struct, which is
planned to be implemented using thunks.

`ClangDeclId` value is now `ClangDecl` which includes the mapped Carbon
instruction in addition to the Clang declaration. This allows finding
the Carbon instruction for a given Clang declaration, which is necessary
for mapping a Clang struct parameter type to the Carbon class without
doing name lookup. We don't take the instruction as part of the hash
key, as discussed in
[Discord](https://discord.com/channels/655572317891461132/768530752592805919/1380575881050718469).

To map the type, we also need to map namespaces. To avoid recursion for
inner namespaces, we use a vector.

Note that the first commit just changes the order of functions in the
file to make review easier.

C++ Interop Demo (that shows missing behavior):

```c++
// hello_world.h

struct S {
  S(const S&) { x = 1; }
  int x;
};

void hello_world(S s);
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

void hello_world2(S s) { printf("hello_world2: %d\n", s.x); }

void hello_world(S s) {
  printf("hello_world: %d\n", s.x);
  hello_world2(s);
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  var s : Cpp.S;
  Cpp.hello_world(s);
  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
hello_world: -1108224096
hello_world2: 1
```

Part of #5533.
2025-06-20 16:51:58 +00:00
Boaz Brickner 8f93bb1045 Move EntityName's CarbonHashValue() to be a "hidden friend", like CarbonHashtableEq() (#5701)
Context:
https://github.com/carbon-language/carbon-lang/pull/5538/files/dfc50609a5b1184cb7970444c1edd524bf17184d#r2152818374
2025-06-20 14:00:38 +00:00
dependabot[bot] 924705e6d8 Bump urllib3 from 2.2.2 to 2.5.0 in /github_tools in the pip group across 1 directory (#5700)
Bumps the pip group with 1 update in the /github_tools directory:
[urllib3](https://github.com/urllib3/urllib3).

Updates `urllib3` from 2.2.2 to 2.5.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.5.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>
<h1>Security issues</h1>
<p>urllib3 2.5.0 fixes two moderate security issues:</p>
<ul>
<li>Pool managers now properly control redirects when
<code>retries</code> is passed — CVE-2025-50181 reported by <a
href="https://github.com/sandumjacob"><code>@​sandumjacob</code></a>
(5.3 Medium, GHSA-pq67-6m6q-mj2v)</li>
<li>Redirects are now controlled by urllib3 in the Node.js runtime —
CVE-2025-50182 (5.3 Medium, GHSA-48p4-8xcf-vxj5)</li>
</ul>
<h1>Features</h1>
<ul>
<li>Added support for the <code>compression.zstd</code> module that is
new in Python 3.14. See <a href="https://peps.python.org/pep-0784/">PEP
784</a> for more information. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3610">#3610</a>)</li>
<li>Added support for version 0.5 of <code>hatch-vcs</code> (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3612">#3612</a>)</li>
</ul>
<h1>Bugfixes</h1>
<ul>
<li>Raised exception for <code>HTTPResponse.shutdown</code> on a
connection already released to the pool. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3581">#3581</a>)</li>
<li>Fixed incorrect <code>CONNECT</code> statement when using an IPv6
proxy with <code>connection_from_host</code>. Previously would not be
wrapped in <code>[]</code>. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3615">#3615</a>)</li>
</ul>
<h2>2.4.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>
<h1>Features</h1>
<ul>
<li>Applied PEP 639 by specifying the license fields in pyproject.toml.
(<a
href="https://redirect.github.com/urllib3/urllib3/issues/3522">#3522</a>)</li>
<li>Updated exceptions to save and restore more properties during the
pickle/serialization process. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3567">#3567</a>)</li>
<li>Added <code>verify_flags</code> option to
<code>create_urllib3_context</code> with a default of
<code>VERIFY_X509_PARTIAL_CHAIN</code> and
<code>VERIFY_X509_STRICT</code> for Python 3.13+. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3571">#3571</a>)</li>
</ul>
<h1>Bugfixes</h1>
<ul>
<li>Fixed a bug with partial reads of streaming data in Emscripten. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3555">#3555</a>)</li>
</ul>
<h1>Misc</h1>
<ul>
<li>Switched to uv for installing development dependecies. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3550">#3550</a>)</li>
<li>Removed the <code>multiple.intoto.jsonl</code> asset from GitHub
releases. Attestation of release files since v2.3.0 can be found on
PyPI. (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3566">#3566</a>)</li>
</ul>
<h2>2.3.0</h2>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</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.5.0 (2025-06-18)</h1>
<h2>Features</h2>
<ul>
<li>Added support for the <code>compression.zstd</code> module that is
new in Python 3.14.
See <code>PEP 784 &lt;https://peps.python.org/pep-0784/&gt;</code>_ for
more information.
(<code>[#3610](https://github.com/urllib3/urllib3/issues/3610)
&lt;https://github.com/urllib3/urllib3/issues/3610&gt;</code>__)</li>
<li>Added support for version 0.5 of <code>hatch-vcs</code>
(<code>[#3612](https://github.com/urllib3/urllib3/issues/3612)
&lt;https://github.com/urllib3/urllib3/issues/3612&gt;</code>__)</li>
</ul>
<h2>Bugfixes</h2>
<ul>
<li>Fixed a security issue where restricting the maximum number of
followed
redirects at the <code>urllib3.PoolManager</code> level via the
<code>retries</code> parameter
did not work.</li>
<li>Made the Node.js runtime respect redirect parameters such as
<code>retries</code>
and <code>redirects</code>.</li>
<li>Raised exception for <code>HTTPResponse.shutdown</code> on a
connection already released to the pool.
(<code>[#3581](https://github.com/urllib3/urllib3/issues/3581)
&lt;https://github.com/urllib3/urllib3/issues/3581&gt;</code>__)</li>
<li>Fixed incorrect <code>CONNECT</code> statement when using an IPv6
proxy with <code>connection_from_host</code>. Previously would not be
wrapped in <code>[]</code>.
(<code>[#3615](https://github.com/urllib3/urllib3/issues/3615)
&lt;https://github.com/urllib3/urllib3/issues/3615&gt;</code>__)</li>
</ul>
<h1>2.4.0 (2025-04-10)</h1>
<h2>Features</h2>
<ul>
<li>Applied PEP 639 by specifying the license fields in pyproject.toml.
(<code>[#3522](https://github.com/urllib3/urllib3/issues/3522)
&lt;https://github.com/urllib3/urllib3/issues/3522&gt;</code>__)</li>
<li>Updated exceptions to save and restore more properties during the
pickle/serialization process.
(<code>[#3567](https://github.com/urllib3/urllib3/issues/3567)
&lt;https://github.com/urllib3/urllib3/issues/3567&gt;</code>__)</li>
<li>Added <code>verify_flags</code> option to
<code>create_urllib3_context</code> with a default of
<code>VERIFY_X509_PARTIAL_CHAIN</code> and
<code>VERIFY_X509_STRICT</code> for Python 3.13+.
(<code>[#3571](https://github.com/urllib3/urllib3/issues/3571)
&lt;https://github.com/urllib3/urllib3/issues/3571&gt;</code>__)</li>
</ul>
<h2>Bugfixes</h2>
<ul>
<li>Fixed a bug with partial reads of streaming data in Emscripten.
(<code>[#3555](https://github.com/urllib3/urllib3/issues/3555)
&lt;https://github.com/urllib3/urllib3/issues/3555&gt;</code>__)</li>
</ul>
<h2>Misc</h2>
<ul>
<li>Switched to uv for installing development dependecies.
(<code>[#3550](https://github.com/urllib3/urllib3/issues/3550)
&lt;https://github.com/urllib3/urllib3/issues/3550&gt;</code>__)</li>
<li>Removed the <code>multiple.intoto.jsonl</code> asset from GitHub
releases. Attestation of release files since v2.3.0 can be found on
PyPI. (<code>[#3566](https://github.com/urllib3/urllib3/issues/3566)
&lt;https://github.com/urllib3/urllib3/issues/3566&gt;</code>__)</li>
</ul>
<h1>2.3.0 (2024-12-22)</h1>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/urllib3/urllib3/commit/aaab4eccc10c965897540b21e15f11859d0b62e7"><code>aaab4ec</code></a>
Release 2.5.0</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/7eb4a2aafe49a279c29b6d1f0ed0f42e9736194f"><code>7eb4a2a</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/f05b1329126d5be6de501f9d1e3e36738bc08857"><code>f05b132</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/d03fe327a71d09728512217149f269763671f296"><code>d03fe32</code></a>
Fix HTTP tunneling with IPv6 in older Python versions</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/11661e9bb4278e43d081f47a516e287a928c2206"><code>11661e9</code></a>
Bump github/codeql-action from 3.28.0 to 3.29.0 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3624">#3624</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/6a0ecc6b16fe30f721021b44a81d19615098c71e"><code>6a0ecc6</code></a>
Update v2 migration guide to 2.4.0 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3621">#3621</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/8e32e60d9024c05bc6f7adda08bdf6c539d0b0d4"><code>8e32e60</code></a>
Raise exception for shutdown on a connection already released to the
pool (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3">#3</a>...</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/9996e0fbf90b77083ad3c73737a6c6395703faa9"><code>9996e0f</code></a>
Fix emscripten CI for Chrome 137+ (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3599">#3599</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/4fd1a99a59725faf0efc946ce3b6bc9a194420af"><code>4fd1a99</code></a>
Bump RECENT_DATE (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3617">#3617</a>)</li>
<li><a
href="https://github.com/urllib3/urllib3/commit/c4b5917e911a90c8bf279448df8952a682294135"><code>c4b5917</code></a>
Add support for the new <code>compression.zstd</code> module in Python
3.14 (<a
href="https://redirect.github.com/urllib3/urllib3/issues/3611">#3611</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/urllib3/urllib3/compare/2.2.2...2.5.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.2.2&new-version=2.5.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-06-19 04:03:33 +00:00
Richard Smith 6a73387809 Remove requirement that the pattern in a for starts with var. (#5685)
This requirement was removed by proposal #1885.
2025-06-18 21:33:23 +00:00
Dana Jansens f236748629 Abandon SubstInst when encountering ErrorInst (#5692)
`SubstInst()` replaces individual instructions, and then rebuilds them
into instructions that contain those instructions. If any instruction is
an `ErrorInst`, the final result will also be an `ErrorInst`. In
pathological cases, it's possible to generate large types, [such
as](https://github.com/carbon-language/carbon-lang/issues/5672) tuples
of tuples of tuples of tuples of `something`. If that `something` is
`ErrorInst`, we can save a lot of work by avoiding building the
surrounding types, and evaluating them all to `ErrorInst`.
2025-06-18 21:33:18 +00:00
Dana JansensandJon Ross-Perkins 76cdbd8a5a Introduce the none.carbon min-prelude (#5694)
The none.carbon min-prelude is not just an empty prelude, it also
prevents any prelude from being imported at all. So no import machinery
runs before the test, only the `package` statement from the prelude
would run.

Use the none.carbon min-prelude in a few tests that were specifying
`--no-prelude-import` to give it a trial run.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-18 20:45:46 +00:00
Dana Jansens 59e2846623 Apply min-preludes to more tests (part 5) (#5690)
This drops file_test runtime from about 4s to 3.5s on my machine.
2025-06-18 20:43:36 +00:00
Jon Ross-Perkins 86f90c4d8f Change extra-args order in min_prelude (#5695)
[Context](https://discord.com/channels/655572317891461132/655578254970716160/1384959655993938064),
making these consistent
2025-06-18 19:55:33 +00:00
Dana Jansens 4a96799e1f Document our practices around using auto and naming variable types (#5663)
We use `auto` for most local variables, and we put the type name into
the variable name in common cases, especially for our ID types.

This was discussed in `#style`:
https://discord.com/channels/655572317891461132/821113559755784242/1380091326900469801
2025-06-18 14:10:01 +00:00
Boaz Brickner 64ad57adef Update toolchain/check/testdata/interop/cpp/function_param_int*.carbon and toolchain/check/testdata/interop/cpp/function_return.carbon tests to use sem ir ranges (#5645)
Follow up of #5594.

Trying to compromise SemIR size, having enough information and
complexity of tests, I've duplicated representative tests to a separate
test file with `--dump-sem-ir-ranges=if-present`.
2025-06-18 07:50:44 +00:00
Dana Jansens 2b7c75d8a5 Avoid incorrect conflicting assignment diags in rewrite constraints (#5686)
When building a FacetType from an existing FacetType, don't diagnose
rewrite constraints that are compatible with the existing FacetType.

To do this, we consider two RHS as identical[1] if they have the same
constant value after substituting from available rewrite constraints in
the being-constructed FacetType, since the syntactic representation of
the RHS is lost during eval.

[1]
https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.qti4vn50zwy
2025-06-18 01:10:26 +00:00
Geoff Romer 1aba7ea9d6 Clean up lingering mentions of MatchContinuation (#5687) 2025-06-18 01:07:55 +00:00
Dana Jansens 28fea821b7 Add min-preludes to more slow tests (part 4) (#5682)
Adds min-preludes more tests which were seen as slow and their
surrounding neighbours. This drops the file_test runtime on my machine
from about 6s to about 4.5s.

For a few files that are clearly only testing diagnostics, we drop the
if-present semir ranges and the associated TODO.
2025-06-17 21:10:04 +00:00
Jon Ross-Perkinsandjosh11b ed82f7ef3f Add ranges to where_expr tests (#5630)
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-06-17 21:04:49 +00:00
Dana Jansens 07aec169e1 Add min-preludes to more slow tests (#5681)
Adds min-preludes more tests which were seen as slow and their
surrounding neighbours. This drops the file_test runtime on my machine
from about 7s to about 6s.

For a few files that are clearly only testing diagnostics, we drop the
if-present semir ranges and the associated TODO.
2025-06-17 20:55:48 +00:00
Dana Jansens bff601e417 Add min-preludes to most of lowering and a few more slow tests (#5680)
Adds min-preludes to a few more slowest tests, and adds them to most of
the lowering tests, with a few exceptions that make use of operators.
This take the runtime of file_test down from about 8s to about 7s on my
machine.

We add support for Negate on uints in the min-preludes.
2025-06-17 20:43:31 +00:00
Dana Jansens e09419bfd4 Make more tests into min-prelude (#5676)
This drops the wall clock time for running file_test from 10s to 8s on
my machine. There's many more tests to convert, as each one takes the
test from ~1s to ~100ms. Compiling the full prelude is a bit slow now
since #5653, and before that file_test was taking about 3.5s.

We introduce a few more flavours of min_prelude to support more tests.
2025-06-17 19:25:57 +00:00
Geoff Romer effb0c93c2 Remove unused vlog_stream_ member. (#5654)
This resolves an unused-private-member warning with recent versions of
Clang.
2025-06-17 18:18:45 +00:00
Dana JansensandJon Ross-Perkins 19d59b2a8d Reduce use of the prelude in tests (#5683)
Remove use of i32/bool when a builtin type or test-define class type can
work. Make `Sub` user-defines in a test that is testing builtin
functions and not trying to test the prelude, in the same way that it
defines its own Negate. Reduce use of the + operator when it isn't
contributing to the test's coverage, since the + operator needs the full
prelude. Remove use of Core.Print when it's not required for the test.

Move `deduce_nested_facet_value.carbon` to its own file since it uses
TypeAnd, and the rest of deduce.carbon does not, but uses i32. This
means they can each use a different min-prelude.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-17 17:58:59 +00:00
Richard Smith fd0f62f980 Make currently publicly unused member functions private. (#5679)
Rename them to `Impl` to avoid splitting an overload set across
different access levels.
2025-06-17 17:33:01 +00:00
Dana Jansens 1a7c1a134e Add some failing tests with cycles and self-referential facet types (#5674)
Most of these tests should pass but don't, though one fails but in the
wrong way.
2025-06-17 16:49:56 +00:00
Richard SmithandGeoff Romer 80529aaef9 Convert the scrutinee of a binding pattern to the right category. (#5662)
When the binding pattern appears within a `var` pattern, convert to a
reference. Otherwise, convert to a value.

This gets the advent of code examples to produce the right answers again
:)

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-06-17 16:45:19 +00:00
Jon Ross-Perkins 1c09de9b87 Add min_prelude/convert.carbon to tests missing ImplicitAs (#5677)
import_use_generic.carbon has the comment "// We're just checking that
this doesn't crash. It's not expected to compile." Because it involves
import behavior by name, I'm not touching it. Other than that, while
maybe it's better to test with less, the `ImplicitAs` errors at best
feel difficult to understand, and at worst could be masking an issue.
2025-06-16 23:50:45 +00:00
Richard Smith c9e4761f0c Modernize some of our examples. (#5655)
Make some code simplifications using new toolchain functionality.

Depends on #5653.
2025-06-16 23:29:04 +00:00
Richard Smith 519e633147 Improve backtrace for lowering crashes. (#5651)
Factor out the logic for mapping from a `LocId` into a diagnostic
location from check into sem_ir so it can be reused by lowering. Include
the function and instruction being lowered in the pretty stack trace.
Example stack trace:

```carbon
2.      filename: examples/sieve.carbon
3.      core/prelude/types/int.carbon:213:3: lowering function Core.Op(Core.IntLiteral as Core.ImplicitAs(i32))
            fn Op[addr self: Self*](other: Self) = "int.sadd_assign";
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4.      core/prelude/operators/arithmetic.carbon:22:27: lowering call
            fn Op[addr self: Self*](other: Other);
                                    ^~~~~~~~~~~~
```
2025-06-16 23:21:22 +00:00
Chandler CarruthandJon Ross-Perkins ac56057f08 Guidance on AI coding tools (#5670)
Establish some guidance on using AI coding tools when contributing to
the Carbon
Language project. These tools have growing popularity and interest, and
it would
be good to have a clear and actively documented set of guidance for
folks
interested or already using them.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-13 23:39:37 +00:00
Chandler Carruth ad8d01d35c Replicate the fix in #5669 to the proposal workflow (#5671) 2025-06-13 23:07:06 +00:00
Jon Ross-PerkinsandDana Jansens 5196d1eb27 Fix the hardening mode defines, also use debug (#5666)
This is based on #5664 because it's fixing an issue which `DEBUG` would
catch. That's also why I'm switching to `DEBUG` from `EXTENSIVE`; I
think we should be okay with the performance cost in `file_test`, which
is probably our main concern.

Note digging into this also got me to notice that the flags weren't
actually enabled; this is fixing the define names.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-06-13 21:18:17 +00:00
Jon Ross-Perkins 3b7dc79796 Add repo flag to gh (#5669)
Different workaround for https://github.com/cli/cli/issues/11055
2025-06-13 18:12:20 +00:00
Dana JansensandJon Ross-Perkins 09a5fddff8 Fix sorting of instructions in Facet Type resolution (#5664)
The sort and dedupe operations in facet type resolution explicitly work
with `ImplWitnessAccess` instructions as being a reference to an
associated constant on some entity. If only one of the instructions is
an `ImplWitnessAccess`, we still want to consider that one as such, not
get its constant value, which may be some concrete type, and use that
for comparison instead.

This makes the new test fail (which we don't want) in a consistent way
with a similar test of TypeAnd (which we also don't want to fail),
making the system more consistent, while leaving some improvements to be
done.

Avoid inconsistent orderings between instructions, by making the
comparison function into a total order. To do so, we sort
ImplWitnessAccess instructions first, and sort them by their InstId.
Non-ImplWitnessAccess instructions come second, and sort them by their
constant InstId. Thanks to jonmeow for figuring out that the function
was not producing a total order and why.

Since this means the order is no longer relative to source order, we
order the two assignments in the diagnostic by source order(ish) by
putting the lower InstId first in the diagnostic output.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-13 18:01:39 +00:00
Dana Jansens f967bf0b85 Manually update gh to fix PR labeling for now (#5665)
Issue https://github.com/cli/cli/issues/11055 suggests updating the `gh`
tool explicitly until the update gets applied to the github worker
images.
2025-06-13 17:35:32 +00:00
Dana JansensandJon Ross-Perkins fff8c14066 Restructure WhereExpr eval to use continue less (#5660)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-13 16:19:17 +00:00
Dana JansensandJon Ross-Perkins f02ad1f1ca Diagnose runtime values in eval where a constant value was expected (#5659)
Uses of `ConstantValueStore::GetConstantInstId` or
`ConstantValueStore::GetInstId` in eval indicate that the code expects a
constant value. Instead of just ending up with `None` in strange places,
diagnose this and convert to an `ErrorInst` when expectations are not
met.

We add `RequireConstantValue` to pair with `GetConstantValue`, and
rename `GetConstantValueIgnoringPeriodSelf` to
`RequireConstantValueIgnoringPeriodSelf` since the former would just be
unused.

Adds a test where a runtime value ends up in the RHS of a rewrite
constraint, where a constant value is expected. This issue was uncovered
by a fuzzer.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-13 14:32:54 +00:00
Richard Smith 344f0b7550 Support for heterogeneous operators. (#5653)
Replace the binary `Operation` interfaces with the `OperationWith(T:!
type)` interfaces described in the design, and add a `Result` associated
type for both unary and binary operations. Update the `impl`s in the
prelude for integer types to use the new form, including supporting
implicit conversion of either operand.

I've tried to split this PR up into commits focused on distinct changes
for review convenience. It may be simplest to review it one commit at a
time.
2025-06-13 01:55:24 +00:00
Dana Jansens 517bec24ef Nested facets (#5644)
Given a facet type: `(Z where .X = .Y) where .X =.Y`

The rewrite constraints in the inner facet type are each an
`ImplWitnessAccess` into a witness for the self of type `Z` (which is
the facet type before the `where`). The rewrite constraints in the outer
facet type are each an `ImplWitnessAccess` for the self of type `Z where
.X = .Y`, which is a different self facet type.

This means when deduping in canonicalization, the first `.X` and the
second `.X` are different instructions, and different constant values,
so they both remain in the rewrite constraints, incorrectly. Then if the
outer `.X` is allowed to evaluate to a value from its facet type, it
finds `.Y` resulting in `.Y = .Y` which is also incorrect.

Because of the failure to dedupe the first facet type, that is also
diagnosed as two different assignments to the same `.X`. To resolve
that, we introduce `CompareFacetTypeConstraintValues()` compare values
in facet type constraints, and treat accesses to the same associated
constant in the same facet value as `equivalent` even when through
different witnesses. This allows us to dedupe the two `.X = .Y` rules
into one in the combined facet type.

Given a different facet type: `(Z where .X = ()) where .X = {}`. Here we
want to diagnose that `.X` has been assigned two different values. To do
so, we need to see that the two `.X` values are the same, and we use
`CompareFacetTypeConstraintValues()` to do this comparison. Then we see
two rewrite rules for the same LHS, and we can diagnose that.

We enable evaluating `ImplWitnessAccess` on `.Self` to pull a value from
rewrite constraints in a facet type so that we can see that we are not
incorrect evaluating the LHS of rewrite constraints and producing
cycles. By doing so, also enable generic code to see and use concrete
values in associated constants in facet types.
2025-06-12 22:06:12 +00:00
Geoff Romer 0ccde0b68b Add pre-commit check for invalid build graph state (#5658)
This can catch things like dependency cycles introduced by
`fix-cc-deps`.
2025-06-12 21:25:48 +00:00
Dana Jansens 3689a3b3e4 Call GetConstantFacetTypeInfo on fully constructed FacetTypeInfo in WhereExpr and BitAnd (#5647)
The `BitAnd` operation combines two `FacetTypeInfo` structures by
concatenating their lists, but did not apply the current specific to the
instructions in the `FacetTypeInfo` as it forgot to go through
`GetContantFacetTypeInfo`.

`WhereExpr` handling duplicates a lot of the logic in
`GetConstantFacetTypeInfo` by calling `GetConstantValue` on things,
instead of calling `GetConstantFacetTypeInfo` on the `FacetTypeInfo` it
constructs. This meant it also needed to call `GetConstantFacetTypeInfo`
on the base facet type, and on any `impls`-requirement facet types
before merging their values together into a single `FacetTypeInfo`.

Instead, make `WhereExpr` more like `BitAnd`, and have it concatenate
things together as-is to construct a `FacetTypeInfo`. Then call
`GetConstantFacetTypeInfo` to canonicalize it and return a constant
value referring to it.

In `GetConstantFacetTypeInfo` we fix a crasher by propagating errors
inserted into the `FacetTypeInfo` out to the `Phase` so that the
resulting instruction depending on the `FacetTypeInfo` is not resolved
to a constant value with errors inside it. A test is added for this,
which was crashing on import of the `FacetType` with an error within
from the imported `impl` decl.

This refactoring gives us three benefits:
* There's now only a single place that does
`ResolveRewriteConstraintsAndCanonicalize`, which is inside
`GetConstantFacetTypeInfo`. This makes the inputs/behaviour of
`ResolveRewriteConstraintsAndCanonicalize` more consistent.
* There's now only a single place that updates the instructions in
`FacetTypeInfo` constraints with new constant values, so that changes
that rely on observing and interacting with that code only need to be
written in a single place. This will avoid duplicating logic in
https://github.com/carbon-language/carbon-lang/pull/5644.
* This will make it easier to move `WhereExpr` handling to a
`EvalConstantInst` function, as it no longer directly depends on
`GetConstantValue()` from `eval.cpp`.
2025-06-12 21:20:54 +00:00
Dana Jansens 7878f6d70f Move LocId dumping to semir/ (#5656)
The `SemIR::File` has access to the `Parse::ParseTree` and
`Lex::TokenizedBuffer` now, so `semir/` can dump a friendly source
location for `LocId`. There were a few other Dump functions in `check/`
that added location info to things, and these can be consolidated into
`semir/` as well. Now `check/` dump functions all just forward over to
`SemIR`, `Parse` or `Lex`.
2025-06-12 20:37:27 +00:00
Jon Ross-Perkins 37af4ef294 Add version to stack traces (#5657)
As we've been discussing stack trace behavior, I was thinking having the
version in crashes would be helpful. e.g.:

```
1.	Carbon version: 0.0.0-0.dev+bdcef04bb.dirty
```
2025-06-12 19:42:09 +00:00
Ivana Ivanovska c7afc85541 Rename splits for intN_t tests (#5615)
Renaming the splits in the tests for `int16_t` and `int32_t` to
emphasize testing typedefs.

Part of #5263 .
2025-06-12 16:05:38 +00:00
Jon Ross-Perkins 3070e5cfc6 Try using getMainExecutable to address argv[0] limitations (#5643)
When finding an executable, this validates that the returned binary is a
symlink back to the same thing as /proc/self/exe, also using that as a
fallback for different things.

Looking back at #3912, we started using `findProgramByName` in order to
avoid path canonicalization done by `GetMainExecutable`. That created
issues as in #5096, wherein an `argv[0]` that's not explicit enough
(`llvm-symbolizer` instead of the full path, done in [LLVM's
Signals.cpp](https://github.com/llvm/llvm-project/blob/4f60f45130c6bd96c79e468fe9927a29af760f56/llvm/lib/Support/Signals.cpp#L198))
leads to incorrect results (finding an `llvm-symbolizer` in `$PATH`).

One option to fix this would be to patch LLVM to provide an absolute
path for `llvm-symbolizer`. However, I'll suggest that passing a
filename in `argv[0]` is not terribly uncommon, and could be a migration
limitation if we force it. The failure mode is also opaque; for example:

```
$ /bin/sh -c "exec -a llvm-symbolizer ./bazel-bin/toolchain/carbon"
error: expected carbon-busybox symlink at `/usr/lib/llvm-19/bin/llvm-symbolizer`
```

Combined with the `setenv` of `LLVM_SYMBOLIZER_PATH` in
`busybox_main.cpp`, this is intended to fix #5096.
2025-06-12 16:05:11 +00:00
Geoff RomerandRichard Smith 0b3edee177 Alphabetize typed_insts.h (#5401)
As requested
[here](https://github.com/carbon-language/carbon-lang/pull/5400#discussion_r2070631805).

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-06-11 23:31:53 +00:00
dependabot[bot] 42dc24d26b Bump brace-expansion from 1.1.11 to 1.1.12 in /utils/vscode in the npm_and_yarn group across 1 directory (#5652)
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.11 to 1.1.12
<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.12</h2>
<ul>
<li>pkg: publish on tag 1.x  c460dbd</li>
<li>fmt  ccb8ac6</li>
<li>Fix potential ReDoS Vulnerability or Inefficient Regular Expression
(<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/65">#65</a>)
c3c73c8</li>
</ul>
<hr />
<p><a
href="https://github.com/juliangruber/brace-expansion/compare/v1.1.11...v1.1.12">https://github.com/juliangruber/brace-expansion/compare/v1.1.11...v1.1.12</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/c85b8ad3f53d1eb65f4996a495cae61949855f7c"><code>c85b8ad</code></a>
4.0.1</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/5a5cc176c080b2fde292a9815dc6ecd97c870d17"><code>5a5cc17</code></a>
fmt</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/0b6a9781e18e9d2769bb2931f4856d1360243ed2"><code>0b6a978</code></a>
Fix potential ReDoS Vulnerability or Inefficient Regular Expression (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/65">#65</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/6a39bdddcf944374b475d99b0e8292d3727c7ebe"><code>6a39bdd</code></a>
4.0.0</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/dd72a59047e30ea265c4a58695a00ea82e90a437"><code>dd72a59</code></a>
fmt</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/278132b187d4418fe8163da5e81710222f47e3f6"><code>278132b</code></a>
feat: use string replaces instead of splits (<a
href="https://redirect.github.com/juliangruber/brace-expansion/issues/64">#64</a>)</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/70e4c1baf9b91c77b1fa303a0c07d35389e9c0a0"><code>70e4c1b</code></a>
add <code>tea.yaml</code></li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/b01a637b0578a7c59acc7d8386f11f8d0710b512"><code>b01a637</code></a>
3.0.0</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/9e781e913fe323e69248d36acebe29008666ba72"><code>9e781e9</code></a>
node 16 is EOL</li>
<li><a
href="https://github.com/juliangruber/brace-expansion/commit/6dad2093f84eac403fb3715a624fede524967cec"><code>6dad209</code></a>
docs</li>
<li>Additional commits viewable in <a
href="https://github.com/juliangruber/brace-expansion/compare/1.1.11...v1.1.12">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.11&new-version=1.1.12)](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-06-11 22:27:34 +00:00
Richard Smith 4e5dccdbf7 When making a direct call to a thunk, inline the call in SemIR. (#5642)
This preserves the constant values of the arguments to the thunk, which
is important if the thunk requires conversion of an `IntLiteral` to some
other type. This should become unnecessary once we have form support,
but avoiding the indirection through a thunk function seems valuable
even once that support is in place.

To support this, track whether a function is a thunk on the Function
object, and if so, what the callee of the thunk is. This information is
also included in formatted SemIR when dumping the thunk.
2025-06-11 21:34:01 +00:00
Dana Jansens bdf5f00af0 Resolve the RHS of rewrite constraints in facets (#5639)
If the RHS of a rewrite constraint refers to an associated constant,
pull the value for that constant from other rewrite constraints. We
repeat this each time a RHS value is changed until we reach a fixed
point, as per the "Rewrite constraint resolution" rule:
https://docs.carbon-lang.dev/docs/design/generics/appendix-rewrite-constraints.html#rewrite-constraint-resolution

While replacing references to associated constants in the RHS, if the
reference is to the LHS of the same rewrite constraint, we diagnose it
as a cycle which has no fixed point, and replace reference to the
associated constant with `ErrorInst`.
2025-06-11 21:11:00 +00:00
Jon Ross-Perkins 122800881b Remove redundant ranges=only flag settings (#5648) 2025-06-11 16:47:40 +00:00
Dana Jansens dfc04b1488 Rename the workflow step that sets labels to a more appropriate name (#5646)
Currently it's called `assign_reviewers` as it was copied from the
workflow that does said task. But this workflow is setting labels, so
call it `set_labels`.
2025-06-11 16:13:57 +00:00
Boaz Brickner 29d4aae722 Update most toolchain/check/testdata/interop/cpp tests to use sem ir ranges (#5594)
All except
`toolchain/check/testdata/interop/cpp/function_param_int*.carbon` and
`toolchain/check/testdata/interop/cpp/function_return.carbon`.

Don't output SemIR for cases that are intended to fail.
2025-06-11 12:35:55 +00:00
Richard SmithandJon Ross-Perkins dc7839e893 Add a new facility GrowingRange for a range that might grow during iteration. (#5641)
Use it to replace most existing modernize-loop-convert lints with
range-based for loops. As requested in review of #5475.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-10 23:21:17 +00:00
Richard Smith 2472f44e44 Track pending thunks on the deferred definition worklist. (#5609)
Instead of using somewhat different approaches for defining in-line
methods at the end of the enclosing scope and defining thunks at the end
of the enclosing scope, we now use the same worklist for both.

This fixes a bug where we would crash when defining thunks if there
happens to be nothing else on the deferred definition worklist, leading
to our leaving the enclosing impl scope before we try to define the
pending thunk. That would only happen if the impl contains no in-line
member function bodies, so only if the impl has only a forward
declaration or a builtin declaration for every method. The latter
case happens (a lot) if we start using thunks in the prelude impls.

One complicating factor here is that this means the deferred definition
worklist moves from the layer containing `check/handle*` and
`check/check_unit.cpp` into the layer containing `check/context.cpp`.
Allowing that required moving a couple of other things that it depends
on -- notably `SuspendedFunction` and `HandleSuspendedFunction` --
around.
2025-06-10 22:09:31 +00:00
Richard Smith e24ba02352 Fix lowering of thunks in generic impls (#5631)
Build a `SpecificConstant` (if needed) and `NameRef` instruction when
referencing the thunk target from a thunk. The former is necessary if
the impl is generic in order to call the right version of the thunk
target. This previously caused a crash in lowering.

Also add some more check testing for the interaction of thunks and
generics. This testing uncovered an unrelated bug with thunks for
generic interface functions for which I've added a TODO.
2025-06-10 20:54:58 +00:00
Jon Ross-Perkins 81ca949ab8 Replacing lowering vectors with FixedSizeValueStore (#5636)
Changes the vectors on `Lower::FileContext` to be `FixedSizeValueStore`
where possible, which we have several at this point.

This changes `FixedSizeValueStore` to prefer inferring the size from a
`ValueStore<IdT>`, which should make adding incorrect sizes harder. Note
I wasn't sure that adding a `size()` to `TypeStore` that returned
`insts().size()` would be good because it doesn't directly work that
way; `ConstantValueStore` would've also required more work since it
doesn't have access to that right now.
2025-06-10 20:15:19 +00:00
Ivana Ivanovska 3d603fced7 Fix C++ function params and return values printed in SemIR (#5468)
Fix `pattern_block_id` and `call_params_id` for C++ function decl
import, to get the correct SemIR printout for the C++ functions i.e.

1) Fill in missing parameter info in the function decls:
```
// CHECK:STDOUT:   %foo.decl: %foo.type = fn_decl @foo [concrete = constants.%foo] {
// CHECK:STDOUT:     %a.patt: %pattern_type.2f8 = binding_pattern a [concrete]
// CHECK:STDOUT:     %a.param_patt: %pattern_type.2f8 = value_param_pattern %a.patt, call_param0 [concrete]
// CHECK:STDOUT:   } {
// CHECK:STDOUT:     %a.param: %i16 = value_param call_param0
// CHECK:STDOUT:     %.1: type = splice_block %i16 [concrete = constants.%i16] {
// CHECK:STDOUT:       %int_16: Core.IntLiteral = int_value 16 [concrete = constants.%int_16]
// CHECK:STDOUT:       %i16: type = class_type @Int, @Int(constants.%int_16) [concrete = constants.%i16]
// CHECK:STDOUT:     }
// CHECK:STDOUT:     %a: %i16 = bind_name a, %a.param
// CHECK:STDOUT:   }
```
2) Print the params and return values:

```
// CHECK:STDOUT: fn @foo_short() -> %i16;
```

```
// CHECK:STDOUT: fn @foo(%a.param: %i16);
```

Closes #5449
2025-06-10 17:17:19 +00:00
Boaz Brickner e4c8150f2c Store Clang Decls in a CanonicalValueStore (#5638)
Saves space since in most cases, we only need a `None` 32 bits index
instead of a null 64 bits pointer.

Based on discussions in [Carbon C++ Interop
weekly](https://docs.google.com/document/d/1YlxEOJ0r-o19o19TCJbFl4Ln1U88yn_Vj23y1Hr5vTk/edit?tab=t.0#heading=h.23l56bt5xwlu)
and Discord
([1](https://discord.com/channels/655572317891461132/768530752592805919/1375121180306047106),
[2](https://discord.com/channels/655572317891461132/768530752592805919/1380575881050718469)).

Note: Any `clang::DeclContext` is also a `clang::Decl`.

Part of #4666.
2025-06-10 16:55:29 +00:00
Richard SmithandDana Jansens 6753a715f6 Avoid moving around large suspended function states in the deferred definition worklist. (#5608)
We already go to some effort to avoid moving these, but we end up still
moving them twice: once when adding to the worklist and again when
reversing a chunk of the worklist.

* To avoid a move when constructing the worklist, add an `EmplaceResult`
utility that allows the result of a function call to be emplaced into a
container.
* To avoid moves when reversing the list, stop reversing it. Instead of
reversing the list and popping tasks as we run them, we accumulate a
sequence of tasks for a deferred definition region, run them in the
order they were enqueued, then pop them all at the end. This will in
some cases increase the high-water-mark of the size of the worklist, but
not asymptotically. The same high-water-mark could be reached with the
old approach by reordering the declarations in the source file.

In passing, we no longer create `LeaveDeferredDefinitionRegion` tasks
for non-nested regions. We don't need them, because we can detect that
condition by our reaching the end of the worklist. This means that the
enter / leave region actions are now always in correspondence -- we only
create them for *nested* regions. The tasks have been renamed to convey
this.

We still move the suspended function states around if the worklist grows
to over 64 entries and gets reallocated. We could potentially address
that issue too by switching to a chunked allocation strategy as is used
by `ValueStore` and then make the tasks noncopyable, but I'm not
attempting that in this PR.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-06-10 13:37:16 +00:00
dependabot[bot] 8727065a52 Bump requests from 2.32.0 to 2.32.4 in /github_tools in the pip group across 1 directory (#5637)
Bumps the pip group with 1 update in the /github_tools directory:
[requests](https://github.com/psf/requests).

Updates `requests` from 2.32.0 to 2.32.4
<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.32.4</h2>
<h2>2.32.4 (2025-06-10)</h2>
<p><strong>Security</strong></p>
<ul>
<li>CVE-2024-47081 Fixed an issue where a maliciously crafted URL and
trusted
environment will retrieve credentials for the wrong hostname/machine
from a
netrc file. (<a
href="https://redirect.github.com/psf/requests/issues/6965">#6965</a>)</li>
</ul>
<p><strong>Improvements</strong></p>
<ul>
<li>Numerous documentation improvements</li>
</ul>
<p><strong>Deprecations</strong></p>
<ul>
<li>Added support for pypy 3.11 for Linux and macOS. (<a
href="https://redirect.github.com/psf/requests/issues/6926">#6926</a>)</li>
<li>Dropped support for pypy 3.9 following its end of support. (<a
href="https://redirect.github.com/psf/requests/issues/6926">#6926</a>)</li>
</ul>
<h2>v2.32.3</h2>
<h2>2.32.3 (2024-05-29)</h2>
<p><strong>Bugfixes</strong></p>
<ul>
<li>Fixed bug breaking the ability to specify custom SSLContexts in
sub-classes of
HTTPAdapter. (<a
href="https://redirect.github.com/psf/requests/issues/6716">#6716</a>)</li>
<li>Fixed issue where Requests started failing to run on Python versions
compiled
without the <code>ssl</code> module. (<a
href="https://redirect.github.com/psf/requests/issues/6724">#6724</a>)</li>
</ul>
<h2>v2.32.2</h2>
<h2>2.32.2 (2024-05-21)</h2>
<p><strong>Deprecations</strong></p>
<ul>
<li>
<p>To provide a more stable migration for custom HTTPAdapters impacted
by the CVE changes in 2.32.0, we've renamed <code>_get_connection</code>
to
a new public API, <code>get_connection_with_tls_context</code>. Existing
custom
HTTPAdapters will need to migrate their code to use this new API.
<code>get_connection</code> is considered deprecated in all versions of
Requests&gt;=2.32.0.</p>
<p>A minimal (2-line) example has been provided in the linked PR to ease
migration, but we strongly urge users to evaluate if their custom
adapter
is subject to the same issue described in CVE-2024-35195. (<a
href="https://redirect.github.com/psf/requests/issues/6710">#6710</a>)</p>
</li>
</ul>
<h2>v2.32.1</h2>
<h2>2.32.1 (2024-05-20)</h2>
<p><strong>Bugfixes</strong></p>
<ul>
<li>Add missing test certs to the sdist distributed on PyPI.</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.32.4 (2025-06-10)</h2>
<p><strong>Security</strong></p>
<ul>
<li>CVE-2024-47081 Fixed an issue where a maliciously crafted URL and
trusted
environment will retrieve credentials for the wrong hostname/machine
from a
netrc file.</li>
</ul>
<p><strong>Improvements</strong></p>
<ul>
<li>Numerous documentation improvements</li>
</ul>
<p><strong>Deprecations</strong></p>
<ul>
<li>Added support for pypy 3.11 for Linux and macOS.</li>
<li>Dropped support for pypy 3.9 following its end of support.</li>
</ul>
<h2>2.32.3 (2024-05-29)</h2>
<p><strong>Bugfixes</strong></p>
<ul>
<li>Fixed bug breaking the ability to specify custom SSLContexts in
sub-classes of
HTTPAdapter. (<a
href="https://redirect.github.com/psf/requests/issues/6716">#6716</a>)</li>
<li>Fixed issue where Requests started failing to run on Python versions
compiled
without the <code>ssl</code> module. (<a
href="https://redirect.github.com/psf/requests/issues/6724">#6724</a>)</li>
</ul>
<h2>2.32.2 (2024-05-21)</h2>
<p><strong>Deprecations</strong></p>
<ul>
<li>
<p>To provide a more stable migration for custom HTTPAdapters impacted
by the CVE changes in 2.32.0, we've renamed <code>_get_connection</code>
to
a new public API, <code>get_connection_with_tls_context</code>. Existing
custom
HTTPAdapters will need to migrate their code to use this new API.
<code>get_connection</code> is considered deprecated in all versions of
Requests&gt;=2.32.0.</p>
<p>A minimal (2-line) example has been provided in the linked PR to ease
migration, but we strongly urge users to evaluate if their custom
adapter
is subject to the same issue described in CVE-2024-35195. (<a
href="https://redirect.github.com/psf/requests/issues/6710">#6710</a>)</p>
</li>
</ul>
<h2>2.32.1 (2024-05-20)</h2>
<p><strong>Bugfixes</strong></p>
<ul>
<li>Add missing test certs to the sdist distributed on PyPI.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/psf/requests/commit/021dc729f0b71a3030cefdbec7fb57a0e80a6cfd"><code>021dc72</code></a>
Polish up release tooling for last manual release</li>
<li><a
href="https://github.com/psf/requests/commit/821770e822a20a21b207b3907ea83878bda1d396"><code>821770e</code></a>
Bump version and add release notes for v2.32.4</li>
<li><a
href="https://github.com/psf/requests/commit/59f8aa2adf1d3d06bcbf7ce6b13743a1639a5401"><code>59f8aa2</code></a>
Add netrc file search information to authentication documentation (<a
href="https://redirect.github.com/psf/requests/issues/6876">#6876</a>)</li>
<li><a
href="https://github.com/psf/requests/commit/5b4b64c3467fd7a3c03f91ee641aaa348b6bed3b"><code>5b4b64c</code></a>
Add more tests to prevent regression of CVE 2024 47081</li>
<li><a
href="https://github.com/psf/requests/commit/7bc45877a86192af77645e156eb3744f95b47dae"><code>7bc4587</code></a>
Add new test to check netrc auth leak (<a
href="https://redirect.github.com/psf/requests/issues/6962">#6962</a>)</li>
<li><a
href="https://github.com/psf/requests/commit/96ba401c1296ab1dda74a2365ef36d88f7d144ef"><code>96ba401</code></a>
Only use hostname to do netrc lookup instead of netloc</li>
<li><a
href="https://github.com/psf/requests/commit/7341690e842a23cf18ded0abd9229765fa88c4e2"><code>7341690</code></a>
Merge pull request <a
href="https://redirect.github.com/psf/requests/issues/6951">#6951</a>
from tswast/patch-1</li>
<li><a
href="https://github.com/psf/requests/commit/6716d7c9f29df636643fa2489f98890216525cb0"><code>6716d7c</code></a>
remove links</li>
<li><a
href="https://github.com/psf/requests/commit/a7e1c745dc23c18e836febd672416ed0c5d8d8ae"><code>a7e1c74</code></a>
Update docs/conf.py</li>
<li><a
href="https://github.com/psf/requests/commit/c799b8167a13416833ad3b4f3298261a477e826f"><code>c799b81</code></a>
docs: fix dead links to kenreitz.org</li>
<li>Additional commits viewable in <a
href="https://github.com/psf/requests/compare/v2.32.0...v2.32.4">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.0&new-version=2.32.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-06-10 13:29:56 +00:00
Boaz Brickner ec97ec9664 Use InImport pointing to C++ imports in ConvertLocInFile() instead of adding a separate InCppImport when emitting (#5614)
I believe we will need to eventually add the specific C++ import
information in `LocId`.

This also seems to fix the `LanguageServerDiagnosticInWrongFile` issue
(#5604).

We're still not in the state we want to be according to
https://github.com/carbon-language/carbon-lang/pull/5246#issuecomment-2784301206.
Will look into removing the location part from the `"In file included
from ..."` line.

Part of #5245.
2025-06-10 09:02:45 +00:00
Jon Ross-Perkins 6683cf3b1c Switch token_infos_ to a ValueStore (#5633)
Split out `TokenInfo` to be able to easily write `using ValueType =
TokenInfo;` on `TokenIndex`. Also fixes a small type issue on
`ValueStore` that affected `mapped_iterator` behavior when writing
`old_tokens_it->first < next_offset`.
2025-06-09 22:24:03 +00:00
Jon Ross-Perkins 78d4cce9f8 Put min_prelude in a testdata dir (#5635)
This makes the min_prelude files a little more consistent with how we
use testdata elsewhere, avoiding some special casing of them.
2025-06-09 22:18:12 +00:00
Dana Jansens f506376e53 Resolve rewrites in facet types, looking for duplicates (#5620)
Add a facet type rewrite constraint resolution step that is run every
time a facet type is constructed, in line with the design here:
https://docs.carbon-lang.dev/docs/design/generics/appendix-rewrite-constraints.html#rewrite-constraint-resolution

The resolution has multiple steps, and this PR implements the first of
them, finding and diagnosing any duplicate rewrites to the same
associated constant.

We already diagnosed this for impl construction, now we do so for all
facet types, which includes the one used for impl construction, so this
diagnostic is a superset of the previous.
2025-06-09 18:51:29 +00:00
Dana Jansens 52727f9e4b Print test names when running with --threads=1 (#5629)
When tests crash by stack overflow (and maybe other ways), they don't
print a stack trace so you don't have any way to know which file it was.
By running with --threads=1 you can figure this out, if we print out the
name of each test before we run it.

This prints each test name on its own line, then allows the autoupdate
sigil to be added to the end of that line:
```
TEST: toolchain/check/testdata/alias/basics.carbon .
TEST: toolchain/check/testdata/alias/builtins.carbon !
TEST: toolchain/check/testdata/alias/export_name.carbon .
TEST: toolchain/check/testdata/alias/import.carbon .
...
```
2025-06-09 16:39:07 +00:00
Jon Ross-Perkins 766ef7077d Change comments and lines to ValueStores (#5621)
Moves LineInfo and CommentData out so that they can easily be set as
`ValueType` on the Index types. I've also been thinking about letting
`ValueStore` take `ValueType` as a parameter instead of requiring it to
be inferred this way, but for these it feels more consistent with the
rest of the toolchain to do it this way.

I'm not doing similar with `TokenInfo` just because the recovery token
splicing makes it more difficult to use `ValueStore`.
2025-06-07 01:30:11 +00:00
Jon Ross-Perkins 2e297b5258 Add a fixed-size ValueStore (#5628)
Trying to build a type around the common idiom we have for types based
on an Id range. The primary advantage of this is it makes clear the `Id`
association, and drops the `.index` use.

Lowering was motivating me because it has a few of these, and check
probably has more (e.g. `tree_and_subtrees_getters`), but I'm just
changing a handful of examples to show the concept and see if there's
agreement.

I wanted to inherit from ValueStoreTypes, but name lookup didn't seem to
find the types without `using` statements, at which point there didn't
seem to be much reason to use inheritance.
2025-06-06 22:10:12 +00:00
Jon Ross-Perkins b7c582ad22 Add floats to SharedValueStores yaml (#5626)
Just fixing a missing print.
2025-06-06 18:05:20 +00:00
Jon Ross-Perkins 1b55459da6 Add filenames to stack traces (#5623)
To make it easier to identify crashing files when testing multiple.

```
(elided)
3.	Check::Context
          filename: duplicate_name_same_line.carbon
          NodeStack:
(elided)
```
2025-06-06 17:29:08 +00:00
Dana Jansens 5b68b8338e Mention where vsce is installed (#5622) 2025-06-06 16:25:02 +00:00
Dana Jansens dc93ec27e1 Consider //@dump-sem-ir-begin and //@dump-sem-ir-end as comments in syntax highlighting (#5624) 2025-06-06 16:18:14 +00:00
Jon Ross-Perkins 0a727c32e9 Change min_prelude to use EXTRA-ARGS and INCLUDE-FILE (#5625)
Now that included files can specify `EXTRA-ARGS`, this uses that to
handle min_prelude files. Also moves `As`/`ImplicitAs` out to a shared
file, partly because we duplicate it a few times over, partly just to
show that it works.

Also removes the `min_prelude/` subdirectories because many of these
files were touched by autoupdate regardless. I noticed one conflict for
`impl_thunk.carbon`, so renaming that one to
`impl_thunk_min_prelude.carbon`.

`GetArgReplacements` I simply noticed was unused, so removing it.
2025-06-06 15:56:58 +00:00
Jon Ross-Perkins 1e9e148c3b Rename the ImportRefs block to Imports (#5618)
I've been mulling the name of this, changing it and updating comments to
try and better reflect the current semantic. "Imports" reflects how
we're currently printing this in SemIR.
2025-06-05 21:24:58 +00:00
Jon Ross-Perkins 9b1a0729a1 Move imported C++ entities to the import block (#5616)
This mirrors how imports work in general, that the imported declarations
shouldn't belong to the first referencing scope (particularly apparent
when referenced across multiple scopes). I think this was just an
oversight here.
2025-06-05 18:44:27 +00:00
Jon Ross-Perkins 51b4abec20 Allow args, includes, and splits in file_test includes (#5610)
This builds a mechanism for the toolchain to construct more complex
min_prelude files, which in turn should allow the toolchain to stop
special-casing the min_prelude directory. For example, instead of:

```
      args.insert(args.end(), {"--custom-core",
                               "--exclude-dump-file-prefix=include_files/"});
```

This should allow (in a `min_prelude` file):

```
// EXTRA-ARGS: --custom-core --exclude-dump-file-prefix=include_files/
```

Then when that min_prelude is included, it'd be used.

But also, this should allow sharing between min_prelude files with use
of `INCLUDE-FILE`, which as we make progressively more complex
min_preludes might become useful.
2025-06-05 16:23:15 +00:00
Richard Smith a508b00883 Fix expected signature for type.and. (#5613)
The former signature unintentionally allowed any parameter and result
types, because it only checked that the type of the type was `type`,
which is tautological (for non-error values). Also add missing tests for
the builtin.
2025-06-04 23:42:20 +00:00
Dana Jansens 315c79ea33 Apply enclosing specifics to symbolic arguments in generic calls (#5597)
When deduce determines the type of its parameters, it converts each
argument to the correct type, generating an error if the argument can't
convert. It is at this point that enclosing specifics are applied to
arguments as well, as the enclosing specifics are stored in
`substitutions_`. However we were only doing this step for concrete
argument values. If the argument is a symbolic value, like a facet value
that has an enclosing specific, we failed to apply that enclosing
specific. Then the unconverted argument (without the enclosing specific
applied) would end up failing to convert to the parameter type even
though deduce found that it should.
2025-06-04 23:23:34 +00:00
Jon Ross-Perkins 126f7b38e3 Mark stdin output file test as no-prelude (#5612) 2025-06-04 23:01:25 +00:00
Jon Ross-Perkins 04d534abee Remove the no_prelude directory, using --no-prelude-import directly (#5607)
People seemed receptive [on
#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1379196447827689553),
so proceeding.

For the two name conflicts, I've set it up so that there's a
"foo.carbon" and "foo_with_prelude.carbon", to indicate that the
no-prelude approach is preferred (with a shorter name).

Note min_prelude will require a little more work/thought, I want to
avoid adding `--custom-core` etc.
2025-06-04 16:56:03 +00:00
Boaz Brickner fb33f7c481 In test_clang_cpp, if CalledProcessError is raised, log the stderr for easier debugging (#5595)
Found this is very useful for debugging since otherwise it's hard to
tell what happened in the process.
Based on similar logic in `scripts/target_determinator.py`.
2025-06-04 06:39:02 +00:00
Boaz Brickner 5435877745 Simplify the test that accesses LangOptions due to handling diagnostic with FixItHints and clarify the test if for diagnostic with FixItHints (#5596)
Followup of #5586.
Part of #5176.
2025-06-04 06:32:12 +00:00
7a55568f15 Fix crash when impl lookup fails and the type of .Self is symbolic. (#5603)
Also fix substitution into constants to provide a source location. This
matters if the result of substitution ends up being part of a generic
eval block.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-06-04 00:57:44 +00:00
josh11bandJosh L 09ca0b8308 Update LLVM (#5605)
Some updates required for
https://github.com/llvm/llvm-project/pull/139584.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-06-04 00:43:40 +00:00
Jon Ross-Perkins 806bee1063 Shift from ARGS to EXTRA-ARGS where possible (#5602)
Adds minimal defaults for codegen so that those tests don't need to
specify the full command line.

Moves driver/testdata/compile to check/testdata/basics/raw_sem_ir, which
seems like it better reflects the focus. Removes the textual IR test
because we have plenty of those now.

Moves a multiline token diagnostic test to parse because (a) diagnostics
doesn't have other tests and (b) this is really testing the way that
parse structures the location.

Drops `--include-diagnostic-kind` from some driver tests that aren't
testing a diagnostic, so the flag felt a bit like noise (even before
this change, there are a few tests that don't specify it because they're
not intended to test an emitted diagnostic, just high-level diagnostic
behaviors).

Adds some comments to reflect my understanding of why a test exists,
when I was pausing to think about it.

Modifies the stdin test to do more dumps; which happens to expose we
currently misbehave.
2025-06-03 22:09:57 +00:00
Jon Ross-Perkins 20c20595ba Fix language-server crash with cpp_ast (#5604)
Removes the nullptr default for safety.

Note, I think cpp support doesn't allow things like `<version>` or
inline code yet, and language-server support doesn't allow non-hermetic
files, so the best I can test is an error.
2025-06-03 22:09:51 +00:00
Jon Ross-Perkins c0cdc712e9 Add docs for dump-sem-ir-ranges (#5598) 2025-06-03 21:15:09 +00:00
Jon Ross-Perkins 26093656de Removes no-longer-needed --dump-sem-ir-ranges=only args (#5600)
The default was flipped by #5587.
2025-06-03 19:58:55 +00:00
Jon Ross-Perkins 3831ca6471 Replace the desugared bit with an extra LocId range (#5592)
This is to reduce the space consumption of the bit which only applies to
NodeId, and it also simplifies logic related to ImportIRInstId by
removing the need for index_without_flags.
2025-06-03 19:37:00 +00:00
Dana Jansens 493bea1647 Fearlessly hold references into ValueStore again (#5589)
Undo changes that were meant to prevent use of a reference into
`ValueStore` after being invalidated. After #5576, the `ValueStore`
makes such references stable, so there's no need to worry about
invalidation.
2025-06-03 18:07:23 +00:00
Jon Ross-Perkins a85d292f8d Change from ToImplicit to AsDesugared (#5591)
This changes `ToImplicit` to `AsDesugared`, and adds a
`GetLocIdForDesugaring` to `InstStore`.

In particular, I'm motivated by the latter, to make it clearer what the
intended call convention is.
2025-06-03 17:55:16 +00:00
David Blaikie 6831c98d74 Refactor interface and impl NameScope importing to resemble classes (#5585)
Similar to the class change made in
c6f25e9018 but without tests as it doesn't
appear that the same bug is reachable for these cases at the moment -
but seems good to match the approach in case cycles appear in the future
and to make the code consistent.

The impl case didn't seem to be able to use the new common utility
function, since it splits the two pieces of work and only does the
second conditionally.
2025-06-03 17:39:38 +00:00
Jon Ross-PerkinsandDana Jansens d0a48504d8 Flip the dump-sem-ir-ranges default in file_test (#5587)
This doesn't remove no-longer-needed flags; I'll do that in a separate
PR after this is merged.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-06-03 17:37:51 +00:00
Boaz Brickner 1899a6b285 Add C++ struct parameter tests with data members (#5540)
Also, add ranges.

Part of #5533.
2025-06-03 16:53:36 +00:00
dependabot[bot] 97cc1383cf Bump tar-fs from 2.1.2 to 2.1.3 in /utils/vscode in the npm_and_yarn group across 1 directory (#5593)
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.2 to 2.1.3
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/mafintosh/tar-fs/commits">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.2&new-version=2.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 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-06-03 13:06:46 +00:00
Jon Ross-Perkins 89a6818424 Move TokenOnly to LocIdForDiagnostics (#5590)
This reclaims a bit inside `LocId`. I'm hopeful we don't actually need
to store the token-only state.

Note I'm looking at this in the context of desugaring; I was thinking
about changing `ToImplicit` logic a little to push more towards
`GetCanonicalLocId`, and the "desugaring" TODO there. Removing
`ToTokenOnly` makes me feel a little more free to rename `ToImplicit`,
since it eliminates consistency as a question.
2025-06-03 01:14:54 +00:00
Richard Smith 14e4f219b1 Support lowering specifics for an imported generic function. (#5475)
When lowering a specific function whose generic was defined in a
different file, switch to that other file's `FileContext` and lower the
generic there. Also pass the `FileContext` corresponding to the specific
into the `FunctionContext`, and use that `FileContext` for resolving
requests for constants and types from the specific.
2025-06-02 21:14:34 +00:00
Dana Jansens 02fc484f23 Make pointers in ValueStore stable across insertions (#5576)
This avoids reallocating the backing buffer in ValueStore so that
references into the ValueStore are never invalidated when adding new
values. This works especially well since we never delete values from a
ValueStore.

The strategy used is to allocate chunks of a fixed size, and inserting
into each chunk until it is full before allocating the next. The
ValueStore starts with an initial allocated chunk in all cases, so that
there is only a single indirection for adding and accessing values from
this chunk. After it's full, additional chunks are allocated in a
vector, so two indirections are required to add or access values in
these chunks.

This obviates the need for
https://github.com/carbon-language/carbon-lang/pull/5529 as we no longer
need to worry about holding pointers into a ValueStore.

We introduce a Flatten operation for ranges. It flattens a "range over
ranges over Ts" down to a "range over Ts". This allows us to make an
range over the values in the ValueStore from a range over the chunks in
the ValueStore. See
https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.flatten
for inspiration for this name choice. Flatten is used in one other case
where we were writing two levels of for loops to do the same thing.

The `array_ref()` accessor is changed to `values()` and its now a range
(typed as a `ValueStoreRange`) over all values as references (like
ArrayRef was, but without random access).

As pointers to a ValueStore can no longer be invalidated, we remove the
ASAN poisoning feature and support from ValueStore.

This may cause a regression in our compile benchmark of up to 5%, though
that is close to or within the noise of the benchmark. We can look at
ways to optimize things further in the future. Perhaps by tuning the
chunk size further, or by making later chunks larger than earlier
chunks, or other strategies.
2025-06-02 19:16:31 +00:00
Richard Smith e91840e1b6 Split a cross-file Lower::Context out of Lower::FileContext. (#5583)
In preparation for lowering information from multiple `SemIR::File`s
into a single `llvm::Module`. The primary purpose of this is to support
lowering a local specific for an imported generic function, where the
instructions for the generic function are in a different file than the
instructions for the specific. See #5475 for a draft PR implementing
that functionality on top of this.

The per-`llvm::Module` state now lives in `Lower::Context`, and
`Lower::FileContext` tracks only the per-`SemIR::File` information.
`Lower::Context` should not mention any `SemIR` IDs that are
file-specific. For now, the C++ lowering and the specific coalescing
logic are kept per-file for simplicity.
2025-06-02 18:02:32 +00:00
Jon Ross-Perkins 0fd129ec95 Update tuple tests, and merge in expr-category (#5549)
In the vein of https://github.com/carbon-language/carbon-lang/pull/5455.

This merges the one expr_category test into tuple testing because it
seemed closely associated (particularly with
in_place_tuple_init.carbon), and it didn't seem worth keeping a
directory for a single test.

Note the entire "access" directory is combined into
element_access.carbon.
2025-06-02 16:36:22 +00:00
Jon Ross-Perkins 39a701084c Update eval tests (#5547)
In the vein of https://github.com/carbon-language/carbon-lang/pull/5455.
This also uses the 'int' min_prelude being added by #5546.
2025-06-02 16:21:11 +00:00
Jon Ross-Perkins 8615b6b411 Add an int min_prelude (#5578)
The general intent here is to support basic use of `i32` and similar
integer types in min_prelude tests, without all the various arithmetic
support.

This is in support of #5547 and #5549. However, I was originally asking
for this to be reviewed as part of #5546 rather than either of those
PRs, and I've retracted #5546 due to [the discussion on Discord about
test change
complexity](https://discord.com/channels/655572317891461132/655578254970716160/1377406366200758293).
So, to try to still get this in (and then merge the already-approved
#5547 and #5549), splitting out this file.

Note this is actually the form of the prelude in #5549, which was adding
negate -- it felt better to me to add that together as long as I'm
splitting it out.
2025-06-02 15:18:41 +00:00
Boaz Brickner 464ee76b9b Fix stack-use-after-scope issue by making LangOptions parameter non temporary (#5586)
The parameter is kept by reference.
Added a test that accesses `LangOptions` and crashes without this fix.

Part of #5176.
2025-06-02 14:28:36 +00:00
Jon Ross-Perkins e3738eb196 Try out a different IdKind table approach (#5528)
I was thinking about these after #5526, was wondering how others will
feel about this kind of approach:

- Adding a helper to `TypeEnum` to get the table construction.
- In what were previously `Make` functions, return the element instead
of returning the table.
- By returning the element, no more need to pass in a nullptr (now have
a concrete instance).

I think this is a mild simplification, but maybe worth it.

Note, would appreciate it if there are thoughts on how to provide a
boilerplate `Invalid` implementation (maybe it'd be fine to just return
`nullptr` and cause a crash that way, but I was hesitant to do that).
2025-05-31 02:15:45 +00:00
Jon Ross-Perkins c70f23408d Add range flag settings to where_expr files (#5582)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-31 01:42:10 +00:00
Jon Ross-Perkins 3c49283b3b Add range flag settings to deduce files (#5579)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-31 01:41:39 +00:00
David Blaikie d614ed0fc9 Assert that non-None NameScopes import as non-None (#5584)
This would've identified c6f25e9018
earlier/more clearly.

I looked for similar assertions for things like
`GetLocalConstantValueOrPush` but it has the right property by
construction (if it's going to return `None`, it pushes work) so an
assertion didn't seem suitable there.

Perhaps there are other such mapping functions that could get this
treatment? Open to pointers.
2025-05-31 01:11:58 +00:00
Boaz Brickner ae454bb48c Test C++ structs as parameters and return types as declarations and definitions (#5537)
Move all function tests to a dedicated directory and all `struct`
function tests to a dedicated file in this directory.

Part of #5533.
2025-05-30 21:52:26 +00:00
Jon Ross-Perkins 7f52cc7c0e Add ranges flags in a smattering of files missed in other PRs (#5581)
Now that I'm getting to a relatively low number of remaining files for
this cleanup, this is my second look for things that I missed before in
directories that were generally already swept up (mostly by the TODOs).
2025-05-30 18:26:33 +00:00
Jon Ross-Perkins 3e2fb5e6ec Add range flag settings to patterns files (#5570)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-30 18:20:49 +00:00
Jon Ross-Perkins 5c59ee6f6f Update global tests (#5552)
Updates in the vein of #5455.

Note this seems a little like it could be merged into `var`, which
already has global tests. But the merge felt a little more complex than
just doing this update.
2025-05-30 17:17:14 +00:00
Dana Jansens 11e82e9872 Revert "Add FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION to fuzzer mode and enable DCHECKs under fuzzing (#5489)" (#5580)
This reverts commit 1889ee3904.

We have identified that this is causing ODR violations, because the
`fuzzer` feature is being added `cc_fuzz_test` targets, and thus any
includes they make, but not to the rest of the build. Any include that
is seen from both places has ODR violations if it branches on
FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION.

We need to apply fuzzer globally when building fuzz targets somehow, or
not set different defines in fuzzer.
2025-05-30 16:20:43 +00:00
Jon Ross-Perkins 0b530de9ed Add range flag settings to operators files (#5567)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-30 15:03:42 +00:00
Jon Ross-Perkins a01648cd44 Use concat in formatter (#5577)
Because this is coming up on #5576
2025-05-30 14:36:19 +00:00
Alina Sbirlea 77afd0678b Prototype for coalescing equivalent specifics of the same generic. (#5314)
This is a working version for coalescing equivalent specifics of the
same generic, with *many* things to add and improve.
2025-05-29 22:24:13 +00:00
Jon Ross-Perkins 370027599c Add range flag settings to var files (#5574)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 20:57:36 +00:00
Jon Ross-Perkins 5c6e94f0ae Add range flag settings to struct files (#5573)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 20:57:04 +00:00
Jon Ross-Perkins f91d23b110 Add range flag settings to return files (#5572)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 20:54:49 +00:00
Jon Ross-Perkins ffc014bbe2 Add range flag settings to packages files (#5569)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 20:26:13 +00:00
Jon Ross-Perkins 59cb7183b2 Add range flag settings to pointer files (#5571)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 20:25:46 +00:00
Jon Ross-Perkins 34b892b774 Fix formatting of forward declared generics (#5530)
Noticed this while working on class tests (crash bug). Forward declared
generics have a decl_id of the forward declaration, not the definition.
I'm giving up trying to have the caller know if it's a start node, and
instead just choosing based on the node kind.
2025-05-29 20:20:06 +00:00
Richard Smith 42c783defa Use linkonce_odr linkage for specific functions. (#5575)
The same specific function will (eventually) be emitted as part of
lowering multiple different source files, so don't give them unique
external linkage.
2025-05-29 20:16:37 +00:00
Jon Ross-Perkins aadd29b36c Update if tests (#5551)
In the vein of #5455. This reuses the bool min_prelude in #5550.
2025-05-29 20:07:40 +00:00
Jon Ross-Perkins e135ea35b6 Add range flag settings to package-expr files (#5568)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 20:02:12 +00:00
a23631f360 Support for lowering references to imported vars. (#5513)
Previously we walked the global variables defined by the current file
and emitted an LLVM global variable definition for each of them. Now
instead, when emitting a constant reference to a global variable, we
emit an LLVM global variable declaration, and we then subsequently walk
the global variables defined by the current file and convert each of
them from a declaration to a definition.

In order to make import of names of global variables work, add support
for import of `var`, as well as support for importing `tuple_access` and
`tuple_pattern` in the case where the `var` has a tuple pattern in its
declaration. Also treat `bind_name`s that are reference bindings to
`var`s as having the same constant reference value as their `var` so
that we can properly import and lower them.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-05-29 19:48:16 +00:00
David BlaikieandRichard Smith c6f25e9018 Ensure an imported Class's NameScope is allocated in phase 2 (#5548)
Entities, such as `Function`s may be created during phase 2 and need to
read the `Class`'s `scope_id` at that point, so it must be made
available earlier (in phase 2, rather than 3) when importing.

(thanks @zygoloid for explaining this all to me)

I'll look into other instances of this 3 phase lookup to see if they
have
similar bugs/if I can create test cases to tickle them as follow-ups.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-05-29 19:21:22 +00:00
Jon Ross-Perkins 4cd0b85600 Update while tests, adding a bool min_prelude (#5550)
In the vein of #5455.

The bool min_prelude will probably also get used for other constructs,
like `if`.
2025-05-29 19:20:28 +00:00
Jon Ross-Perkins 560b5734a4 Add range flag settings to interop files (#5564)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.
2025-05-29 18:46:37 +00:00
Jon Ross-Perkins f8019d8b58 Add range flag settings to index files (#5561)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:45:46 +00:00
Jon Ross-Perkins 27aa0898e0 Add range flag settings to if_expr files (#5562)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:44:49 +00:00
Jon Ross-Perkins 825773dcb3 Add range flag settings to impl files (#5560)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:44:09 +00:00
Jon Ross-Perkins 4193c306a4 Add range flag settings to function files (#5558)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:43:14 +00:00
Jon Ross-Perkins 2e3fb4dc1c Add range flag settings to namespace files (#5566)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:42:44 +00:00
Jon Ross-Perkins 8fb5bcedd5 Add range flag settings to interface files (#5563)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:41:55 +00:00
Jon Ross-Perkins 0b8fa690cd Add range flag settings to let files (#5565)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:35:15 +00:00
Jon Ross-Perkins cef617ac02 Add range flag settings to facet files (#5557)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:33:37 +00:00
Jon Ross-Perkins 3fb4d9a468 Add range flag settings to class files (#5556)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:32:57 +00:00
Jon Ross-Perkins 6318987343 Add range flag settings to generic files (#5559)
Where `--no-dump-sem-ir` is used, change to `--dump-sem-ir-ranges=only`.
Otherwise, add `--dump-sem-ir-ranges=if-present` with a TODO to change
to `only`.

Note, SemIR is affected just because the extra comments change line
numbers in files where splits aren't in use.
2025-05-29 18:19:58 +00:00
Thomas Köppe f18fc40a32 Add missing standard library header inclusions (#5486)
Discovered by clang-tidy.

See also #5316.
2025-05-28 22:48:20 +00:00
Jon Ross-Perkins 270174cd82 Move the ir test (#5510)
This test has its own directory, since #3056. We haven't added any more,
so fold it into basics. Also simplify it a little using `else`, and
`no_prelude`.

Note, I'm not even sure how much we need this test given the
`%.loc<line>_<col>`, but I feel slightly worse deleting it.
2025-05-27 23:31:22 +00:00
Dana Jansens 69ab97d716 Don't wrap an ErrorInst as a subpattern of another pattern (#5542)
When a pattern is an error, avoid wrapping it as a subpattern in a
RefParamPattern or VarPattern. This allows further error handling to
observe the error occurred without having to unwrap it.

This avoids a crash when an invalid associated constant is written which
has a VarPattern in it. The associated constant machinery expects an
AssociatedConstantDecl but was getting a VarPattern with an ErrorInst
inside. Now it receives an ErrorInst directly, which it is already
looking for.

This choice means that `var` statements in an `interface` will always be
diagnosed as being non-constant, or as being a constant with a `var`, so
we don't need an extra diagnostic saying that `var` is not allowed in an
interface, as this just leads to two diagnostics on the same thing.

This crash was found by a fuzzer.
2025-05-27 18:13:12 +00:00
Jon Ross-Perkins 3946cac281 Update const tests for splits, preludes, and ranges (#5532) 2025-05-27 17:05:33 +00:00
Boaz Brickner 5095af991f Make MatchContext::WorkItem, CalleeFunction, InitRepr, ReturnTypeInfo Printable (#5535)
Found these to be useful for debugging.
2025-05-27 16:50:13 +00:00
Boaz Brickner 0a5dc9a9cc Use C++ trailing return type in toolchain/check/testdata/interop/cpp/no_prelude/function.carbon (#5541) 2025-05-27 16:20:00 +00:00
Jon Ross-Perkins 90649d60f0 Fix crash on 'destroy' with return type and no params (#5527)
Fuzzer-found crash
2025-05-23 19:33:06 +00:00
Jon Ross-Perkins 95ce06a7a4 Adjust KindHasGetConstantValueOverload approach (#5526)
Tinkering with #5517, splitting out this suggestion to try to avoid
delaying merge. I figured out what I was missing on the variadiac
expansion. :)

(and also realized the struct could probably be a function)
2025-05-23 17:58:08 +00:00
Jon Ross-Perkins cea9954e28 Update basics tests for ranges, splits, and min_prelude (#5509)
Updating tests in the style of
https://github.com/carbon-language/carbon-lang/pull/5455.

- Moving `Run`-specific tests into their own directory, with a README to
explain why it's unusual.
  - Note, I suspect we'll also get more over time (e.g., with arguments)
- This makes a little more use of `if-present` just because there are
more tests that want to print their full output.
- I'm combining the two empty-ish tests, thought I do still want the
*really* empty one to be fully empty (i.e., no tokens provided by the
file).
- Dropping multifile.carbon because it doesn't seem like an interesting
test to keep.
2025-05-23 17:50:02 +00:00
Dana JansensandJon Ross-Perkins 5aea18f949 Avoid resolving the decl block for specifics in imported instructions (#5517)
Move the operation of resolving the specific decl block from
`GetConstantValue()` to `TryEvalTypedInst()`, with is now happening
after replacing the fields of the instruction with new constant values,
but before running the evaluation of the instruction. Since imported
instructions are not evaluated, this avoids resolving the specific decl
block from imported instructions, resolving a TODO in
`AddImportedConstant()`. Now `AddImportedConstant()` can replace
constant values in its fields without having to worry about that
operation resolving any specific decl blocks.

We get to add a new TODO however, to explain why we still need a special
case in resolving specific decl blocks for handling `Impl` construction.
The witness table contains instructions with specifics referring to the
generic self of the impl declaration. But the table must be constructed
before the impl's generic is finished, in order to make the instructions
dependent for the generic. But then resolving the specific decl block
can't be done when the instructions are created and evaluated, as that
requires a finished generic.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-23 16:58:46 +00:00
Jon Ross-Perkins 2c013ada42 Update choice tests for ranges (#5525)
Note the amount of IR excluded is pretty small, but non-zero (mainly
prelude-related, due to the way a choice depends on `UInt`)

Renaming fail_todo_params.carbon to just params.carbon, and folding in
fail_invalid.carbon.
2025-05-22 22:34:12 +00:00
Jon Ross-PerkinsandDavid Blaikie b310958600 Update builtins tests for ranges (#5512)
Updating tests in the style of
https://github.com/carbon-language/carbon-lang/pull/5455.

Notable things for builtins:

- #4748 disabled semir output in int tests, but not other tests. After
discussion with zygoloid, adding ranges just for runtime calls that seem
significant. The rest can rely on type checking to demonstrate
correctness.
- Fixes cases of things like `RuntimeCallIsValidBadReturnType` using the
wrong number of args, and being invalid as a result.
- Splits out the too few, too many, and bad return type tests -- I think
this helps highlight where the above is an issue.
- Expands use of `library "[[@TEST_NAME]]";` in tests where package
names were previously in use.

Ranges tests were already updated for splits, so not really touching
that. Also, the prelude interaction gets a little gnarly because these
also partly test prelude bits.

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2025-05-22 21:31:56 +00:00
Jon Ross-Perkins 14227e7214 Refactor CollectNamesInBlock to put the switch on its own (#5503)
This refactors `CollectNamesInBlock` to pull out the lambdas and try to
give the switch its own function. I'm hoping that, on the whole, this
makes the flow a little easier to see.

This also moves `AnyBranch` handling into the switch, instead of before
the switch.

Note, I think the helper class approach is still a little complex, but I
believe it should be negligible cost. And I couldn't think of a better
way to translate the lambdas to helper functions without adding required
arguments at the call site, which I suspected might be a source of
readability friction.
2025-05-22 21:23:07 +00:00
Jon Ross-PerkinsandRichard Smith 65c1dcec5f Force -fPIE for compiles (#5521)
In LLVM, CLANG_DEFAULT_PIE_ON_LINUX is
[configurable](https://github.com/llvm/llvm-project/blob/main/clang/test/CMakeLists.txt#L8),
so change lowering to specify a value.

Also, adjust how the target is set so that function_decl.carbon isn't
trying to overload every flag, and so that the target isn't forgotten
elsewhere.

This is fixing issues introduced by #5427; note #5520 is also a related
fix.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-05-22 21:21:46 +00:00
Dana Jansensandjosh11b 950d83451a Add diagnostics for invalid impl declarations (#5420)
Outside of `match_first` this adds diagnostics for invalid non-final and
final `impl` declarations in line with those being proposed in
https://github.com/carbon-language/carbon-lang/pull/5337.

- Two non-final `impl`s with the exact same type structure is invalid.
- A `final impl` that matches the self/constraint of another `impl` as a
query would always be preferred, making the second one invalid.
- Two `final impl`s that overlap (have compatible type structures) in
different files is invalid.
- Two `final impl`s that overlap (have compatible type structures) in
the same file is invalid outside of `match_first`.
- A `final impl` in a different file from its root self type and
interface is invalid.

We add tests for all these scenarios as well as correct scenarios.

The "compatible" test for two type structures was being done
symmetrically, which is incorrect. We want it to test that a query type
structure is the same _or more specific_ in a compatible way with an
impl's type structure. This is corrected in the implementation, and the
diagnostics now have to test both directions to get the desired output,
as expected.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-05-22 18:58:47 +00:00
Richard Smith 6e7c035bef Stop emitting llvm.ident metadata saying the compiler was Clang. (#5520) 2025-05-22 18:48:58 +00:00
Dana Jansens f198b977f5 Give different inst id types different labels in CARBON_CHECK output (#5519)
For an `IdKind value`, `CARBON_CHECK(false, "{0}", value)` prints the
`Label` of the id type in place of the `{0}`. For different inst types,
we would like to display `TypeEnum(...)` with the actual inst type
rather than always `TypeEnum(inst)`. The latter is misleading,
suggesting the `IdKind` value is `InstId` when it may be `TypeInstId`,
or `MetaInstId`, etc.
2025-05-22 18:48:22 +00:00
Dana Jansens dd1b010b01 Add missing library in destroy_calls.carbon test file split (#5518) 2025-05-22 16:31:58 +00:00
Jon Ross-Perkins c0d31d428b Change range formatting to be more conservative about specifics (#5516) 2025-05-22 16:31:27 +00:00
Boaz Brickner 4901db832c Deduplicate getting the function in HandleInst() for Call (#5515)
Part of #5514.
2025-05-22 15:45:10 +00:00
Jon Ross-Perkins 66b51923d7 Update as tests for ranges, splits, and min_prelude (#5508)
Updating tests in the style of
https://github.com/carbon-language/carbon-lang/pull/5455.

I'm leaving adapter_conversion.carbon pretty much as-is because of the
`adapt_i32.carbon` test, which I'm not clear how critical `i32` is there
but feels specific enough that maybe it can't be `min_prelude`. Other
tests felt all pretty reasonable to adjust to `min_prelude` and a single
file (`basics.carbon`).
2025-05-21 22:26:05 +00:00
Jon Ross-Perkins c1eea8f2eb Update array tests for ranges, splits, and min_prelude (#5507)
Updating tests in the style of #5455.

array indexing requires integers, so this is a more prelude-dependent
area than some. But as it turns out, writing something like `3` never
references `Core.IntLiteral` so seeing if I can roll with more minimal
preludes.
2025-05-21 19:12:02 +00:00
Jon Ross-Perkins 0091c699a9 Unwrap FormatInst templating (#5505)
Now that `FormatInstLhs` and `FormatInstRhs` are no longer templated,
remove `FormatInst` templating.
2025-05-21 16:21:13 +00:00
Boaz Brickner 852d0191a9 Add support for importing C++ inline functions (#5427)
This requires:
* Making `FunctionDecl` mutable since generating code
(`HandleTopLevelDecl()`) requires a mutable declaration and since we
manually add `used` attribute to force code generation.
* Passing the file system to `Lower` since it's needed by Clang code
generation.
* Creating an internal Clang LLVM module and link it against the Carbon
LLVM module.

Demo:

```c++
// hello_world.h

extern int puts;
inline void hello_world() {
  ((int (*)(const char*))&puts)("hello world");
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

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

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o --output=demo
$ ./demo
hello world
```

Based on https://github.com/carbon-language/carbon-lang/pull/5406.

Part of #5405.
2025-05-21 07:02:05 +00:00
Richard Smith 5b884ae14d Improve lowering for global variables. (#5492)
- Track the `VarPattern` instruction on the `VarStorage` instruction so
that it's available for name mangling.
- Mangle global variables based on the first binding name within their
pattern.
- Give global variables external rather than internal linkage, except if
they have no bindings whatsoever in their pattern.
- To support lowering references to bindings nested within a global var,
such as for `var (x: i32, b: i32)`, add some basic initial support for
reference constant expressions. Treat a global `var` as a reference
constant, and treat an aggregate access into a reference constant as a
reference constant.
2025-05-21 00:09:10 +00:00
Jon Ross-Perkins 7c2a6ef0e9 Restructure FormatInstRhs to allow for better logic sharing (#5494)
Taking a stab at restructuring towards allowing better reuse. Some of
that is with `AnyAggregateInit` and `AnyImportRef`. Some with
`FormatDeclRhs`.

This adds a `FormatArg` dispatch table so that `FormatInstRhs` doesn't
rely as heavily on templating. I'm mixed on the intermediate result -- a
step further might be to change `FormatArg` to dispatch to a
`FormatArgAndKind` that could use a switch. But, figured I'd check in on
the general direction.

Note this kind of direction opens up changing `FormatInst` to not be
templated, too, removing the `#define CARBON_SEM_IR_INST_KIND(InstT)`
variant of `FormatInst`.
2025-05-20 23:05:23 +00:00
Jon Ross-Perkins 14f19b5a86 Use TypeEnum for ScopeId to refactor call structure (#5491)
I'm trying to make the offsetting a little easier to understand, and
also get a better `requires` structure on calls. The second is for an
attempt to refactor the `Formatter` API, but also changing the `InstId`
`derived_from` requires seems helpful for clarity on what's really
happening.
2025-05-20 22:16:28 +00:00
df36a555e8 Interface extension and final impl update (#5337)
We make 5 changes:

- Allow `require Self impls I` in an `interface` or `constraint` scope
to omit the `Self`, so it can be written `require impls I`.
- Rename `extend I` to `extend require impls I` in an `interface` or
`constraint` scope.
- Define `extend impl as I` and `extend final impl as I` in an
`interface` scope to copy the members of `I` and define an `impl` of `I`
in terms of the extending interface.
- Allow a non-final `impl` to overlap a final `impl` as long as it isn't
subsumed by the final `impl`. The final `impl` will be given priority on
the overlap.
- Allow `final` on a `match_first` block, used to declare overlapping
final impls.

These features work together to allow a form of interface extension
where:

- Types only need to `impl` the extending interface to also get an
`impl` of the extended interface.
-   Multiple interfaces can extend the same interface.
-   An interface can extend multiple interfaces.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
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>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-05-20 20:03:56 +00:00
Geoff RomerandJon Ross-Perkins bada271089 Updates to pattern matching for objects (#5164)
This proposal re-affirms (with additional rationale) that a `var`
pattern
declares a durable complete object, and refines the terminology for
binding
patterns in a `var` pattern to be more explicit about the intended
semantics. It
also makes several other changes and clarifications to the semantics of
pattern
matching on objects:

- The storage for a variable pattern is initialized eagerly, rather than
being
    deferred until the end of pattern matching.
- Any initializing expressions in the scrutinee of a `match` statement
are
    materialized before matching the `case`s.
- An initializing expression can only initialize temporary storage or a
single
variable pattern, not a tuple/struct pattern or a subobject of a
variable
    pattern. Removing this limitation is left as future work.

Finally, as a drive-by fix, it clarifies what parts of the `match`
design are
still placeholders.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-20 19:03:35 +00:00
Geoff Romer 515eb6b45b Better diagnostic message in CHECK (#5504) 2025-05-20 16:38:08 +00:00
Boaz Brickner c39efe321e Refactor toolchain/check/testdata/interop/cpp/no_prelude/function_decl.carbon (#5477)
Rename file and shard files to shorter name given context.
Add `todo_` to file shards where appropriate.
Add shard files section comments.
2025-05-20 16:15:49 +00:00
Jon Ross-Perkins 94d4ba682d Remove docker and devcontainer as unused (#5500)
As far as I'm aware, the the devcontainers aren't in frequent use, which
is why they fall out of date. Comparing with
https://github.com/llvm/llvm-project/, I don't see devcontainer configs
maintained as part of llvm
(https://github.com/llvm/llvm-project/issues?q=devcontainer doesn't have
much either) so I think we should trim these instead of investing in
maintenance.

These configs aren't being maintained. In the docker configs, note `RUN
bazel build //explorer` is broken. Also, #5496 noted the clang version
is out of date.

Closes #5496
2025-05-20 00:24:19 +00:00
Jon Ross-Perkins 27d0d26739 Replace value_kind with has_type, make FormatInstLhs name-dependent (#5501)
InstValueKind is really just wrapping HasTypeIdMember. Rather than
exposing this as an enum, expose it as a bool since it better reflects
what's going on.

In eval.cpp, AddImportedConstant should never be called on an untyped
instruction.

In FormatInstLhs, we can also depend on whether InstNamer has assigned a
name in order to decide whether to print an instruction. This should
avoid some divergence with CollectNamesInBlock.

We also discussed restoring InstValueKind::Untyped, but that's mainly
motivated by the formatter, and the InstNamer approach gives a more
localized implementation.
2025-05-19 23:26:32 +00:00
Geoff RomerandRichard Smith fbc5994750 Support importing var parameters (#5400)
This restructures the import and merge logic to support parameter
patterns in a more scalable way.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-05-19 22:50:16 +00:00
Boaz Brickner 8e666cea3e Add section descriptions in toolchain/check/testdata/interop/cpp/no_prelude/cpp_diagnostics.carbon as agreed in #5467 (#5497)
Part of #4666.
2025-05-19 21:39:57 +00:00
Jon Ross-Perkins fbaae723bc Collapse identical overloads of FormatInstLhs (#5495)
This is code sharing, but also removes some emphasize on templated call
structure.
2025-05-19 21:19:17 +00:00
Boaz Brickner 04d2643fd7 Reformat banner comments in toolchain/check/testdata/interop/cpp/function_param_*.carbon , following the agreed format in #5467 (#5498)
I've decided to keep `int` and similar as low case, as it refers to an
actual type.

Part of #5436
2025-05-19 21:17:23 +00:00
Geoff Romer 9e2ad3e454 Use GetWithAttachedType consistently in import (#5483)
This unblocks merging #5400.
2025-05-19 20:12:56 +00:00
Boaz Brickner 804613f6b7 Fix speicifc typo (#5499) 2025-05-19 14:57:13 +00:00
Boaz Brickner 6842c51fd1 Rename toolchain/check/testdata/interop/cpp/no_prelude/function_decl_inline.carbon and its shard files to simpler names (#5476)
Part of #5405.
2025-05-18 23:30:47 +00:00
Boaz Brickner 42f4d20e36 Improve toolchain/check/testdata/interop/cpp/no_prelude/namespace.carbon (#5478)
* Add // === headlines on group of file shards.
* Rename shard files to shorten given the file context them and add
`todo` where appropriate and group them together..
2025-05-17 15:17:41 +00:00
Jon Ross-Perkins 100a4f038d Update tests of alias for ranges, splits, and min_prelude (#5455)
Doing a few things here, to sound people out on a broader test cleanup:

1. Adding `--dump-sem-ir-ranges=<value>` to all files.
- The default is currently `if-present`. I'd like to change the default
to `only` in tests. Always setting it both makes it clear which tests
have been looked at as part of cleanup, and makes changing the default a
simpler "remove" action (versus "find changed tests and add lines").
- I'm only using `if-present` in import tests; ranges would hide
imported instructions, but I think the imported instructions are more
relevant in those.
2. Removing `--no-dump-sem-ir` uses.
- `--dump-sem-ir-ranges=only` has similar results to `--no-dump-sem-ir`,
so this is partly consolidating.
- Relying on the "only" value allows for easier combining of test files
into splits.
3. Evaluating where splits may be used.
    - Historically, we had to have each test be an individual file.
4. Preferring files with a split named `fail_` over files that use the
default name.
- I think this makes test files a little more consistently named, and
should ease the path if people want to add more split tests (vs pushing
people towards adding files).
- But I can switch back for single-split tests if the leaning is more
that we shouldn't repeat.

Specific to an `alias`, significant notes:

1. Consolidates several tests into a `basics.carbon` test.
- In there, adds a simple alias test; I didn't immediately see a trivial
test like that.
2. The "aliased_name_in_diag" test was no longer testing what it was
supposed to; however, there's "preserve_in_type_printing" so I'm
removing it as duplicative (vs switching to a min_prelude test).
3. Moves out a control flow test that didn't appear related to `alias`.
2025-05-16 23:22:10 +00:00
Jon Ross-Perkins e78a57bb82 Adjust formatting of blocks and scopes (#5474)
This is making two inter-related changes:

- Change `file` to reuse the formatter logic of `constants` and
`imports`, meaning empty `file` scopes will be omitted
- Mark `<elided>` sections in blocks (not in non-block scopes, because
they're not as sequential)
2025-05-16 22:50:28 +00:00
Alina Sbirlea e68d65d4f6 Get type in specific when lowering certain instructions. (#5493)
Fix handling of instructions where the type lookup has to be based on
the specific.
2025-05-16 22:25:50 +00:00
Jon Ross-Perkins dbf12eb3fc Add a SameAsOneOf helper (#5490)
Trying to make repeated `std::same_as` easier to write. Calling it
"concepts.h" because I figure we'll maybe have a couple more things like
this.

Was looking at this because I may add a couple more similar constructs.
2025-05-16 01:39:19 +00:00
Jon Ross-Perkins 5a3a977df4 Add more documentation to formatting (#5482) 2025-05-15 22:28:59 +00:00
Dana Jansens 1889ee3904 Add FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION to fuzzer mode and enable DCHECKs under fuzzing (#5489)
The `FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION` flag is a standard flag
proposed by LibFuzzer that is meant to inform compiled code that it is
being built for fuzzing, as described here:
https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode

We add the flag to our `fuzzing` feature/config, and enable DCHECKs when
under fuzzing so that we can catch bugs that currently are caught on the
other side of DCHECK, even if they don't cause ASAN to trap a read/write
beyond the capacity of a value store.
2025-05-15 19:53:06 +00:00
Jon Ross-Perkins ebc26dfad9 Update LLVM (#5487)
Also updates lowering tests
2025-05-15 19:14:53 +00:00
Dana Jansens e9823df130 Update the test comment explaining the fix for #5481 (#5488)
The fix for #5481 changed but the comment explaining what needs to
happen (and now happens due to the #5481 PR) was not updated.
2025-05-15 17:00:09 +00:00
Dana Jansens 4f59fb1346 Substitute into the type of BindSymbolicName or SymbolicBindingPattern (#5481)
When a `LookupImplWitness` instruction is created in a generic function
for a witness obtained from a `BindSymbolicName`, it stores the
`BindSymbolicName` as the query self type along with the interface it
obtained from it.

Later, when an argument is substituted into the `LookupImplWitness` in
deduction, and it is re-evaluated, the `BindSymbolicName` in the query
interface's specific arguments was being substituted, but the same
`BindSymbolicName` in the query self type was not. This was because we
did not substitute into the type of `BindSymbolicName`. In this case the
type is a `FacetType` which has inside it one or more specific
interfaces. The same substitution needs to be applied to both the
interfaces in the self type as to the interfaces in the query.

This issue was found by a fuzzer - though in a weirder and more invalid
way, by putting all of the code for our test case inside an `interface`,
which creates an implicit generic `Self` in the enclosing context and
yet makes it concrete inside a function body.
2025-05-15 16:30:32 +00:00
Dana Jansens 3d07794650 Gracefully error in non-compound member lookup into a runtime facet value (#5485)
And update tests to clarify that we should be able to do lookup into a
runtime facet value for an associated constant if the FacetType itself
provides that constant (with a `where` clause), but should not be able
to if it does not.

This fixes a fuzzer-found crash.
2025-05-15 16:25:53 +00:00
dependabot[bot] 723bb409df Bump undici from 6.21.1 to 6.21.3 in /utils/vscode in the npm_and_yarn group across 1 directory (#5484)
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.1 to 6.21.3
<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.21.3</h2>
<h2>What's Changed</h2>
<ul>
<li>[Backport v6.x] append crlf to formdata body by <a
href="https://github.com/github-actions"><code>@​github-actions</code></a>
in <a
href="https://redirect.github.com/nodejs/undici/pull/4210">nodejs/undici#4210</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v6.21.2...v6.21.3">https://github.com/nodejs/undici/compare/v6.21.2...v6.21.3</a></p>
<h2>v6.21.2</h2>
<h2>What's Changed</h2>
<ul>
<li>fix(types): add missing DNS interceptor by <a
href="https://github.com/slagiewka"><code>@​slagiewka</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/4024">nodejs/undici#4024</a></li>
<li>[v6.x] fix wpts on windows by <a
href="https://github.com/mcollina"><code>@​mcollina</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/4093">nodejs/undici#4093</a></li>
<li>Removed clients with unrecoverable errors from the Pool <a
href="https://redirect.github.com/nodejs/undici/pull/4088">nodejs/undici#4088</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/slagiewka"><code>@​slagiewka</code></a>
made their first contribution in <a
href="https://redirect.github.com/nodejs/undici/pull/4024">nodejs/undici#4024</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v6.21.1...v6.21.2">https://github.com/nodejs/undici/compare/v6.21.1...v6.21.2</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/nodejs/undici/commit/da0e823ac0e89390256d61c429df0cf236afb79e"><code>da0e823</code></a>
Bumped v6.21.4</li>
<li><a
href="https://github.com/nodejs/undici/commit/dbbe0a2d5004cd7b6016e52736f59ce37bdb1556"><code>dbbe0a2</code></a>
append crlf to formdata body (<a
href="https://redirect.github.com/nodejs/undici/issues/3625">#3625</a>)
(<a
href="https://redirect.github.com/nodejs/undici/issues/4210">#4210</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/b63d939953fe20cfd6718e8eed437da983ac7b12"><code>b63d939</code></a>
Bumped v6.21.2</li>
<li><a
href="https://github.com/nodejs/undici/commit/de1e4b8a39d102bb34155c3fdec3f18806b93d9c"><code>de1e4b8</code></a>
[v6.x] fix wpts on windows (<a
href="https://redirect.github.com/nodejs/undici/issues/4093">#4093</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/4e07dda835ffb2ff7a1b1323dd94c61b8feaa3c5"><code>4e07dda</code></a>
test: fix windows wpt (<a
href="https://redirect.github.com/nodejs/undici/issues/4050">#4050</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/133387138c9158d3b6e9493833986c34837035ad"><code>1333871</code></a>
Removed clients with unrecoverable errors from the Pool (<a
href="https://redirect.github.com/nodejs/undici/issues/4088">#4088</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/a0e76c73a8ecb913beea7e2210e40d12b7c5cf69"><code>a0e76c7</code></a>
fix(types): add missing DNS interceptor (<a
href="https://redirect.github.com/nodejs/undici/issues/4024">#4024</a>)</li>
<li>See full diff in <a
href="https://github.com/nodejs/undici/compare/v6.21.1...v6.21.3">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=6.21.1&new-version=6.21.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>
2025-05-15 15:48:07 +00:00
Dana Jansens 8b087738b7 Handle FunctionType and FunctionTypeWithSelfType in TypeIterator without crashing (#5480)
A fuzzer found that converting a pointer to a `FunctionTypeWithSelfType`
to `type` does an impl lookup and ends up in TypeIterator with the
`FunctionTypeWithSelfType` being iterated over in the self type, where
we crash. It's a valid type, so the iterator should be able to walk over
and return it.

We also constructed a similar example for `FunctionType`.
2025-05-15 13:25:38 +00:00
Boaz Brickner 4071372677 Improve toolchain/check/testdata/interop/cpp/no_prelude/{class,struct,union}.carbon (#5467)
* Add // === headlines on group of file shards.
* Rename shard files to shorten given the file context them and add
`todo` where appropriate.

Not splitting this file for now.

Part of #5150.
2025-05-15 09:01:18 +00:00
Dana Jansens 9d5575c920 Revert to Ubuntu 22 builders (#5479)
The Ubuntu 24 builders have a newer GLIBC than is present on the
compiler-explorer machines:
https://github.com/compiler-explorer/compiler-explorer/issues/7636#issuecomment-2880962252.
This results in the following error when running Carbon nightly:
```
/opt/compiler-explorer/carbon-trunk/bin/carbon: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.38' not found (required by /opt/compiler-explorer/carbon-trunk/bin/carbon)
```

To resolve this, we need to build Carbon in a sysroot with a compatible
glibc version, and the most straightforward way to do that is to bump
our builders back down to Ubuntu 22.

To do that, we can't use apt.llvm.org again, since Ubuntu 22 is no
longer supported there. So we revert back to pulling a Linux X64 tarball
from the LLVM GitHub Releases page. Instead of getting an
ubuntu-specific tarball (which does not exist), we grab the generic
Linux one, which seems to work fine.

Note that the binaries in the LLVM release package appear to depend on
glibc version 2.34, as determined by `objdump -T bin/clang|grep GLIBC_|
sed 's/.*GLIBC_\([.0-9]*\).*/\1/g' | sort -Vu`, so these binaries should
hopefully be okay to package with the Carbon toolchain for the
compiler-explorer machines as well.
2025-05-14 20:41:07 +00:00
Boaz Brickner 2b48033da7 Refactor toolchain/check/testdata/interop/cpp/function_decl.carbon (#5457)
* Split to 4 files: `function_param_int16`, `function_param_int32`,
`function_param_unsupported.carbon`, `function_return`.
* Add // === headlines on group of file shards.
* Rename shard files to shorten them and make them more consistent given
the file context.
* Deduplicate identical .h files and group their tests.

Potential future improvements:
* Split further. For example, pointers and references might be somewhat
separate from int primitives.
* Remove `import_` shard file prefix, as it repeats itself, but leaving
for now as it makes it more explicit.

Part of #5263
2025-05-14 16:00:27 +00:00
Jon Ross-Perkins dc61460b5a Change default flags for min_prelude tests (#5471)
I think this would probably have prevented the missed include in #5469
-- it would've just failed completely with a "missing prelude"
diagnostic.

Also note this excludes the included IR from output, because it's
probably low-value to print.
2025-05-13 18:02:24 +00:00
josh11bandJosh L 1769062c1c Clean up bazel config comment change made in #5459 (#5470)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-05-13 17:55:33 +00:00
Dana Jansens 55849f43f3 Make patterns/min_prelude/underscore.carbon into a min_prelude test (#5469)
The test was placed under a `min_prelude/` path prefix but the
--custom-core and min-prelude include had been omitted.
2025-05-13 17:30:19 +00:00
Jon Ross-Perkins 2f81858a36 Switch BuildData to char arrays (#5464)
string_view was suggested at
https://github.com/carbon-language/carbon-lang/pull/5451#discussion_r2080640267,
but it turns out it's helpful to be even more hermetic for build
configuration.
2025-05-12 23:46:02 +00:00
Chandler Carruth ad7ea48acd Pin the version of prettier used by pre-commit (#5463)
Without this, `npx prettier` can end up running some other version.
2025-05-12 22:26:31 +00:00
Dana Jansens fad008d5da Flatten TypeIterator::Step::Any to not use nested variants (#5453)
Instead of wrapping `ClassStart` with `StartOnly` or `StartWithEnd`,
provide both `ClassStart` and `ClassStartOnly`. Use inheritance to share
the fields. Initializing the subclass as an aggregate is still possible,
but requires an extra set of curlies.

This flattens the switch in TypeStructureBuilder::Build to a single
level.

Since this puts 19 elements in the Any variant, we need to extend the
CARBON_KIND_SWITCH support to more than 12 elements, so we bump it up to
24.

This was suggested by @jonmeow here:
https://github.com/carbon-language/carbon-lang/pull/5430#discussion_r2078444685
2025-05-12 19:27:20 +00:00
Jon Ross-PerkinsandChandler Carruth b1004012c3 Add linkstamp support to get the target name (#5451)
This removes hardcoding of the test target name from file_test.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-05-12 19:01:01 +00:00
Dana Jansens 517c4d3c20 Remove VariantMatch; use CARBON_KIND_SWITCH for std::variants (#5437)
Teach CARBON_KIND_SWITCH to handle mutable lvalues and rvalues, and
CARBON_KIND to forward along rvalues so that it's possible to write
`case CARBON_KIND(const T& t)`, `case CARBON_KIND(T& t)`, and `case
CARBON_KIND(T&& t)`, depending on the type that was passed to
CARBON_KIND_SWITCH.

Replace all uses of VariantMatch with their equivalent of a switch using
CARBON_KIND_SWITCH, and remove the VariantMatch helper from the
codebase.
2025-05-12 18:56:52 +00:00
Dana Jansens 010efd2e40 Preserve the is_final bit when importing an impl declaration (#5461)
We were importing all impls as non-final, since we forgot to set the new
field when constructing the imported Impl. Adds a test that fails before
this PR, since the imported Impl is treated as non-final.
2025-05-12 18:10:36 +00:00
Jon Ross-Perkins d5db325d19 Remove old clang-format workaround for attr on enum (#5460)
The underlying https://github.com/llvm/llvm-project/issues/85476 is
fixed, and appears to format as desired with the current clang-format
version.
2025-05-12 16:54:41 +00:00
Dana JansensandRichard Smith b24944bfba Allow using CARBON_KIND_SWITCH on a std::variant (#5433)
We use CARBON_KIND_SWITCH for handling the output of TypeIterator in the
TypeStructureBuilder

Here is how the errors look when it is misused:
- If you don't cover ever type in the variant with a case
  ```
Enumeration value 'VariantTypeT1NotHandledInSwitch' not handled in
switch
  ```
Is attached to the CARBON_KIND_SWITCH() usage, the `T1` being a 0-based
index into the std::variant's type list, indicating which type was
missed.
- If you have a case for a type that is not in the variant
  ```
In template: constraints not satisfied for class template
'ValidCaseType' [with T = char]
  ... bunch of instantiation stuff ...
kind_switch.h(124, 12): Because 'char' does not satisfy
'TypeFoundInVariant'
  ```
Where `char` was the type I put in the `CARBON_KIND` macro, which was
not in the variant.
- If you have too many types in your variant (currently > 12)
  ```
In template: static assertion failed due to requirement 'sizeof...(Ts)
<= 12': CARBON_KIND_SWITCH supports std::variant with up to 12 types.
Add more if needed.
  ```
  Is attached to the CARBON_KIND_SWITCH() usage.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-05-12 16:26:55 +00:00
Dana Jansens a7841eabc8 Require clang 19 in bazel (#5459)
Now that we're using Clang 19 in our CI tests (since
https://github.com/carbon-language/carbon-lang/pull/5440), require 19+
in the bazel rules.

Drop support for the old hardening flags for libc++ in Clang 16 and 17.
2025-05-12 16:18:17 +00:00
Jon Ross-Perkins 7aeaa24874 Switch clang-tidy config comment format (#5458)
With the clang-19 minimum, we can intermingle comments.
2025-05-12 16:08:24 +00:00
Jon Ross-Perkins cc416171e2 Have FormatScopeIfUsed consider ranges before printing (#5454)
If there will be no in-scope instructions printed, have
`FormatScopeIfUsed` skip the relevant scope.

Note, this only affects constants and imports. It's not changing the
file scope, which is usually printed when empty.
2025-05-12 15:55:03 +00:00
Dana JansensandJon Ross-Perkins f5e69734d9 Bump clang version to 19 (#5440)
The version of clangd/clang-tidy on developer machines has slowly
diverged from the one on the CI builders, which is causing a slowly
increasing amount of pain as clang-tidy CI runs fail (incorrectly) over
things that a newer clangd/clang-tidy was perfectly fine with locally.
This bumps the Clang version used in the ubuntu builders to 19, which is
the most recent in Debian stable.

We use https://apt.llvm.org instead of LLVM's GitHub releases
(https://github.com/llvm/llvm-project/releases) as the former more
reliably has packages for newer Clang/LLVM versions on x64. The
community-build releases binaries on LLVM's GitHub have stopped
including Ubuntu packages that match the GitHub x64 Ubuntu workers for
some time (for at least the 18 and 19 releases).

By moving to apt.llvm.org packages we only download and install the
headers and libraries needed for development, rather than every output
of building llvm, which is much faster and saves lots of disk space. We
also remove the system installations of other versions of clang/llvm so
we should end up using negative disk space. We can no longer easily
cache the installation but apt.llvm.org is a reliable end point.

We bump the ubuntu image version for the github workers to 24.04, as
apt.llvm.org has stopped building images for 22.10 in 2022 at its end of
life.

The `pre_commit` workflow disabled sudo unlike the other workflows that
install Clang/LLVM, including the `clang-tidy` workflow (which is also
run on `pull_request`). We bring it into alignment with the other
workflows so that we can install the llvm packages. And we lock its
ubuntu image to 24.04 so that it can be moved in lockstep with the other
workflows that depend on Clang/LLVM.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-12 15:12:53 +00:00
Jon Ross-Perkins 937caaecce Add --dump-sem-ir-ranges for controlling dump output (#5450)
Right now, a lot of tests have started setting `--no-dump-sem-ir`. My
thought is that we can look at:

1. Put ranges in a bunch more files.
2. Shift more towards `--dump-sem-ir-ranges=only` instead of
`--no-dump-sem-ir`, because it allows mixing fail-tests with no IR
alongside tests that contain IR.
3. Evaluate switching the default to `--dump-sem-ir-ranges=only`, and
instead set `--dump-sem-ir-ranges=if-present` only in files that want to
typically show all IR (particularly import-related tests, where ranges
don't work well).

In real-world use, my thought is also that it'd be helpful to be able to
add the dump range comments to files, see the output (i.e., the default
behavior of `if-present`) but then also be able to pass `ignore` in
order to see the full IR without modifying the file (possibly also
useful in tests). That model is why I went for tri-state handling.

Note `only` can also have an interesting side-effect. Because core files
(including min_prelude versions) typically won't have ranges, they'd be
implicitly excluded.
2025-05-12 14:51:10 +00:00
Dana Jansens b6a55c0818 Diagnose impls that are fully overlapped by a final impl (#5417)
Such impls will never be used, so they should not exist. And test that a
final impl partially overlapping a non-final impl is accepted.

There is a question about a final impl partially overlapping a final
impl that is part of
https://github.com/carbon-language/carbon-lang/pull/5337
2025-05-10 17:36:28 +00:00
Dana Jansens ccc94439e5 Don't reuse the reference into the ImplStore after doing deduce (#5456)
Deduction can import stuff which can invalidate all of the value stores.
Refactor out the code that diagnoses unused generic bindings, and scope
the reference into the ImplStore so it can't be used after. Fetch the
impl from the store again when setting the witness to error afterward if
needed.
2025-05-09 20:35:18 +00:00
Richard Smith 69b9982e95 Convert discarded calls in thunks. (#5452)
No functionality change right now: we reject thunks where the signature
has no return type and the callee has a return type. But discarding the
expression is still the right thing to do.
2025-05-09 16:35:28 +00:00
Boaz Brickner 2cb0df42e0 Add C++ interop inline function tests (#5406)
This shows that `inline` is ignored and the function definition is not
generated.

Demo:

```c++
// hello_world.h

inline void hello_world() {}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

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

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o --output=demo
ld.lld: error: undefined symbol: hello_world()
>>> referenced by main.carbon:8
>>>               main.o:(main)
error: linker command failed with exit code 1 (use -v to see invocation)
```

Part of #5405.
2025-05-09 16:33:16 +00:00
Ivana Ivanovska f8443ae09e [Carbon/C++ interop] Add support for C++ type short (#5393)
Added support for `short`/`int16_t`. Both function parameters and return
values this type will be supported.

Demo:

```c++
// hello_short.h

#include <cstdint>
auto foo_short(int16_t a) -> int16_t;
```

```c++
// hello_short.cpp

#include "hello_short.h"
#include <cstdio>

auto foo_short(int16_t a) -> int16_t {
    printf("a = %i \n", a);
    return a;
}
```

```c++
// main.carbon

library "Main";

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

fn Run() -> i32 {
  var a: i16 = 3;
  Cpp.foo_short(a);
  return 0;
}
```

```
$ clang -c hello_short.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link hello_short.o main.o --output=demo
$ ./demo
a = 3 
```

Part of #5263
2025-05-09 08:51:46 +00:00
71715263ce Add build option --features=poison_value_stores. (#5438)
With this enabled, entities that live in value stores are poisoned
whenever any action is taken that might invalidate pointers and
references to those options -- in particular, adding another item to
that value store, or attempting to load any entity from an import IR.
Subsequent uses of those pointers or references then trigger an ASan
failure.

This detects latent bugs where the pointer or reference to the entity
would become stale if we got unlucky about when the value store
reallocates, even in cases where the reallocation didn't actually
happen.

This is not enabled by default: it finds a lot of latent bugs, so our
tests don't pass with this option. This PR also includes fixes for a few
of those bugs.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-05-08 21:07:04 +00:00
Richard Smith 04505f4a64 Don't CHECK-fail when emitting IR with cross-file locations. (#5447)
If a function contains instructions whose locations are in another file,
skip providing debug locations for those instructions rather than
CHECK-failing.

This happens when emitting a thunk where the signature is declared in
one file and the call target is in another file: some parts of the thunk
use the original signature as their locations, whereas other parts of it
use the location of the call target.
2025-05-08 20:16:51 +00:00
Dana Jansens e6a6624ec6 Include concrete non-type values in the type structure and use for impl candidate selection (#5431)
Non-type values were being represented as "Concrete" in the type
structure's shape, which was incorrect when the value was symbolic. Now
they are represented as "Concrete" or "Symbolic" as appropriate.

When concrete, a matching concrete ConstantId is stored in the type
structure's concrete values, so that they will be used for equality
comparison. And then impl matching comparison is taught to look in the
concrete values for mismatches when it finds a "Concrete" or
"ConcreteOpenParen" shape on both sides of the comparison, and return
false if they are not equal. This reduces the number of candidate impls
selected in impl lookup, which avoids doing type deduction against impls
that won't match anyway due to the concrete values in the query not
matching concrete values in the impl. As a result we see fewer specifics
being generated in the semir.
2025-05-08 18:41:36 +00:00
Dana Jansens a9a94b03ac Pull type iteration out into a TypeIterator, build the TypeStructureBuilder on it (#5430)
The TypeStructureBuilder recursively iterates through a type, interface,
or facet value and constructs a type structure that includes each
concrete and symbolic value found. This iteration is a more general
thing that can be useful elsewhere. For instance, to get just the root
type out of a general type, it is the result of the first iteration
step.

We abstract out the iteration logic into a SemIR::TypeIterator to create
a clear boundary between the work of iterating and the work of building
the TypeStructure from it.

Along the way this pointed out some issues in the TypeStructureBuilder
where it could have ambiguity between types that include non-type
values. So we add some tests for these cases, and they now pass. There
are also TODOs left behind, as concrete TypeStructure is overly specific
right now in order to keep these tests passing, which means that the
concrete elements can't be used for impl lookup matching yet. Only the
shape of concrete vs symbolic is used for now, and then type deduction
is used to compare the actual concrete types, which could be skipped
when the concrete values could be compared directly and reject an impl
for not matching.
2025-05-08 16:46:45 +00:00
Jon Ross-Perkins 74c0ed413c Update tool versions beyond just bazel (#5446)
#5445 updates to bazel 8.2.1, this does more updates (including to
buildifier, which does autofixes like the `sh_test` loads in the other
PR).

Note I'm using the latest available clang-format wheel. That's not
really something I expect people to have installed, but should mostly be
consistent. I'm specifically skipping clang-format 18 because it had
some broad regressions, and 19 got really confused by a `requires` on a
trailing return. Using the latest seemed probably okay since most people
won't see the difference. Do note that trailing returns in macros,
https://github.com/llvm/llvm-project/issues/47664, seems to be cropping
up again as an issue.
2025-05-08 16:24:28 +00:00
Ivana Ivanovska afea14d14d [Carbon/C++ interop] Add more tests for int function params support (#5392)
Added tests for `signed int`, `signed`, `std::int32_t` and `const int&`.
This is an addition to PR #5197.

Part of #5064
2025-05-08 13:57:34 +00:00
Jon Ross-Perkins 1bb5fe73f0 Update to bazel 8.2.1 (#5445)
- Updates incompatible flags.
- `rules_flex` is no longer used, so enable its flag.
- Fixes `sh_test` deps for
`--incompatible_disable_autoloads_in_main_repo`
- Broadens the exception for `rules_cc` and `bazel_tools` due to changes
to runfiles deps; trying to avoid minutiae that shouldn't affect the
decision.
2025-05-08 00:10:14 +00:00
Jon Ross-Perkins ae16332a11 Fix handling of null StringRef file buffers (#5428)
The current behavior hits UBSAN and ASAN issues.

Note, `RequiresNullTerminator` is already set to `false` in
`source_buffer.cpp`; setting it in `compile_helper.cpp` is making things
more consistent. The related logic is an [assert
fail](https://github.com/llvm/llvm-project/blob/main/llvm/lib/Support/MemoryBuffer.cpp#L52).

This was fuzzer-discovered.
2025-05-07 22:42:58 +00:00
Richard SmithandJon Ross-Perkins 66caff2c26 Make the file_test binary work without custom environment variables. (#5442)
Instead of crashing when run outside of `bazel`, make the toolchain's
`file_test` binary work properly when no test-specific environment
variables are set. This makes it a lot easier to run `file_test` under a
debugger.

There are two main changes here:

- Don't crash if `$TEST_TMPDIR` is unset. Instead, fall back to LLVM's
temporary directory (typically `$TMPDIR`). We already did this in some
places in tests. We now do it in more places.
- Don't fall back to a target label of `<target>` in the reproduction
commands if `$TEST_TARGET` is unset, because this causes all the tests
to fail because their output doesn't match the expected output due to a
differing bazel run command. Instead explicitly specify the target from
the `FileTestBase`-derived class.

Infrastructure for this has been added generally, but only rolled out to
the toolchain `file_test` binary for now.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-07 22:28:13 +00:00
Richard Smith f2a16d8742 Don't crash if a builtin fn is declared with positional parameters. (#5444)
Crash discovered by fuzzer.
2025-05-07 22:27:29 +00:00
Richard SmithandJon Ross-Perkins e060342411 Defer building thunks until the end of the enclosing definition. (#5403)
Instead of building the definition of a thunk immediately when we
generate the thunk declaration, wait until we reach the `}` of the
outermost class, interface, etc. -- at the same time when we would parse
the definition of the thunk if it were defined inline.

This fixes issues where we fail to define the thunk because it requires
an enclosing class to be complete, or its definition depends on
something declared later in the enclosing class.

Make the representation of a suspended function scope, and its
constituent suspended components, be move-only, and switch to passing it
around by rvalue reference instead of by value because it's expensive
both to move and especially to copy.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-07 22:20:39 +00:00
Jon Ross-Perkins 6f32a003d2 Remove needs_substitution logic (#5443)
This is fixing a deduce crash, with regression tests added in
binding_pattern.carbon. In `needs_substitution`, it adds the
`BindSymbolicName` with the compile time bind index corresponding to the
wrong generic scope, which causes a bad result. It appears
`needs_substitution` logic is no longer needed (per zygoloid,
`CheckDeductionIsComplete` handles related issues) so can be removed.

This changes the order of IR in use_assoc_const.carbon but the result
appears equivalent to me.

This was a fuzzer-found crash.
2025-05-07 22:13:33 +00:00
8c4ff33cb1 The name of an impl in class scope (#5366)
```
class C {
  impl as I;
}
```

is redeclared

```
impl C.(as I)
```

for purposes of `match_first`/`impl_priority` blocks and definitions.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-05-07 17:30:51 +00:00
Richard Smith 32e68cfb5b Fix debug location for variable allocas and lifetime markers. (#5432)
`IRBuilderBase::SetInsertPoint` weirdly replaces our debug location with
one copied from the new insertion point, so undo its damage after
calling it.

Also included: a couple of cleanups I made while tracking this down.
2025-05-06 21:26:59 +00:00
Jon Ross-Perkins 7b9ec95118 Print ubsan stack traces (#5429)
Ran into this trying to debug #5428 

Before:

```
lex.cpp:793:21: runtime error: null pointer passed as argument 1, which is declared to never be null
string.h:90:51: note: nonnull attribute specified here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior lex.cpp:793:21
```

After:

```
lex.cpp:793:21: runtime error: null pointer passed as argument 1, which is declared to never be null
string.h:90:51: note: nonnull attribute specified here
    #0 0x5572db22a680 in Carbon::Lex::Lexer::MakeLines(llvm::StringRef) /proc/self/cwd/toolchain/lex/lex.cpp:793:14
    #1 0x5572db227ee4 in Lex /proc/self/cwd/toolchain/lex/lex.cpp:738:3
(etc)

SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior lex.cpp:793:21
```

Interestingly, even though this is labelled as UB, it's using the
ASAN_SYMBOLIZER_PATH (specifically not LLVM_SYMBOLIZER_PATH). But
canonically UBSAN_SYMBOLIZER_PATH may also be used per
https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/ubsan/ubsan_flags.cpp#L53,
so I'm adding it to the list out of an excess of caution.

Also doing some small related cleanup:

- Removing `ASAN_SYMBOLIZER_PATH` from `--test_env` because it should
now be getting overridden by these settings (also was a little
inconsistent in that `LLVM_SYMBOLIZER_PATH` was not included).
- Improving the environment construction and documentation.
2025-05-06 17:39:42 +00:00
josh11bandJosh L c455dbef54 Clean up KeywordModifierSet after #5345 (#5425)
See comment
https://github.com/carbon-language/carbon-lang/pull/5345#discussion_r2074260967

> `Impl` is already a part of `Method` and refers to using `impl` as a
modifier keyword on virtual methods (to be replaced by `override`, see
#5253 ), as opposed to `ImplDecl` which is the modifiers allowed on an
`impl` declaration. It would make more sense to delete this than use
`Impl` here.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-05-06 16:56:06 +00:00
Richard Smith 8b0f9e503e Add mangling support for thunks. (#5424)
A thunk may have the same mangling as the function that it's a thunk
for, so add `:thunk` to the mangling to disambiguate.
2025-05-05 21:48:51 +00:00
Dana Jansens 08065ee764 Do a stable sort when splitting up impls by interface (#5423)
Keep the impls for each interface in the order that they were declared.
This ensures that the resulting diagnostics will be deterministic.
2025-05-05 20:51:27 +00:00
Dana Jansens f9e7564d37 Avoid unused case variable (#5421) 2025-05-05 20:15:20 +00:00
Richard SmithandJon Ross-Perkins c49789d80b Don't use GetCanonicalLocId when determining what instruction an instruction was imported from. (#5418)
The canonical location of the instruction may be an entirely different
instruction, which the instruction in question was not imported from. In
particular, we shouldn't assume that we can use the constant value of an
instruction that the *location* of an imported instruction refers to as
the constant value of the imported instruction.

The only time we should be looking at the `ImportIRInstId` for a `LocId`
is when determining its location in some other file.

Fixes a crash when importing thunks (which can contain instructions
whose location points to an instruction in a differnt IR).

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-05 19:58:30 +00:00
Dana JansensandJon Ross-Perkins aa491d8fd8 Implement non-final impl overlap diagnostics (#5412)
When two non-final impls have the same type structure (neither is a
specialization of the other), it is an error unless they are within a
`match_first` block. For now, we don't have `match_first` implemented,
so it's always an error.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-05 19:01:41 +00:00
Dana Jansens 9cdc9d4538 Add test for impl lookup on struct types with different field names and orders (#5416)
This test demonstrates the scenarios discussed in
https://github.com/carbon-language/carbon-lang/issues/5413
2025-05-05 18:57:09 +00:00
Dana Jansens 25946868bd Add tests for where you can or can't write a final impl (#5419)
A final impl must be written in the same file as the root self type or
the interface. This provides tests that should fail but don't yet for
writing a final impl in a third file that defines neither, as well as a
blanket final impl over an interface outside the file that defines the
interface.
2025-05-05 18:23:54 +00:00
ed863d6eae Forward impl declaration of an incomplete interface (#5168)
Revise rules for what is required and provided by declarations and
definitions of interfaces and impls. In particular:

-   allow `impl` declarations of incomplete interfaces, and
- shift from a "use the information from the type definition if it
happens to be complete" model to a "only use the information from the
definition in contexts where it is required to be defined or complete"
model.

Resolves questions-for-leads issues
[#4566](https://github.com/carbon-language/carbon-lang/issues/4566),
[#4672](https://github.com/carbon-language/carbon-lang/issues/4672),
[#4579](https://github.com/carbon-language/carbon-lang/issues/4579).

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-05-03 19:42:33 +00:00
Jon Ross-Perkins 1b96e40b63 Update LLVM version (#5415)
Fixes a compile failure with the new version, essentially:

```
external/+llvm_project+llvm-project/llvm/include/llvm/Support/FormatVariadicDetails.h:157:1: error: implicit instantiation of undefined template 'llvm::support::detail::missing_format_adapter<clang::LookupResultKind>'
```
2025-05-02 23:07:50 +00:00
Jon Ross-Perkins 0683742f19 Cache multi-IR info, particularly include_in_dumps (#5408)
Right now we construct `tree_and_subtrees_getters` a couple different
ways, it's just not obvious because one's abstracted in `check`. But
also, when formatting IR, we'll repeatedly do the `IncludeInDumps`
string check, which felt odd to me since it only needs to be calculated
once per IR.

This also shifts `CheckIRId` selection a little earlier, and in doing so
makes `CheckParseTrees` accept a sparse `units` argument. I actually
think this is a positive: it makes `CheckIRId` a little more stable
across possible command lines, when file loading fails (which is the
only time that a file will have a `CompilationUnit` but not a
`Check::Unit`).

Trying to build on the shared issue between these, I'm adding a
`MultiUnitCache` to store the calculated arrays. For the subtree
getters, this is very minor and avoids at most one incremental array
construction (moving logic out of `CompileSubcommand::Run` might be the
bigger benefit). For `include_in_dumps`, when dumping SemIR, this is
changing a calculation run once per entity (in each IR) to be calculated
once per IR (globally), i.e. O(M*N) -> O(N).

Note this seems to be marginal for performance of file_test:

- Before: Stats over 10 runs: max = 5.3s, min = 4.7s, avg = 4.9s, dev =
0.2s
- After: Stats over 10 runs: max = 4.9s, min = 4.7s, avg = 4.8s, dev =
0.1s

I was mainly thinking about this in the context of dumping SemIR ranges.
There, the impact may actually decrease because a range won't do any
cross-IR printing. But, I'm expecting to add another layer for whether
we're printing IR for a file, and that made the `should_format_entity`
callback stick out for me.
2025-05-02 22:53:46 +00:00
Richard Smith abda0cbc38 Minor simplification. (#5414)
Avoid checking whether the import IR is already known twice --
`AddImportRef` does that check.
2025-05-02 20:17:32 +00:00
Dana Jansens 90898a8e19 Avoid witnesses in redecls when handling errors in handle_impl (#5409)
When we fill the witness table with errors, set the witness id to an
error too, which signals to impl lookups to not use the impl.

Make the use of the `Impl` from the store more consistent once it's been
added to the store (or known to be there already).
2025-05-02 19:49:06 +00:00
Jon Ross-Perkins 1f268b5d8b Consolidate token-related range handling to one struct (#5399)
This consolidates Lex::TokenizedBuffer::DumpSemIRRange and
Parse::TreeAndSubtrees::TokenRange into a single InclusiveTokenRange,
also making the OverlapsWithDumpSemIRRange function take the new struct.

I considered switching to `llvm::iterator_range<Lex::TokenIterator>`,
but we often want to see if the range is size one. Using `TokenIterator`
just looked like it'd add a bunch of offsetting to make it work; I view
that as low-value overhead.

For example:

```
  Lex::InclusiveTokenRange token_range = GetSubtreeTokenRange(node_id);
  auto begin_loc = tree_->tokens().TokenToDiagnosticLoc(token_range.begin);
  if (token_range.begin == token_range.end) {
    return begin_loc;
  }
  auto end_loc = tree_->tokens().TokenToDiagnosticLoc(token_range.end);
```

would become:

```
  llvm::iterator_range<Lex::TokenIterator> token_range = GetSubtreeTokenRange(node_id);
  auto begin_loc = tree_->tokens().TokenToDiagnosticLoc(*token_range.begin());
  if (token_range.begin() + 1 == token_range.end()) {
    return begin_loc;
  }
  auto end_loc = tree_->tokens().TokenToDiagnosticLoc(*(token_range.end() - 1));
```

So I'm keeping the bespoke struct.
2025-05-02 18:47:02 +00:00
Geoff Romer 34a9e24920 Restore disabled CHECK in pattern handling. (#5410)
I believe this was unblocked by #5320, but it was overlooked at that
time.
2025-05-02 18:08:43 +00:00
Jon Ross-Perkins 6469f67b14 Switch to a constant-time approach for dump ranges, tracking node parents (#5394)
- Adds parent information as a single-pass calculation
  - Moves off `GetSubtreeTokenRange` because it's O(N)
- Stops using the node's subtree when formatting a single instruction
- This excludes `%F.call` and the following `return`, for example,
because only parameters are marked for formatting
2025-05-02 17:01:10 +00:00
Jon Ross-Perkins f27c202305 Set ASAN_SYMBOLIZER_PATH in addition to LLVM_SYMBOLIZER_PATH (#5407)
Not sure why these are handled separately, but they are.
2025-05-02 15:06:48 +00:00
Boaz Brickner 2aa5fbfa4a Move the logic in TryConvertClangDiagnosticLoc() to ConvertLocInFile() (#5391)
Make `AbsoluteNodeId` support Clang source locations.

Part of #5245.
2025-05-02 08:08:11 +00:00
Richard Smith cab91d0590 Don't require a thunk for parameter name differences. (#5404)
When checking whether we can use the function in an impl directly to
satisfy a signature in an interface, allow the parameter names to differ
between the two declarations.
2025-05-02 03:01:00 +00:00
Richard SmithandJon Ross-Perkins 95903dc624 Generate thunks for functions in impls (#5390)
Generate a thunk when a function in an `impl` has a different signature
than the function in the interface. This follows the design in
[#3763](https://docs.carbon-lang.dev/proposals/p3763.html#impl-members-vs-interface-members),
although some of the checks described there are not yet implemented.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-05-01 22:17:55 +00:00
Richard SmithandDana Jansens 4f5d11a28b Build generic eval blocks incrementally (#5313)
Instead of building an eval block as a separate pass at the end of a
generic, build the eval block incrementally.

The larger change here is that asking for the type or constant value of
an instruction now always returns an unattached type or constant value,
in order to preserve the behavior that we previously achieved by doing
the rewrite to attached types and constant values at the end of handling
the generic.

This also incidentally fixes some subtle issues where attached types and
constant values would leak out into check and cause it to get confused
about differences between attached and unattached values. Check should
no longer see attached values except where it explicitly asks for them.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-05-01 20:24:15 +00:00
Richard Smith 797b14eb8e Import ImplWitnessTable into the imports block instead of the constants block. (#5374)
Don't import `ImplWitnessTable` into the `constants` block, because we
generally don't put `Unique` constants there. This matches the handling
of the other kinds of `Unique` constants. In order to keep the
instruction visible in formatted SemIR, add it to the `imports` block
instead.

Also fix a bug in the instruction formatter that resulted in
instructions in the `imports` block being omitted from the output if
they were only referenced by earlier instructions in the `imports` block
and by instructions in the `constants` block. This was already resulting
in some referenced instructions being omitted from the output, but also
occurred frequently for `impl_witness_table` instructions after this
change because it is common for the only reference to those instructions
to be from `impl_witness` instructions in the `constants` block.
2025-05-01 00:08:43 +00:00
Geoff Romer 34887403ab Model patterns as constant values (#5385)
This will enable us to simplify support for parameter and return
patterns in import, which operates primarily on constants.
2025-04-30 22:32:41 +00:00
Jon Ross-Perkins 500cf63d0d Remove the stack from postorder tree printing (#5396)
I was thinking about this while working on parent generation on #5394
(which does a similar loop), it's just a simplification.

Also remove surplus spaces in the preorder print.
2025-04-30 20:31:28 +00:00
Jon Ross-Perkins 64e0760275 Remove unnecessary abs (#5395)
Noticed while working on #5394
2025-04-30 19:03:09 +00:00
Richard Smith 5226f3d14a Factor out GetInstWithConstantValue and use it from another place that duplicates the same logic. (#5388) 2025-04-29 23:28:46 +00:00
Richard Smith 98ee8f365e Update documentation to match #5355. (#5376) 2025-04-29 22:47:00 +00:00
Jon Ross-Perkins 8eae40646a Add formatter support for dump-sem-ir ranges (#5379)
This prints instructions that are inside the range, and entities that
overlap with the range. Note this can lead to incomplete printing of
entity contents.
2025-04-29 22:18:52 +00:00
Dana JansensandRichard Smith 13da710e94 Poison impl lookup queries with concrete results (#5373)
Once a concrete result has been found, it's not legal to write an `impl`
that would change the concrete result afterward.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-29 21:55:11 +00:00
Jon Ross-Perkins bd99b74608 Adds a bazel query to retry syncing deps (#5386)
Trying to improve resilience against failures such as:

```
INFO: Repository rules_jvm_external+ instantiated at:
  <builtin>: in <toplevel>
Repository rule http_archive defined at:
  /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_tools/tools/build_defs/repo/http.bzl:392:31: in <toplevel>
ERROR: /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_tools/tools/build_defs/repo/http.bzl:137:45: An error occurred during the fetch of repository 'rules_jvm_external+':
   Traceback (most recent call last):
	File "/home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_tools/tools/build_defs/repo/http.bzl", line 137, column 45, in _http_archive_impl
		download_info = ctx.download_and_extract(
```


https://github.com/carbon-language/carbon-lang/actions/runs/14719625211/job/41311145495?pr=5379

It looks like GitHub currently has a high rate of these, which it
shouldn't, but also maybe we can do a little more to weather these
service issues.

To show flag behavior:

```
╚╡./scripts/run_bazel.py --attempts=5 --retry-all-errors :foo
Command ':foo' not found. Try 'bazel help'.
Retrying exit code 2 because it may be transient...
Command ':foo' not found. Try 'bazel help'.
Retrying exit code 2 because it may be transient...
Command ':foo' not found. Try 'bazel help'.
Retrying exit code 2 because it may be transient...
Command ':foo' not found. Try 'bazel help'.
Retrying exit code 2 because it may be transient...
Command ':foo' not found. Try 'bazel help'.

╚╡./scripts/run_bazel.py --attempts=5 --retry-all-errors query //... | wc -l
INFO: Invocation ID: ffdf9480-0245-442d-885f-ee91a3d86b68
Loading: 0 packages loaded
367

╚╡./scripts/run_bazel.py --attempts=5 :foo
Command ':foo' not found. Try 'bazel help'.
```

On the last run, [test (ubuntu-22.04,
opt)](https://github.com/carbon-language/carbon-lang/actions/runs/14737410033/job/41366888473?pr=5386)
has an example of this working:

```
INFO: Invocation ID: 3f276297-6dc5-4007-a333-dcadd4db55f4
 no actions running
 no actions running
 no actions running
 no actions running
 no actions running
 no actions running
 no actions running
 no actions running
 no actions running
WARNING: Download from https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz failed: class java.io.IOException GET returned 618 jwt:jwt-not-provided
INFO: Repository bazel_skylib+ instantiated at:
  <builtin>: in <toplevel>
Repository rule http_archive defined at:
  /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_tools/tools/build_defs/repo/http.bzl:392:31: in <toplevel>
ERROR: /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_tools/tools/build_defs/repo/http.bzl:137:45: An error occurred during the fetch of repository 'bazel_skylib+':
   Traceback (most recent call last):
	File "/home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_tools/tools/build_defs/repo/http.bzl", line 137, column 45, in _http_archive_impl
		download_info = ctx.download_and_extract(
Error in download_and_extract: java.io.IOException: Error downloading [https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz] to /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_skylib+/temp62784[869](https://github.com/carbon-language/carbon-lang/actions/runs/14737410033/job/41366888473?pr=5386#step:5:887)09382546624/bazel-skylib-1.7.1.tar.gz: GET returned 618 jwt:jwt-not-provided
 no actions running
 no actions running
ERROR: Error loading '@@rules_python+//python/extensions:python.bzl' for module extensions, requested by /home/runner/work/carbon-lang/carbon-lang/MODULE.bazel:147:23: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/rules_python+/python/extensions/python.bzl:48:6: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/rules_python+/python/private/python.bzl:17:6: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_features+/features.bzl:3:6: Encountered error while reading extension file 'globals.bzl': no such package '@@bazel_features++version_extension+bazel_features_globals//': no such package '@@bazel_skylib+//lib': java.io.IOException: Error downloading [https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz] to /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_skylib+/temp6278486909382546624/bazel-skylib-1.7.1.tar.gz: GET re
ERROR: Error loading '@@rules_cc+//cc:extensions.bzl' for module extensions, requested by https://bcr.bazel.build/modules/rules_cc/0.1.1/MODULE.bazel:12:29: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/rules_cc+/cc/extensions.bzl:16:6: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_features+/features.bzl:3:6: Encountered error while reading extension file 'globals.bzl': no such package '@@bazel_features++version_extension+bazel_features_globals//': no such package '@@bazel_skylib+//lib': java.io.IOException: Error downloading [https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz] to /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_skylib+/temp6278486909382546624/bazel-skylib-1.7.1.tar.gz: GET returned 618 jwt:jwt-not-provided: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/rules_cc+/cc/extensions.bzl:16:6: at /h
ERROR: Error loading '@@rules_python+//python/extensions:python.bzl' for module extensions, requested by /home/runner/work/carbon-lang/carbon-lang/MODULE.bazel:147:23: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/rules_python+/python/extensions/python.bzl:48:6: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/rules_python+/python/private/python.bzl:17:6: at /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_features+/features.bzl:3:6: Encountered error while reading extension file 'globals.bzl': no such package '@@bazel_features++version_extension+bazel_features_globals//': no such package '@@bazel_skylib+//lib': java.io.IOException: Error downloading [https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz] to /home/runner/.cache/bazel/_bazel_runner/8f839eaeb716f9d034eabdfa7ebecdb0/external/bazel_skylib+/temp6278486909382546624/bazel-skylib-1.7.1.tar.gz: GET re
INFO: Invocation ID: e2062912-715f-47ec-a0bc-9d1b4fee9e5d
 no actions running
 no actions running
 no actions running
 no actions running
 no actions running
 no actions running
<root> (carbon@_)
Retrying a failure because it may be transient...
INFO: Invocation ID: 7d4ee250-882f-480d-9c8d-2d92e67462fc
Loading: 0 packages loaded
367
```
2025-04-29 20:22:47 +00:00
Jon Ross-Perkins 828eccebba Switch dump-sem-ir-start to dump-sem-ir-begin (#5378)
Simply about consistency with begin/end naming.
2025-04-29 20:06:58 +00:00
Jon Ross-Perkins 5eae636a33 Stop mutating the original tests array when sorting. (#5387)
`FileTestCase` remembers its matching test by pointer, which breaks down
when `tests_` is sorted.
2025-04-29 20:04:13 +00:00
Jon Ross-Perkins e3c1b57118 Make children of InstId directly use the FormatName overload (#5375)
Based on #5372, where I noticed this.
2025-04-29 19:49:14 +00:00
Jon Ross-PerkinsandDana Jansens 5da87f43da Split SemIR's formatter class into a more typical h+cpp (#5372)
Trying to make it easier to see the API at a glance. The class has
become really long, and this doesn't fundamentally change that, but
hopefully makes it easier to navigate. The entry structure also had some
cruft that I'm removing.

I'm trying to keep functions in the same order as they currently are.
The delta still looks unhappy because of the churn, but hopefully this
at least explains the ordering in formatter.h. You can try using the
"Add indent" commit on the PR to see a better before-after delta.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-04-29 18:00:07 +00:00
Boaz Brickner 8ba3da9730 Fix "is is" typo (#5382) 2025-04-29 15:32:17 +00:00
Dana Jansens e2984d9fc3 Avoid ToTokenOnly for the AddrSelfIsNonRef diagnostic (#5371)
The location of the diagnostic is an instruction id, not a parse node.
Converting to a parse node to call ToTokenOnly will drop the descendents
of the instruction being diagnosed, but the diagnostic is about the
whole instruction not just the root parse node of whatever instruction
it happens to be.
2025-04-29 15:25:27 +00:00
Geoff Romer 7c85397f8b Stop treating symbolic binding patterns as constants (#5361)
This was originally needed to support constant evaluation of name
expressions, but that's now done in a different way.

This is actually a step toward treating all patterns as constants. The
upcoming change will do so in a slightly different way, and so it will
simplify the review to start from a baseline where patterns are never
constant.
2025-04-28 23:45:15 +00:00
Ivan Duranandjosh11b 13a522f608 Document lambdas (#5300)
Moved everything from "Syntax Overview" through "Self and Recursion" in
https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p3848.md
to docs/design and added the link to it in README.md

Still needs a short summary for the README

Closes #4898

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-04-28 20:13:27 +00:00
Dana JansensandJon Ross-Perkins 315e206ff1 Construct LocId from InstId directly (explicitly) instead of doing lookups when possible (#5355)
Remove calls to `InstStore::GetLocId()` to build a LocId from an InstId
now that they can be constructed directly from the InstId. Most uses of
LocId are just plumbing, so this does not affect them. However places
that want to look inside the LocId do not want to work with the InstId
form. In these places, introduce `InstStore::GetResolvedLocId()` which
converts a LocId (or an InstId as an optimization) into a LocId which is
not backed by an InstId. These locations can be printed (they have a
line and column when they are a NodeId), they can have flags added to
them (`ToImplicit`, `ToTokenOnly`), they can be converted to an
underlying ImportIRInstId, or they may be `None`.

`Dump()` is made to print a resolved location instead of printing the
InstId in the location, since (at least in my experience) the resolved
location is what is interesting in debugging, and this saves manual
`MakeInstId` steps in the debugger every time a location is of interest.

The LocId constructor from InstId is made `explicit` to add clarity to
function calls passing an `inst_id` now directly instead of calling
`context.insts().GetLocId(inst_id)`. To avoid needing to construct
`SemIR::LocId(...)` explicitly in all cases though, the diagnostics code
in Check uses `DiagnosticLocId` as its template parameter which accepts
InstId as well and does the construction of LocId from it.

Because LocId now requires an explicit construction from InstId, any
callers to `AddInst()` functions will have to explicitly convert to
LocId if they had an InstId, but not if they pass a NodeId. To make this
difference clear to callers, we `requires` that the input type can be
converted to LocId. This ensures that passing an InstId results in an
error at the callsite where the InstId is passed, instead of generating
a compiler error when trying to construct `LocIdAndInst` inside
`AddInst()`, which is less clear about what went wrong and doesn't seem
entirely intentional.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-04-28 19:06:24 +00:00
Geoff Romer fafb655d39 Separate pattern types from expression types (#5360)
This is a step toward treating patterns as compile-time constants, so
that we can import them more easily.
2025-04-28 16:54:37 +00:00
Boaz Brickner 84384cf126 Remove exceptions for performance-enum-size (#5370)
This is a followup of `performance-enum-size` disablement in
https://github.com/carbon-language/carbon-lang/pull/5368.
2025-04-28 15:45:54 +00:00
Jon Ross-Perkins 70659fe350 Default FileTest to brief output (#5364)
Trying to make it easier to skim test output for failures. Note this
excludes all the RUN and OK. Failing tests may still be verbose due to
the diff printed, but CHECK-fails should become short.

```
==================== Test output for //toolchain/testing:file_test:
Running tests with 128 thread(s)
...
Done!
[==========] 1272 tests from 1 test suite ran. (688 ms total)
[  PASSED  ] 1272 tests.
================================================================================
```
2025-04-28 15:16:47 +00:00
Boaz Brickner 0647d0e045 Properly link to the discussion in the TODO (#5369)
Followup of https://github.com/carbon-language/carbon-lang/pull/5262.

Part of #5245.
2025-04-28 14:25:45 +00:00
Boaz Brickner 63b14ee245 Disable clang-tidy performance-enum-size (#5368)
See discussion in
https://github.com/carbon-language/carbon-lang/pull/5352 and
https://discord.com/channels/655572317891461132/655578254970716160/1365319438198378577
2025-04-28 12:16:19 +00:00
josh11bandJosh L e52b51e66a Forbid virtual methods with compile-time parameters in the design (#5365)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-04-26 03:30:25 +00:00
Jon Ross-Perkins 7181a37997 Make it easier to see test performance (#5363)
Trying to make it easier to see possible bottlenecks.

Disabling hyperthreading seems like a significant reduction in
contention (15% improvement for me). Going down by half again reduces a
contention a little further, but not significantly from what I see. My
thought is that just flipping the flag is going to work best for people
cross-system versus a "divide by four", but welcome to other opinions
there. Note, I'm not digging into the source of the contention here,
just observing it.

Current default on my system (equivalent to `--threads=128`):

```
Running tests with 128 thread(s)
...
Ran 1272 tests in 3955 ms wall time, 397615 ms across threads
```

Disabling hyperthreads (equivalent to `--threads=64`):

```
Running tests with 64 thread(s)
...
Ran 1272 tests in 3520 ms wall time, 161957 ms across threads
```

`--threads=32`:
```
Running tests with 32 thread(s)
...
Ran 1272 tests in 3329 ms wall time, 69327 ms across threads
```

And for `./autoupdate_testdata.py --threads=64 --print_slowest_tests=5`:

```
Running tests with 64 thread(s)
...
Ran 1272 tests in 3417 ms wall time, 157946 ms across threads
  Slowest tests:
  - toolchain/lower/testdata/function/generic/call_recursive_basic.carbon: 1508 ms, 1484 ms in Run
  - toolchain/lower/testdata/builtins/print_read.carbon: 1506 ms, 1506 ms in Run
  - toolchain/lower/testdata/array/field.carbon: 1488 ms, 1487 ms in Run
  - toolchain/lower/testdata/builtins/int.carbon: 1482 ms, 1475 ms in Run
  - toolchain/lower/testdata/function/definition/params_one.carbon: 1472 ms, 1471 ms in Run
```

In test:

```
==================== Test output for //toolchain/testing:file_test:
Running tests with 64 thread(s)
...
Ran 1272 tests in 2968 ms wall time, 177732 ms across threads
  Slowest tests:
  - toolchain/lower/testdata/builtins/int.carbon: 1544 ms, 1533 ms in Run
  - toolchain/lower/testdata/array/function_param.carbon: 1539 ms, 1537 ms in Run
  - toolchain/lower/testdata/basics/zero.carbon: 1537 ms, 1536 ms in Run
  - toolchain/lower/testdata/function/call/params_one.carbon: 1535 ms, 1534 ms in Run
  - toolchain/lower/testdata/function/definition/params_zero.carbon: 1531 ms, 1531 ms in Run
[==========] Running 1272 tests from 1 test suite.
[----------] Global test environment set-up.
```
2025-04-25 22:06:18 +00:00
Jon Ross-PerkinsandRichard Smith d617cca530 Factor out GetCanonicalFileAndInstId for code sharing. (#5362)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-25 20:04:49 +00:00
Jon Ross-PerkinsandRichard Smith 949cc21ccc Remove SemIR:: from most sem_ir files (#5358)
This is just cleanup, at least some from LocId replacements.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-25 16:06:10 +00:00
Boaz Brickner d2826ae841 Disable clang-tidy modernize-use-ranges (#5359)
See discussion in
https://github.com/carbon-language/carbon-lang/pull/5353
2025-04-25 13:31:08 +00:00
Boaz Brickner 609ccefd18 Introduce a Clang diagnostic instruction and use it to point to C++ source locations on Clang errors and warnings (#5262)
Introduce `ImportIRId::Cpp` and refer to clang source location in its
`ImportIRInst`.

Part of #5245.
2025-04-25 13:05:45 +00:00
David BlaikieandJon Ross-Perkins 1e2d4c3405 Reject generic virtual functions (#5356)
Not entirely sure what the SemIR representation for this should be - do
we put the bogus thing in the vtable, and just not lower it later? The
patch currently doesn't add the function to the SemIR vtable - which
then means you could find a virtual function that's not in the vtable,
which seems similarly confusing.

I guess we could make the function non-virtual?

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-04-25 00:07:35 +00:00
Jon Ross-PerkinsandDavid Blaikie a342e5c117 Add lexing for dump-sem-ir-start and end (#5357)
Syntax rationale is on `DumpSemIRRange` to try and record this, since
I'm not sure this belongs in the language design. The intent of this is
to be able to subset SemIR, which will be done separately in the
formatter.

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2025-04-24 22:17:04 +00:00
Jon Ross-Perkins fb39e3c569 Adjust patch indent for buildifier (#5354)
Noticed from
https://github.com/carbon-language/carbon-lang/pull/5338/files/5bac558d8d9bd8adbfdd5e9e44bf7a24d75e1d8d..e0d2089c86df1fb2e97c58d727b7f531f952829b#diff-bab6d9fe4c98e775b8a74edf0079d3052a11faf16c133b69172181744e537d81R25
2025-04-24 17:03:19 +00:00
Boaz Brickner 23d92c05ca Fix clang-tidy: move assignment operators should be marked noexcept [performance-noexcept-move-constructor,-warnings-as-errors] (#5266) 2025-04-24 15:37:24 +00:00
Jon Ross-Perkins 8512e9198e Fix single-threaded runs for single test (#5350)
Typo fix.

```
$ bazel test :file_test_base_test --test_output=all
...
Running tests with 128 thread(s)
...
$ bazel test :file_test_base_test --test_output=all --test_arg=--gtest_filter=FileTestBaseTest.testing/file_test/testdata/two_files.carbon
...
Running tests with 1 thread(s)
...
```
2025-04-24 00:58:09 +00:00
David Blaikie 77c5f63be7 Skip upfront emission of vtables for generic classes (#5349)
These will need to be emitted lazily, as we do for functions - this
addresses the crash/removes the impossible (because we don't have a
specific) non-lazy path.
2025-04-23 22:55:07 +00:00
David Blaikie b00a037c52 Mangle impls even if they impl an interface with associated constants (#5348)
Fixes issue #5307
2025-04-23 22:08:54 +00:00
Jon Ross-Perkins 281e79e83b Prepare tests for adding a prelude dependency to destruction (#5346)
Adds an empty `min_prelude/destroy.carbon` in anticipation of turning it
into an interface. Update `no_prelude` tests to be `min_prelude` and
import it where needed; in some cases, modify the file to remove the
dependency (i.e., rewrite code to have nothing to destruct).
2025-04-23 21:41:59 +00:00
josh11bandJosh L 367c210871 Test clean up follow up to #5320 (#5344)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-04-23 20:03:36 +00:00
Jon Ross-PerkinsandGeoff Romer 03e693873b Detect control flow in entities nested inside functions (#5336)
Right now, return_scope_stack is being used to determine whether logic
is in a function scope. However, we need to handle nested entities
inside function scopes. For example where this crashes right now:

```
base class C(B:! bool) {}

fn F() {
  class B {
    extend base: C(true or false);
  }
}
```

This is doing a few things to make this kind of code not crash:

- Split `scope_stack().Push` into `PushForDeclName`, `PushForEntity`,
`PushForExpr`, and `PushForFunction` so that better decisions can be
made about behaviors.
- Hide `return_scope_stack` in the API, instead using interfaces to get
at the underlying data.
- Also using `PushForFunction` to update it similar to the other stacks
that `ScopeStack` manages.
- Add `IsInFunctionScope` as the best way to determine presence in
function scope.
- Remove `PeekIsLexicalScope` since destruction really wants function
scope information anyways.
- Clean up `destroy_id_stack` handling to be for function scopes rather
than lexical scopes.
- Return after related `context.TODO`s in a couple more spots, so that
code doesn't proceed to add control flow in spite of the lack of
support.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-04-23 19:03:53 +00:00
51498547c9 Always use LookupImplWitness instructions for symbolic witnesses (#5321)
We eliminate the `FacetAccessWitness` instruction, which would sometimes
immediately evaluate to a concrete `ImplWitness`, and sometimes remain
symbolic. This instruction is now replaced by `LookupImplWitness` in all
cases. To support the same use cases, when it is evaluated,
`LookupImplWitness` will look in the self value if it's a facet value,
and attempt to return a concrete `ImplWitness` from it before looking
for an `impl` statement.

The `LookupImplWitness` instruction's value is now canonical, even when
it evaluates to a symbolic `LookupImplWitness` instruction, by
canonicalizing the self value of the lookup query. This canonicalization
unwraps `FacetAccessType` and `FacetValue` instructions to get to an
underlying canonical facet value. However we must preserve and use the
non-canonical query while evaluating the instruction in order to look
for a concrete `ImplWitness` if the query self value was a concrete
`FacetValue`. The canonicalization ensures that symbolic witnesses
obtained from a facet value are compatible with those obtained from an
impl statement, as long as the self types originate from the same
canonical facet value though they may have been narrowed.

Member access now unconditionally does a `LookupImplWitness()`
operation, instead of only sometimes doing the lookup for a final impl
declaration.

`EvalImplLookupResult` is marked `[[nodiscard]]` so that we don't
construct it and forget to return it. This was a mistake made at one
point during the creation of this PR. And the `has_concrete_value()`
method no longer has a precondition that `has_value()` is true, since we
want to look for a concrete result only in the new use of
`EvalImplLookupResult` returned from lookup into the query self facet
value.

The TODO from `FacetAccessWitness` evaluation is addressed by ensuring
the index of the witness in the `FacetValue` comes from the required
interfaces of the `FacetValue`'s type, and that the type (a `FacetType`)
is the same facet type used in the query to construct the `FacetValue`'s
witness block. This is made possible by eliminating the
`FacetAccessWitness` indirection. The lookup into a `FacetValue` happens
while evaluating `LookupImplWitness` and it does so directly on the self
value. This gives a consistent view of the witness set and the facet
type, as they both come from the same instruction.

All of this with 400 less lines of code. :)

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-23 16:39:09 +00:00
Dana Jansens 94dca7967b Allow extend final impl as for impl declarations (#5345)
In a class, an `impl as` can now be both `final` and `extend` instead of
only one or the other.

In https://github.com/carbon-language/carbon-lang/issues/5319 we decided
this is already allowed by the design but was an oversight in the
implementation.
2025-04-23 15:20:18 +00:00
Richard Smith ca8df34d0d Format the call parameters of a function, not the patterns. (#5342)
This makes the parameters printed in a SemIR `fn` declaration match the
arguments printed in a SemIR `call` instruction.
2025-04-22 18:52:21 +00:00
Geoff Romerandjosh11b f5b5731c76 Separate fields from other var decls in parse (#5320)
This enables us to decouple class fields from pattern matching.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-04-22 17:15:53 +00:00
josh11bandJosh L b477797239 Clarify generic design about the type before as (#5341)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-04-22 00:04:48 +00:00
Richard Smith 5501424524 Collect per-entity names when processing the entity, not each declaration. (#5340) 2025-04-21 23:36:57 +00:00
Richard Smith 64baa84e4d Stop substituting into MetaInstId operands. (#5328)
A `MetaInstId` is intended to represent a handle to an instruction in a
generic as an operand to a template action; substituting into the action
should not substitute into the referenced instruction.

Fixing this exposed a bug in `GetOrAddInst` where it would return an
`InstId` of an unattached symbolic constant in some cases, rather than
the `InstId` of an instruction that has the relevant (attached) constant
value. That's fixed for now by turning off the `GetOrAddInst`
optimization in that case, but in future we can refine this by adding
the instruction to the eval block for the generic only, and not to the
body of the generic.
2025-04-21 21:19:14 +00:00
Richard Smith b5ae988a08 Add builtins for compound assignment operators. (#5335)
Provide builtins for compound assignments instead of defining them in
the prelude as a use of a binary operator and an assignment. This allows
us to lower compound assignment directly to LLVM operations instead of
producing a function call. In the short term this also allows us to
define a type-generic compound assignment in the prelude.
2025-04-21 20:38:11 +00:00
Chandler Carruth 2bdea71c25 Simplify freeing with new LLVM (#5334)
We now have upstream support for a clean way to forcibly enable freeing
memory in a library context, so use that.
2025-04-18 22:05:25 +00:00
Richard Smith 89c9714825 Fix handling of member types of generic classes. (#5332)
Instead of evaluating a non-parameterized class or interface to a
constant with `SpecificId::None`, use the self specific for that class
or interface, which will not be `None` if there is an enclosing generic.
2025-04-18 15:09:50 +00:00
Dana Jansens 9a6c74f0cd Introduce FindIfOrNull() FindIfOrNone() and Contains() (#5322)
`FindIfOrNull` returns a pointer to the element in the range if it's
found, and nullptr otherwise. `FindIfOrNone` returns a copy of the
element in the range if it's found, and `T::None` (for a range of
elements of type `T`) otherwise. `Contains` returns a bool indicating
whether the element in the range is found.

These functions replace `llvm::find()` and `llvm::find_if()` when you
want a single answer back instead of an iterator. This avoids the need
to check against `end()`, allowing the return condition to be tested as
a standard bool.

We replace uses of `find()` and `find_if()` that did not require an
iterator with these new helpers.

Note that the return type of `FindIfOrNull` is a pointer since we can
not write `optional<T&>`, which must be tested for null. If the null
check is omitted, UB occurs and the resulting code may end up with an
incorrect pointer (https://crbug.com/40153300) into the range (or
elsewhere), rather than a null dereference. And this would be very
confusing to debug. Hopefully debug builds and sanitizers keep this from
being an issue we sink a bunch of time into debugging.
2025-04-18 14:17:48 +00:00
Chandler Carruth 55705aaef8 Update LLVM, picking up new -disable-free flag logic (#5333)
This requires fixing some uses of deprecated APIs.
2025-04-18 03:49:27 +00:00
josh11bandJosh L 034e374f0a Add TODOs re: pattern_block_id to inst_namer.cpp (#5331)
From
https://github.com/carbon-language/carbon-lang/pull/5310#discussion_r2045291737

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-04-18 00:58:31 +00:00
josh11bandJosh L dfd5fe368d Fix comment typo in toolchain/sem_ir/inst_kind.h (#5330)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-04-17 22:54:13 +00:00
josh11bandJosh L ecb99e55e7 definitions_required -> definitions_required_by_decl in toolchain/check/check_unit.cpp (#5329)
Updates message to reflect changes in #5090 .

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-04-17 22:48:37 +00:00
Richard Smith 19532967fa Stop pushing a fake generic for the duration of check. (#5326)
This fake generic was used for two reasons:

- The declaration name stack assumes that each declaration name is
processed within a generic scope. This is important if the name might
have generic parameters, which are always parsed even for declarations
that disallow them in check.
- Out-of-line redeclarations of generic entities produce instructions
with symbolic constant values in non-generic scopes.

The former case is addressed by pushing a generic each time we start a
declaration name, even if we will reject generic parameters later. The
latter case is worked around for now by not building a symbolic constant
type or value for instructions that appear outside of any generic, and
will be addressed more completely by #5310 and follow-ups.
2025-04-17 21:58:37 +00:00
Dana Jansens 886dc842f0 Make toolchain/check/testdata/facet/no_prelude/access.carbon into a min-prelude test (#5327) 2025-04-17 21:25:17 +00:00
Dana Jansens c3e112e664 Document and configure running lldb from the command line (#5324)
The docs explain that you must use `--local-lldbinit` in the command
line, and include an example of how to run a file_test under lldb from
the command line.

This PR includes `.lldbinit` file and `lldbinit.py` file which set up
our default options, copied from the VSCode launcher.

The instructions include settin the `max-string-summary-length`, and we
include this in the vscode launcher for lldb, as printing `Dump()`
output can easily get truncated otherwise when printing an InstBlockId.
2025-04-17 21:18:25 +00:00
Dana Jansens 84a0060447 Allow a struct/tuple type literal to implicitly convert into a facet value (#5325)
We already had conversion in place to implicitly convert these literals
to `type`. Now they can also convert to `FacetType`. This is done by
first doing a conversion to `type` and then converting that type value
to `FacetType`.
2025-04-17 20:56:36 +00:00
Dana Jansens c38e723dd8 Rename singleton InstId constants to TypeInstId (#5323)
These constant instructions are all TypeInstId already in their type,
and this makes their names match.

Change the name of MakeSingletonInstId as well and update its comment.
2025-04-17 18:57:20 +00:00
Thomas Köppe bf32da8dad Add missing standard library header inclusions (#5316)
Discovered by clang-tidy.
2025-04-17 15:37:57 +00:00
David Blaikie f45a632d77 Implement virtual call dispatch (#5308)
Adds a `virtual_index` to `SemIR::Function` used to determine which
vtable slot
to use when calling the given function.

Then use that to lower the function call to use the vtable and
specifically the
relative vtable ABI to match the vtable entries.
2025-04-17 14:42:30 +00:00
Richard SmithandJon Ross-Perkins 48dc411776 Stop using Add*InstInNoBlock during import. (#5317)
`Add*InstInNoBlock` adds an instruction in the current context,
including adding its type and constant to the current generic eval block
if necessary. This is inappropriate during import, because the current
generic is generally not related to the instructions we're importing.

Previously we worked around this by pushing a placeholder generic onto
the generics stack, but that workaround doesn't interact well with
building generics incrementally. Instead, change the import code to
create instructions directly instead of via `Add*InstInNoBlock`.

This also allows a little simplification, because all the import logic
created imported instruction locations in the same way.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-04-16 23:56:08 +00:00
Jon Ross-Perkins 401c72a5c3 Allow no-op functions to have unused arguments (#5318)
For example, we might want `[self: Self]` to be ignored.
2025-04-16 22:03:21 +00:00
Jon Ross-Perkins 4923445e3a Drop Singleton from ErrorInst::SingletonInstId and similar (#5304)
We frequently want to operate on singletons. Per discussion, drop
`Singleton` to make the code shorter.

This started off as wanting to write `inst_id.is_error()`, but the
dependency relationship between ids.h and singleton_insts.h would
require some kind of delayed evaluation to allow the implementation to
remain in headers (which I suspect is helpful to have for inlining). I
could have added something like `IsErrorInst`, forward declared in ids.h
and defined in singleton_insts.h (which would always be included by
typed_insts.h), but the template approach felt like a decent balance
between (a) removing the boilerplate `::SingletonInstId`, (b)
understandability, (c) still visually mirroring if we immediately return
a singleton, and (d) flexibility for more than just `ErrorInst`. But TBH
I'd probably still have written `is_error()` if it didn't require
addressing the cross-header cycle.

Then I tried `SemIR::InstId::Is<SemIR::ErrorInst>`, which generally
worked with types but generated the complaint that it didn't shorten
*all* singleton uses. So pulling back on `::Is`, and instead just
dropping `Singleton`.
2025-04-15 22:40:29 +00:00
Jon Ross-Perkins 838417e358 Update check_deps roots (#5311)
- Add pkg rules to the search, specifically so that we can pull the full
release tar instead of the busybox binary.
- Shift the tree_sitter exclusion to the script, so that it's easier to
use the script.
- tcmalloc_if_linux_opt isn't really interesting (it's referenced by
.bazelrc).
- Misc tiny changes to the query, just to simplify it.
2025-04-15 22:33:29 +00:00
Jon Ross-Perkins 72cfaad1c7 Remove the indirect_value library (#5312)
This was used by explorer, and no longer has uses.
2025-04-15 20:16:58 +00:00
Jon Ross-Perkins dc8fab1d81 Refactor PerformCall (#5302)
`PerformCall` has gotten a little long, 130 lines; splitting out some
functions to help size. `PerformCallToFunction` in particular seems
symmetric with `PerformCallToGenericClass` and
`PerformCallToGenericInterface`.
2025-04-15 17:20:32 +00:00
Jon Ross-PerkinsandChandler Carruth b49e89e97e Add a no-op builtin function which shouldn't generate code. (#5306)
This is part of a broader plan to have noop destructor functions for
trivial destruction.

Note this emits a SemIR call (`%no_op: init %empty_tuple.type = call
%NoOp.ref() [concrete = constants.%empty_tuple]`), but not LLVM IR. My
thought was this was probably okay, since even though it'll be a little
spammy with destructor calls, the flipside is there'll probably already
be a fair amount for the name reference, and this at least shows when
the call is injected (and discarded).

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-04-15 00:33:39 +00:00
Dana Jansens da83b65aa2 Concrete impl takes precedence over a facet value (#5305)
If a concrete impl is found via lookup, its associated constants should
be used over the constants found through a facet value.
2025-04-14 18:48:55 +00:00
Dana Jansens afa946aefa Specialization test with final assoc constant can pass now (#5303) 2025-04-14 16:10:17 +00:00
Alina Sbirlea 02e9ac21bf Fix type when lowering associated constants. (#5295)
Get type in specific when lowering associated constants. This resolves
crash when getting type for type_id is not found, when the query is for
a specific.
Note: Currently lowering only supports mangling of impls that can viewed
as a single interface (single ImplConstraint).
2025-04-14 15:55:12 +00:00
Dana Jansens eabe1cf9b8 Avoid crashing when a NamespaceType is in a type structure (#5301)
NamespaceType is not valid to use as an argument for generics, but when
it's there handle it gracefully through to the diagnostic.

Found by fuzzer.
2025-04-14 14:59:27 +00:00
Jon Ross-Perkins 55da026a46 Remove the SemIRLoc typedef (#5299)
Replace SemIRLoc typedef uses with explicitly SemIR::LocId, loc ->
loc_id for consistency.
2025-04-14 14:28:15 +00:00
Jon Ross-Perkins 77cbcd0aa8 cc_toolchains has defs.bzl, fix references (#5297) 2025-04-14 14:22:02 +00:00
Jon Ross-Perkins 9759387a13 Collapse GetAbsoluteNodeId overload (#5298)
Since LocId can handle a NodeId, this overload isn't really needed
anymore. Probably helpful to simplify.
2025-04-12 00:30:19 +00:00
Dana Jansens f0663715dd Even more usage of TypeInstId (#5296)
Use TypeInstId in many more places where the instruction is required
to/known to always be a type value. This should be a somewhat exhaustive
set of places, as it covers all instructions given to
GetTypeIdFromTypeInstId().

The things of interest here are:

- Singleton instructions are always of type TypeType, so they are now
TypeInstIds.
- ErrorInst::SingletonInstId gets upcast to be an InstId because it's
sometimes used to define the type of a variable (as in `auto inst_id =
SemIR::ErrorInst::SingletonInstId;` that may hold other InstIds.
- Parse nodes don't really know about TypeInstId, so NodeStack::Push
needs to do some special casing to avoid CHECK failures when given a
TypeInstId but expecting an InstId. We leave a TODO behind here because
the nodes which are being pushed a TypeInstId should probably be taught
to expect that, but such a change is a bit tricky, so too much for this
PR.
2025-04-11 21:47:43 +00:00
Dana JansensandRichard Smith 0e8d354567 Split the witness table into a separate ImplWitnessTable instruction (#5272)
This allows us to import the table for a given impl only once, while we
can import many ImplWitness instructions with different specifics for a
generic impl.

For example in convert_facet_value_to_narrowed_facet_type.carbon we see
that a single witness table is imported for the BitAnd interface, with
multiple witnesses (for different specifics) imported and sharing the
same table.

The ImplWitnessTable now contains a back-link to the Impl the witness is
for, allowing inst namer to name that interface in the textual semir,
and allowing the interface to be found when debugging from a witness.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-11 20:30:04 +00:00
Dana Jansens c34a8d0a3a Convert remaining type-value InstId fields to TypeInstId (#5294)
After #5280 there are a few more typed instructions that have an `InstId
type_inst_id` that always holds a type value. These are converted to
`TypeInstId` to encode this fact in the type system. The
`ConvertAggregateElement()` function in convert.cpp is now able to
receive `TypeInstId` for a couple arguments as well.

Additionally, the `type_inst_id` field of `StructTypeField` is made into
a `TypeInstId`.

The `TupleType::elements_id` is renamed to `TupleType::type_elements_id`
to try record the fact that it's an InstBlock of type value
instructions. We don't introduce a TypeInstBlockId at this time, but it
might be nice to make blocks of TypeInstIds in the future.

To assist in working with a block of InstId that are type values, two
additional helpers are added to the TypeStore:
- GetBlockAsTypeInstIds which turns an `ArrayRef<InstId>` into a range
of `TypeInstId`
- GetBlockAsTypeIds which turns an `ArrayRef<InstId>` into a range of
`TypeId`

We use these helpers in places that iterate over the
`TupleType::type_elements_id`.
2025-04-11 20:11:03 +00:00
Jon Ross-Perkins 8c3fa80691 Add cc rule wrappers for cc_env (#5277)
Rules executed by bazel don't necessarily have the right environment to
find the symbolizer, which was the intent of `cc_env` setting
`LLVM_SYMBOLIZER_PATH`. So far, this has kind of been a case-by-case
fix, but every so often I'm trying to debug a crash in a test that
doesn't provide it. Rather continuing down this route, instead add
drop-in wrappers for cc rules so that it's hard to forget.

Note `bazel/cc_rules` is intended to mirror `bazel/carbon_rules` and
`bazel/cc_toolchains`, rather than `@rules_cc`.

AFAICT there isn't a great way to add this as a default for the `bazel
run` environment. It's not typically going to be set on its own,
forwarding `$PATH` would be too broad, and the [action
`env_sets`](https://bazel.build/docs/cc-toolchain-config-reference#using-action-config)
I think are not quite what we need (I think those don't include output
execution, only compilation).
2025-04-11 19:58:54 +00:00
Jon Ross-Perkins faeb024462 Remove explorer deps from MODULE.bazel (#5293)
These are only used by explorer, which is being removed by #5290
2025-04-11 15:49:33 +00:00
Jon Ross-Perkins ea130f1e73 Remove explorer/ and installers/ directories (#5290)
References were removed by #5287, #5291, and #5292; this is just
deleting the directories themselves.

Note this does not change anything else (e.g. removing things in
MODULE.bazel that were only used by explorer). I'm trying to make a pure
delete that's easy to review.
2025-04-11 15:36:50 +00:00
Jon Ross-Perkins fe29224016 Refactor LocId to merge in SemIRLoc (#5284)
The main goal of this is to collapse the LocId and SemIRLoc types into a
single type, eliminating the need for APIs to decide which to use. This
originated from discussion about UnwrapSemIRLoc in #5169. Although that
was removed in #5202, it's probably still a good direction for LocId.

This changes the packing of LocId to allow adding InstId, making it
tri-modal: ImportIRInstId, InstId, or NodeId. This has a side-effect of
reducing the available space for ImportIRInstId, although not by much
due to the pre-existing `ImplicitBit` behavior. If needed, we could also
probably play with packing a bit more since `ImplicitBit` really only
applies to `NodeId`, but I was trying to keep the logic a little
simpler. Note `TokenOnlyBit` can still apply to `ImportIRInstId`.

This leaves in place a typedef for SemIRLoc -- I intend to clean that up
separately.

Some Discord discussion is
[here](https://discord.com/channels/655572317891461132/655578254970716160/1353755830058745959).
2025-04-11 13:35:58 +00:00
Jon Ross-PerkinsandRichard Smith 422df75a92 Switch tree-sitter from explorer to toolchain testdata (#5292)
Noticed as part of #5290; `srcs` is needed to make `$(locations)` work.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-10 23:45:19 +00:00
Dana JansensandRichard Smith cf57c85545 Introduce TypeInstId (#5288)
TypeInstId is an InstId whose constant value has a type of TypeType.
This includes:
- Type value instructions, the `ClassType` or `IntLiteralType`
instructions.
- Constraint value instructions, which are the `FacetType` and
`TypeType` instructions, each of which also have type TypeType.

TypeInstId encodes in the type system that it is safe to convert the
instruction's value to a TypeId, and CHECKs at construction that this
invariant is maintained.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-10 22:59:02 +00:00
Jon Ross-Perkins 03a31bd0de Drop explorer from website (#5291)
Noticed this while preparing #5290, I think it can be split out.
2025-04-10 22:55:38 +00:00
Jon Ross-PerkinsandRichard Smith a94136d477 Remove references to explorer (#5287)
I'm doing this separately from removing the explorer/ and installers/
directories so that it's easier to review the side-effects.

Note for the main README, I didn't think it was worth keeping a mention
of "used to have a prototype interpreter, now archived" versus focusing
on the existing toolchain (for "Currently, we have fleshed out").

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-10 22:05:45 +00:00
Richard Smith a74ca9071b Remove all remaining uses of TypeIds as instruction operands. (#5280)
In preparation for shifting from `TypeId`s potentially representing
attached types to always representing unattached types, using
[terminology suggested on
Discord](https://discord.com/channels/655572317891461132/963846118964350976/1359286326779973712).
This change causes us to track slightly more type spelling information
through SemIR.

One change that has significant impact on the SemIR output is that we
now build a `struct_type` instruction in each class representing the
types of the fields, including the spelling used for those types. This
is now no longer always identical to the corresponding canonical
`struct_type` for the object representation, so it's built separately
and owned by the class.

Also remove `TypeBlock` support entirely, as its only use was
representing `TupleType`s, which now use an `InstBlock`.
2025-04-10 20:53:42 +00:00
Dana Jansens 1445ec9e4f Remove toolchain/check/testdata/impl/fail_impl_as_scope.carbon (#5289)
The same things are tested in
toolchain/check/testdata/impl/no_prelude/fail_impl_as_scope.carbon,
along with more cases.
2025-04-10 20:06:49 +00:00
Richard Smith 47fa1b5991 Rename StringifyType to reflect that it can stringify non-type constants. (#5285)
Use it to stringify associated constant values in diagnostics. In
passing, add missing support for stringifying bool literals. Note that
there are some cases that it doesn't stringify properly, but that's not
new here; such cases could already be observed when stringifying generic
arguments.
2025-04-10 19:15:27 +00:00
Dana Jansens aec90e3ae1 Rename rewrite_value to rewrite_inst_id to clarify what it's holding (#5286)
Also add a note about the RewriteConstraint insts being canonical
2025-04-10 16:42:24 +00:00
Dana JansensandRichard Smith 76c68153a2 Look for final impl when accessing associated constant in facet (#5269)
While facets may come with a rewrite for an associated constant, they
are symbolic. A final impl has the ability to provide a concrete value
instead, which allows generic code to use the concrete value in place of
the associated constant's (fully qualified) name.

For instance, instead of `I.Type`, the concrete type `()` can be used if
there is an `impl final [T:! type] T as I where .Type = ()` impl.

This does not yet cache the result of the lookups.

Depends on https://github.com/carbon-language/carbon-lang/pull/5255

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-10 13:48:49 +00:00
Boaz Brickner 68111a994c C++ Interop: Basic C++ record (class/struct/union) import support (#5156)
Focus: Calling static C++ function defined in C++ classes.

Limitations:
* Ignores visibility (public / protected / private).
* No support for: dynamic classes, member methods, data members,
declarations without definitions, importing inheritance.

Based on #5142.

C++ Interop Demo with a class:

```c++
// hello_world.h

namespace some_namespace {

class MyClass {
 public:
  static void hello_world();
};

}  // namespace some_namespace
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

namespace some_namespace {

void MyClass::hello_world() { printf("Hello World!\n"); }

}  // namespace some_namespace
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  Cpp.some_namespace.MyClass.hello_world();
  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
Hello World!
```

Part of #5150.
2025-04-10 08:15:12 +00:00
Richard Smith a91752de60 Represent rewrite constraints in FacetTypeInfo with InstId not ConstantId. (#5281)
This follows the pattern used elsewhere, and allows facet types in eval
blocks to directly reference their operands instead of doing so
indirectly via a `ConstantId` attached to the generic. This prepares us
for making `ConstantId`s always be unattached.

In passing, add a stringified version of the `InstId` to diagnostics in
a couple of places where it seems useful.
2025-04-10 03:56:12 +00:00
Dana Jansens c15dea4fa2 Stop erasing ImplWitnessAssociatedConstant instructions from the witness table (#5283)
Unintentionally, we were adding ImplWitnessAssociatedConstant to the
witness table and then immediately evaluting and replacing it with its
constant value instruction, which is incorrect. The point of the
instruction is to be a symbolic value in the witness table that is a
dependent of the generic impl declaration being built.
2025-04-09 23:03:45 +00:00
Richard Smith 6322c7734e Don't define an unscoped enumeration out of line. (#5282)
The C++ language semantics for doing so are weird and a bit broken.
Under
[CWG1485](https://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1485)
this code may become invalid in the future.
2025-04-09 22:41:31 +00:00
Jon Ross-Perkins a527626d87 Add tests and range enforcement for current LocId use-cases (#5274)
This is trying to document the status quo. Note
https://github.com/carbon-language/carbon-lang/pull/4497 placed
restrictions on a bit, and this is in part flowing back to restrictions
on both NodeId and ImportIRInstId limits.
2025-04-09 17:41:37 +00:00
Alina Sbirlea 7da972b773 Create a single global for the PrintInt format string. (#5275)
Create a single global for the PrintInt format string. Cleaner tests.
2025-04-09 16:47:32 +00:00
Alina Sbirlea 694a329bdd Reuse LLVM global constants. (#5273)
Reuse LLVM global constants: do not generate a new llvm::Global constant
for a pointer to a global constant for the same Carbon const_inst_id,
reuse already generated one.
2025-04-09 16:36:42 +00:00
Dana JansensandJon Ross-Perkins 20444c0103 Move explorer out of toolchain git repo (#5270)
The explorer is an archived codebase, without a plan to restart
development on it. The costs incurred by keeping it in the main git repo
can be alleviated by moving it to a new sibling repo, without
diminishing the usefulness of the explorer codebase for demonstrating
implementation of the carbon language design.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-04-09 13:35:53 +00:00
Boaz Brickner 817dacfc77 Fix clang-tidy: function 'rewind' has no error detection; 'fseek' should be used instead [bugprone-unsafe-functions,-warnings-as-errors] (#5265) 2025-04-09 13:17:26 +00:00
Ivana Ivanovska 7580df8b8a [Carbon/C++ interop] Add support for int function params (#5197)
Added support for `int` function parameters. Currently only
pass-by-value is supported.

```c++
// hello_int.h;

auto foo_int(int a, int b) -> int;
```

```c++
// hello_int.cpp

#include "hello_int.h"
#include <cstdio>

auto foo_int(int a, int b) -> int {
    printf("a = %i \n", a);
    printf("b = %i \n", b);
    return a + b;
}
```
```c++
// main.carbon

library "Main";

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

fn Carbon_foo(b: i32) {
  Core.Print(b);
}

fn Run() -> i32 {
  Carbon_foo(Cpp.foo_int(2, 8));
  return 0;
}
```

```
$ clang -c hello_int.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link hello_int.o main.o --output=demo
$ ./demo
a = 2 
b = 8 
10
```

Part of  #5064
2025-04-09 11:38:39 +00:00
Richard Smith 1a4d6ca255 Store an InstId instead of a TypeId in UnboundElementType. (#5260)
This gives a slightly simpler representation for `UnboundElementType`s
in eval blocks, and in principle allows us to preserve the spelling of a
field's type into the `UnboundElementType` and thereby into a field
reference, although as of right now this doesn't affect our diagnostic
output in any way.

During error recovery for a field with a non-concrete type, preserve the
type in the `UnboundElementType` regardless. It's not really problematic
to have a non-concrete type there, and this makes it easier to track the
instruction used to specify the type.

This is a step towards switching symbolic types to always be abstract
during type checking.
2025-04-08 22:21:44 +00:00
Richard Smith bfef32b482 Add an EvalOrAddInst function. (#5258)
Use that instead of `AddInstInNoBlock` to get the value of an
instruction when evaluation might depend on the `InstId` but only the
`ConstantId` of the instruction is desired by the consumer.
2025-04-08 21:04:30 +00:00
Dana Jansens d07f70cfb3 Add insts for witness table entries that are unset or associated constants (#5255)
Instead of using None, use an explicit ImplWitnessTablePlaceholder in
the witness table for entries that have not yet been populated, to aid
debugging. This would ensure they would show up very clearly in the
SemIR. This uncovered some `<invalid>` in the SemIR under erroneous
conditions that have now been turned into `<error>`.

Add the ImplWitnessAssociatedConstant instruction which wraps the
canonical instruction found from the constant value of the rewrite
constraint. This ensures that we have an instruction inside the eval
block for a generic impl declaration for each rewrite constraint's
value, which allows Subst to be performed to rewrite the symbolic
constant of the ImplWitnessAssociatedConstant instruction to associate
it with the generic. This will prevent the otherwise orphaned symbolic
constant of the rewrite's value from being used which can not have a
specific applied to them.

While applying the new insts in InitialFacetTypeImplWitness(), rearrange
the function to use less nesting. And avoid using entity names from
imported instructions (as we found is not effective in deduce.cpp) and
use a local instruction by going through the constant value.

This PR is part of the effort to allow a rewrite to name a generic
parameter, such as `impl forall [T:! type] T as Z where .X = T`, however
tests for this involve a final impl so that we can typecheck that the .X
value is a specific T, so the tests will come with that work. This piece
is split off because introducing new instructions causes a lot of SemIR
churn, and I wanted to get that done separately.
2025-04-08 19:10:49 +00:00
Geoff RomerandDana Jansens cda97cb292 Include all symbolic parts in structure comparison (#5247)
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-04-08 19:02:55 +00:00
Alina Sbirlea 3ccb0b82f8 Add/update lowering tests. (#5254)
Add lowering tests for future redesign.
2025-04-08 17:26:16 +00:00
Boaz Brickner 7d2029e8ca Fix clang-tidy: result of a data() call may not be null terminated, provide size information to the callee to prevent potential issues [bugprone-suspicious-stringview-data-usage,-warnings-as-errors] (#5267)
Replaced using `llvm::StringRef` with `const std::string&` so we can
have `c_str()`.
2025-04-08 15:39:55 +00:00
Boaz Brickner afa29d5e66 Fix clang-tidy: use a ranges version of this algorithm [modernize-use-ranges,-warnings-as-errors] (#5268) 2025-04-08 15:37:52 +00:00
Richard Smith 0631e18184 Provide an InstId when evaluating a constant in cases where one is needed (#5202)
For each kind of instruction, specify whether its constant evaluation
needs an `InstId` or not. If it does, ensure that all constant
evaluation of that instruction provides one. Otherwise, allow calling
into the evaluator without providing an `InstId`.

This allows us to reliably use the `InstId` in evaluation steps that
either need a location or need to look at the original operands of the
instruction prior to evaluation, and also to support `TryEvalInst` calls
safely for instructions whose evaluation does not need an `InstId`.
2025-04-08 00:40:21 +00:00
Jon Ross-Perkins 1ffd56ac3e Use Get*Type in a couple spots (#5257)
These seemed like spots that didn't need to call `TryEvalInst` directly.
I'm relying on tests for coverage. :)
2025-04-07 22:41:27 +00:00
4af0c8f8d1 Implement ...where .Self impls... (#5238)
* Also remove facet type deduction, since we decided against it on
[2025-04-02](https://docs.google.com/document/d/1Iut5f2TQBrtBNIduF4vJYOKfw7MbS8xH_J01_Q4e6Rk/edit?pli=1&resourcekey=0-mc_vh5UzrzXfU4kO-3tOjA&tab=t.0#heading=h.95phmuvxog9n).

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-04-07 20:45:45 +00:00
Geoff Romer 87f0e9723f Rename StateStackEntry to State (#5256)
Also clean up `State` -> `StateKind` in the toolchain docs, which was
missed in #5249.
2025-04-07 18:58:41 +00:00
Richard Smith a45dc42d82 Store an InterfaceId and a SpecificId in AssociatedEntityType. (#5252)
Instead of storing a `TypeId` that always refer to a facet type that
always contains exactly a single interface, store the interface
directly.

Also improve stringification of `LookupImplWitness` and witness access
into it, switching to using newly-added functionality for stringifying
specific interfaces.
2025-04-05 16:08:09 +00:00
David Blaikie 8e7bb2f953 Initialize vptrs to point to vtables (#5244)
Adds a mapping to keep track of vtable LLVM IR decls/defs for use.
Adds the vtable_id to the vtable_ptr initialize instruction for lookup.
Adds emission of vtable declarations for use outside the file that
defines the vtable. (this isn't done lazily, it's done for any imported
class - it could be done lazily & maybe eventually has to be lazy to
handle generics)
2025-04-05 06:11:34 +00:00
Geoff Romer 8c113c1241 Rename Parse::State to Parse::StateKind (#5249)
Also renames variables of that type to match. A follow-up PR will rename
`Parse::StateStackEntry` to `Parse::State`. This is more consistent with
the naming of similar enums elsewhere in the toolchain, and with the
prevailing practice of using `state` rather than e.g. `entry` as the
name of a `StateStackEntry`.

See also discussion
[here](https://discord.com/channels/655572317891461132/963846118964350976/1326280585592700990)
2025-04-05 04:25:00 +00:00
Thomas Köppe 2fa2425ef5 Minor clang-tidy recommended cleanup (#5248)
Some minor code health improvements discovered by clang-tidy:

* avoid copying; use const reference
* harmonize parameter names
* use more efficient absl::StrSplit-by-character
2025-04-04 17:49:40 +00:00
5e338d544e Towards more async "sync"-ing (#5233)
(Note: this is *not* anything related to April 1st.)

Proposal to switch our week-to-week Carbon project development syncs to
be more
async.

-   Start of each week, create a summary of what happened last week.
- Publish this in GitHub discussions for async reading and further
discussion.
-   Stop our weekly meeting focused on these summaries.
-   Start up a new discussion meetings every two months.
    -   Structure will be a 10-minutes-or-less update, and a "demo".
- Demo may be traditional: showcase a newly landed thing in Carbon.
    -   Or demo may showcase an interesting top-of-mind language design
        discussion.
- Either way, goal will be to field lots of questions about the topic
and
        have a good discussion everyone understands, not to reach some
        "conclusion" or "decision".

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-04-04 07:08:40 +00:00
Boaz Brickner 61c705311f Remove unused variable diagnostics_stream (#5239) 2025-04-04 00:33:14 +00:00
Geoff RomerandJosh L 38ce7e3011 Handle EntityNameId::None during evaluation. (#5237)
Fixes a crash bug found by the fuzzer

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-04-04 00:32:36 +00:00
Dana Jansens 6eddf72979 Avoid crashing during associated constant lookup on a runtime facet value (#5243)
Perhaps we will disallow member lookup on and conversion of runtime
facet values. For now, leave a TODO and produce a TODO diagnostic
instead of crashing.
    
Related to #5241.
2025-04-03 22:46:11 +00:00
Boaz Brickner cfdd5fbdb5 Simplify GetAbsoluteNodeIdImpl() by merging while (true) with the first if (#5240) 2025-04-03 22:44:34 +00:00
Richard SmithandDana Jansens bba32900c3 Preserve type sugar in ArrayType, ConstType, and PointerType. (#5235)
Each of these types takes another type as an operand. Instead of storing
that other type as a `TypeId`, store it as an `InstId` so that we can
track how it was written, not only its canonical form.

The canonical constant values of these types continue to store the
canonical constant values of their operands, as normal.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-04-03 21:14:03 +00:00
Dana Jansens 164310c6b8 Facet values (like type values) can be copied around at runtime (#5242)
Give them a value representation of copy, and allow conversions between
two facet values of the same type to work.

Convert was assuming that facet values are compile time constants, but
thye can also be runtime values. In that case, we have no support for
converting to a different facet value of a different facet type. But if
the types are equal then it's all fine.

In theory it seems that we should be able to convert if the target facet
type can be found through the source value's FacetType. But currently
that happens through impl lookup and it requires constant values. Adding
a test for this.

Related to #5241
2025-04-03 19:34:54 +00:00
Richard Smith c33adfafd3 Replace GetTypeInSpecific with GetTypeOfInstInSpecific. (#5232)
Reduce usage of `GetConstantInSpecific` to a single caller in constant
evaluation, with a TODO to remove that.

This gets us closer to being able to fully perform type-checking against
abstract types instead of types anchored within a particular generic.
2025-04-02 22:52:11 +00:00
Alina Sbirlea 077cf56a8a Emit function definitions in check, for all specifics seen. (#5090)
Emitting definitions in check. This resolves the crash in lowering which
necessitated definitions be emitted.
Some of the test changes need further review.
2025-04-02 21:51:25 +00:00
Richard Smith 6ee1006a61 Update stringifying of array types to match the new array syntax. (#5236) 2025-04-02 21:00:55 +00:00
Richard Smith 8b9f1a8966 Don't re-evaluate imported constants. (#5217)
Trust that import_ref produces constants that are already in their
evaluated form. We still do one pass over the operands to map them into
their canonical constant values. Even that is mostly unnecessary, but
there are a few instructions produced by importing that still need it
for now.
2025-04-02 18:26:36 +00:00
David Blaikie 8847178242 Emit (relative) vtables (#5231)
One of the remaining three steps for proof-of-concept virtual function
lowering (the other two being: initializing vptrs to point to these
tables, and using the vptr+table at call sites).

Introduces a (placeholder?) mangling of vtables as ".$vtable" at the end
of the mangling of the class name.

Uses a scheme similar to clang's relative vtables - though those are
relative to the vtable slot, and this is relative to the start of the
vtable (seemed simpler? though I haven't looked at it in detail, perhaps
in lowering call sites I'll find the relative-to-vtable-slot is nicer,
easy enough to change).
2025-04-02 17:59:08 +00:00
Boaz Brickner feb78e778d Change OutputMapping::Map::io_ from reference to pointer (#5227)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-04-02 17:54:13 +00:00
e9c90af92e Reduce redundant diagnostics (#5234)
* "extending non-facet-type constraint" is already diagnosed by
`ImplAsNonFacetType`
* `impl` declarations with errors in the facet type no longer require
definitions

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-04-02 16:36:14 +00:00
bc439ad092 Forward impl declarations of incomplete facet types (#5219)
Implements some of the changes from proposal #5168.

* The data structure for complete facet types has been repurposed for
identified facet types. Identified facet types are now a concept in the
toolchain, but without named constraint support they are not
substantially different from incomplete facet types.
* Identified facet types keep the list of required specific interfaces
in sorted order, for efficiency improvements in impl lookup. Found
another way to identify the interface to impl (or number of impls if not
1).
* Forward `impl` declarations of identified but incomplete facet types
are allowed unless the facet type has rewrites. An incomplete facet type
with rewrites is already either an error or has more than one interface
and so can't be implemented, so this case can't be exercised very well
yet.
* Forward `impl` declarations of interface without rewrites use a
placeholder inst block for the witness.
* Changed some machinery to use RequireIdentifiedFacetType to access the
interfaces of the facet type so we only need to add support for
expanding named constraints into interfaces in one place.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-04-02 01:46:27 +00:00
Richard Smith 265968b396 Make evaluation of symbolic bindings simpler and more uniform (#5215)
Factor out logic to evaluate `EntityNameId` instead of duplicating it
between `BindSymbolicName` and `SymbolicBindingPattern`. Remove support
in `SymbolicBindingPattern` for evaluating a pattern to the constant
value of the corresponding binding, which doesn't really make any sense
given that patterns don't generally evaluate to the value that they
matched.

This results in the handling for `SymbolicBindingPattern` being simply
the default handling for an always-constant instruction, so remove the
special case for it entirely and change its constant kind to `Always`.
It's not entirely clear that it makes sense for `SymbolicBindingPattern`
to be treated as a constant when other patterns aren't, but we seem to
be relying on this in various places, so leave it as a constant for now.
Changing it to never be constant will be a smaller change now -- it just
requires changing the `constant_kind`.

The IR changes in the tests are fairly widespread, but mechanical, and
there are two kinds of things changing:

- `symbolic_binding_pattern`s in specifics now evaluate to
`symbolic_binding_pattern`s, not to the argument values. This means in a
few cases we end up with additional `symbolic_binding_pattern`
constants.
- We evaluate the type operand of `symbolic_binding_pattern` now, so an
error in the type will now properly be propagated into an error in the
pattern's constant value.
2025-04-01 20:24:00 +00:00
David Blaikie 4739828cca Generalize non-const ClassInit lowering beyond only InitializeFrom insts (#5199)
Fixes #5186

With @zygoloid's kind assistance, this generalizes the existing
non-const lowering of ClassInit, that had previously only handled
InitializeFrom, to find other cases - such as a nested ClassInit used to
initialize a class member.

This refactors the `FindReturnSlotArgForInitializer` from
`check/convert.cpp` into `sem_ir/file.{h,cpp}` for use from lowering
(since lower doesn't depend on check, which I assume is an intentional
layering constraint - so figured it made sense to move it to sem_ir, and
found one or two similar-ish utility functions in `sem_ir/file.{h,cpp}`,
so figured that was a good spot)
2025-04-01 18:45:07 +00:00
Boaz Brickner 50833a9c3b Change Lexer::ErrorRecoveryBuffer::buffer_ from reference to pointer (#5228)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-04-01 16:04:19 +00:00
Boaz Brickner ccd2cb346a Change CodeGen::Make() to take module and errors as pointers and not references (#5229)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-04-01 14:55:04 +00:00
Boaz Brickner 6e2dbb5b61 Change CopyOnWriteBlock::file_ from reference to pointer (#5230)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-04-01 14:40:28 +00:00
Dana Jansens 1056d50e7b Make ImplWitness constant_kind=Always (#5226)
impl witnessnes only make sense at compile time, they are a
compiler-generated witness that a type implements an interface.
2025-03-31 21:04:23 +00:00
josh11bandJosh L df958940c3 Builtin facet type conversion is final (#5220)
Don't look for a user-defined conversion (implementation of `As` or
`ImplicitAs`) if the builtin conversion to a facet type fails impl
lookup. This is the behavior we want, and reduces noise in diagnostics.

Partial implementation of #5122. Still to do:
* Give an error if the users tries to implement such a conversion, since
it is now unreachable.
* Add notes to the diagnostic explaining why impl lookup failed.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-31 16:11:07 +00:00
0ebe031dac More Dump() output for constants, generics, specifics (#5222)
Example output:

Symbolic `constant_id`:

```
(std::string) $2 = "symbolic_constant36: {inst: inst74, generic: generic3, index: generic_inst_in_decl2, kind: checked}
inst74: {kind: FacetType, arg0: facet_type3, type: type(TypeType)}
  - type: type(TypeType): type; {kind: TypeType, type: type(TypeType)}
  - value: symbolic_constant26
generic3: {decl: inst75, bindings: inst_block41}
inst75: {kind: ImplDecl, arg0: impl0, arg1: inst_block39}
  - value: concrete_constant(inst75)"
```

`generic_id`:

```
(std::string) $3 = "generic3: {decl: inst75, bindings: inst_block41}
inst75: {kind: ImplDecl, arg0: impl0, arg1: inst_block39}
  - value: concrete_constant(inst75)
inst_block41:
  - inst60: {kind: BindSymbolicName, arg0: entity_name4, arg1: inst<none>, type: type(TypeType)}
generic decl block: inst_block46:
  - inst85: {kind: BindSymbolicName, arg0: entity_name4, arg1: inst<none>, type: type(TypeType)}
  - inst86: {kind: ClassType, arg0: class0, arg1: specific7, type: type(TypeType)}
  - inst87: {kind: FacetType, arg0: facet_type4, type: type(TypeType)}
  - inst88: {kind: RequireCompleteType, arg0: type(symbolic_constant36), type: type(inst(WitnessType))}
  - inst89: {kind: ImplWitness, arg0: inst_block42, arg1: specific9, type: type(inst(WitnessType))}"
```

`specific_id`:

```
(std::string) $1 = "specific8: {generic: generic0, args: inst_block67}
inst_block67:
  - inst255: {kind: BindSymbolicName, arg0: entity_name67, arg1: inst<none>, type: type(inst(IntLiteralType))}
generic0: {decl: inst51, bindings: inst_block7}
inst51: {kind: ClassDecl, arg0: class0, arg1: inst_block_empty, type: type(inst52)}
  - type: type(inst52): <type of Int>; {kind: GenericClassType, arg0: class0, arg1: specific<none>, type: type(TypeType)}
  - value: concrete_constant(inst54): {kind: StructValue, arg0: inst_block_empty, type: type(inst52)}
specific decl block: inst_block68:
  - inst255: {kind: BindSymbolicName, arg0: entity_name67, arg1: inst<none>, type: type(inst(IntLiteralType))}
  - inst255: {kind: BindSymbolicName, arg0: entity_name67, arg1: inst<none>, type: type(inst(IntLiteralType))}"
```

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-03-31 15:58:32 +00:00
josh11bandJosh L 384be1dbe3 Change conversion diagnostic from saying "value" to "expression" (#5221)
Avoids TODO to make the message change based on the expression category.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-31 15:45:58 +00:00
Boaz Brickner 97b234358e Change ImportContext.context_ from reference to pointer (#5207)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-31 07:11:08 +00:00
Jon Ross-Perkins 9134e36ec0 Extend CARBON_KIND_SWITCH to support ArgAndKind (#5216)
This builds on #5212 which is adding ArgAndKind. This further modifies
CARBON_KIND_SWITCH support so that we can use it with ArgAndKind in
addition to Inst. That creates a quirk where it's easier if ArgAndKind
provides `kind` as an accessor instead of a data member, so I'm just
switching it to a class.
2025-03-29 00:37:46 +00:00
Richard Smith 660d62ecc1 Preserve source locations in imported eval blocks (#5213)
Don't lose track of where the instructions in an eval block are across
import.
2025-03-28 23:41:40 +00:00
Jon Ross-Perkins 4cb61ae4e1 Remove ArgKinds to encourage safer coding patterns (#5212)
#5171 ran into an issue where the wrong kind was associated with an arg
(`auto arg1 = RefineOperand(context, loc_id, arg0_kind,
action.arg1());`). This PR is trying to reduce risk of similar errors by
replaced `ArgKinds()` with instead an `ArgAndKind` structure and
corresponding accessors.

A couple things I considered and discarded were:

- Adding `CARBON_KIND_SWITCH` support (in this PR -- see #5216).
- The particular way that `ForCase` works would need to change, and I
was hesitant to do that here.
- But this is why I did add `As` to `ArgAndKind`, because it had me
thinking in that direction.
- Trying to make wrapper functions like `MutateArgs(callback_fn);`. This
kind of approach gets a little messy due to some of the conditional
passes, and in particular the reverse-iteration done for `PopOperand` in
subst.cpp
- Making something like `args_and_kinds() -> std::array<ArgAndKind, 2>`.
There's one spot where iteration is already set up as a loop, but for
others it felt a little convoluted with less gain than
`MutateArgs`-style things.

I'm not sure if there's a better way to set up the table generators, I
might keep tinkering with those for ideas.
2025-03-28 23:24:36 +00:00
dependabot[bot] 2973cafd60 Bump tar-fs from 2.1.1 to 2.1.2 in /utils/vscode in the npm_and_yarn group across 1 directory (#5214)
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.1 to 2.1.2
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/mafintosh/tar-fs/commit/d97731b0e1b8a244ab859784b514cfcf5585ad3d"><code>d97731b</code></a>
2.1.2</li>
<li><a
href="https://github.com/mafintosh/tar-fs/commit/fd1634e869e7c5f85948e95eabdaa8451a085de5"><code>fd1634e</code></a>
symlink tweak from main</li>
<li>See full diff in <a
href="https://github.com/mafintosh/tar-fs/compare/v2.1.1...v2.1.2">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.1&new-version=2.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 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-03-28 22:39:55 +00:00
Boaz Brickner ac3bf0d3fa Change TypeStructureBuilder.context_ from reference to pointer (#5211)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:23 +00:00
Boaz Brickner 3acca8402f Change NodeIdTraversal.context_ from reference to pointer (#5210)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:17 +00:00
Boaz Brickner 9d3664baa9 Change PendingBlock.context_ from reference to pointer (#5209)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:11 +00:00
Boaz Brickner bd24d74975 Change SubstConstantCallbacks.context_ from reference to pointer (#5208)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:03 +00:00
Dana Jansens 496eddfaf4 Handle FacetAccessType as the self type in symbolic impl lookups (#5200)
It is possible to construct a symbolic impl lookup query that, when
evaluated against a specific, will have a self type that is:
- A facet value instruction with a symbolic constant value
- That constant value is rewritten to a FacetValue pointing through a
FacetAccessType to a symbolic facet value.

Impl lookup looks through the FacetValue to the type inside since
FacetValue will reduce the number of interfaces available to match the
minimum deduced requirements.

Impl lookup also unwraps FacetAccessType in the self type of the query
and the impl, so that queries on FacetAccessType and on facet values can
both compare against the impl's self type with a simple constant value
equality check.

We were unwrapping FacetAccessType on the way into impl lookup, and then
assumed that meant it would never be a FacetAccessType in the symbolic
impl lookup instruction. However, as we can see, the query self
instruction can be symbolic and its value can be rewritten. And in that
case it can contain or become a FacetAccessType.

So we need to also unwrap the FacetAccessType when doing a symbolic impl
lookup.

Closes #5187
2025-03-28 16:02:41 +00:00
Boaz Brickner 15bb7d5ac6 Change DeductionWorklist.context_ from reference to pointer (#5204)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 15:29:09 +00:00
Boaz Brickner 624ebbd805 Change TypeCompleter.context_ from reference to pointer (#5206)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 15:29:02 +00:00
Boaz Brickner afe034f9f4 Change RebuildGenericConstantInEvalBlockCallbacks.context_ from reference to pointer (#5205)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 15:14:02 +00:00
Boaz Brickner 181c7b9290 Change EvalContext.context_ from reference to pointer (#5203)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 14:48:18 +00:00
Boaz Brickner e7e52a14ba When compiling C++, output a diagnostic per C++ diagnostic (#5177)
Part of #5176.
2025-03-28 08:46:17 +00:00
Jon Ross-Perkins a5df8ad736 Support destruction of storage (#5171)
What this does:

- Adds tracking where storage is allocated.
- Determines if that storage supports destruction and, if so, records
the `destroy` function for it.
- Calls any found `destroy` functions when going out-of-scope.

What this does not do:

- Precise scope tracking of temporaries. We currently don't define
temporary scopes, which would probably be the solution.
- Destruction for anything but a `class` with `fn destroy`, in an
implicit return. That excludes:
- Classes with members that need destruction, particularly in the
absence of `fn destroy`.
  - Structs, tuples, and arrays.
  - Explicit returns, break, continue, nested scopes.

Noting the exclusions in particular, I think those will need work to
support, but this should set the right framework.

The cleanup block concept stems from clang and trying to share code
across cleanups, from discussion with chandlerc. Note in this
implementation I try to find `destroy` functions early on: that's so
that, when destruction is present on multiple paths, particularly
non-shared paths, we only bind the `destroy` method once.

Implementation-wise, I'll note this adds a `has_cleanup` flag to
`TemporaryStorage` and `VarStorage`. There are several related options,
but this felt similar to other information we're trying to track on
instructions. My goal with this is to mitigate the chance of accidental
calls where the storage may not be tracked for destruction. Alternatives
I considered were to not add the flag (I was worried about heightened
risk of errors), or to just add a concept for the relevant `requires`
(which just felt inconsistent).

Cleanup logic ends up in control_flow in this change because I thought
it was a reasonably consistent place for the cleanup block concept and
its pretty direct control flow interactions.
2025-03-28 00:29:17 +00:00
Dana Jansens 3469922275 Rename ImplSymblicWitness to LookupImplWitness (#5201)
The instruction does act somewhat like a witness, saying that an impl
does exist for a lookup, but the instruction more concretely represents
an impl lookup - since that is done when it is evaluated.
2025-03-27 21:46:08 +00:00
Jon Ross-PerkinsandDana Jansens 3ae62f8130 Rewrite Dump calls to use std::string returns (#5195)
Thought this might be interesting for you to allow more continuous
stream use. Also eliminates the need for `DumpNoNewline`.

```
expr Dump(context, complete_type_id)
(std::string) $0 = "type(inst1553): <builtin i32>; {kind: IntType, arg0: signed, arg1: inst1508, type: type(TypeType)}"
complete_type_id.Dump()
(std::string) $1 = "type(inst1553)"
expr Dump(context, specific_id)
(std::string) $2 = "specific166: {generic: generic0, args: inst_block772}"
expr Dump(context, query_self_const_id)
(std::string) $3 = "concrete_constant(inst1510): {kind: ClassType, arg0: class0, arg1: specific166, type: type(TypeType)}"
expr Dump(context, MakeFacetTypeId(arg))
(std::string) $4 = "facet_type22: {impls interface: interface10}
  - interface10: {name: name26, parent_scope: name_scope0} `BitAnd`
complete: complete_facet_type22
  - interface10: {name: name26, parent_scope: name_scope0} `BitAnd` (to impl)"
```

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-03-27 21:17:54 +00:00
josh11bandJosh L c7a338be59 Replace uses of "defined" with "complete" (#5196)
As of #5087, these terms are no longer synonyms. This change preserves
the original meaning.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-27 18:14:26 +00:00
Dana Jansens 10eae855bc Test cleanup: remove old todo and duplicate test (#5198)
The todo_fail_specialization_written_after_use_is_poisoned.carbon has a
similar test in impl/lookup/min_prelude/specialization_poison.carbon
now.
2025-03-27 16:30:14 +00:00
Dana Jansens f9aa2b79b8 Diagnose the unused generic params on an impl decl (#5189)
These parameters are never deduced, so they prevent the impl decl from
ever being used. But we also don't emit diagnostics inside impl lookup,
so there's nothing provided to the user explaining that they made an
impl that is useless.
2025-03-27 15:25:21 +00:00
Jon Ross-Perkins 0a3efb76ed Use DiagnosticEmitter for phase-specific types (#5188)
Given the namespacing of `Diagnostics` in #5173, now we can use
`DiagnosticEmitter` for phase-specific emitters. This is consistent with
how we do `Context`, and also check had started this with
`DiagnosticBuilder` in anticipation of the namespacing.

Also renames `Emitter::DiagnosticBuilder` to `Emitter::Builder` for
consistency with other `Diagnostics` entities.

In check, I'm still splitting `DiagnosticEmitterBase` and
`DiagnosticEmitter` just to keep the emitter definition separate from
the context.

Also cleans up some incorrect check diagnostic emitter dependencies in
lower.
2025-03-27 00:41:30 +00:00
Jon Ross-Perkins 9d3e1d3c55 Small cleanups to impl.cpp (#5194)
This could've been part of #5185, but I missed it there.
2025-03-26 23:43:45 +00:00
Dana Jansens 1d7d78c6da Add more output in dump for generics, impls (#5190) 2025-03-26 22:59:32 +00:00
Richard Smith 4acc9cac5d Replace GetInstForSpecific with direct support for rendering a SpecificId in diagnostics. (#5192)
Avoids misbehavior caused by GetInstForSpecific's side effects, such as
recursively reentering constant evaluation.
2025-03-26 22:53:32 +00:00
Dana Jansens e65866d8c3 Add tests for poisoning specializations and final associated constants (#5191)
- A concrete query should poison any further specializations of an impl
that are found in the same file.
- A symbolic query should poison any final specializations of an impl
that are found in the same file.
- A final generic specialization should allow generic code to use the
concrete type in an associated constant.

The last one was discussed in open discussion:
https://docs.google.com/document/d/1Iut5f2TQBrtBNIduF4vJYOKfw7MbS8xH_J01_Q4e6Rk/edit?resourcekey=0-mc_vh5UzrzXfU4kO-3tOjA&tab=t.0#heading=h.g7v3y38ydkc7

We decided to take this approach for now, as it reduces possible states
that we have to deal with in the toolchain. And we can revisit if it's
causing problems for ordering impls in carbon code.
2025-03-26 22:12:15 +00:00
David BlaikieandRichard Smith 45d042cab8 Fix crash in lowering vptr initialization (#5184)
Seems the instructions got emitted out of order & that caused problems
for lowering. This was because most of the initialization instructions
were added to a PendingBlock, but the vptr initialization instructions
were added to the (non-pending) block directly.

(I don't fully understand the pending stuff (is there a different test I
could/should write that demonstrates the vptr init instructions not
being discarded because they didn't go in the pending block (before this
patch)), or the out of order instruction problem (could we add more
robust checking for instruction ordering?) - but perhaps this is
adequate understanding for this bug fix at least)

Fixes #5094

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-03-26 21:52:16 +00:00
Jon Ross-PerkinsandRichard Smith 402093941e Allow pushing multiple items at once for StringifyType (#5182)
My intent with `Push` is to make it easier to see the ordering
relationship between output and , at least in some cases.

I'm using a variant with `Push`, but that could've also been a function
with variadic arguments. The `ArrayRef` approach felt useful in that it
generates less code, and allows the `PushItem` construction in
`FunctionTypeWithSelfType` handling. Note I didn't really use that
elsewhere, but in theory it could be.

Adds support for `llvm::ListSeparator` in order to help eliminate
`llvm::seq` use.

Also increases the variant use here. The discriminated `Step` union was
added in #4511, and it's not clear to me from that PR why variant wasn't
used. In general I'm trying not to change API choices that were made
there.

I considered renaming all the `PushString` etc functions to just be
`Push` overloads, but I'm on the fence about whether that's just going
to be a naming bikeshed, so I left them alone. Also considered a
`WriteAndPush("foo", {...});`, but that'd require merging `StepStack`
and `Stringifier` and I'm hesitant to go ahead with that. This PR I view
as more objective refactoring that hopefully makes everyone happier.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-03-26 21:46:17 +00:00
Jon Ross-Perkins 0d3d829478 Cleanup pass over llvm::seq uses (#5185)
I was thinking about this after `seq` changes in #5182, and looked for
other uses that might be replaceable. Here's the resulting cleanup
around `seq`:

- Switch to `enumerate` or `zip` when possible.
- `int _` -> `auto _` (it's typically a `size_t`, but there's no reason
to cast when unused)
- Fix a case of cast style `(size_t)...` -> `static_cast<size_t>(...)`
- Switch `(void)close_children_count` to `[[maybe_unused]]`
2025-03-26 19:25:03 +00:00
Jon Ross-Perkins acbe6530c3 Move diagnostics into a namespace (#5173)
What this really does is avoids shadowing names, so that we can
comfortable have things like `Check::DiagnosticEmitter` or
`Check::DiagnosticLoc` without shadowing being a concern.

Note, down this path I'm also thinking about:

- Renaming misc DiagnosticConsumer/DiagnosticEmitter classes, possibly
just to DiagnosticConsumer/DiagnosticEmitter (so
`Check::DiagnosticEmitter` instead of `SemIRLocDiagnosticEmitter`).
- Dropping `Diagnostic` from `Emitter::DiagnosticBuilder`.
- But not for `Check::DiagnosticBuilder`, because `Check::Builder` would
be ambiguous.
- Renaming diagnostics/diagnostic_* to drop "diagnostic".

[Discussion about SemIRLoc ->
DiagnosticLoc](https://discord.com/channels/655572317891461132/655578254970716160/1353771570463768698)
reminded me of this (in particular the older [Check::DiagnosticBuilder
discussion](https://discord.com/channels/655572317891461132/655578254970716160/1344363562608627763)),
but I'd only do that rename if there's matching consensus about a path
forward where we keep SemIRLoc, and in a way that it's only ever used
for diagnostics (the divergence from which is at the root of current
LocId discussion).

I'm trying to keep that separate from a namespace addition for clarity.
2025-03-26 19:12:10 +00:00
David Blaikie d317c56916 Minor refactor to reduce indentation (#5183)
This also makes the CHECK (rather than FATAL) fail closer to the
relevant condition.
2025-03-26 18:43:06 +00:00
Dana JansensandJon Ross-Perkins 53c98a8619 Support specialization in impl lookup with a symbolic query/impl. (#5169)
Add a new instruction called ImplSymbolicWitness which represents a
search for an impl declaration given a self type and an interface to
find implemented for the self type. The self type is stored as a
constant instruction id, rather than as a ConstantId, as instructions
don't currently support holding ConstantId. The interface is stored as a
SpecificInterface but we can't fit all of it directly into the
instruction. So we add a new id to refer to the SpecificInterface as
follows.

Add a new SpecificInterfaceId which indexes into a canonical value store
on SemIR::File. This tracks all `SpecificInterface`s stored in an
instruction - specifically the ImplSymbolicWitness instruction.

The SpecificInterface on Impl is still stored there as a value, not as
an id, and no id is eagerly constructed for it. We wait until an id is
needed to make one. Since they are canonical, a new id is only create
when a new SpecificInterface value is seen.

When doing impl lookup, and the query is not concrete, and the impl is
not effectively final, the query needs to consider future impls that may
specialize either the self type or the constaint to make a more precise
match and replace the found impl declaration. Instead of returning the
ImplWitness instruction from the found impl, we generate a
ImplSymbolicWitness instruction, storing the query so that it can be
replayed later. This instruction is added to the generic eval block and
thus will be re-evaluated later with a SpecificId that may make the
query more concrete. When evaluating the instruction and replaying the
query, the lookup has the same conditions and if it does not decide to
use the found impl concretely, then the same instruction is returned
from eval, leaving it as symbolic.

--- Impl lookup changes ---

Impl lookup gets a little more interesting now. It continues to look in
the facet value for a witness if the self type is a facet value. Then
falls back to looking for an impl declaration. This step is no longer
done directly. Instead, we construct a ImplSymbolicWitness instruction
and evaluate it immediately for each interface that are in the query
facet type.

The ImplSymbolicWitness instruction, when evaluated, calls back to the
impl lookup code, with a query specific interface. There we resume back
into the same code path as from before, finding a witness in an impl
declaration. But we may return "found a non-final impl" instead of a
concrete witness. If eval receives this back, it evaluates to the
current ImplSymbolicWitness instruction as the resulting constant value.

To pass lookup failures back through eval, a result of InstId::None from
the second step of impl lookup will result in a non-constant value,
which is used as a signal back up the stack to the original impl lookup
function that the lookup failed. Using a non-constant value here would
break evaluation of the generic eval block if impl lookup could fail
there, however we know it will not since we only leave behind an
ImplSymbolicWitness instruction in the eval block if we found at least
one matching impl already, and we just want to look for a better match
with a more specific query.

We must take care to not store a reference into any value store across
computation in impl lookup, since impl lookup can recurse into itself
invalidate those stores. That includes the SpecificInterface obtained
from a SpecificInterfaceId, which impl lookup also inserts into the
store.

--- The long tail ---

Adding a new instruction and a new id type requires a myriad of changes
to support them:

We add Dump() support for SpecificInterfaceId. And fix a crash in Dump
for SpecificId::None. We also add MakeSpecificInterfaceId() for dumping
arbitrary ids.

The type of ImplSymbolicWitness is a new singleton builtin type
instruction called WitnessSymbolicType (like WitnessType is the type for
an ImplWitness).

Both ImplSymbolicWitness and WitnessSymbolicType are given `Value` as
their expression category as they are builtin constant values. And
BuildInfo() in TypeCompleter is taught about them both, returning a
`ValueRepr::Copy`.

WitnessSymbolicType is added to the set of SingletonInstKinds, so that
it can have a singleton instrution id as a static member.

Lower's BuildTypeForInst() is taught to make an empty struct for
WitnessSymbolicType, similar to WitnessType.

Instruction formatter (FormatterImpl) grows support for printing a
SpecificInterfaceId so that it can print both arguments of
ImplSymbolicWitness on the RHS when printing the SemIR instruction. To
print a SpecificInterfaceId, it prints both the interface id and the
specific id (if there is one). For example, for a query on a generic
interface `Z` with one parameter, the RHS includes the query, interface,
and specific:
```
%Z.impl_symbolic_witness: <symbolic witness> = impl_symbolic_witness %U, @Z, @Z(%U.as_type) [symbolic]
```

IdKind is extended to include SpecificInterfaceId.

InstFingerprinter is taught to look through SpecificInterfaceId and use
the interface and specific ids in the fingerprint.

InstNamer is taught about SpecificInterfaceId, counting the interfaces
when building an index. It is also tought about ImplSymbolicWitness,
using the name of the interface within and the `.impl_symbolic_witness`
suffix. For example, here the LHS is named after the interface in the
query:
```
%Z.impl_symbolic_witness: <symbolic witness> = impl_symbolic_witness %U, @Z, @Z(%U.as_type) [symbolic]
```

StringifyTypeExpr is taught about WitnessSymbolicType, which uses its IR
name since it's a singleton. And about ImplSymbolicWitness which uses
its constant value. The handling of ImplWitnessAccess also needed to be
adjusted, since it assumed that ImplWitnessAccess::witness_id would
always be a FacetAccessWitness, but it can now also be an
ImplSymbolicWitness. (It seems that the witness_id is also assigned
ImplWitness instructions, but those ImplWitnessAccess instructions don't
ever seem to get stringified in a diagnostic at this time.) At the
moment the ImplWitnessAccess with a symbolic witness is just stringified
as "<symbolic>", such as in:
```
x.carbon:1:2: error: cannot implicitly convert value of type `()` to `<symbolic>` [ConversionFailure]
  let a: C(D).(Z.X) = ();
                      ^~
```

There is a TODO left behind to include more information there.

The TypeStructure builder is made to handle WitnessSymbolicType and
WitnessType. These come up now in deduce where a generic impl will have
a ImplSymbolicWitness in a FacetValue for a generic self type. The query
may have a concrete ImplWitness in the same position. Since deduce tries
to deduce through the FacetValue, it tries to convert ImplWitness to
ImplSymbolicWitness, tries to do an impl lookup for `impl ImplWitness as
ImplicitAs(ImplSymbolicWitness)` and causes us to build type structures
with each of these.

Subst is updated to handle pushing and popping SpecificInterfaceId.
Without this, when finishing a generic's eval block, we would walk into
the ImplSymbolicWitness instruction, and its arguments, and fail to
recurse down into the SpecificInterfaceId. Then any specifics inside
would be left as "orphaned" without any generic id attached to them, and
we would never update the instructions in the SpecificInterface's
instructions (inside its own SpecificId) with new constant values when
evaluating the generic eval block against a specific. To do this we push
the specific_id inside the SpecificInterface, and when popping we pop
the specific_id then construct a new canonical SpecificInterface with it
and return that id.

We add support for importing ImplSymbolicWitness by importing its self
constant instruction and specific interface id. However we also had to
add import support for SpecificImplFunction, which can now appear in the
generic eval block for a generic impl declaration, and thus must be
imported with the declaration. This is done very similarly to
SpecificFunction, except the `type_id` is a singleton value.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-03-26 15:10:23 +00:00
Richard Smith e25f58adec Rebuild the type of a bind_symbolic_name when building an eval block (#5174)
When transforming instructions with symbolic constant values into the
eval block, we previously special-cased `bind_symbolic_name` (and
`symbolic_binding_pattern`) because they are places where symbolicness
is introduced, rather than propagated from operands, and just copied
them into the eval block. However, `bind_symbolic_name` can be dependent
on other symbolic constants, because it can have a type that is
dependent. In this case, the copy in the eval block would not have its
type properly adjusted to refer to the type within the eval block.

Fix this by performing substitution into `bind_symbolic_name` rather
than copying it directly, and instead, detect cases where substitution
determined that the instruction was unchanged despite having a symbolic
constant value, and force it to be rebuilt in that case.

I've not found any way that the previous behavior actually caused
problems, or affected the observable behavior of the toolchain. The type
of these instructions in the eval block doesn't make much difference to
anything because they get immediately replaced by their corresponding
argument values when we run the eval block. But this came up and caused
some test output churn when I was making a different change, and it
seems like a fix to our representation even if it's not changing
behavior, so I'm splitting it out so it can be handled separately.
2025-03-25 22:53:25 +00:00
Jon Ross-Perkins 75bbfb3f90 Refactor StringifyTypeExpr to use overloads (#5180)
StringifyTypeExpr has gotten a little long. I know there's some
preference for the effects of explicitly handling cases, but maybe it's
okay to adopt an overload pattern similar to what we do elsewhere? Note
I'm trying to force types to provide overloads, as a case which are
clearly intended to be handled.

Also, perhaps subtly, the list of "singleton" instructions previously
included Vtable, which is not a singleton. With this change, which
instead directly handles singleton instructions by
`requires(IsSingletonInstKind(InstT::Kind))`, Vtable will switch default
handling. But it's not directly printed for types, so there is no net
impact on IR.

At present I have this split from `StepStack` because with these changes
it'd no longer be a simple stack. It felt like maybe the type separation
would help readers.
2025-03-25 20:31:08 +00:00
josh11bandJosh L a7d9ac576c Narrowing facet type conversion tests (#5172)
Merges in the "subtyping" tests from the `impl/lookup` directory along
with some new tests into
`convert_facet_value_to_narrowed_facet_type.carbon` in the `facet`
directory.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-25 00:11:00 +00:00
Boaz Brickner 44bcceba86 When import C++ names, add the note on the ClangLookup() as well (#5142)
Currently has no effect because we can't do lookup in classes, yet.

Part of #4666.
2025-03-24 17:27:20 +00:00
Alexander Kornienko b3c7a7e988 Fix a compilation error with a recent Clang (#5170)
This fixes a `copy constructor must pass its first argument by
reference` compilation error when compiled with a recent enough Clang
(after
https://github.com/llvm/llvm-project/commit/fe0d3e3764961b62f43f1b129f30aaec5f30bc16,
targeted for LLVM 21 release).

```
carbon/lang/common/set.h:81:59: error: copy constructor must pass its first argument by reference
   81 |   SetView(SetView<std::remove_const_t<KeyT>, KeyContextT> other_view)
      |                                                           ^
```
2025-03-24 15:45:45 +00:00
Ivana Ivanovska ce2ff0a35d Add support for int return type in Carbon/C++ interop (#5114)
Adding support for importing C++ functions with `int` return type in
Carbon.

Part of #5063

Here is a demo of the functionality:

```c++
// hello_int.h;

auto foo_int() -> int;
```

```c++
// hello_int.cpp

#include "hello_int.h"

auto foo_int() -> int {
    return 1;
}
```

```carbon
// main.carbon

library "Main";

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

fn Carbon_foo(b: i32) {
  Core.Print(b);
}

fn Run() -> i32 {
  Carbon_foo(Cpp.foo_int());
  return 0;
}
```

```
$ clang -c hello_int.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$  bazel-bin/toolchain/carbon link hello_int.o main.o --output=demo
$ ./demo
1
```
2025-03-24 15:18:20 +00:00
Jon Ross-PerkinsandRichard Smith c0ee446cec Refactor InstBlockStore's API, AddDefaultValue -> AddPlaceholder (#5166)
`AddDefaultValue` doesn't quite capture the intended semantics; it
should typically be replaced with an actual value when dealing with
control flows. Trying to indicate the "assign later" with
`AddPlaceholder`, mirroring `AddPlaceholderInst`.

Shifting the `protected` functionality on `BlockValueStore` so that it's
not providing functions just for `InstBlockStore` to use. Also hoping
that seeing the comments next to the function name makes them easier to
understand, whereas `using` buries that a little.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-03-21 23:09:37 +00:00
Dana Jansens 6dbcc78e6c Rewrite symbolic constants in generic redeclarations (#5154)
When a generic function declaration was encountered for the second or
more time, we would FinishGenericRedecl() for the function decl, but
this just popped the generic region stack and moved on.

The issue with that is when the stack entry is gone, we lose the
symbolic constants from that declaration, and are unable to rewrite them
to point to the actual generic. This left us with a function declaration
with abstract symbolic values that were not useful, and in a function
call we use the declaration attached to the definition, which would be a
declaration with broken symbolic values. Then the function would be
uncallable since deduce would be unable to determine argument types
without the generic bindings.

This resolves the issue for functions, as well as ensuring the correct
generic id from a previous declaration is used for other generic entity
types that have redeclarations.

When a function declaration is qualified, such as defining a class
method outside the class body, we need only the function declaration to
contribute to its generic region stack. The code was collecting constant
values from all qualifier segments together incorrectly.

So when we PushNameQualifierScope(), we also drop the current generic
region stack and rewrite its constant values by calling
FinishGenericRedecl(), and open a new stack entry for the next part of
the qualified declaration.

If a generic declaration somehow has more dependent instruction than a
previous declaration, it would add new instructions to its eval block
with indices beyond the elements in the actual declaration eval block,
since we only store the block from the first declaration found. To avoid
this we plumb through that we are in a redeclaration, and terminate with
an ICE instead of adding new instructions to crash on later.

Fixes #5136.
2025-03-21 22:26:08 +00:00
Jon Ross-Perkins 832c6398d6 Reduce explicit SemIR::LocIdAndInst construction (#5153)
Building on #5151 reducing `UncheckedLoc` use, further remove uses of
the `SemIR::LocIdAndInst` constructor where we typically have overloads
that don't need it. Add parallel convenience wrappers for placeholder
insts.

Also refactors `MergeReplacing`. I don't think it makes sense to add an
overload for `ReplaceLocIdAndInstBeforeConstantUse`, but we can still
reduce the `LocIdAndInst` construction there.
2025-03-21 21:45:53 +00:00
Dana Jansensandjosh11b 402dc2c064 Add some test cases of specialization (#5165)
- A test that should fail that looks to see we poison impls when we do a
concrete lookup, so you can't define an impl specialization after we
looked for it. This currently passes but should fail.
- A test with a final specialization with a type constant written before
a generic function using it. The generic function should be able to know
the concrete type of the constant. This currently fails, and was
discussed in open discussion here:
https://docs.google.com/document/d/1Iut5f2TQBrtBNIduF4vJYOKfw7MbS8xH_J01_Q4e6Rk/edit?resourcekey=0-mc_vh5UzrzXfU4kO-3tOjA&tab=t.0#heading=h.swr8311y952x
- A test with a specialization written after a generic function, which
will be used symbolically so the type constant will not be known. This
fails and should continue to, though the error diagnostic may change in
time.
- A test with a specialization written after a generic function, and
which returns a value typed as the type constant from that
specialization. The generic is called with types that should cause it to
use that specialization in the specific, so the caller gets back the
type expected. This currently fails but should pass.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-03-21 20:38:24 +00:00
Jon Ross-Perkins 868efb7c86 Make INCLUDE-FILE less sensitive to path changes (#5159)
It's helpful for stability to not have the path in the repo reflected in
test files, something I'm separately running into. So to reduce this,
align INCLUDE-FILE with other split behavior:

- Use the filename (with a "include_files/" subdir to disambiguate),
rather than the full path.
- Note if we eventually want to support splits in these, the same
approach could be extended.
- Only provide as an arg if the user requests files as args.

Factoring AddFile back because it's hard to share; I'm also advocating
to remove the prelude manifest, which would mean the remaining call
could be removed.
2025-03-21 16:03:25 +00:00
Dana JansensandRichard Smith 6041e9aa9d Use a "type structure" of each impl to choose the best match (#5124)
The type structure is built for the impl lookup query for the
combination of the self type and the interface being queried. Then it is
built for each `impl` definition that is a potential candidate.

The type structures are compared to ensure they have a compatible
structure, and the `impl` declaration is not considered if they do not.

Finally, the type structures are used as a sorting key for the candidate
`impl` declarations, with the most-specified type structures (the ones
with the furthest distance to the first symbolic value) coming first in
the ordering.

See
https://docs.carbon-lang.dev/docs/design/generics/overview.html#parameterized-impl-declarations
for the design of the type structure and related ordering.

Most of the commits in this PR landed in #5158 (11ae0e27ab) by
mistake, but this includes the final changes since that PR was written.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-03-21 15:27:45 +00:00
Dana Jansens 9131b3a0de Use CARBON_KIND in deduce for FacetAccessType (#5163)
Small cleanup to use CARBON_KIND instead of .As<>
2025-03-21 00:02:05 +00:00
David Blaikie 4f0a0819c5 Minor test updates to out of date comments (#5161)
These two cases seem to work correctly now - must've forgot to clean
them up at some point.
2025-03-21 00:01:15 +00:00
Dana JansensandRichard Smith 11ae0e27ab Deduce through FacetValue (#5158)
When the parameter is a deduced symbolic FacetValue, refering to a
BindSymbolicName, and the argument is a concrete FacetValue that would
match the FacetType requirements on the BindSymbolicName's type, we
currently do not deduce that the argument matches the parameter.

The argument is not _converted_ to the parameter type because they are
both FacetValues of the same FacetType type. However they are also not
equal constant values so the argument is not saved as a deduced match
for the parameter.

In order to accept the FacetValue, we need to consider them as
`deduce_through`, which attempts to deduce each of the fields in the
argument FacetValue against the fields in the parameter FacetValue.
This deduces that the argument's concrete type matches the symbolic
BindSymbolicName and its witnesses are the same.

Since the parameter is a FacetValue, its argument is not the type that
needs to be recorded as the deduced type for the binding. The
BindSymbolicName inside the parameter is the place that we need to find
the deduced type for the binding. So simply walking into the FacetValue
gets us to that position, where we eventually record the deduced
argument type as being the concrete type from the original argument
FacetValue.

Similarly, when determining what interfaces are satisfied by a
FacetValue for deduce, we want to use the full type available in the
FacetValue rather than just those from its FacetType. Determining
availability of interfaces here is equivalent to converting, and we want
converting a FacetValue to always work on the full available type info.
Only API access (member lookup) is restricted by a FacetValue to the
interfaces provided by its FacetType type.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-03-20 23:52:50 +00:00
Dana Jansens b10c1ccbb9 Look through FacetAccessType and FacetValue self types in impl lookup (#5160)
If a self type is FacetAccessType, we look through it at the facet
value, both for the query and the impl declaration. This ensures that
while FacetAccessTypes match each other for constant value equality
still, they an also match with facet value queries, such as:
```
impl forall [T:! Y] T as Z {}
                    ^ FacetAccessType for BindSymbolicName of type FacetType(provides Y).

fn F(y:! Y) {
  y as Z;
  ^ Facet value
}
```

Here the facet value and FacetAccessType don't have the same constant
value. Deduction will give the `T!: y` binding the facet value of `y`,
but the `T` in `T as Z` is a FacetAccessType to that binding, which is a
different constant value. Looking through the FacetAccessType gives us
the desired constant value for comparison with the query.

Additionally if the query self value is a FacetValue instruction, look
through that at the underlying type value. Impl lookup is used to
convert from one type or facet value to a new facet value of the desired
facet type. We want facet values to always be able to convert to
everything possible, rather than to have that restricted to just their
current FacetType:
https://github.com/carbon-language/carbon-lang/issues/5137. So this
allows queries such as `(C as Y) as Z` for a class `C` and interfaces
`Y` and `Z`.
2025-03-20 23:47:45 +00:00
Jon Ross-Perkins 381a01f673 Fix clang-tidy action handling of deletes (#5162)
Example error I'm trying to fix:

https://github.com/carbon-language/carbon-lang/actions/runs/13979696174/job/39142020031

file_system.cpp is deleted and not part of any targets. It should be
excluded from the query.
2025-03-20 23:25:42 +00:00
Boaz Brickner 3a5e18b1a1 In C++ interop, stop referring to the diagnostics consumer before deleting it (#5149)
Part of #4666
2025-03-20 18:37:25 +00:00
josh11bandJosh L a62a8cfd84 Add test with example from 2025-03-19 discussion (#5157)
This example motivated a decision to add a feature where we do impl
lookup to see if there is a matching `final` impl even in some cases
where it is already established that the type implements the interface.
I don't know when we plan on implementing this, but I wanted to capture
the example as test so we would have a TODO to address it.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-20 17:17:27 +00:00
Dana Jansens 489d5298f2 Add a newline to the end of Printable::Dump() (#5155)
This makes it friendlier in interactive debuggers. If you want to print
a value without a newline from code, you will have to be calling Print()
anyway since Dump() is private, and Print() does not add a newline.
2025-03-20 16:03:43 +00:00
josh11bandJosh L d431e1fbf4 Never perform instance binding with implicit Self in an interface (#5121)
Resolves TODO by creating new function `GetAssociatedValue` with the
logic from `PerformCompoundMemberAccess` restricted to the
non-instance-binding case.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-20 04:25:35 +00:00
Jon Ross-Perkins 701f12d9a2 Clean up LocIdAndInst::UncheckedLoc uses (#5151)
Adds subset conversion of `NodeIdOneOf` due to the choice usage, plus
the pre-existing TODO. Fixes incorrect information about nodes on
StructLiteral and TupleLiteral.

After this change, `UncheckedLoc` is only used in a couple import
contexts (hard to verify) plus `InstStore::GetWithLocId`.
2025-03-20 00:48:35 +00:00
Jon Ross-Perkins 84a8c458f9 Error when using emitter.Build().Emit() (#5152)
I've found myself cleaning up other cases of this, so moving to disallow
it.

```
In file included from toolchain/check/merge.cpp:5:
In file included from ./toolchain/check/merge.h:8:
In file included from ./toolchain/check/context.h:13:
In file included from ./toolchain/check/decl_introducer_state.h:8:
In file included from ./toolchain/check/keyword_modifier_set.h:11:
In file included from ./toolchain/sem_ir/name_scope.h:10:
In file included from ./toolchain/sem_ir/ids.h:12:
./toolchain/diagnostics/diagnostic_emitter.h:95:11: error: static assertion failed: Use `emitter.Emit(...)` or `emitter.Build(...).Note(...).Emit(...)` instead of `emitter.Build(...).Emit(...)`
   95 |           false,
      |           ^~~~~
toolchain/check/merge.cpp:92:61: note: in instantiation of function template specialization 'Carbon::DiagnosticEmitter<Carbon::Check::SemIRLoc>::DiagnosticBuilder::Emit<>' requested here
   92 |   context.emitter().Build(loc, ExternRequiresDeclInApiFile).Emit();
      |                                                             ^
1 error generated.
```
2025-03-19 23:33:52 +00:00
Richard Smith 584426dfa2 Initial work on support for templates (#5081)
This broadly follows the design described in [this design
document](https://docs.google.com/document/d/1eWW8MTko3PIqxZ32-GhsdaRSYqoDicxMB1VeessMTOg/edit?pli=1&tab=t.0).

Support is provided for only two primitives for now -- simple member
access and type conversion -- to demonstrate the basics of the
functionality.
2025-03-19 20:19:21 +00:00
Richard Smith 38d3ff650f Qualified lookup into types being defined (#5087)
Allow qualified name lookup into classes and interfaces as soon as we
reach the `{` of the definition, rather than disallowing such lookups
until we reach the `}`.
2025-03-19 15:29:51 +00:00
Dana Jansensandjosh11b 5724407e4d Delete the GetConstantValue overload for AbsoluteInstId (#5145)
This prevents conversion from an InstId which is its base class, and
documents that this is invalid in the code.

Also expand the comment on the AbsoluteInstBlockId, which I had locally
but seem to have not saved and included in #5141.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-03-19 03:59:04 +00:00
Richard Smith 1d08b731da Remove some unnecessary / unused SFINAE support. (#5148)
We were going to lengths to make these functions callable only if
`LocIdAndInst` was constructible, but nothing was depending on that and
it was harming readability and probably making diagnostics worse. So
stop doing that.
2025-03-19 03:53:35 +00:00
Alina Sbirlea 5a4b63a040 [Refactor] Move call_params_id from EntityBase to FunctionFields. (#5146)
Move call_params_id from EntityBaseWithParams to FunctionFields.

No visible difference for Function. Since field call_params_id is
function specific fits better in FunctionFields.
2025-03-18 23:49:24 +00:00
Dana Jansens b72d8dfc0e Append the source-map configs for lldb (#5147)
Currently we do `settings set` twice which means the second one
overrides the first one, instead of ending up with a source-map that has
both entries in it.
2025-03-18 23:08:23 +00:00
Richard Smith 4d2cca48c7 Compute a correct SpecificFunction when resolving an indirect call to an impl function (#5116)
When performing a call through an impl witness, the callee that we
type-check against is the function in the interface, so we form a
specific for that callee. However, once the impl witness access
resolves, the eventual callee is a different function -- the function in
the impl -- so this would cause us to form a `SpecificFunction` where
the callee is one function but the specific refers to a different
function.

Address this by adding another instruction, `SpecificImplFunction`, that
takes a function in an impl and a specific for the corresponding
function in the interface, and computes and returns a `SpecificFunction`
referring to the corresponding specific function in the impl, or returns
a direct reference to the function in the `impl` if it's not a generic
function.
2025-03-18 21:26:52 +00:00
Jon Ross-Perkins 24c173b10f Try using same_pkg_direct_rdeps for clang-tidy action (#5144)
This is trying to reduce how much we run tidy over due to poor
performance of tidy.

It's opening the door for issues where a header file is modified in a
way that introduces tidy issues in a different target. However, that's
not the typical tidy issue we see.

There may also be a risk where a source file indirectly becomes a source
file for a target in a way that `same_pkg_direct_rdeps` doesn't return,
but I'm not sure that's applicable for how we use targets.

An example of this locating a diagnostic error can be found in the "Add
tidy issue" commit's run (which I cancelled before it finished running,
but note the error):

https://github.com/carbon-language/carbon-lang/actions/runs/13932649182/job/38993348130?pr=5144
2025-03-18 21:04:29 +00:00
Dana Jansens 5a86df1058 Dump the LocId with the InstId from Check (#5140)
Check can print the full location for a LocId properly, but SemIR can
not since File doesn't have access to Lex.

So when dumping InstId from Check, include the LocId, to avoid making us
type `call Dump(context, context.insts().GetLocId(x))` all the time.
2025-03-18 19:44:22 +00:00
Dana Jansens e7493d9112 Dump the inst block with the specific (#5138)
Every time I dump a specific id, the next thing I do is dump the inst
block. This saves typing `SemIR::MakeInstBlockId(x)` all the time.
2025-03-18 19:43:49 +00:00
Jon Ross-Perkins b555392cee Add a typed node return to AddNode (#5123)
Building on #5120, make a variant of `AddNode` that returns typed nodes,
and replace `UnsafeMake` uses with it. This switches to templating in
import parsing so that we can get type validation.

With this change, `UnsafeMake` ends up used in three places: `Tree::As`,
`Tree::TryAs`, and `Context::AddNode`. That should mean that all typed
nodes are verified.
2025-03-18 16:59:33 +00:00
Dana Jansens a801a982bc Delete the GetConstantValue overload for AbsoluteInstBlockId (#5141)
This prevents conversion from an InstBlockId which is its base class,
and documents that this is invalid in the code.
2025-03-18 16:29:28 +00:00
Boaz Brickner caaeabce09 Update comment following a rename (#5139)
Rename:
https://github.com/carbon-language/carbon-lang/pull/4100/commits/6da9a9ee19eec002878a0d59a1af00d24f515d9a
2025-03-18 15:19:22 +00:00
Jon Ross-Perkins dfe1c880ea Clean up node kind information for namespaces (#5120)
This flows out of #5084 and trying to reduce UnsafeMake use. It turns
out imports and namespaces were using unexpected node kinds (previously
ImportIntroducer instead of ImportDecl, for example). This fixes and
adds validation.

I was uncertain about whether to just remove the is_convertible check,
since I don't see it as motivating creation of a conversion between
NodeIdOneOf types. So I've just left a TODO for now.
2025-03-18 00:44:18 +00:00
Jon Ross-Perkins 8738497301 Fix parse support for 'fn F[];' (#5135)
According to approved syntax at
https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p3848.md#syntax-defined,
`fn F[]` without explicit parameters should be valid. This makes it
work, then adds some validation to prevent `class C[]` in check.

Note that for `fn`, positional parameters are a TODO -- but this allows
me to test validation in `fn destroy[]` which is rejected, not just a
TODO.
2025-03-18 00:31:17 +00:00
Geoff RomerandJon Ross-Perkins a584ee120e Add support for _ binding patterns (#5097)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-03-17 22:29:56 +00:00
Dana Jansens d8d2da4ea0 Make conversion tests into min_prelude tests (#5106)
Avoid duplicating a `Core` package into each test, point them to
//toolchain/testing/min_prelude/convert.carbon which we add in this PR
with the As and ImplicitAs interfaces.

Move the tests of facet conversions from builtin_conversions/ to facet/
and the test of deducing through a member access into deduce/. This
eliminates the check/testdata/builtin_conversions/ directory, which was
making it hard to find where tests are for facet conversions. Now we
have one fewer place, and facet/ seems to be a fine home for them.
2025-03-17 15:27:41 +00:00
Jon Ross-Perkins 3ddc752d49 Allow InstNamer to rediscover singleton instructions (#5133)
This fixes a crash where a singleton (particularly errors) can be found
in multiple scopes, which InstNamer finds disagreeable.
2025-03-17 14:55:32 +00:00
Boaz Brickner fcd38a4d7f Add support for importing C++ namespaces (#5103)
This adds support for having different C++ `NameScope`s (and not just
the main `Cpp` scope), and we keep a pointer to `clang::DeclContext`
these scopes so we can look up C++ names in the right part of the AST.

C++ Interop Demo with a namespace:

```c++
// hello_world.h

namespace some_namespace {

void hello_world();

}  // namespace some_namespace
```

```c++
// hello_world.cpp

#include <cstdio>

namespace some_namespace {

void hello_world() { printf("Hello World!\n"); }

}  // namespace some_namespace
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  Cpp.some_namespace.hello_world();
  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
Hello World!
```

Closes #5102
2025-03-15 20:41:48 +00:00
Alina Sbirlea fdedbb037d Add some tests for lowering generics. (#5131)
Adding some tests that show current lowering and limitations.
2025-03-15 05:44:18 +00:00
josh11bandJosh L fb3721df9a Impl lookup allowed for incomplete facet types (#5132)
New planned direction is to not require completeness. Updated comments
to reflect that some care will be needed once named constraints are
supported. Long term plan is [discussed in
#5089](https://github.com/carbon-language/carbon-lang/pull/5089#discussion_r1985908453):

> We have some options. In our last conversation, it sounded like it
would be beneficial for named constraints to have their own witnesses,
with entries in declaration order. This would allow accesses to the
named constraint while it was being defined. So there would be something
of a hierarchy in a facet type witness, with a named constraint taking a
single slot in a facet type witness, independent of its definition.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-15 02:21:49 +00:00
Dana Jansens ce7a0a4d07 Support conversion from facet value to facet value (#5085)
When converting from a facet value (an instruction whose type is
FacetType), we require making a FacetAccessType
to have a type instruction when building the resulting FacetValue.
Otherwise, the conversion is the same for values of type TypeType, and
we relax the convert function to support either.

Corrects the test expectations for converting `Goat as Animal`, a facet
value of type FacetType, into `Eats`, a facet type of type TypeType.
This would be a promotion in the typish hierarchy which is incorrect. We
had an extra case in Convert that was handling this, and it's now
removed. `Animal`, a facet type, does still correctly convert into
`Eats`, a facet type, if `impl Animal as Eats` exists.
2025-03-14 23:58:36 +00:00
Dana Jansens 1374a41b08 Print NOAUTOUPDATE when _not_ autoupdate (#5134)
Currently it prints the message for autoupdate tests
2025-03-14 22:57:33 +00:00
Jon Ross-Perkins 216c499cbf Add declaration checking for fn destroy (#5127)
This adds support for the `destroy` name, and checking of `fn destroy`
structure. It does not add support for the actual destructor calls.
2025-03-14 22:54:12 +00:00
Jon Ross-Perkins 93ecd70827 Writeup for why we don't do deeply restrictive parsing (#5129)
Modifiers came to mind since we had a bit of discussion way back when,
about whether parse or check was the best place to do validation. Trying
to capture the tradeoffs to consider here.

Note, I'm writing this up mainly because I was asked why I don't reject
`fn destroy;` in parse twice (but still allowing things like `fn
destroy();` or `fn destroy[]();`), so I've been thinking a reference of
the higher-level parsing philosophy would be helpful.
2025-03-14 22:22:29 +00:00
Jon Ross-Perkins 21687e8cb1 Fix use of keyword names in qualifiers with params (#5130)
This is a crash bug, since NameQualifierWithParams needs a specific open
kind. I'd missed that this wasn't actually tested.
2025-03-14 20:16:01 +00:00
Dana Jansens 417b3833e2 Produce helpful diagnostics when converting to a facet fails (#5109)
When converting to a facet there are three different failure modes:

1. You provided a non-type value. Only types can convert to facets. So
we tell you that we found a non-type value.
2. You provided a facet type (which has type TypeType) which does not
have witnesses for the the target facet's type. So we tell you that the
type `T` implements `X` but needs to implement `Y`.
2. You provided a (non-facet-type) concrete type (of type TypeType)
which does not implement the target facet's type (which is a FacetType).
So we tell you that we need the type to implement the FacetType but it
does not.
3. You provided a FacetAccessType (which is of type TypeType also, but
we special case this), whose underlying FacetType is not compatible with
the target facet's type. So we tell you that we need the type to
implement `X` but found a FacetAccessType `T` which implements `Y`.

Closes #5027
2025-03-14 15:50:03 +00:00
Jon Ross-Perkins db21c38550 Use the NameComponent's name_id when making an entity base (#5125)
This changes the SemIR of invalid redeclarations, because previously
they lacked a name. We've avoided this in diagnostics so it doesn't
otherwise come up, but I plan to use it for more easily validating
redeclarations.
2025-03-14 15:27:24 +00:00
Dana Jansens a3fc83f85a Add a failing todo test for using a symbolic associated constant (#5128)
The type of the constant should be resolved to the concrete C(D) but its
only treated as the symbolic C(T).
2025-03-14 13:22:57 +00:00
Dana Jansens ce08e4d9a1 Avoid UAF in impl lookup when deduce imports an impl from Core (#5126)
Deduction can do conversion, and conversion can import impls from the
Core package. If you have the right number of impls in your ImplStore at
that moment, it will reallocate and any pointer into context.impls()
will be invalidated.

In particular, in impl lookup, we currentl loop over context.impls() and
do deduction on each impl. So this can break the for loop. Additionally,
we pass around a reference to the currently-being-looked-at Impl, which
becomes invalidated.

This is very challenging to test in any reliable way as you need a
specific number of impls in your ImplStore. I hit it when making changes
to a test in the middle of a bunch of file splits. Putting the same test
in its own file did not trigger the issue. It was caught by ASAN, which
showed:
- The memory was allocated by SmallVector in handle_impl when making the
Impl.
- The memory was freed by SmallVector reallocating in import_ref.cpp
- The memory was accessed when reading through the `impl` reference in
FindWitnessInImpls(). I was able to reproduce by printing the
`impl.interface.interface_id` after the call to GetWitnessIdForImpl()
which does the deduction.

I didn't save the ASAN stack and now I can't find the exact permutation
of the test file that caused it to occur in order to reproduce. :(

To avoid the UAF we stop passing around the Impl reference, and pass
around either the ImplId, or values from the Impl. To avoid copying the
entirety of the impl ids in context.impls() into a separate container in
order to iterate safely, we move the early outs from
GetWitnessIdForImpl() up to the caller where it can use them to reduce
the number impl ids that we iterate over. Type structures will be able
to further reduce the size of this set.
2025-03-14 00:44:51 +00:00
DavidLoftusandJon Ross-Perkins c302d0bc7a Allow LSP test_file to autofill didOpen params from previous splits (#5078)
Currently file tests for LSP must provide carbon source code as an
escaped string within notify params, i.e.
```
[[@LSP-NOTIFY:textDocument/didOpen:
  "textDocument": {
    "uri": "file:/class.carbon",
    "languageId": "carbon",
    "text": "class A {\n  fn F();\n  fn G() {}\n}\n"
  }
]]
```

This works fine for simple, single line files but gets annoying when
working with more complicated files which are necessary when testing
more complicated features e.g. goto-definition

```
--- class.carbon
class A {
  fn F();
  fn G() {}
}
--- STDIN
[[@LSP-NOTIFY:textDocument/didOpen:
  "textDocument": {
    "uri": "file:/class.carbon",
    "languageId": "carbon",
    "text": "AUTOFILL"
  }
]]
```

This PR extends file_test_base to be able to parse the notify/call
params and inject files from the test_file's splits into the JSON input.
I purposely avoid using the clangd types and manually parse the
llvm::json::Value here to avoid introducing a depdendency on clangd to
the generic file_test_base, but happy to change if we think that is
fine. Also happy to accept other suggestions on alternative methods to
achieve same result.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-03-13 17:22:20 +00:00
Richard Smith 59003a5d4c Fix crash discovered by fuzzer. (#5100)
If the vtable of a base class is erroneous, generate an erroneous vtable
for the derived class too.
2025-03-12 21:35:31 +00:00
josh11bandJosh L 5966fbc758 Get impl witnesses from facets cast to type (#5115)
Addresses a TODO in `impl_lookup.cpp`.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-12 20:55:07 +00:00
Jon Ross-Perkins b336e4bd0d Remove method keywords from class functions. (#5112)
Note this builds on #5098
2025-03-12 18:56:38 +00:00
Boaz Brickner a4a229b637 Initialize cpp_mangle_context_ in Mangler's constructor (#5095)
This is a followup of [a
comment](https://github.com/carbon-language/carbon-lang/pull/5062/files/89e56d51858bcc18d4242d4e5c9ee0e7496d887e#r1979993815)
in #5062.

Add a mutable AST pointer to `FileContext`.

This is necessary since we use [Clang with lack of const
correctness](https://github.com/llvm/llvm-project/pull/130096#issuecomment-2704413782).

Alternatives in Clang:
* Change `ASTUnit::getASTContext() const` to return a non-const
`ASTContext`. [Tried and was rejected upstream due to weakening const
correctness](https://github.com/llvm/llvm-project/pull/130096).
* Change `createMangleContext()` to be `const`. Tried that and it seems
like it relies heavily on non const API.
* Change `MangleContext::mangleName()` to `const`. Tried that but there
are several lazy initialization and id creations happening that modify
the context. See details in
https://github.com/llvm/llvm-project/pull/130613.

Alternatives in Carbon:
* Use `const_cast` on `ASTContext` when calling `createMangleContext()`.
* Make `FileContext::sem_ir_` point to a mutable `SemIR::File`.
* Change `File::cpp_ast()` to be const while keeping it return a mutable
pointer.

Part of #4666.
2025-03-12 18:49:43 +00:00
Dana Jansens 288181453e Prevent BitAnd for facet types from matching non-type values (#5111)
Currently this test fails with trying to access a comptime function with
runtime values:
```
fn F() {
  let a: J = {} as J;
  let b: J = {} as J;
  // CHECK:STDERR: fail_bit_and_values_no_impl.carbon:[[@LINE+7]]:3: error: non-constant call to compile-time-only function [NonConstantCallToCompTimeOnlyFunction]
  // CHECK:STDERR:   a & b;
  // CHECK:STDERR:   ^~~~~
  // CHECK:STDERR: core/prelude/operators/bitwise.carbon:96:3: note: compile-time-only function declared here [CompTimeOnlyFunctionHere]
  // CHECK:STDERR:   fn Op[self: Self](other: Self) -> Self = "type.and";
  // CHECK:STDERR:   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // CHECK:STDERR:
  a & b;
}
```
The issue is that the BitAnd impl for facet types is matching on any
value of any type:
```
impl forall [T:! type] T as BitAnd
```
What we really want is for it to match on facet types (which are type
values), which is written as:
```
impl type as BitAnd
```
After this change, the error makes more sense in the above test:
```
fn F() {
  let a: J = {} as J;
  let b: J = {} as J;
  // CHECK:STDERR: fail_bit_and_values_no_impl.carbon:[[@LINE+4]]:3: error: cannot access member of interface `Core.BitAnd` in type `J` that does not implement that interface [MissingImplInMemberAccess]
  // CHECK:STDERR:   a & b;
  // CHECK:STDERR:   ^~~~~
  // CHECK:STDERR:
  a & b;
}
```
2025-03-12 18:35:03 +00:00
Richard Smith 6fd139b805 Renumber inner parameters when checking an impl function against an interface function. (#5113)
This allows the numbering of the parameters to match when checking for a
valid redeclaration. It also prepares us to produce the proper numbering
when generating a thunk.
2025-03-12 13:54:49 +00:00
Jon Ross-Perkins e6872f9499 Change NodeIdOneOf and similar to use "requires" and explicit UnsafeMake (#5084)
This doesn't change functionality, but I was seeing better diagnostics
in VS Code.

This also changes the NodeId constructors for related types (also
NodeCategory and NodeIdForKind) to use UnsafeMake for construction. That
originated from avoiding ambiguity coming from `requires`, but the
constructor mode is also one we should typically avoid (e.g., preferring
`Parse::Tree::As`).
2025-03-12 00:33:54 +00:00
josh11bandJosh L ebaf62efb9 Associated constants can be used in member function signatures (#5089)
This required allowing incomplete facet types where previously
completeness was required. Once we support named constraints, we will
need a way to consistently go from an interface to a facet type witness
index without requiring the interface to be complete in these cases.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-12 00:33:46 +00:00
Jon Ross-Perkins 68f6906c9f Refactor BuildFunctionDecl (#5098)
Trying to break apart the function on reasonable boundaries because it's
big. Changes behavior of class functions with virtual modifiers to
remove the modifier when diagnosing, which is more consistent with other
modifier diagnostics.
2025-03-11 22:53:13 +00:00
Dana Jansens bdf5d17b06 Move impl cycle tests to min-prelude (#5108)
Use the facet_types min-prelude instead of defining a Core package in
the test file.
2025-03-11 19:38:12 +00:00
Dana Jansens 82fe19ee99 Remove redundant deduced specifics (#5107)
When deduction has to substitute binding parameters into further generic
parameters, we do conversion of the argument to the substituted type.
Then we replace the argument instruction id with that Converted
instruction. This causes a redundant specific to be created for the
Converted instruction which is not needed. What we want is the specific
for its constant value.

So when we replace the argument instruction id, replace it with the
instruction from the constant value of the converted argument.

This was raised in [discord
#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1349067541070217306).
2025-03-11 19:16:32 +00:00
Boaz Brickner 201a4dc1c6 Move the test for unsupported C++ interop decl type out of function_decl.carbon (#5104)
It's not specific for functions

Part of #4666
2025-03-11 17:47:41 +00:00
Dana JansensandJon Ross-Perkins c9c88e5b54 Make file test readme refer to toolchain docs (#5105)
Instead of duplicating the content (slightly differently)

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-03-11 17:36:31 +00:00
Jon Ross-Perkins 10eb8ed314 Reuse a merged function's type ID (#5099)
This makes inline and out-of-line functions produce the same type.

I was looking at this and wasn't sure if it was deliberate. It seems
desirable to reuse the type when possible, since it's probably cheaper
too.
2025-03-11 16:21:57 +00:00
Dana Jansens d58b523a5e Add INCLUDE-FILE: and --custom-core for file tests to specify a minimal prelude library (#5080)
The INCLUDE-FILE option is only used in the toolchain tests for now. If
specified in a file test, the given file path is added to the test's
arguments. For toolchain tests this makes the file's package available
to the test. The `--custom-core` command line flag is added to the
driver, which avoids adding the production `Core` package to the command
line. Together, these allow a test to provide their own minimal `Core`
package.

For example, this would replace `Core` with the package and prelude in
`facet_types.carbon`.
```
// INCLUDE-FILE: toolchain/testing/min_prelude/facet_types.carbon
// EXTRA-ARGS: --custom-core
```

To support this:
* //testing knows how to parse INCLUDE-FILE out of the header of a test
file.
* //testing adds the file to the virtual file system, and includes it in
the test's arguments.
* //toolchain/driver grows the --custom-core command line flag to avoid
loading the production `Core` package.

Tests that were creating their own minimal prelude to define BitAnd on
types are now pointed to
toolchain/testing/min_prelude/facet_types.carbon as the prelude. They no
longer need to `import Core` in each test as a result.

Such tests are no longer `no_prelude`, but instead have their own
prelude. So they are moved to a `min_prelude` subdirectory.

Closes #5076
2025-03-10 19:44:50 +00:00
Dana Jansensandjosh11b 4539114c21 Return a set of ImplWitnesses from impl lookup (#5075)
A query facet type may contain multiple required interfaces, in which
case impl lookup should return an ImplWitness for an impl that is used
for each interface in the query. We bundle these together into an
instruction block and return that from impl lookup. The witnesses are in
the same order as the interfaces in the
`CompleteFacetType::required_interfaces`. This allows walking the
`required_interfaces` to find an interface to give an index that can
also be used to grab a witness from this set, or from FacetValue.

FacetValue now has an InstBlockId for the set of witnesses of the
FacetType, instead of a single ImplWitness instruction id.

FacetAccessWitness includes the index of the witness (determined from
the position in `required_interfaces`) of the witness it's accessing
from the FacetType.

The
toolchain/check/testdata/facet/no_prelude/fail_todo_call_combined_impl_witness.carbon
test demonstrates the fix in the resulting SemIR. We can see the calls
to methods on a multi-interface FacetType result in a FacetAccessWitness
with an index of the correct interface, and this results in a witness
that leads to the correct impl's function.

There is a TODO in member access, where it does not have a
`CompleteFacetType` yet, so it uses the index in
`FacetTypeInfo::impls_constraints` instead, but this can be incorrect in
the presence of named constraints, which when completed can add more
interfaces to the `CompleteFacetType` and which are sorted into an
arbitrary order with the rest there.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-03-10 16:00:35 +00:00
josh11bandJosh L 176f9f1cc4 Improve debug Dump for NameScopeIds (#5088)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-10 15:38:56 +00:00
josh11bandJosh L b3be298f7f Fix test that used i32 in a no_prelude directory (#5086)
Exclude SemIR since the point of the test is that it diagnoses something
invalid, not that any particular SemIR is produced.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-08 06:18:18 +00:00
Alina Sbirlea 7fd54eded0 Reverse nesting of BoundMethod and SpecificFunction. (#5079)
During SemIR, when identifying a specific in a specific context, we'd
have to either look through a specific or through a bound method.
Canonicalize which one to look through first, by having the BoundMethod
created around a SpecificFunction instead.
This changes a lot of check tests.

TODO: As the SemIr does not currently allow removal (access to insts()
is intentionally const), the bound instruction created prior to finding
the specific is not removed from the instructions.
Options: (1) leave as is, (2) add a way to remove the previous bound,
(3) rethink how/when the BoundMethod inst is created.
2025-03-08 01:34:06 +00:00
josh11bandJosh L 820ace95e8 Update LLVM (#5082)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-07 19:34:31 +00:00
Jon Ross-Perkins baffb66bc9 Fix empty arg handling in extension (#5083)
Oops, broken in #5056
2025-03-07 19:19:04 +00:00
josh11bandJosh L aa90ab3862 Fix non-instance compound member access (#5059)
Implements the rule:

> For compound member access `a.(b)` where `b` names a _non-instance_
member of an interface `I`:
> * `a` is implicitly converted to `I`
> * let `T` be the result of symbolically evaluating the converted
expression
> * `impl` lookup is performed for `T as I`.
>
> Instance binding is never performed.

See
https://docs.carbon-lang.dev/docs/design/expressions/member_access.html#impl-lookup-for-compound-member-access.
Before this PR, non-instance members were treated as instance members.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-07 01:37:07 +00:00
Geoff RomerandRichard Smith 6d4f2567a7 Add support for var patterns (#5069)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-03-06 19:06:51 +00:00
josh11bandJosh L 331f55f0a2 Handle impl with bad interface on import (#5051)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-06 18:02:29 +00:00
ea1a0c8b84 Find impl witnesses in facets (#5060)
Impl lookup for an interface `I` for a facet with facet type requiring
an interface `I` will now succeed, getting the witness from the facet.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-03-06 17:58:53 +00:00
Alina Sbirlea d3869a529b Continue: emit function definitions for specifics. (#5068)
Resolve instruction id depending on the context from which a function is
called.

Calling a function in a function context that does not have a definition
emitted before reaching lowering will cause a crash. This needs a change
in check/eval layer.
2025-03-06 17:40:35 +00:00
Boaz Brickner 156ab889f8 Support mangling imported C++ functions using Clang's MangleContext (#5062)
Keep a pointer to the Clang declaration in Carbon's function declaration
and use it in Carbon mangling by calling Clang mangling.
Create Clang's `MangleContext` once on demand.

Part of #4666.

C++ Interop Demo:

```c++
// hello_world.h

void hello_world();
```

```c++
// hello_world.cpp

#include <cstdio>

void hello_world() { printf("Hello World!\n"); }
```

```
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  Cpp.hello_world();
  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
Hello World!
```
2025-03-06 09:51:01 +00:00
Boaz Brickner d25140e8b9 Add a test that should catch checking poisoned names when extending a class (#5071)
See
https://discord.com/channels/655572317891461132/655578254970716160/1346727881912619081

Part of #4622.
2025-03-06 08:45:23 +00:00
Dana Jansens d9bee4b26d Fix the error message in fail_todo_convert_facet_value_to_narrowed_facet_type.carbon (#5077)
Now that BitAnd for types exists, we should get an error about type
conversion, not about BitAnd not existing. Add `type.and` to the Core
package in the test in order to improve the error message.

This test will likely be made to pass by #5060.
2025-03-05 23:00:32 +00:00
Dana Jansensandjosh11b a0b7f39591 Support impl lookup for multiple interfaces in a facet type (#5047)
If the query facet type has more than one interface, we must find an
impl that provides that interface for the query type for each interface.
This just looks like a for loop over the interfaces and ensuring we
found one impl witness for every one.

However the impl matching must change since it can't look at the
constant value of the entire query facet type for comparison with the
impl, as that query facet type may be for multiple interfaces and we are
looking to match an impl of a single interface.

To do this we break the query facet type up into each interface and make
sure the interface ids match. Then ensure that the impl was able to
deduce any generic parameters using the specific of the single query
interface.

There are some TODOs left here:

1. If the facet type for the query or the impl constraint has
"other_requirements" then we can't verify that they match since they are
lost. We fall back to comparing the constant id of the query to the
impl's constraint (after deducing generics in the impl). This correctly
eliminates mismatches but eagerly eliminates impls that could match the
query interface as well when there's more than one interface in the
query.

2. We don't return a witness for every interface in the query facet
type. Since we can't demonstrate any use of the witness there yet, for
cases that can have more than one interface in the query facet type,
this doesn't break anything that was previously working. The return
value is currently treated as a bool for cases with multiple interfaces
in the facet type (as a test for "can this be converted") but the
converted-to facet value's witnesses are unused.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-03-05 22:14:44 +00:00
Jon Ross-Perkins 79a86074b1 Fix crash when exporting a poisoned name (#5074)
Also document the constraint on `prev_inst_id`

Crash was fuzzer-found.
2025-03-05 21:55:30 +00:00
David Blaikie e71d5942bc Function decl lowering for incomplete parameter/return types (#5038) (#5066)
While current examples of this could also be addressed by emitting
declarations on use (by which stage the associated types would have to
be complete by construction) - it's expected that future examples
(vtables, function pointers) will need to work in this case anyway, so
might as well implement this feature.
2025-03-05 20:02:14 +00:00
Jon Ross-PerkinsandChandler Carruth 10a87c045a Destructor syntax (#5017)
Fix destructor syntax ambiguity by switching to `fn destroy` mirroring
standard function syntax. This is a purely syntactic change, maintaining
destructor semantics.

This comes from leads question #4999

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-03-05 16:38:44 +00:00
Jon Ross-Perkins d6b6ba17fa Update pip3 mentions to pipx (#5065)
Install advice already says pipx.
2025-03-05 03:12:55 +00:00
Chandler Carruth ca2ef22476 Add remaining clang symlinks and test them (#5050)
We only had the single `clang` symlink, but in case its useful to use
the toolchain with some other build system that expects `clang++`, or
even `clang-cl` or `clang-cpp`, fill in the rest of the symlinks.

The different `clang` flavors don't really need anything to support in
the subcommand as there is already an excellent way to get the exact
behavior of these names using Clang's `--driver-mode` flag, so these
just use that. That makes this change really *only* about busybox
behavior.

We don't really have a dedicated test path for things that are only
exposed via the symlinks, so I've added a simple Python integration test
we can use for that. I can backfill some testing of other symlinks if
useful (the `ld.lld` one might be worthwhile), although there is minimal
interesting logic to cover there.
2025-03-05 03:09:45 +00:00
Jon Ross-Perkins 659808429a Consolidate on @platforms//os:macos (#5070)
Noticed because we have a new dep on @platforms//os:macos in
https://github.com/carbon-language/carbon-lang/blob/trunk/toolchain/base/BUILD#L131

macos is preferred according to the definition at
https://github.com/bazelbuild/platforms/blob/dd28c190c563531c06ba3bd64eca1cc9ca3e667f/os/BUILD#L70C1-L74C2
2025-03-04 23:47:37 +00:00
Geoff Romer f08e046d9e Update text representation of CallParamIndex to match new name (#5067) 2025-03-04 23:28:42 +00:00
Geoff Romer d264f14027 Clean up handling of Call params (#5061)
- Explicitly document that `*Param` and `*ParamPattern` insts represent
`Call` parameters.
- Stop wrapping compile-time parameter patterns in `ValueParamPattern`
insts (because they aren't `Call` parameters).
- Document how `MatchContext::results_` relates to the `Call`
parameters, and be more consistent about when it's written to.
- Remove `RuntimeParamIndex::Unknown`: we no longer need to distinguish
"this `Param`'s runtime index is unknown" from "this `Param` isn't a
runtime param", because we no longer use `Param`s at all in the latter
case.
- Rename `RuntimeParamIndex` to `CallParamIndex`.

As a side effect of removing the `ValueParamPattern` insts, this fixes a
minor diagnostic bug where `NoteInitializingParam` didn't identify the
specific parameter that led to a deduction failure, because it expects
generic parameters to only be represented by `SymbolicBindingPattern`s,
but before this change they could be wrapped in `ValueParamPattern`s.
2025-03-04 21:01:59 +00:00
Alina Sbirlea 4e21c0c1fc Basic lowering generic function definitions. (#5016)
Resolve the specific type for the callee, to lower the proper specific
function called.
2025-03-04 18:41:29 +00:00
Jon Ross-PerkinsandRichard Smith 92b3e61289 Support language-server arguments in the extension. (#5056)
I was on the fence about just having a string which was
"language-server", but was thinking split options might be less
error-prone (e.g., changing options to just "-v" and trying to figure
out why nothing worked).

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-03-04 18:32:57 +00:00
Chandler CarruthandGeoff Romer 1459332031 Add subcommands and busybox entry points for LLVM tools (#5049)
This adds support for most of the remaining LLVM command line tools
using a generic, generated wrapper. The subcommand interface for these
is (much) less interesting than our other subcommands, but it gives us
a uniform and consistent layer.

Note that I structured these as nested sub-sub-commands below an `llvm`
subcommand because of an expectation that we will want to add more, and
ones that don't use this generic layer. Some concrete future work:

- Add the `opt` and `llc` tools as subcommands for easier debugging and
  experimentation with LLVM IR output from Carbon's toolchain.
- Potentially sink `lld` below the `llvm` layer given that it has
  significantly less user visibility than commands like `clang`.

Unfortunately, the current driver subcommand APIs make nested
subcommands awkward. I've added a somewhat rough hack here to let the
LLVM tools go in, but there are some TODOs that I want to address in
a follow-up that works to adjust the structure of this code to be more
conducive to nesting like this.

Depends on #5048 -- only the last commit should be reviewed here.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-03-04 18:00:06 +00:00
josh11bandJosh L c2281d1250 Update tests for upcoming #5059 and #5060 on member access and finding impl witnesses in facets (#5054)
Here are some test changes so the diffs that come from my upcoming
functionality changes are easier to see. Upcoming functionality
includes:
* Compound member access with non-instance associated constants will
change to comply with the design
https://docs.carbon-lang.dev/docs/design/expressions/member_access.html#impl-lookup-for-compound-member-access
in #5059 .
* Impl lookup will add support for finding impl witnesses in facets
#5060

I'm also making the toolchain/check/testdata/impl/compound.carbon test
into a no_prelude version, and adding a version that tests with
importing.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-04 17:59:30 +00:00
josh11bandJosh L 4fd273a928 2 small simplifications in member access (#5055)
* `IsInstanceMethod` can look in the function's `self_param_id` instead
of iterating through all of the implicit parameter patterns.
* An associated entity is always associated with a single interface, so
we don't need to handle the case when it isn't.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-03 23:11:38 +00:00
josh11bandJosh L 900052fcf1 Clarify conversion diagnostic (#5052)
TODO to resolve whether it should conditionally say "object of"
depending on the category

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-03 22:09:48 +00:00
Dana Jansens 3d5d62e1c7 Allow making sets and maps with move-only keys and/or values (#4982)
When the key or value is move-only, then the set or map will be as well.
2025-03-03 21:23:18 +00:00
Dana Jansens 2d1bfcac2e Perform member lookup on FacetAccessType (#5058)
The name scope lookup and member name lookup both need to handle the
case where the base inst is a FacetAccessType. Then we move from the
FacetAccessType to the FacetType which is the type of the instruction
inside the FacetAccessType.

We do name lookup on FacetType already, so "unwrapping" the
FacetAccessType to the FacetType just makes use of that path. Similarly
we do member access on FacetType already, so we can reuse that codepath
with the FacetType found in the FacetAccessType.
2025-03-03 20:17:36 +00:00
Dana Jansens 84b978e40d Test that (T as I) as type recovers its original type (#5057)
`T as I` outside of a type position is a facet value, which does not
have the interface of its original type. But when used in a type
position, or converted explicitly back to `type`, it recovers its
original type.

See
https://docs.carbon-lang.dev/docs/design/generics/details.html#facet-types:
> The requirements determine which types may be implicitly converted to
> a given facet type. The result of this conversion is a facet. For
> example, Point_Inline from the “Inline impl” section implements
> Vector, so Point_Inline may be implicitly converted to Vector as
> considered as a type. The result is `Point_Inline as Vector`, which
> has the members of Vector instead of the members of Point_Inline. If
> the facet `Point_Inline as Vector` is used in a type position, it is
> implicitly converted back to type type, see. This recovers the
> original type for the facet, so `(Point_Inline as Vector) as type` is
> `Point_Inline` again.
2025-03-03 19:42:24 +00:00
Boaz Brickner 28de6c9b7d Add --no-dump-sem-ir to all name_poisoning tests (#5053)
Follow up of previous PR discussions
([#4950](https://github.com/carbon-language/carbon-lang/pull/4950/files/89c2e66dc3190159e2f8d94c31bff31bdd0d81a1..a1650a7d73c8f4013b4b77e4d7d60933f1f6d676#r1972257889),
[#4987](https://github.com/carbon-language/carbon-lang/pull/4987/files#r1964105413)).
Part of #4622.
2025-03-03 19:25:55 +00:00
Jon Ross-Perkinsandjosh11b c44e688e5d Add parsing for 'fn destroy' (#5045)
Syntax is proposed in #5017, but has already been discussed with leads.
Semantics is left as a TODO.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-03-03 17:37:10 +00:00
Chandler Carruth 437d3b9af6 Factor out fuzzing disablement in the driver (#5048)
We end up needing to do this in any driver subcommand that reaches into
external code that may not be fully fuzz-clean. No need to grow multiple
different diagnostics for each, we can use a common diagnostic.
2025-03-03 16:14:06 +00:00
Boaz Brickner 87b9cab7b1 Add support for importing a trivial global C++ function (#5033)
ASTUnit is owned by `CompileSubcommand`, passed through `Unit` to be
populated in `ImportCppFiles()` and used via `SemIR::File`.
When generating the AST, pass `-x c++` args to compile C++ (temporary
until we pass args properly).
`Cpp` namespace is marked as a special namespace and has dedicated logic
in `LookupNameInExactScope()`.
The logic for importing declarations from C++ to Carbon is in
`import_cpp.cpp`, but we're likely to want to refactor this
signfiicantly over time as it grows (perhaps a dedicated directory?).

Part of #4666.
2025-03-03 10:38:19 +00:00
Jon Ross-Perkins f0403dadab Move None to IdBase (#5030)
Use CRTP to eliminate per-type declarations of `None`. Note this adds
`None` to a few that may not need it, but eliminates a lot off
boilerplate.

Note this leaves `GenericInstIndex::None` because it has a more complex
construction.

Also fix `InstId::InitTombstone` to be `NoneIndex - 1`
2025-03-01 08:00:17 +00:00
Jon Ross-Perkins 5574ad361d Add more empty stack verification (#5020) 2025-03-01 07:56:04 +00:00
Jon Ross-Perkins dc0c2622ac Fix multiline incremental sync. (#5046)
Previously the start index was incorrect. Adding comments where I was
double-checking things along the way.
2025-02-28 23:04:07 +00:00
Jon Ross-PerkinsandGeoff Romer 6d6987dce4 Narrow the CRC scope in file_test (#5043)
This narrows the scope of the CRC to try to get better behavior around
mutex lock releasing on crash. Closes #5042.

This breaks apart `ProcessTestFileAndRun` because we need to process the
test file for `SET-CAPTURE-CONSOLE-OUTPUT`. The test file processing
should more reliably not crash than the core `Run` logic though, so
should be reasonably safe to put outside the CRC.

Also support --threads=1 for disabling threading. This is the flipside
for me of reducing how much is in the CRC: make it easier to run on a
single thread if the CRC gets in the way of debugging. This also means a
typical copy-paste execution of a single test will be single-threaded.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-02-28 21:25:15 +00:00
Boaz Brickner fc5dcfe957 Add a test for the case that impl function is poisoned (#4950)
This adds missing coverage.
Part of #4622.
2025-02-28 21:10:37 +00:00
Jon Ross-Perkins f7e0b61c3a Refactor HandleIdentifierName away (#5044)
Most of the logic is actually in `GetIdentifierName`. I'm moving the
`CHECK` there for better sharing, also with `IdentifierNameExprId`.

Note this PR is mainly motivated by #5045, which would make this the
only place that needs `AnyNonExprIdentifierNameId` in specific (other
places need to deal with both identifiers and keywords).
2025-02-28 20:06:06 +00:00
Jon Ross-Perkins ec58a48994 Consolidate parse function tests (#5039)
These tests pretty much predate split tests. There are lots of files as
a result, and I think consolidation will help (hopefully others agree).
2025-02-28 19:34:48 +00:00
Boaz Brickner 43b9969058 Split impl/no_prelude/name_poisoning.carbon to interface/no_prelude/name_poisoning.carbon and move interface tests there (#5031)
See
https://github.com/carbon-language/carbon-lang/pull/4950#discussion_r1972252460.
Part of #4622.
2025-02-28 08:06:13 +00:00
Richard Smith f30fa2d3db Move the EvalConstantInst overloads out of eval.cpp into their own file. (#5040)
For now they're all in the same file; we might consider splitting them
further if that file gets too large.
2025-02-28 00:50:43 +00:00
Jon Ross-Perkins 536bfd9cbf Switch test manifests to embedded C++ (#5036)
Inconsistent execution environments make using a path-as-define
difficult, so switch to an embedded file.

Also fixes the lldb launch so that passing tests run cleanly, and adds
TEST_TARGET to gdb (but without testing there). I'm dropping `sourceMap`
because it's not handled quite correctly (also not great to be trying to
pass source mappings in two different ways), and `env` didn't seem to be
working as intended either; maybe specifying `initCommands` causes other
things to not be evaluated. But the straight `initCommands` looks like
it's working. I used lldb to validate execution of these changes.

```
Running initCommands:
(lldb) command script import external/+llvm_project+llvm-project/llvm/utils/lldbDataFormatters.py
(lldb) settings set target.source-map "." "/usr/local/google/home/jperkins/dev/carbon-lang"
(lldb) settings set target.source-map "/proc/self/cwd" "/usr/local/google/home/jperkins/dev/carbon-lang"
(lldb) env TEST_TARGET=//toolchain/testing:file_test
(lldb) env TEST_TMPDIR=/tmp
Running tests with 128 thread(s)
.
Done!
Note: Google Test filter = ToolchainFileTest.toolchain/check/testdata/const/collapse.carbon
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from ToolchainFileTest
[ RUN      ] ToolchainFileTest.toolchain/check/testdata/const/collapse.carbon
[       OK ] ToolchainFileTest.toolchain/check/testdata/const/collapse.carbon (0 ms)
[----------] 1 test from ToolchainFileTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (1 ms total)
[  PASSED  ] 1 test.
Process 3869310 exited with status = 0 (0x00000000) 
```
2025-02-27 23:31:13 +00:00
Boaz Brickner 80e1a6ef61 Avoid copying NameScope and only allow moving it (#5032)
This class is not intended to be copied.
Part of #4622.
2025-02-27 22:46:46 +00:00
Alina Sbirlea 1f5e5a7b44 Add basic lowering of generic function definitions. (#5015)
Very basic (incomplete) lowering of function definitions for generics.
2025-02-27 21:17:46 +00:00
Dana JansensandJon Ross-Perkins 0d10b5cd4c Allow facet types to be combined (#5026)
The resulting facet type has its complete facet type canonicalized by
sorting and deduplicating the `required_interfaces`.

Impl lookup now uses the complete facet type. It continues to diagnose
with a TODO if it sees a complete facet type with 0 or more than 1
interface in it. Impl lookup to convert from a type to a facet value
hits this diagnosis.

Member lookup by name works on a facet type with more than one interface
because the name knows which interface to look for from the name, and
AppendLookupScopesForConstant() looks through all interfaces on the
complete facet type already to get the correct scope for the name.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-27 19:48:10 +00:00
Dana JansensandJon Ross-Perkins 129cf35d78 Support BitAnd operator between facet types (#5022)
Doing so results in TODOs in the resulting semir, since we don't handle
combining the facet types together properly or doing lookup into them.
There's a test added demonstrating this, which will be made to work in
followups.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-27 17:53:48 +00:00
Dana Jansens 92e635c2f0 Use the constant value unconditionally in deduce diagnostic (#5034)
When finding the binding entity name, always go through the binding
instruction's constant value to get a canonical instruction which will
always have an entity name attached to it.

Currently the only instructions in this position without an entity name
are ImportRefLoaded. But other indirect instructions may exist in the
future, which evaluate to an AnyBindName but are not themselves one. So
this makes the code more robust to change in the future.
2025-02-27 17:06:02 +00:00
f97f1a3e11 Add error for virtual member function without self (#5005)
This tripped over a lowering crash when a member function with self was
declared-but-not-defined, so that's why some test cases were updated to
have (empty) function definitions.

I'll follow-up with/look into a fix for the
self-declared-but-not-defined cases separately.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-02-27 17:01:29 +00:00
Jon Ross-PerkinsandDana Jansens 467e510d40 Document abbreviation style things (#4996)
We had a long discussion of this, so trying to document what seems to be
the conclusion... and also clean up the exceptions that I could find.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-02-27 02:13:17 +00:00
Richard Smith 0d2f364f39 Split evaluation up into one function per instruction kind (#5008)
Replace the large and growing `TryEvalInstInContext` function with one
function per kind. While we still have special-case handling for a small
number of instruction kinds, most instructions are now handled either
fully automatically or use a common codepath that evaluates the
instruction operands and then performs an eval-context-independent
evaluation of the instruction.

To support this, `InstConstantKind` is expanded to describe more
fine-grained details about how each kind of instruction interacts with
constant evaluation. Also, the operand kinds of instructions become
slightly more fine-grained: we now distinguish between operands that
describe the destination of an initializing expression (`DestInstId`)
from other `InstId` operands, because `DestInstId` operands need
different treatment during constant evaluation. In particular, an
initializing expression can have a constant value even if its
destination is non-constant or has not yet been set, because evaluation
of an initializing expression doesn't include the store to the
destination.

Some minor test changes:

- We now more consistently propagate errors into the results of constant
evaluation, so more instructions that depend on errors have a constant
value of `<error>`.
- Diagnostic location for invalid array types now point at the whole
array type rather than the array index expression, because
`EvalConstantinst` doesn't have access to the original expression.
- Diagnostic for failed `RequireCompleteType` doesn't print the original
type any more because `EvalConstantInst` doesn't have access to the
original expression.

As a follow-up, some of this -- in particular, the `EvalConstantInst`
overloads -- will be moved to a separate file, in an effort to split the
overall constant evaluation machinery apart from the logic to evaluate
each individual kind of instruction.
2025-02-27 01:31:26 +00:00
Jon Ross-Perkins 90b6f5a22c Refactor NodeCategory for X-macros (#5029)
Taking an approach similar to NameId in #5018
2025-02-27 01:00:10 +00:00
Richard Smith c4c3381b18 Add TypeId::is_symbolic and is_concrete. (#5024)
These just forward to the corresponding members of `TypeId`.
2025-02-27 00:21:01 +00:00
Jon Ross-Perkins 46752eeed6 Change manifest passing to drop the flag outside explorer (#5025) 2025-02-27 00:01:09 +00:00
Jon Ross-Perkins 977578add1 Update icons for slightly better sizing (#5013)
Changes utils/vscode/images/icon.png to 256x256 (["The path to the icon
of at least 128x128 pixels (256x256 for Retina
screens)."](https://code.visualstudio.com/api/references/extension-manifest#fields)),
and updates the favicon.png to use the same source image.

For reference, changing this to:

https://docs.google.com/drawings/d/16V_E_LS7zqZu6VkNdZgIMqSwc96eV_fw98nIYoY1bBg/edit

The image changes slightly because I don't recall my prior source (and
it didn't seem important to precisely match font size), but hopefully
the drawing helps.
2025-02-27 00:00:55 +00:00
Dana Jansens 0beda27192 Fingerprint impl blocks in semir (#5021)
This avoids the suffix changing when adding new impls to the prelude, or
in user code.
2025-02-26 22:47:57 +00:00
Dana Jansensandjosh11b e5feced884 Avoid crash when deduce fails for imported generic (#5001)
An imported generic has bindings which are of type ImportRefLoaded, and
if they come from another package, they have no entity name attached to
them.

Since a binding name is always a constant-time value, we can get the
constant value instruction for the imported instruction to get a
canonical non-imported instruction. And that one will have a local
`NameId`.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-02-26 22:39:11 +00:00
Jon Ross-Perkins 9fc40f86f9 Rename 'long term' to 'long term issue' (#5023)
We were discussing this, `long term` only applies to issues and not PRs
(per past discussion, we don't really expect PRs should be inactive for
months). Renaming to `long term issue` to be more specific and hopefully
reduce confusion.
2025-02-26 22:03:58 +00:00
Alina Sbirlea 7a9af69595 Refactor function definition lowering. (#5014)
Some refactoring to start adding lowering of function definition
generics.
2025-02-26 20:03:34 +00:00
Jon Ross-Perkins 422cc3d48a Move diagnostic usings off Context (#5007)
There aren't remaining uses on `Context` other than `DiagnosticEmitter`
itself. I'm adding `SemIRLoc` because I feel odd about having both
`Carbon::Check::DiagnosticBuilder` and
`Carbon::DiagnosticEmitter<T>::DiagnosticBuilder`, but it seems
relatively little additional typing outside the handful of
`DiagnosticEmitter` uses on `Context` itself:

```
Context::DiagnosticEmitter
DiagnosticEmitter<SemIRLoc>

Context::DiagnosticBuilder
SemIRLocDiagnosticBuilder

Context::BuildDiagnosticFn
BuildSemIRLocDiagnosticFn
```

Also clean up #include's while I'm finishing here.
2025-02-26 18:44:36 +00:00
Dana Jansens ebc1080c5d Improve diagnostics for impl lookup cycles (#4998)
And add a couple more tests that fail currently but should pass in the
future.
2025-02-26 18:37:43 +00:00
Boaz Brickner 3573763def Use Generics in no_poison test instead of pointers. (#5011)
Followup of [#4987
comment](https://github.com/carbon-language/carbon-lang/pull/4987/files/b015f99d0e86f5dfe3b1709bec8a426a584f7804#r1964119857).
Part of #4622.
2025-02-26 17:41:11 +00:00
Richard Smith dbfb133fed Disable misc-confusable-identifiers clang-tidy check for now. (#5019)
This check is very slow. See
https://github.com/llvm/llvm-project/issues/128797
2025-02-26 07:10:59 +00:00
Jon Ross-Perkins 9d85b23b4b Use an x-macro for special NameId values. (#5018)
Doing an in-file X-macro, though maybe we'll want to move it out to a
#include if we keep piling on more. I know there's `destroy` to add, and
possibly `copy` and `move`, but I don't know what threshold we'll want
for a separate file.

Note this does set up for an advantage where we can `switch` instead of
repeated `if` for special names, shifting to compile errors for new
values.

I also considered a simpler enum approach (with an implicit conversion
to `NameId`) but that runs into issues with things like
`Id::Kind::For<...>` as a consequence of calls like `name_id ==
special_name_id` (just requires another `operator==`) and
`context.node_stack().Push(node_id, SemIR::NameId::SelfType);` (a little
more complex how we'd want to handle it).
2025-02-26 02:23:22 +00:00
josh11bandJosh L 29c1f552c7 InvalidIndex -> NoneIndex in comments (#5012)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-02-25 18:22:03 +00:00
Jon Ross-Perkins e7b68572fa Consolidate post-check logic (#5003)
Right now, some post-run logic is does in `Run()`
(`CheckRequiredDefinitions();` and
`context_.sem_ir().set_has_errors(unit_and_imports_->err_tracker.seen_error());`)
whereas other parts are done by `Finalize`. Noting the goal to move
things off `Context`, this consolidates into a new `FinishRun`. Note
#4962 is adding another bit of post-run that can be consolidated in;
this seems likely to keep growing slowly.

Note this also creates more parity with mutation source, like the
`context_.scope_stack().Pop();` matches the push done by
`CheckUnit::ImportCurrentPackage` and
`context_.inst_block_stack().Pop()` was pushed in `CheckUnit::Run()`.

Also makes `exports()` more consistent with other Context APIs. Makes
`VerifyOnFinish` `const` so that it can't accidentally mutate state, and
is instead only validating that the Context is in its expected
configuration at completion.
2025-02-25 02:07:43 +00:00
Jon Ross-Perkins 197e784140 Add parsing for partial types (#5009) 2025-02-25 02:07:10 +00:00
Jon Ross-Perkins de0cab1e66 Move ChoiceDeferredBinding for style (#5002)
https://google.github.io/styleguide/cppguide.html#Declaration_Order says
types go first. Also moving the accessor to match the order of members
(`choice_deferred_bindings_` was added between `var_storage_map_` and
`region_stack_`).
2025-02-25 02:05:07 +00:00
Jon Ross-PerkinsandGeoff Romer 961f20e859 Make FileTest run tests async by default (#4991)
This takes the mechanism currently used for autoupdate and expands it to
the regular tests (deliberately trying to unify logic for
test/autoupdate/dump to deliver consistent behavior). I'm seeing about a
85% reduction in test time, though results will vary based on test
system.

This does some small edits to test output to make it fit better with the
new flow. Note I'm stopping printing of the "here's how to run" on every
test by default, since it's autoupdated into file content by default.
However, it's still there for test failures.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-02-24 23:20:08 +00:00
Jon Ross-Perkins 21252b5e94 Add missing trailing return types (#5006)
Noted CopyNameFromImportIR while glancing around (this one's interesting
because it's NameId, not void nor auto), did a scan just for a few other
cases. Not an exhaustive fix, and TBH assuming we'd prefer `auto ... ->
auto` since equivalent Carbon syntax would probably be `fn ... -> auto`
2025-02-24 22:41:59 +00:00
Dana Jansens 2ca3f92131 Don't incorrectly find cycle in a generic impl (#4990)
If the `impl as` clause is on a generic interface, the parameters to the
generic may be constrained by _other_ interfaces. This then requires
another impl lookup, but it should be looking for a different impl since
it's for a different interface.

To avoid considering the same impl again, we discard it from
consideration if the interface itself does not match the interface being
queried.

Note that the query FacetType can have more than one interface in it
eventually, and a `context.TODO()` call is left to notify when we run
into this.
2025-02-24 21:53:48 +00:00
Boaz Brickner 5b67bb8981 Refactor name poisoning tests to be more organized, complete and consistent (#4987)
This is also following
https://github.com/carbon-language/carbon-lang/pull/4900#discussion_r1945606053,
which points that name poisoning tests are not in the correct place.
Part of #4622.
2025-02-24 08:59:36 +00:00
3ebd098597 Completing a type no longer ignores facet types (#5004)
Make facet types complete like other types. This means that in the body
of an interface, the type of `Self` is incomplete. This involved fixing
an issue where eval of a specific_id that was already canonical was not
resolving the specific declaration, which could occur as part of
substituting into a facet type.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-02-22 21:40:43 +00:00
Alina Sbirleaandjonmeow 1d48270dc4 Emit diagnostics missing declaration of owned function. (#4962)
Emit diagnostics for a function declared in a non-owning library, that
is not redeclared (or defined) in the owning library.

---------

Co-authored-by: jonmeow <jperkins@google.com>
2025-02-22 01:29:22 +00:00
Dana Jansens 210c26e369 Use llvm::map_range() instead of using mapped_iterator directly (#4997)
map_range() is a nice helper for constructing a pair of
mapped_iterators.
2025-02-21 22:13:38 +00:00
Jon Ross-Perkins d843cc53fb Small rephrasing of 'partial' interaction with final classes (#5000)
I believe this reflects the intent, but the phrasing of "even if
`MyBaseClass` is not" implies that `MyBaseClass` _can_ be final in
`partial MyBaseClass`. Also, make clear it's allowed on `abstract`
classes, not only `base` (this seems explicitly intended from the
`MyAbstractClass` example around line 1482).
2025-02-21 21:52:45 +00:00
Chandler CarruthandJon Ross-Perkins 8d1d491ad0 Add LLD subcommand and busybox support (#4973)
This removes the separately built and installed LLD binary. The symlinks
used by Clang when directly invoking LLD now point back to the main
`carbon-busybox` binary and dispatch through the newly added subcommand.

With this change we're down to shipping a single busybox binary in the
toolchain, removing duplicate installed copies of LLD and all its LLVM
dependencies. =]

The LLD subcommand works a bit differently from the `clang` subcommand
because the CLI for LLD is specific to which platform flavor of linker
is being invoked.

As part of this, I've extracted some of the common functionality in the
Clang runner into a base class that can be re-used. I expect to use this
again in a follow-up change to add subcommands to run other LLVM tools.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-21 04:26:45 +00:00
Jon Ross-Perkins 2ea2166cf8 Update pre-commit (#4995)
`pre-commit autoupdate --freeze && pre-commit run -a`
2025-02-21 00:27:15 +00:00
Dana Jansens d199ce327a Make FacetTypeInfo and CompleteFacetType stores share id indices (#4989)
The CompleteFacetType value store is now a RelationalValueStore. This
type of store uses some _other_ id as the key for insertion. It allows
checking if values of the _other_ id are present in the store, since
those ids are handed out by another store and will (necessarily) exist
before there is a matching value in the RelationalValueStore.

The lookup for precense of the _other_ id returns the id of a value in
the RelationalValueStore. That id can be used to get the value out of
the store.

For our use case, the RelationalValueStore maps from FacetTypeId to
CompleteFacetTypeId. So you add a CompleteFacetType to the store with a
FacetTypeId. Then you can query with a FacetTypeId to see if there
exists a CompleteFacetTypeId. And if there is, you can use that
CompleteFacetTypeId thereafter to get the CompleteFacetType value from
the store.

This removes the need for ValueStore::GetMutable() and removes the
method. FacetTypeInfo no longer has a field that needs to be carefully
excluded from hash and comparison.
2025-02-20 22:59:06 +00:00
Dana Jansensandzygoloid 24bde46181 Change array syntax from [T; N] to array(T, N) (#4981)
In line with the proposal in #4682, this changes the array syntax to be
array(T, N). `array` is a builtin keyword which must be followed by
parens containing two expressions and a separating comma.

The array type expression is still fully builtin, it does not forward to
a Core.Array library type yet. It merely adds the `ArrayType`
instruction, as was done with the previous syntax.

Followup work will change the instruction to reference to Core.Array,
once the library type exists and can be used directly.

---------

Co-authored-by: zygoloid <richard@metafoo.co.uk>
2025-02-20 22:42:47 +00:00
fc7b0016ce Tuples and structs with abstract types are abstract (#4986)
Expands the CompleteTypeInfo to include information about abstract
classes and computes that information as part of completing the type.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-02-20 22:26:10 +00:00
Jon Ross-Perkins c2bc3c1719 Find the exe prior to busybox resolution (#4993)
This is required to make $PATH entries work.
2025-02-20 21:06:18 +00:00
Geoff Romer 9cb6b7190f Configure lldb to support /proc/self/cwd paths (#4992)
On my machine, the LLVM debug information seems to use source file paths
relative to `/proc/self/cwd`, which is the current working directory of
whatever process refers to it. Consequently, VSCode can't find those
files, because it has a different current working directory. This change
enables VSCode to rewrite those paths to a usable form.
2025-02-20 21:05:56 +00:00
Dana Jansens 88283bfc56 Make open question on class variables more explicit (#4988) 2025-02-20 18:56:10 +00:00
josh11bandJosh L cb2257e678 Should-fail tests using abstract tuples and structs (#4985)
Currently the toolchain does not recognize that tuples and structs with
abstract elements should be considered abstract.

Also make the existing `fail_abstract` test into a `no_prelude` test.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-02-20 16:56:41 +00:00
Dana JansensandGeoff Romer 53e4367c58 Add and correct tests of impl lookup on generic interfaces (#4974)
These tests expose cycles during deduction, when the generic parameters
in an impl statement require deduction and the impl clause that
satisfies them comes after the one containing the generic parameters.
This causes the same impl to be looked at repeatedly, and produces a
cycle diagnostic.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-02-20 15:48:15 +00:00
Dana Jansens 4b45caa8e0 The Core.Array type for direct-storage immutably-sized buffers (#4682)
We propose to add `Core.Array(T, N)` as a library type in the `Core`
package. Since arrays are a very frequent type, we propose to privilege
use of this type by including it in the `prelude` library of the
package.

We would like to see a shorthand where `Core.Array` is automatically
imported into the file scope, and this proposal includes future work to
this effect.
2025-02-20 15:28:59 +00:00
Geoff RomerandJon Ross-Perkins 74e1a9949f Support tuple patterns outside parameter lists (#4923)
Parameter lists need substantially different treatment than tuple
patterns in other contexts, so this change splits them into separate
parse node kinds.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-20 03:17:45 +00:00
Richard Smith 35f5a7f115 Reorder the token in a parse node to match its actual location. (#4984)
Also add a TODO for another parse node whose typed representation is
imprecise. Just clarifications; no behavior change is intended.
2025-02-20 02:25:05 +00:00
Richard Smith 1be726d3a2 Fix NodeCategory printing. (#4983)
Rearrange `NodeCategory` printing so we get a compile-time error for
missing switch cases if it's missing any categories. Add several missing
categories.

In passing, fix some minor things in the `NodeCategory` class
definition, and fix an overly-permissive typed node.
2025-02-20 01:50:42 +00:00
Geoff Romerandjosh11b 09b06b4234 Document grammar of field and associated constant decls (#4980)
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-02-20 01:28:01 +00:00
Chandler CarruthandJon Ross-Perkins 5b30888dd8 Fix clang runner to avoid leaking memory (#4972)
Sadly, the Clang driver unconditionally injects the `-disable-free` flag
to CC1 invocations. =/ This ends up with us leaking memory when invoking
Clang programmatically, for example in unit tests.

I've fixed this by post-processing the flags. The alternatives I see all
involve duplicating even more code from within Clang's internals into
our runner, and we already have a lot of that. I have left a TODO to try
and follow up with upstream about fixing this in a more sustainable way,
but wanted to get the testing in place anyways.

I've also threaded a flag through the various layers so that when we're
on the command line we can actually skip this and get the same compile
time benefits that Clang itself gets from disabling freeing all of the
internal data structures.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-20 00:25:18 +00:00
Jon Ross-Perkins 5c6f27904f Remove FileTestBase::ValidateRun (#4979)
`ValidateRun` is explorer-specific, so move out the error production to
be specific within explorer. This is related to other work I'm trying to
do which would make this require more special-casing to maintain; since
the toolchain doesn't need it, it's easier to drop.
2025-02-20 00:20:47 +00:00
eb69d7420e First iteration of completing and resolving facet types (#4920)
* Add `RequireCompleteFacetType` and `ResolveFacetTypeImplWitness` to
`check::Context`. Goal was to move code from `impl.cpp` (mostly) without
functional changes.
* Complete type information is cached with the facet type, and is stored
in a `complete_facet_types()` table.
* Main functional change is to diagnose attempts to use a rewrite
constraint on an associated function. Some existing diagnostics have
been updated.
* Remove `check::Context::RequireDefinedType`:
  * For class types, use `RequireCompleteType`
  * For facet types, use `RequireCompleteFacetType`
* Introduce a `SemIR::SpecificInterface` to hold an interface and
specific id pair.
* Keep the specific interface ids in the impl object.
* Avoid some extra copies in `Dump` functions.
* Future work missing from this PR:
  * Resolving for member access or actions that require impl lookup.
  * Resolving rewrites constraints that refer to non-concrete values.
* Any support for adding implied constraints that result from a `where`
clause (though TODOs have been added).

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-02-19 22:10:11 +00:00
Dana Jansens 7c7e169994 Avoid diagnosing conversion errors inside deduction of impl arguments (#4976)
When conversion fails, the impl should simply not match, no error should
be generated.
2025-02-19 21:46:46 +00:00
Jon Ross-Perkins 524a6337f4 Improve decl_name_stack comments (#4977)
Trying to make it clearer what these correspond to. Had suggested a
small edit on
https://github.com/carbon-language/carbon-lang/pull/4902/files#r1960682518,
but since that was missed, suggesting an incrementally larger edit since
`name_id` and `loc_id` are now more tied.
2025-02-19 19:46:23 +00:00
Jon Ross-Perkins 186ca0e505 Remove Context::DumpFormattedFile (#4978)
Asked on
[#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1339388316977729627),
it sound like this is unused. Also with the `Dump` methods, having
`Dump(context)` might be more helpful for findability (could just move
it here if that's desired).
2025-02-19 18:33:59 +00:00
Dana JansensandRichard Smith 11aba70c1d Add enumerate() for ValueStore and ImplStore (#4975)
This allows iterating on all values in a store along with the Id for
each value, instead of `llvm::enumerate(store.array_ref())` which would
give you the indices.

While the indices are really the same as the Ids, this provides a
typesafe way to enumerate() over a store.

There's no use for this right now, but I thought I needed this, and it
helped me debug, and it was a pain to write correctly without dangling
references.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-02-19 18:32:13 +00:00
Dana Jansens 3f01310039 Make choice work for alternatives without parameters (#4815)
This adds support for choice types at a similar level to that of a C
enum, where each alternative has a name but no additional
data/parameters attached to it. We generate a TODO diagnostic if
parameters are specified.

Because there's no extra data, the storage is a simple unsigned integer
discriminant of the smallest possible size.

A choice without any alternatives is not constructible. A choice with a
single alternative is, and has an empty tuple in place of a discriminant
since it has only one state. The empty tuple is used to make the class
non-constructible. This can be improved.

Each alternative is turned into a let binding on the choice that is a
value of the choice with that alternative set as the active one in the
discriminant. This isn't possible to write in user code with a class
right now, since the let binding has the same type as the choice
(which is a class) it is within. It's possible to generate it in semir
however by adding the binding after the class is marked complete.
2025-02-19 16:37:36 +00:00
Boaz Brickner 6a99c4e970 When diagnosing a duplicated name, add the name to the diagnosis (#4902)
In order to have the name available for diagnostics, we now always set
`NameId` in `NameContext` and put `poisoning_loc_id` as part of the
union with `resolved_inst_id` instead (since we never need both).
2025-02-19 07:19:23 +00:00
Richard Smith e0b2f5d772 Add and propagate template phase for constants. (#4964)
Treat template bindings as introducing template phase, and propagate it
in the same way we propagate the checked generic phase.

Rename "symbolic" to "checked symbolic" to make room for "template
symbolic". Also rename "phase" to "dependence".
2025-02-18 18:57:34 +00:00
Dana Jansensandjosh11b 382094b725 Support conversion of facet-ish values for type deduction (#4956)
A value of type FacetAccessType can convert to a facet value of a target
FacetType if the value's underlying facet value's FacetType is 
compatible.

A value of type FacetType can convert to another value of type FacetType
if the value's FacetType is compatible with the target FacetType.

During impl lookup, the comparison of the lookup type and the impl's
type needs to consider more than strict equality. If the impl's self
type is a FacetAccessType, we instead need to verify that the FacetType
of the lookup type and of the impl's self type are compatible (which is
like a problem of another impl lookup). For now we check that they are
equal by unwrapping the FacetAccessType to the constant facet value
within, and compare that with the lookup type.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-02-18 18:14:03 +00:00
Jon Ross-Perkins 3d6f14fca5 Refactor FileTestBase to split logic between multiple files (#4968)
I'm refactoring logic to try to make these files more manageable,
particularly as I'm looking at ways to use more threads. I'm renaming
FileTestBase::TestContext to TestFile and FileTestBase::TestFile to
TestFile::Split to try to be more consistent in how we talk about test
files and file splits in general. This change is not expected to change
any behavior, it's just refactoring.

This PR has two commits:

- Copying files for viewing deltas in GH
- Moving logic

The delta of the two commits is the main PR. The second commit can be
viewed on its own to see the delta versus file_test_base.* files where
the logic currently rests (there's still a reordering in run_test.cpp as
part of making one function static).
2025-02-18 17:10:23 +00:00
Chandler Carruth cf29449faf Move test file writing to our common testing file_helpers (#4971)
This will make it easy to share across tests. Factored out of a change
adding new uses of the file.
2025-02-18 03:27:49 +00:00
Chandler Carruth 151bd14fd3 Refactor stdout and stderr capturing to a library (#4970)
This should make it easy to add more tests which need the specific
behavior here. It also isolates where we reach into GoogleTest's
internals to a single common place.
2025-02-16 16:12:14 +00:00
fe2c0b48cf Begin packaging builtin Clang headers (#4959)
This digs the Clang builtin headers out of the Clang package and
reconfigures them to install into our installation prefix, under the
LLVM installation subtree.

---------

Co-authored-by: Ilya Biryukov <ibiryukov@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-15 23:03:32 +00:00
a881e21432 Language Server - implement incremental document sync (#4926)
The language server is now able to subscribe to and apply incremental
changes to the document. Source code is assumed to be utf-8. It does not
currently handle utf-16 code points.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-15 02:05:56 +00:00
Jon Ross-Perkins 9cd3f0aa3d Remove obsolete '...' hints on node kind macros (#4958)
We used to have more arguments, but they've mostly been removed now.
2025-02-15 01:36:46 +00:00
Jon Ross-Perkins e3764ff6f3 Clean up Context API (#4969)
- Add a better class comment.
- Remove the obsolete `type_ids_for_type_constants_` and `TypeNode`.
- For `bind_name_map`, fix declaration order and move comment to be
consistent with other members.
- Reorder accessors to better match order of data members.
  - This is how I noticed `type_ids_for_type_constants_`
- Put a bigger notice so that `sem_ir` helper functions don't end up in
the middle of other members again.
2025-02-15 01:18:54 +00:00
Jon Ross-PerkinsandRichard Smith 38d25cf622 Share ReadFile in tests (#4967)
Small cleanup for code sharing. Note, `*ReadFile` will trigger a
CHECK-failure on error; the relevant implementations would previously
have failed silently (empty string).

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-02-15 00:17:01 +00:00
Jon Ross-Perkins d4f15ab26e Publish empty diagnostics on close (#4954)
Without this, diagnostics will linger after closing a file.

This refactors towards a pattern of putting outgoing calls as methods on
`Context`. I'm mixed on this, mainly thinking it's an improvement on
using `outgoing` directly (because it shares the name and structure),
might want to move it to a side-class later that is _only_ LSP wrappers.

I could also make inheritance private on OutgoingMessages and these
kinds of methods public there, but I'm hesitant to adopt that approach
versus a type separation.
2025-02-15 00:09:20 +00:00
Dana Jansensandjosh11b f038aead4c Diagnose cycles in impl lookup (#4947)
Cycles are defined as reaching two independent lookups in a chain that
have all the same types involved. The acyclic rule states that this is
not possible and results in an error:
https://docs.carbon-lang.dev/docs/design/generics/details.html#acyclic-rule

To do this we need to track the types involved in impl lookup. The
interface constant includes the whole facet type being looked up, which
includes any specific types for generics or where constraints. Thus we
just need to compare the constant ids to look for this condition.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-02-14 22:21:53 +00:00
Boaz Brickner 4a93b6667e Add the used name to the NameUseBeforeDecl diagnostic (#4901)
Part of #4622.
2025-02-14 21:54:35 +00:00
Boaz Brickner d65f0d959d Add a test for the case that extend poisons a class member (#4960)
Part of #4622.
2025-02-14 20:31:58 +00:00
Jon Ross-Perkins 95fd890698 Allow pre-commit to talk to googleapis (#4966)
Example:
-
https://app.stepsecurity.io/github/carbon-language/carbon-lang/actions/runs/13320074606
-
https://github.com/carbon-language/carbon-lang/actions/runs/13320074606/job/37247235705

I'm not sure what it's being used for (even blocked, nothing unexpected
failed) but if bazel or similar is trying to talk to this it should be
fine.
2025-02-14 20:21:20 +00:00
Dana Jansensandjosh11b d5f3d3365a Allow checking to continue after 'impl as' outside class (#4937)
Currently it returns false which just ends typechecking. Instead handle
the error state later and avoid firing overlapping diagnostics in
'extend impl as'.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-02-14 20:02:10 +00:00
Jon Ross-Perkins 311b4ff03d Refactor AddInst-family functions to their own file (#4941)
This in particular uses free functions because it's likely to end up
more consistent with types (versus a wrapper object for InstStore).
Note, this is unlikely to have a performance impact, but if it does, we
can look into related approaches (and we've already discussed using
LTO).

Renames `PendingBlock::AddInst` to `PendingBlock::Add` because
`MakeElementAccessInst` expects the matching name to exist.
2025-02-14 19:44:36 +00:00
Boaz Brickner dd7c64bad0 When diagnosing a duplicate name, point to the name instead of the instruction (#4953)
Left TODOs where more work is necessary before this change can be
applied or its impact can be verified.

Includes #4952, to avoid regression in some cases.

Similar to #4938. See
https://discord.com/channels/655572317891461132/655578254970716160/1339007384361762857.
2025-02-14 19:21:50 +00:00
Boaz Brickner 986a2a064c Add poisoned names to the format (#4961)
Part of #4622.
2025-02-14 19:18:51 +00:00
Jon Ross-Perkins 44a5e371b2 Reduce clangd-displayed errors for def files (#4957)
When I open a .def file, there are often 4 errors:

- The #error
- The #define is not defined
- Missing `;`
- Identifier naming

This PR is meant to disable all of these, since they can be distracting
from fixable diagnostics.
2025-02-14 17:54:39 +00:00
DavidLoftus 9cf5306c01 Update rules_cc to 0.1.1 (#4965)
rules_cc@0.1.0 was yanked from
[BCR](https://registry.bazel.build/modules/rules_cc) due to prematurely
removing cc_proto_library, this inconsistently causes the following
build error:

> ERROR: Error computing the main repository mapping: Yanked version
detected in your resolved dependency graph: rules_cc@0.1.0, for the
reason: rules_cc 0.1.0 is yanked due to incompatible change (prematurely
removing cc_proto_library from defs.bzl), please upgrade to 0.1.1.
Yanked versions may contain serious vulnerabilities and should not be
used. To fix this, use a bazel_dep on a newer version of this module. To
continue using this version, allow it using the --allow_yanked_versions
flag or the BZLMOD_ALLOW_YANKED_VERSIONS env variable.

This PR updates to 0.1.1 as recomended in warning and
[bazelbuild/rules_cc#268](https://github.com/bazelbuild/rules_cc/issues/268#issuecomment-2651269117).
2025-02-14 17:02:03 +00:00
Boaz Brickner 809bcf10ed Fix bad merge of comments introduced in #4884 (#4955)
Part of #4622.
2025-02-14 00:34:48 +00:00
Jon Ross-Perkins dc8f47e6ad Move type functions off Context (#4951)
This creates a new check/type.h for most logic, and also moves some
functions to TypeStore in sem_ir/type.h. My approach for TypeStore is to
focus on moving the read-only functions there.
2025-02-13 23:02:38 +00:00
Boaz Brickner 23e5677c8e Avoid poisoning non identifier names (#4884)
There are different use cases where we call
`Context::LookupQualifiedName()` on non identifiers, like
`NameId::SelfType`, which implicitly triggers poisoning these names. I
don't think poisoning non identifiers like`Self` is ever useful.

Use cases where `Self` is being poisoned:
* Checking allowed access:
https://github.com/carbon-language/carbon-lang/blob/e257051612e4217295e206fd3274fc75e22d206a/toolchain/check/member_access.cpp#L62,
for example, in
https://github.com/carbon-language/carbon-lang/blob/e257051612e4217295e206fd3274fc75e22d206a/toolchain/check/testdata/alias/no_prelude/fail_aliased_name_in_diag.carbon#L21
* Using the type `Self` as a parameter type:
https://github.com/carbon-language/carbon-lang/blob/e257051612e4217295e206fd3274fc75e22d206a/core/prelude/operators/arithmetic.carbon#L78

Part of #4622.
2025-02-13 20:00:54 +00:00
David BlaikieandJon Ross-Perkins aa71f31787 Refactor implicit Self param into a member on SemIR::Function (#4928)
This ensures the data is available for more uses (specifically for
diagnosing virtual/abstract/impl functions on non-instance methods).

It still doesn't quite address the TODO to move the Self param search
all the way back to the param walk in all cases. To do that in the case
that still has a separate search loop, I think we'd have to change
`Check::NameComponent` to carry this information (as it carries the
implicit_param_patterns-id) - though there's comments in NameComponent
suggesting it shouldn't carry function-specific things like
`call_params_id` and `return_slot_pattern_id` - so I wasn't sure if it
was suitable to add more there, but I can - possibly in a follow-up
change.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-13 19:07:17 +00:00
Jon Ross-Perkins e70f9cd71d Move diagnostic helpers from Context to other files (#4949)
Trying to find more specific homes for shared diagnostic function calls.
2025-02-13 18:08:11 +00:00
Richard Smith 6dda094928 Superficial support for template modifier on symbolic bindings. (#4948)
Change parse tree from `template (T:! type)` to `(template T):! type`,
so that we have information about whether a binding is a template
binding available when forming the representation of the binding
pattern. This incidentally fixes a bug that we would accept `template
addr A:! B` instead of the intended `addr template A:! B`.

Track whether a symbolic binding is a template binding on the
`EntityName` object. I'm borrowing a bit from the `CompileTimeBindIndex`
for this in order to avoid making `EntityName`s larger. Longer-term, we
should think about using a different representation for symbolic
bindings, to avoid including these fields in all `EntityName`s, but
that's out of scope for this change.

So far, template bindings are treated as having the same phase as
checked bindings, but that will change in a future PR.
2025-02-13 02:15:22 +00:00
Geoff RomerandJon Ross-Perkins f502e8d6ff Avoid speculatively pushing a pattern block in impl handling (#4943)
To do this, we restructure the parse tree to make `forall` a leaf node
that comes before the parameter list.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-12 23:21:57 +00:00
Jon Ross-Perkins 95f2140a04 Update compiler explorer mentions in README (#4946)
The explorer interpreter is still there, but it's non-default so it's a
little hard to link to (we could do a shortlink like
https://carbon.compiler-explorer.com/z/8P1WE97nn if you want to keep
that). As is, I assume it's okay to just state that this is now the
toolchain.
2025-02-12 23:15:43 +00:00
Jon Ross-Perkins 0c37ce6908 Delete unused ParamPatternInfo::GetNameId (#4942)
Perhaps GetPrettyName replaced all uses?

As long as I'm here, also fix struct declaration order.
2025-02-12 22:38:36 +00:00
Jon Ross-Perkins b628fd80ef Remove explorer from issue templates (#4945) 2025-02-12 22:24:25 +00:00
Jon Ross-Perkins afef6cd940 Refactor name lookup logic out of Context (#4930)
This is a pretty straight move of name lookup functionality to
name_lookup.*
2025-02-12 22:03:08 +00:00
Richard Smith c6d35e1c4a Rename template constant -> concrete constant. (#4939)
This implements a direction decided in a
[recent
discussion](https://docs.google.com/document/d/1Iut5f2TQBrtBNIduF4vJYOKfw7MbS8xH_J01_Q4e6Rk/edit?resourcekey=0-mc_vh5UzrzXfU4kO-3tOjA&tab=t.0#heading=h.mas1g68xx9ct)
to switch away from "template constant" when naming a constant that
doesn't depend on any generic parameters, because that creates confusion
with template-dependent constant values that depend on a template
parameter.
2025-02-12 21:24:51 +00:00
Jon Ross-Perkins 188821ba1a Fold Context::GetCurrentScopeAs back into ScopeStack (#4936)
This adds a `SemIR::File` pointer to `scope_stack` so that
`GetCurrentScopeAs` doesn't require the argument, which would be why the
helper existed on `context`.
2025-02-12 21:01:19 +00:00
Boaz Brickner 1aa6573d4e When diagnosing poisoned name, point to the declared name instead of the entire declaration (#4938)
See
https://discord.com/channels/655572317891461132/655578254970716160/1339007384361762857.

Part of #4622.
2025-02-12 20:59:55 +00:00
Richard Smith b78ab1bbae Register a vscode build task to save all files and run autoupdate. (#4940)
Also exclude external and bazel-out directories from vscode so that the
build tasks list can be brought up quickly.
2025-02-12 20:49:54 +00:00
czapiga 0396bbf9df Improve match parsing diagnostics (#4934)
Adds diagnostics for missing `case` guard parenthesis.
Adds test for which `lex` parenthesis check succeeds but errors are
reported in `parse` phase.
2025-02-12 20:10:51 +00:00
Jon Ross-Perkins 8af64ceca6 Change Context::IsImplFile to File::is_impl (#4931)
Note this mirrors parse_tree().packaging_decl().is_impl, but I'm
preferring to keep the version that doesn't access the parse tree so
that we could change tree storage without hurting as much.
2025-02-12 19:42:07 +00:00
Jon Ross-Perkins 71c91eaf14 Refactor subpattern logic out of Context (#4929)
Note this is building on #4927 which factors out RegionStack, because
this heavily uses the region stack. However, it's a more complex level
of logic that appears specific to pattern handling.

I've moved InsertHere to pattern_match.cpp because it appears to be in
specific use there.
2025-02-12 19:14:37 +00:00
Dana Jansens d6ce8f192d Don't use an impl when 'extend impl' is an error (#4935)
If 'extend impl' is invalid, mark the impl as invalid by putting an
ErrorInst in the witness_id field.

The construction of the witness_id can otherwise return an ErrorInst but
impl lookup was not checking for that. Now have impl lookup check for an
error there before attempting to deduce generic parameters, which avoids
infinite recursion through deduction in cases like a cyclical impl of
itself.

Adds a testcase for infinite impl-of-itself lookup found by fuzzer.
2025-02-12 18:50:08 +00:00
Dana JansensandRichard Smith 857aa6095e Improve comments on conversion from type value to type id (#4885)
The GetTypeIdForTypeConstant() and GetTypeIdForTypeInst() methods
convert from a type value to the type id of that value. The comments say
it can only be done for values of type `type` but it can be done for any
type value, which are either `TypeType` (aka `type`) or `FacetType`.

For example, for a `FacetValue` instruction as follows:
```
inst116: {kind: FacetValue, arg0: inst46, arg1: inst59, type: type(inst52)}
  - type type(inst52): Generic(GenericParam); {kind: FacetType, arg0: facet_type2, type: type(TypeType)}
  - value template_constant(inst117): {kind: FacetValue, arg0: inst46, arg1: inst59, type: type(inst52)}
```
The GetTypeIdForTypeInst() method will give the type id of the type
value (the type _in_ the FacetValue instruction) such as:
```
type(inst117): ImplsGeneric as Generic(GenericParam); {kind: FacetValue, arg0: inst46, arg1: inst59, type: type(inst52)}
```

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-02-12 15:03:15 +00:00
Dana Jansens 30b2b5ef81 Use FacetAccessType when converting to a value of type FacetType (#4925)
When attempting to convert to a value of type FacetType, and the source
value is a FacetAccessType, then if the type of the underlying
FacetValue is the same as the target, we can use the FacetValue there as
the conversion output.

If the type of the FacetValue differs, then we still want to do impl
lookup with the FacetValue to see if it matches with the target
FacetType, but that is still a TODO.

This allows a generic function with a value whose type is constrained by
a FacetType (thus the value's type is a FacetAccessType), to call other
functions with the value as an argument when it is constrained by the
same FacetType:
```
fn F[T:! FacetType](x: T);
fn G[T:! FacetType](x: T) { F(x); }
```

It is also an optimization to avoid impl lookup where we've already done
it to produce the FacetAccessType.

Adds a bunch of new tests with values of types which are constrained by
a facet type (or "facet value value" for short), with some more tests
that currently fail and should be made to pass.
2025-02-12 14:35:11 +00:00
Dana Jansens 2a17465e06 Add a test where a FacetType is deduced as another FacetType (#4917) 2025-02-12 14:05:30 +00:00
Chandler CarruthandRichard Smith b636065f53 Safety milestones and a 2025 roadmap (#4880)
We propose updating our milestones to accelerate design and
implementation of
memory safety in Carbon, and a roadmap for 2025 reflecting this change.
We also
provide a retrospective for 2024's progress.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-02-12 02:23:46 +00:00
Boaz Brickner 3f599c250b Generate Cpp namespace when import Cpp is used (#4873)
Also defined a dedicated `ImportCppDecl` `InstKind`.
Part of #4666
2025-02-12 01:44:37 +00:00
Jon Ross-Perkins 6c4767e310 Replace GetImportIRId with check_ir_map accessor logic (#4932)
This is particularly subtle for me because `GetImportIRId` was
deliberately returning a mutable reference...
2025-02-12 01:22:17 +00:00
Jon Ross-Perkins 588bdd74c3 Refactor region_stack logic out of Context (#4927) 2025-02-12 00:21:07 +00:00
DavidLoftusandDavid Blaikie 0931c601be Organize symbol hierarchy in LSP documentSymbol handler (#4914)
This PR updates the HandleDocumentSymbol function to build a tree of
symbols, rather than a flat list. Symbols found while traversing another
symbols body are added as a child.

Adds a simple test showing functions within nested class.

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2025-02-11 22:04:50 +00:00
Jon Ross-Perkins b0d49ba957 Move control flow block functions to their own file. (#4921)
context.cpp is getting large, so I'm looking at a few ways to cut out
clusters of functions. This felt like a logical cluster of functions to
move to their own file.

Note this doesn't touch the implementation at all, beyond what's needed
to change from `Context` members to context args.
2025-02-11 21:38:09 +00:00
Richard SmithandJon Ross-Perkins 8eb4e24cb6 Implement #4864: Core is a keyword (#4909)
Change representation of package names from `IdentifierId` to
`PackageNameId`, and add a special value `PackageNameId::Core` for the
Core package. Add a `Core` expression to name the Core package, and
support for parsing the `Core` keyword in `package` and `import`
declarations.

For now, I've made no changes to instruction fingerprinting or name
mangling. This means that fingerprints and mangled names will collide
between names in the `Core` package and names in a `r#Core` package. See
#4908.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-11 21:33:57 +00:00
josh11bandJosh L 50b3c825e4 Handle extend impl in function body (#4924)
Crash bug found by fuzzer.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-02-11 21:19:55 +00:00
Dana Jansens a9c1bc4f0f Handle building a value repr when the type is named through an aggregate (#4910)
BuildValueRepr is used to determine the value representation of a type,
but the instruction determining the type may be an indirection through
to another instruction, such as a TupleAccess with `T.0` or a
StructAccess with `T.f`. In these cases, step through the indirection
and try again on the resulting type.

This eliminates a crash as these Access instructions do not resolve to a
type themselves and would otherwise end up in this FATAL line:
```
  CARBON_FATAL("Type refers to non-type inst {0}", inst);
```

While here, remove the reference to TupleIndex in typed_insts.h as it
has been subsumed by TupleAccess in 7f930d0f58.

ClassElementAccess is not yet handled, but a fail_todo test is added. It
fails because `ConvertToValueOfType()` in `ExprAsType()` returns a
non-constant value for a ClassElementAccess instruction, where it must
not for a StructAccess.
2025-02-11 21:12:19 +00:00
Jon Ross-Perkins 0a55081c5d Move TypeCompleter and closely related helper functions to their own file (#4922)
context.cpp is getting large, so I'm looking at a few ways to cut out
clusters of functions. This felt like a logical cluster of functions to
move to their own file.

Note I have two commits in this PR: one moving the functionality to a
new file, and one specifically changing TypeCompleter to use out-of-line
function implementations. This is to assist reviewability.
2025-02-11 18:51:46 +00:00
Jon Ross-Perkins 2fef1cb713 Switch to trailing returns in toolchain and related code. (#4919)
Also makes the style guide explicitly comment on void, but this was the
intent IIRC because it matches Carbon's `-> ()` (and "always" versus
"except for void", which we definitely went back and forth on).

Includes adjusting function pointers, which I definitely forget this
syntax works sometimes.

Excludes utils/tree_sitter/src/scanner.c because it claims to be C, but
really we should probably fix that to be cpp.
2025-02-11 18:11:14 +00:00
Dana Jansens 316a6c59e9 Deduce facet values for arguments to generic fns receiving a facet type (#4865)
The fn receiving a facet type needs to deduce a type from a
FacetAccessType, which is the SemIR type representing the parameter type
that is a generic parameter. For example:

```
  fn F[T: Interface](val: T);
```

Here T is a generic parameter that is a facet value, but the `val`
parameter's type is the facet value converted from a FacetType to a
TypeType, with `as type`. The result of that conversion is a
FacetAccessType. So the deduction code sees a FacetAccessType for the
type of `val`.

We make deduction undo the `as type` conversion to move back to the `T`
parameter declaration, which has type FacetType in order to deduce the
required facet value (which is itself a type constrained by the
FacetType). And when we have a facet value (of type FacetType) to be
deduced, we will also convert the argument if it is of an appropriate
type to a FacetValue that matches the FacetType using the changes from
PR #4863.

Tests with `impl forall` can cause impl deduction to recurse forever and
crash, so those tests are omitted in this PR and they will come in
follow-up work that address the infinite recursion.

Rebased on top of PR #4885
2025-02-11 02:03:33 +00:00
dependabot[bot] d0fec30776 Bump esbuild from 0.24.0 to 0.25.0 in /utils/vscode in the npm_and_yarn group across 1 directory (#4918)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [esbuild](https://github.com/evanw/esbuild).

Updates `esbuild` from 0.24.0 to 0.25.0
<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.25.0</h2>
<p><strong>This release deliberately contains backwards-incompatible
changes.</strong> To avoid automatically picking up releases like this,
you should either be pinning the exact version of <code>esbuild</code>
in your <code>package.json</code> file (recommended) or be using a
version range syntax that only accepts patch upgrades such as
<code>^0.24.0</code> or <code>~0.24.0</code>. See npm's documentation
about <a
href="https://docs.npmjs.com/cli/v6/using-npm/semver/">semver</a> for
more information.</p>
<ul>
<li>
<p>Restrict access to esbuild's development server (<a
href="https://github.com/evanw/esbuild/security/advisories/GHSA-67mh-4wv8-2f99">GHSA-67mh-4wv8-2f99</a>)</p>
<p>This change addresses esbuild's first security vulnerability report.
Previously esbuild set the <code>Access-Control-Allow-Origin</code>
header to <code>*</code> to allow esbuild's development server to be
flexible in how it's used for development. However, this allows the
websites you visit to make HTTP requests to esbuild's local development
server, which gives read-only access to your source code if the website
were to fetch your source code's specific URL. You can read more
information in <a
href="https://github.com/evanw/esbuild/security/advisories/GHSA-67mh-4wv8-2f99">the
report</a>.</p>
<p>Starting with this release, <a
href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a>
will now be disabled, and requests will now be denied if the host does
not match the one provided to <code>--serve=</code>. The default host is
<code>0.0.0.0</code>, which refers to all of the IP addresses that
represent the local machine (e.g. both <code>127.0.0.1</code> and
<code>192.168.0.1</code>). If you want to customize anything about
esbuild's development server, you can <a
href="https://esbuild.github.io/api/#serve-proxy">put a proxy in front
of esbuild</a> and modify the incoming and/or outgoing requests.</p>
<p>In addition, the <code>serve()</code> API call has been changed to
return an array of <code>hosts</code> instead of a single
<code>host</code> string. This makes it possible to determine all of the
hosts that esbuild's development server will accept.</p>
<p>Thanks to <a
href="https://github.com/sapphi-red"><code>@​sapphi-red</code></a> for
reporting this issue.</p>
</li>
<li>
<p>Delete output files when a build fails in watch mode (<a
href="https://redirect.github.com/evanw/esbuild/issues/3643">#3643</a>)</p>
<p>It has been requested for esbuild to delete files when a build fails
in watch mode. Previously esbuild left the old files in place, which
could cause people to not immediately realize that the most recent build
failed. With this release, esbuild will now delete all output files if a
rebuild fails. Fixing the build error and triggering another rebuild
will restore all output files again.</p>
</li>
<li>
<p>Fix correctness issues with the CSS nesting transform (<a
href="https://redirect.github.com/evanw/esbuild/issues/3620">#3620</a>,
<a
href="https://redirect.github.com/evanw/esbuild/issues/3877">#3877</a>,
<a
href="https://redirect.github.com/evanw/esbuild/issues/3933">#3933</a>,
<a
href="https://redirect.github.com/evanw/esbuild/issues/3997">#3997</a>,
<a
href="https://redirect.github.com/evanw/esbuild/issues/4005">#4005</a>,
<a href="https://redirect.github.com/evanw/esbuild/pull/4037">#4037</a>,
<a
href="https://redirect.github.com/evanw/esbuild/pull/4038">#4038</a>)</p>
<p>This release fixes the following problems:</p>
<ul>
<li>
<p>Naive expansion of CSS nesting can result in an exponential blow-up
of generated CSS if each nesting level has multiple selectors.
Previously esbuild sometimes collapsed individual nesting levels using
<code>:is()</code> to limit expansion. However, this collapsing wasn't
correct in some cases, so it has been removed to fix correctness
issues.</p>
<pre lang="css"><code>/* Original code */
.parent {
  &gt; .a,
  &gt; .b1 &gt; .b2 {
    color: red;
  }
}
<p>/* Old output (with --supported:nesting=false) */<br />
.parent &gt; :is(.a, .b1 &gt; .b2) {<br />
color: red;<br />
}</p>
<p>/* New output (with --supported:nesting=false) */<br />
.parent &gt; .a,<br />
.parent &gt; .b1 &gt; .b2 {<br />
color: red;<br />
}<br />
</code></pre></p>
<p>Thanks to <a
href="https://github.com/tim-we"><code>@​tim-we</code></a> for working
on a fix.</p>
</li>
<li>
<p>The <code>&amp;</code> CSS nesting selector can be repeated multiple
times to increase CSS specificity. Previously esbuild ignored this
possibility and incorrectly considered <code>&amp;&amp;</code> to have
the same specificity as <code>&amp;</code>. With this release, this
should now work correctly:</p>
<pre lang="css"><code>/* Original code (color should be red) */
</code></pre>
</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/evanw/esbuild/blob/main/CHANGELOG-2024.md">esbuild's
changelog</a>.</em></p>
<blockquote>
<h1>Changelog: 2024</h1>
<p>This changelog documents all esbuild versions published in the year
2024 (versions 0.19.12 through 0.24.2).</p>
<h2>0.24.2</h2>
<ul>
<li>
<p>Fix regression with <code>--define</code> and
<code>import.meta</code> (<a
href="https://redirect.github.com/evanw/esbuild/issues/4010">#4010</a>,
<a
href="https://redirect.github.com/evanw/esbuild/issues/4012">#4012</a>,
<a
href="https://redirect.github.com/evanw/esbuild/pull/4013">#4013</a>)</p>
<p>The previous change in version 0.24.1 to use a more expression-like
parser for <code>define</code> values to allow quoted property names
introduced a regression that removed the ability to use
<code>--define:import.meta=...</code>. Even though <code>import</code>
is normally a keyword that can't be used as an identifier, ES modules
special-case the <code>import.meta</code> expression to behave like an
identifier anyway. This change fixes the regression.</p>
<p>This fix was contributed by <a
href="https://github.com/sapphi-red"><code>@​sapphi-red</code></a>.</p>
</li>
</ul>
<h2>0.24.1</h2>
<ul>
<li>
<p>Allow <code>es2024</code> as a target in <code>tsconfig.json</code>
(<a
href="https://redirect.github.com/evanw/esbuild/issues/4004">#4004</a>)</p>
<p>TypeScript recently <a
href="https://devblogs.microsoft.com/typescript/announcing-typescript-5-7/#support-for---target-es2024-and---lib-es2024">added
<code>es2024</code></a> as a compilation target, so esbuild now supports
this in the <code>target</code> field of <code>tsconfig.json</code>
files, such as in the following configuration file:</p>
<pre lang="json"><code>{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;ES2024&quot;
  }
}
</code></pre>
<p>As a reminder, the only thing that esbuild uses this field for is
determining whether or not to use legacy TypeScript behavior for class
fields. You can read more in <a
href="https://esbuild.github.io/content-types/#tsconfig-json">the
documentation</a>.</p>
<p>This fix was contributed by <a
href="https://github.com/billyjanitsch"><code>@​billyjanitsch</code></a>.</p>
</li>
<li>
<p>Allow automatic semicolon insertion after
<code>get</code>/<code>set</code></p>
<p>This change fixes a grammar bug in the parser that incorrectly
treated the following code as a syntax error:</p>
<pre lang="ts"><code>class Foo {
  get
  *x() {}
  set
  *y() {}
}
</code></pre>
<p>The above code will be considered valid starting with this release.
This change to esbuild follows a <a
href="https://redirect.github.com/microsoft/TypeScript/pull/60225">similar
change to TypeScript</a> which will allow this syntax starting with
TypeScript 5.7.</p>
</li>
<li>
<p>Allow quoted property names in <code>--define</code> and
<code>--pure</code> (<a
href="https://redirect.github.com/evanw/esbuild/issues/4008">#4008</a>)</p>
<p>The <code>define</code> and <code>pure</code> API options now accept
identifier expressions containing quoted property names. Previously all
identifiers in the identifier expression had to be bare identifiers.
This change now makes <code>--define</code> and <code>--pure</code>
consistent with <code>--global-name</code>, which already supported
quoted property names. For example, the following is now possible:</p>
<pre lang="js"><code></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/e9174d671b1882758cd32ac5e146200f5bee3e45"><code>e9174d6</code></a>
publish 0.25.0 to npm</li>
<li><a
href="https://github.com/evanw/esbuild/commit/c27dbebb9e7a55dd9a084dd151dddd840787490e"><code>c27dbeb</code></a>
fix <code>hosts</code> in <code>plugin-tests.js</code></li>
<li><a
href="https://github.com/evanw/esbuild/commit/6794f602a453cf0255bcae245871de120a89a559"><code>6794f60</code></a>
fix <code>hosts</code> in <code>node-unref-tests.js</code></li>
<li><a
href="https://github.com/evanw/esbuild/commit/de85afd65edec9ebc44a11e245fd9e9a2e99760d"><code>de85afd</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/evanw/esbuild/commit/da1de1bf77a65f06654b49878d9ec4747ddaa21f"><code>da1de1b</code></a>
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/4065">#4065</a>:
bitwise operators can return bigints</li>
<li><a
href="https://github.com/evanw/esbuild/commit/f4e9d19fb20095a98bf40634f0380f6a16be91e7"><code>f4e9d19</code></a>
switch case liveness: <code>default</code> is always last</li>
<li><a
href="https://github.com/evanw/esbuild/commit/7aa47c3e778ea04849f97f18dd9959df88fa0886"><code>7aa47c3</code></a>
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/4028">#4028</a>:
minify live/dead <code>switch</code> cases better</li>
<li><a
href="https://github.com/evanw/esbuild/commit/22ecd306190b8971ec4474b5485266c20350e266"><code>22ecd30</code></a>
minify: more constant folding for strict equality</li>
<li><a
href="https://github.com/evanw/esbuild/commit/4cdf03c03697128044fa8fb76e5c478e9765b353"><code>4cdf03c</code></a>
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/4053">#4053</a>:
reordering of <code>.tsx</code> in <code>node_modules</code></li>
<li><a
href="https://github.com/evanw/esbuild/commit/dc719775b7140120916bd9e6777ca1cb8a1cdc0e"><code>dc71977</code></a>
fix <a
href="https://redirect.github.com/evanw/esbuild/issues/3692">#3692</a>:
<code>0</code> now picks a random ephemeral port</li>
<li>Additional commits viewable in <a
href="https://github.com/evanw/esbuild/compare/v0.24.0...v0.25.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=esbuild&package-manager=npm_and_yarn&previous-version=0.24.0&new-version=0.25.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-02-11 00:36:02 +00:00
DavidLoftus 9547b72b23 Update HandleDocumentSymbol to provide accurate symbol ranges (#4915)
This PR updates the construction of clang::clangd::DocumentSymbol to
produce "range" and "selectionRange" properties that match the
[textDocument/documentSymbol](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_documentSymbol)
spec.

"selectionRange" is constructed by finding start and end position of the
symbols identifier.

"range" property is constructed by finding the left most and right most
token of the AST, the code makes an assumption that left most token is
always the first node in postorder traversal from that node, and the
right most is the node itself. AFAIK this is true for most of the
grammar other than infix operators. For symbols with a body, the right
most token is the open bracket, so we extend the range to its matching
closing bracket.
2025-02-10 23:40:10 +00:00
DavidLoftusandjonmeow 2eddfbd7bf Add restart LSP command to VSCode extension (#4916)
This PR adds a new command to the Carbon VSCode extension "carbon:
Restart language server" which acts similar to clangd / bazel
extensions. While not useful during regular working of the extension
this helps when LSP either crashes or the toolchain is updated.

In order to support graceful restart, I needed to add a Call handler for
"shutdown" which is noop for now. Lsp clients always call shutdown
before sending exit.

---------

Co-authored-by: jonmeow <jperkins@google.com>
2025-02-10 23:39:49 +00:00
Dana JansensandRichard Smith 063b9d8ca9 Deduce the FacetValue for an argument for a generic FacetType parameter (#4882)
When a function has a generic FacetType parameter, it can depend on
other FacetTypes bound as earlier parameters. To deduce the FacetValue,
we need to know the impl to attach to it, which requires knowing the
full type signature of the generic FacetType parameter. To do this,
after deducing other arguments to determine the value of non-generic
FacetType parameters, we substitute them sequentially into later
symbolic parameters to get their full facet types, then converts the
arguments to those full facet types to get the FacetValue. For example:

```
fn F(T: type, U: Interface(T));
```

Here the `T` binding is deduced to the be the caller's argument type.
But the Interface(T) can not be properly deduced to a FacetValue in the
first pass, and it will just be the caller's argument type directly.
After the first deduce pass, we will substitute the deduced T binding
into Interface(T), at which point the argument type can and will be
converted to a matching FacetValue as long as an impl can be found.

Closes #4868

This is based on PRs #4881 and #4863

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-02-10 20:31:37 +00:00
Boaz Brickner e1c9cef7ec Add a test showing how Core can be implicitly poisoned (#4900)
Alternatively, if poisoning `Core` is considered a bug, we could avoid
poisoning it (see #4903).

Part of #4622.
2025-02-10 18:28:40 +00:00
Jon Ross-Perkins f89985d0f4 Add support for publishDiagnostics (#4912)
<img width="536" alt="Screenshot 2025-02-06 at 3 02 18 PM"
src="https://github.com/user-attachments/assets/27b7673d-f8d4-4f9f-9e5d-20c3a88b8c78"
/>

Requires the caching work in #4897
2025-02-07 23:04:35 +00:00
Richard Smith 1917ea223e Avoid redundantly specifying Id::Kind. (#4911)
When a node kind's Id::Kind is determined from its category, don't also
require it to be listed in the switch over all node kinds. This was both
redundant and also error prone -- and in practice for several node
kinds, the Id::Kind computed in the two different ways was different.

Instead, have the switch over node kinds handle only special cases that
can't be handled by their category, and enforce that each node kind has
an Id::Kind specified in exactly one way via checks in the .cpp file.

This refines the previous change in #4280 -- we still get the improved
errors for missing updates, but now also don't require redundant
additions to the switch.
2025-02-07 22:35:18 +00:00
Jon Ross-Perkins d005ac034a Add notes about PR labels (#4913)
Add a code review note for PRs. Background discussion of NFC happened [a
month
ago](https://docs.google.com/document/d/1Iut5f2TQBrtBNIduF4vJYOKfw7MbS8xH_J01_Q4e6Rk/edit?resourcekey=0-mc_vh5UzrzXfU4kO-3tOjA&tab=t.0#heading=h.brv2irjg39vf),
it just slipped my mind to update docs.
2025-02-07 22:13:19 +00:00
Jon Ross-Perkins 9e466b9335 Cache calculated file state in LSP (#4897)
Add caching of parsed documents, and testing of the textDocument
handlers. This is based on #4896, which splits out some of the
boilerplate to calls.

Note, this caches the entire parse state because we'll want to try to
emit diagnostics when we see the update, without waiting. It may be
helpful to do that asynchronously, but we don't want to wait for another
call (such as documentSymbol). Really, we'll probably want to also add
check for diagnostics, at least.
2025-02-07 01:04:42 +00:00
Geoff Romer 55714dd4ed Diagnose var in interfaces (#4907)
Previously this was ignored, and then #4720 accidentally made it a crash
bug
2025-02-06 20:36:00 +00:00
Jon Ross-Perkins e79d3be5bd Combine DiagnosticConverter into DiagnosticEmitter (#4878)
At present, we typically define a DiagnosticConverter, then store an
instance of it and a DiagnosticEmitter that wraps it. This is relatively
minor in general, but I've been trying to create more self-contained
DiagnosticEmitter classes (which hold their own DiagnosticConverter,
similar to NullDiagnosticEmitter), and there it just gets in the way.

Since we don't reuse DiagnosticConverter instances, this combines the
definition into DiagnosticEmitter. Mainly this means we don't have a
separate object in play, and less to carry around.

The most impact is probably to SemIRDiagnosticConverter, which was also
the most complex. Now `SemIRLocDiagnosticEmitter`, this gets some
different construction flow. Note in the PR I've split the file rename
to its own commit, to try to help delta views. However, the most
substantial parts of the refactoring are split into #4876, which this
depends upon.
2025-02-06 20:27:57 +00:00
Jon Ross-Perkins a16a17daf0 Fix bazel warning (#4906)
After #4891, now I'm getting:

```
WARNING: Option 'incompatible_disable_native_apple_binary_rule' is deprecated
```

Sorry about the churn here.
2025-02-06 19:02:00 +00:00
Dana JansensandJon Ross-Perkins 7d46add4e1 Fix comment on DeclNameAndParamsAfterImplicit (#4904)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-06 19:01:48 +00:00
Dana Jansensandjosh11b f3a898bac0 Support implicit conversion from a type value to a facet value (#4863)
If a type satisfies the requirements of a FacetType, then that type as a
value can be converted to a FacetValue, which binds the type value to
the FacetType.

For instance, if the class A implements an interface B, then
```
  fn F(b:! B) {}
```
can be called with the type `A`
```
  F(A);
```
This does not handle yet receiving non-type values matching a FacetType,
as that requires deducing the required FacetValue for the caller's
argument. Follow-up work will do this step.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-02-06 18:56:32 +00:00
Jon Ross-Perkins 40f3de2c07 Remove deprecated python_version setting (#4905) 2025-02-06 18:51:12 +00:00
Dana Jansens 7d6cd3da6d Add a test and check-support for positional params with a return type (#4899)
Functions with positional parameters omit any implicit or explicit
parameter lists. This causes them to not have a pattern block, which
crashes if there is a return type that needs to add to the pattern
block.

Add a test covering this and handle it by having the ReturnTypeId
handler peek at the node stack and conditionally add the missing pattern
block. To do so it looks to see if the previous node is a
`IdentifierNameNotBeforeParams` which implies it was not expecting a
pattern (since there are no params) and thus the pattern block was not
added to the stack.

Note that lambdas also allow functions to omit an identifier, which will
need a pattern block on the stack for implicit parameters, explicit
parameters or a return type, without seeing any IdentifierName-like
parse nodes. To handle this, we will need to look for additional nodes
in the future and add the missing pattern block to the stack - possibly
for the FunctionInitializer, but the parse support needs to be created
for lambdas first.
2025-02-06 17:49:00 +00:00
Jon Ross-PerkinsandChandler Carruth 7eee9a3489 Refactor resolving a location into a SemIR library (#4876)
At present, lower depends on `Check::SemIRDiagnosticConverter` for debug
info. That was to support a quick implementation of debug info, but
isn't great because it's both an unusual dependency on check's
implementation, and relying on diagnostic structures for debug info.

This cleans that up by splitting relevant logic out to a library in
sem_ir, and having lowering use sem_ir's library instead of check's.
Additionally, a small refactoring of `Parse::TreeAndSubtrees` to allow
getting locations in lowering without going through a `DiagnosticLoc`.
I'm adding `Parse::GetTreeAndSubtreesFn` in because it's a complex
signature to have in so many spots.

I chose to have `ResolveNodeId` return a `SmallVector` because it seemed
likely to be fairly compact, but that could also be using an optional
callback to handle resolved node IDs, possibly just returning the last
entry. This could be switched if preferred.

Note this change shouldn't affect behavior, it's just moving code
around.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-02-06 00:55:20 +00:00
Jon Ross-Perkins 34ceb6bbbe Add @LSP-CALL to file_test (#4896)
Adds @LSP-CALL and refactors LSP keyword handling to implicitly handle a
little more of the LSP structure. This is coming out of textDocument
call handling, where this at least reduces some boilerplate of
`"params": {...}`.
2025-02-05 23:39:27 +00:00
Dana Jansens a735a4e463 Make the constant value of AsCompatible match its type (#4881)
AsCompatible changes a source instruction's type to a compatible type,
so it also needs its constant value to take on the compatible type.
Otherwise the type of the instruction and its constant value will
differ, which makes moving to the constant value into a lossy
transformation.

Part of #4868
2025-02-05 20:16:52 +00:00
Dana JansensandJon Ross-Perkins e78624cad2 Set bazel flags for 'common' instead of 'build' (#4895)
We want to ensure the default flags are used consistently for all bazel
commands/steps.

Flag aliases do not track which commands/steps they work with though so
they can not use 'common'.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-05 17:35:25 +00:00
Dana JansensandJon Ross-Perkins 3d78808c90 Add a disk cache limit of 100G for bazel (#4893)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-05 16:49:23 +00:00
Jon Ross-Perkins e0e0eb8374 Update llvm for string changes (#4894)
This is primarily to get commits involved in
https://github.com/llvm/llvm-project/pull/120534
2025-02-05 02:32:02 +00:00
Richard Smith d71b84438f Add a writeup for how associated constants are processed. (#4856)
Also fix a bug found when working through this.
2025-02-05 01:28:25 +00:00
Samiur Khan a7de3b81c3 Adds help and alsologtostderr flags to comp database generation script (#4869)
Adds `--help` and `--alsologtostderr`, latter as a boolean switch. Error
message was being sent to `/dev/null` by default, this allows it to
print to stderr. Helps in debugging why the script may be failing.

Tested by running
1. `./scripts/create_compdb.py`. This is the baseline (trunk). Can fail
or succeed. Not evaluated.
2. `./scripts/create_compdb.py --help`. Prints help. Expected.
3. `./scripts/create_compdb.py --also`. Fails. Expected because of
disabled abbreviations.
4. `./scripts/create_compdb.py --alsologtostderr`. Correctly printed
error logs. Expected.
2025-02-05 01:28:14 +00:00
Jon Ross-Perkins c94d40748f Update bazel incompatible flag list (#4891)
Note one of these was added in 8.0.1, so this PR requires #4888. I just
forgot to check flags when updating, and figured it's just as well to
split this.

- `--incompatible_disable_native_apple_binary_rule`: Not sure why I
didn't have this before, maybe a copy-paste error? It's not new, it's
documented as deprecated... but even though it should be a no-op,
bazelisk recommends adding it.
- `--incompatible_disallow_empty_glob`: #4783 removed the conflict; I
mistakenly removed the comment instead of uncommenting
- `--incompatible_locations_prefers_executable`: New flag;
https://github.com/bazelbuild/bazel/releases/tag/8.0.1
2025-02-04 23:43:15 +00:00
Richard Smith 6af3d050ea Don't recover from import errors by producing an error constant. (#4892)
Instead, produce a CARBON_FATAL error. Returning an Error constant from
the importer seems reasonable but turns out to not work well in
practice, because it violates the invariant that a constant value should
not have an error as an operand.

Also, don't produce an error constant for a valid ImportRefLoaded that
whose value is not constant; preserve the non-constant value instead.
2025-02-04 23:36:55 +00:00
Richard SmithandJon Ross-Perkins fcfb1345d5 Support accessing associated functions by member access into facets (#4872)
For an expression such as `(Type as Interface).AssocFn()`, track the
`Self` type `Type` in the result of the member access so that it's
available when checking the function call.

This introduces a new kind of type, `ImplFunctionType`, that represents
the type of a function that is expected within an impl, modeled as the
type of the function within the interface plus a value to use as `Self`.
Calls to values of this type behave like calls to the underlying
function except that the `Self` parameter is pre-bound to the self type
from the facet.

In order to support this, fix an issue where the imported list of
generic bindings lost their association with their enclosing generic.
This adds a little complexity to `import_ref`, including a new recursive
cycle that I intend to address in a follow-up PR.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-02-04 22:38:38 +00:00
Calvin dcfccd3187 Support references in ErrorOr (#4889)
### Context & Motivation

The error handling utilities in `//base/error.h` are very useful for
writing code with strong safety guarantees. While hardening the `Dump`
debug utilities (from review in #4866), I encountered a rough edge with
references and pointers. After a [brief Discord discussion in
#contributing-help](https://discord.com/channels/655572317891461132/1052653651895779359/1334675462877610038),
it was suggested that adding support for references to `ErrorOr` would
be a good candidate to move forward.

Using a reference type with the `ErrorOr` class (e.g. `ErrorOr<Node&>`)
produces two errors:

<ol>
<li><strong><code>variant can not have a reference type as an
alternative</code></strong>
<ul><li>From private field: <code>std::variant&lt;Error, T&gt;
val_;</code></li></ul>
</li>
<li><strong><code>'operator-&gt;' declared as a pointer to a
reference</code></strong>
<ul><li>From member function: <code>auto operator-&gt;() -&gt;
T*</code></li></ul>
</li>
</ol>

### Changes

To support reference types, both errors are resolved:

1. `std::reference_wrapper` is conditionally used for storage when `T`
is a reference type
2. type trait aliases like `using ValueT = std::remove_reference_t<T>`
are used to produce compatible types for methods like `auto operator->()
-> ValueT*`
2025-02-04 21:08:43 +00:00
Jon Ross-Perkins 6803127ab0 Update to bazel 8.0.1 (#4888) 2025-02-04 20:53:15 +00:00
Jon Ross-Perkins 2929254168 Update LLVM version, fix breaks (#4886)
- The actual reason I started this: minor lowering updates in the golden
LLVM IR
- Process.inc changed enough to need a patch context update.
- https://github.com/llvm/llvm-project/pull/123126 added `proto_library`
uses without a `load`, which is broken in bazel 8
- Just commenting these out because we don't use them. I'll follow up
separately about a possible fix, but continuing to use `WORKSPACE` is a
bigger issue LLVM probably should address.
- Note this update is also triggering removal of `migrate_cpp`, in #4887
2025-02-04 18:13:29 +00:00
Jon Ross-Perkins 621d2d24f2 Update actions/cache version (#4890)
Seeing if an update fixes this, or if this is just a bug in GitHub's
enforcement.

```
Error: This request has been automatically failed because it uses a deprecated version of `actions/cache: 0c45773b623bea8c8e75f6c82b208c3cf94ea4f9`. Please update your workflow to use v3/v4 of actions/cache to avoid interruptions. Learn more: https://github.blog/changelog/2024-12-05-notice-of-upcoming-releases-and-breaking-changes-for-github-actions/#actions-cache-v1-v2-and-actions-toolkit-cache-package-closing-down
```
2025-02-04 18:03:47 +00:00
2729022f47 Diagnose impl function with mismatched signature compared to virtual (#4816)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-02-04 04:52:32 +00:00
Boaz Brickner c67920e631 When diagnosing name used before declared, set the location of the usage (#4860)
Done by adding a poisoning location for each poisoned name.
Part of #4622.
2025-02-03 20:01:09 +00:00
Jon Ross-Perkins a8aca3ce71 Remove legacy migration prototype (#4887)
Although migration tooling is intended for Carbon, this tooling was
primarily a proof-of-concept prototype. The last time it got significant
work was in 2022
(https://github.com/carbon-language/carbon-lang/commits/trunk/migrate_cpp);
since then, we've mainly been doing small cleanups to keep it building.
We're now hitting an issue in #4886 that `TypeNodes.inc` isn't exposed
as a `#include`.

We already had thoughts about rewriting this as a `RecursiveASTVisitor`,
per `rewriter.cpp`/`rewriter.h`. That may justify a significantly
different approach than had been set up in `cpp_refactoring`. But, it's
hard to tell.

Either way, my sense is that rather than incrementally trying to keep
this code building, we should revisit it when we're ready and have a
long-term strategy for how migration should work.
2025-02-03 19:57:15 +00:00
Jon Ross-Perkins 77ea777b13 Expose currently-silent failure in language server (#4879)
Not sure if I mixed up a merge somewhere, but this is what
`parse_error.carbon` was supposed to test. Note
`unexpected_reply.carbon` was basically doing the same test, with a
minor issue of `change` vs `result` to get better output.
2025-02-03 16:47:38 +00:00
Boaz Brickner 65180a77c3 Use designated initializers in import.cpp (#4883)
From
https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting:
"Use designated initializers (`{.a = 1}`) when possible for structs".
2025-02-03 15:41:28 +00:00
Richard SmithandChandler Carruth e257051612 No predeclared identifiers, Core is a keyword (#4864)
Introduce a principle that the Carbon language should not encroach on
the
developer's namespace. Satisfy this principle by making `Core` a
keyword.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-02-01 03:03:30 +00:00
Alina Sbirlea e4e6332ad4 Check explicit params exist. (#4875)
If there are no explicit params, then `last_param_node_id` should be
`implicit_params_loc_id`. But there is no use case currently, so for now
we assume explicit params exist and assert if not, so this can be found
and updated then.
2025-01-31 19:53:43 +00:00
Jon Ross-Perkins b0b1554904 Refactor diagnostic_emitter.h (#4871)
I'm planning on eliminating DiagnosticConverter. As part of this,
collapse it into diagnostic_emitter.h, and refactoring the header a
little so that it's more readable when making changes.
2025-01-31 18:23:58 +00:00
Jon Ross-Perkins 133717cd7e Eliminate NodeLocConverter (#4870)
I'm looking at eliminating `DiagnosticConverter`. This change removes
`NodeLocConverter` (albeit adding `UnitAndImportsDiagnosticConverter`),
and in doing so, refactors lex conversion functions to extract them out
from the `DiagnosticConverter` functions.

I'll be following up with changes that collapse `DiagnosticConverter`
logic into `DiagnosticEmitter` locations. The intent is that we
shouldn't need separate ownership of both types.
2025-01-30 22:30:33 +00:00
Jon Ross-Perkins 16b2cafae1 Clean up language server's output handling (#4855)
Handles verbose logging and printing errors as diagnostics to stderr
when there's no way to communicate them back on a request.
2025-01-30 18:34:03 +00:00
Jon Ross-PerkinsandChandler Carruth 7befe2ce9f Switch custom error stream output to diagnostic (#4846)
This switches most error printing to use diagnostics instead of direct
stream writes, even when not a specific file diagnostic. I'm allowing
empty filenames for this use-case.

This allows a little more specific testing to validate coverage of
output using the diagnostic coverage test. I'm adding a few tests to
cover things that weren't previously tested.

Separately, this also forces a little more standardization in format...
considering how changes like #4568 show effort being spent to _mirror_
diagnostic style, my thought is now to just use diagnostic code where
possible.

Note this also allows incrementally better testing of the language
server; I'm changing the crash fix from #4847 in favor of diagnostic
testing.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-01-30 01:58:07 +00:00
Jon Ross-Perkins 7d2958ad37 Broaden file_test support for LSP requests (#4854)
Adds `@LSP-NOTIFY` and `@LSP-REPLY` to capture the slightly different
formats versus a typical call. Removes special-casing for `exit`.
2025-01-29 21:31:10 +00:00
Jon Ross-Perkins 4ecf914a07 Make SemIRLoc data private to diagnostics (#4867)
I think the name of `SemIRLoc` might be leading to a few suggestions to
use it for non-diagnostic purposes that I've been responding to. At the
same time, a short name seems desirable given its frequency of use for
diagnostics. I did also clean up misuse in #4857, and eval.cpp (noted
below) might be similar. We don't typically use `friend` to emphasize
relationships, but given the diagnostic-specific intent and ways it's
been used, perhaps it's reasonable to close the API of this type using
`friend`?

eval.cpp inspects contents, but it's not clear that's needed because
changing logic doesn't affect tests, so I'm just removing it. Note that
SemIRLoc could've also been a loc_id, and it seems like the current
approach would mishandle that (i.e., print for `LocId::None` when that
seems not to be the intent). I figure we can add a `has_value` or
`AddNoteRequiringLoc` or something like that if needed.
2025-01-29 20:46:30 +00:00
Dana Jansens bb67c7dfb2 Add SemIR::MakeSymbolicConstantId(int) (#4862)
Symbolic constants are negative values (starting at -3 at the moment)
but instead of having to figure the correct integer value for
MakeConstantId, provide a function to make a symbolic constant directly.
2025-01-29 16:55:14 +00:00
Boaz Brickner 7c01bb4e5c Return the NameId for a new instruction regardless if it's unresolved because it's poisoned or not (#4861)
i.e. Support `Poisoned` in `NameContext::name_id_for_new_inst()`.
Part of #4622.
2025-01-29 14:20:05 +00:00
Jon Ross-Perkins 3bd7252f29 Clean up obsolete import handling in class/function (#4857)
Noticed because the `new_loc.inst_id` use would be invalid as-is
2025-01-28 22:49:03 +00:00
Jon Ross-Perkins ad0a47d06b Change LookupNameInCore to use a LocId (#4858)
SemIRLoc is doing extra wrapping which shouldn't be used here.
2025-01-28 22:33:07 +00:00
Boaz Brickner f4e19f4390 Change DeclNameStack::LookupOrAddName() to return SemIR::ScopeLookupResult instead of a pair (#4852)
This makes the lookup API more consistent and would make it easier to
add poisoning location.
Part of #4622.
2025-01-28 21:36:20 +00:00
Boaz Brickner 51d7e6315e When looking up a name in a scope, propagate the lookup result when it's poisoned (#4851)
Instead of creating a new poisoned result.
This would allow propagating the poisoning location when we add it.
Part of #4622.
2025-01-28 17:45:24 +00:00
5abe5a3c21 Stop allowing impl redeclarations to differ syntactically in where clause (#4850)
Based on [the lastest thinking on
#4672](https://github.com/carbon-language/carbon-lang/issues/4672#issuecomment-2606209281)
, require a full syntactic match for impl redeclaration, instead of
excluding the `where` restriction. This means no updates to the impl
witness on redeclaration, and no diagnostics that those updates are
consistent.

Not included in this PR, but will need to be done in the future:
* Support for assigning values to associated constants in the body of
the impl definition. This will require moving the checking that
non-function associated constants are set from the definition start to
definition end.
* Identify semantic redeclarations that are not syntactic matches to
give a failed redeclaration diagnostic. This should be done once we are
already identifying impl declarations with the same type structure in
order to require they be identified in an impl_priority/match_first
block.
* Merging of the functions in `check/impl.cpp` that are now always
called together.

Also add some test coverage of `where` parsing I developed in PR I've
now abandoned because of this new simplification of the impl
redeclaration semantics.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-28 06:00:34 +00:00
Jon Ross-Perkins 0d0e202ce8 Switch Driver back to parameters for construction (#4849)
This is for more complex construction, see #4846
2025-01-27 23:48:44 +00:00
Jon Ross-Perkins 8727445656 Add a framework for LSP testing. (#4841)
Also adds tests for exit and initialize, just basic things.
2025-01-27 16:15:04 +00:00
Richard Smith 809c53287a Fix crash when driver fuzzer finds language-server. (#4847)
The driver fuzzer, unlike the actual driver, provides a null
`input_stream`, which caused the `language-server` subcommand to crash.
2025-01-27 15:36:09 +00:00
Boaz Brickner 3d39ab67bf Wrap lookup result in a new ScopeLookupResult (#4831)
Benefits:
* Provide a proper API for accessing lookup information.
* Make assumptions on whether the result is poisoned or not and how we
can use `InstId` explicit.
* Allow safely reusing the `InstId` value for pointing to the poisoning
entity for poisoned results (in a future PR).
* Consolidate `LookupNameInExactScopeResult`, `std::pair<SemIR::InstId,
bool>` and part of `LookupResult`.
Part of #4622.
2025-01-27 10:05:23 +00:00
Richard Smith 5f888e1124 Treat associated constants as entities parameterized by Self (#4837)
Add a full entity representation for associated constants, and build a
`Generic` object for them. This `Generic` is parameterized by the
enclosing `Self` type, allowing the use of `Self` within the type of the
associated constant to be supported.

When performing impl lookup for an associated constant, produce the type
with the provided self type substituted for its `Self` along with any
generic parameters of the interface.

Split the handling of associated constant declarations into two parts,
corresponding to the code before the `=`, and the code between the `=`
and `;` (if any). The former goes into the generic declaration region;
the latter into the generic definition region. This prepares us to
handle the default value for an associated constant, but for now we're
just storing the information and not actually using it.

Remove the entity type field from `assoc_entity_type`, because it's
almost unused and is an attractive nuisance -- it must necessarily be a
type in the generic scope of the associated constant rather than in the
scope of the instruction (because there is no `Self` anywhere else),
which means that it's hard to substitute into or derive meaning from.

See `toolchain/check/testdata/impl/assoc_const_self.carbon` for tests of
the new functionality; these used to cause the toolchain to crash.
2025-01-25 02:13:52 +00:00
Jon Ross-Perkins b06fcc97f6 Clean up a few details of lex yaml printing (#4845)
- Escape dumped token strings (what got me here)
- Change the quoting from backticks to quotes
- Also add a `FormatEscaped` helper function for this, updating other
`.write_escaped` uses
2025-01-24 21:52:02 +00:00
Jon Ross-Perkins 22c0198835 Fix flag name from #4835 (#4844) 2025-01-24 17:25:46 +00:00
Jon Ross-Perkins aec951d7c3 Fix autoupdate handling of carriage return (#4840)
Switching from RE2 to StrReplaceAll because it seems a fair fit for what
actually needs to be done here. Also pick up \t for visibility reasons.

This came up because clangd's LSP-related APIs print carriage returns.
2025-01-24 16:41:57 +00:00
Richard Smith bc952b1a4b Document numeric type literals in lexical conventions. (#4842)
Also improve the precision of some other nearby documentation.
2025-01-24 01:57:42 +00:00
Jon Ross-Perkins ad49647661 Refactor ToolchainFileTest functions out-of-line (#4839)
I'm going to be adding more, and it's large already. Also adding API
comments.
2025-01-24 00:56:13 +00:00
Richard SmithandJon Ross-Perkins 58fba078ee Add a flag to make CHECK failures non-fatal for debugging. (#4835)
`toolchain/autoupdate_testdata.py --allow-check-fail` can now be used to
perform an autoupdate even if some `CARBON_CHECK`s are failing. What
this does will depend on how the toolchain behaves after the `CHECK`
failure, and of course there's no guarantees there, but this can be
useful if it's easier to debug the `CHECK` failure by looking at the
produced SemIR.

Internally, this uses `bazel build --config=non-fatal-checks`, which in
turn specifies a `--per_file_copt` for `check_internal.cpp`. The intent
here is that the rebuild required to enable or disable this mode is as
small as reasonably possible.

This mode is not compatible with `-c opt`, as it's important that check
failure calls are `[[noreturn]]` in `-c opt` mode.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-23 20:47:51 +00:00
Jon Ross-Perkins 1670baf180 Make binary operators non-member (#4838)
Came up on #4831, style:

"For a type T whose values can be compared for equality, define a
non-member operator== and document when two values of type T are
considered equal."
https://google.github.io/styleguide/cppguide.html#Operator_Overloading

Note while we could put some of these out-of-line, it's helpful to keep
them inside the braces:
- For private member access
- For templated cases so that we aren't duplicating templates
- Very mild preference for keeping class's API documented within the
braces
2025-01-23 20:25:06 +00:00
Geoff Romer 96256652c5 Use FullPatternStack instead of node stack for binding context (#4829) 2025-01-23 17:25:31 +00:00
Jon Ross-Perkins 9c0faf007e Invalid comment cleanup (#4836)
This is a followup from #4834, I searched for "invalid" uses in our
codebase. This is mostly changing comments, and a couple debug
functions, but shouldn't affect testable behavior.

Note a couple things I'll highlight as not changing (but could) are:
- `ReturnTypeInfo::is_valid`
- `"invalid"` uses in the formatter
- `AddInvalid` for `!has_value` in `inst_fingerprinter` (because the
cases it's called sound invalid-ish)
2025-01-23 02:21:48 +00:00
Jon Ross-Perkins 6b5eb1a101 Id::Invalid -> Id::None (#4834)
High level, replacing `Id::Invalid` with `Id::None` and `Id::is_valid`
with `Id::has_value` for clarity, as discussed
[here](https://discord.com/channels/655572317891461132/655578254970716160/1331664574545395794).
The `IntId` refactoring is needed together with `AnyIdBase` because it's
also used with `ValueStore`.

Note, trying to be careful not to rewrite `EnumBase::InvalidIndex`, or
`is_valid` in general (e.g., `IdKind::is_valid`).

I've tried to sequence commits here:

1. Automatic replacements:

- `((?:Id|Index)(?: |::|\(|Base(?:\(|::)))Invalid((?:Index)?\W)` ->
`$1None$2`
  - `<invalid>` -> `<none>`
  - `InvalidNodeId` -> `NoneNodeId`
  - `/\*invalid\*/` -> `/*none*/`
  - `id((?:_|\(\))(?:\.|->))is_valid` -> `id$1has_value`

2. Manual edits:

  - In `int.h` and `int_test.cpp`
    - `IntT` has `is_value`, which I'm renaming to `is_embedded_value`.
    - Manual edits to comments in this file.
  - `AnyIdBase` and `IdBase`
- Declaration of `is_valid` -> `has_value`, `InvalidIndex` ->
`NoneIndex`.
  - In `ids.h` and `ids.cpp`
    - `is_valid` -> `has_value`
- `// An explicitly invalid ID.` -> `// An ID with no value.`; similar
for index
    - Various math on `InvalidIndex` -> `NoneIndex`
    - Various mentions of "valid" in comments
  - In `value_store.h`, for `IdT::Invalid`, plus one comment
- In `impl.h` and `tokenized_buffer.h`, we had different initialization
of `::None` values (versus `ids.h` syntax) that I fixed manually.
  - Spot checks to compile
- Particularly where `is_valid` replacements didn't catch spots due to
different naming.

3. Autoupdate tests

4. verbose.carbon (NOAUTOUPDATE)

5. Comment spot checks

Note there are probably other mentions of "Invalid" that should be swept
up, but I'd like to argue for merging and separating out remaining
cleanup since this is so sweeping (and likely to hit merge conflicts
from churn). We'll probably have lingering mentions of "invalid" for a
bit regardless, just because there are uses of "invalid" in non-Id APIs.
2025-01-22 23:15:00 +00:00
David Blaikie b292943648 Sink comment into implementation (#4833)
This comment applies equally to any called passing `check_syntax=false`,
such as for virtual function impls, being tested in #4816
2025-01-22 22:26:35 +00:00
David Blaikie d620f3f2da Remove unused parameter (#4832)
Post-commit review in #4732
2025-01-22 20:27:05 +00:00
Calvin 3f4de65ad8 Improve SemIR naming of import_refs (#4824)
Changes the name of SemIR `import_ref`s to use the format
`<package>.<entity>`.

<table>
<tr><th>Before</th><th>After</th></tr>
<tr>
<td><code>%import_ref.05a: type</code></td>
<td><code>%Main.D: type</code></td>
</tr>
<tr>
<td><code>%import_ref.8f2: &lt;witness&gt;</code></td>
<td><code>%Main.import_ref.8f2: &lt;witness&gt;</code></td>
</tr>
</table>

* [Discord discussion in
#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1330253540999827577)
* Closes #4769
2025-01-22 07:22:07 +00:00
dependabot[bot] fe92e3f552 Bump undici from 6.21.0 to 6.21.1 in /utils/vscode in the npm_and_yarn group across 1 directory (#4830)
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.0 to 6.21.1
<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.21.1</h2>
<h1>⚠️ Security Release ⚠️</h1>
<p>Fixes CVE CVE-2025-22150 <a
href="https://github.com/nodejs/undici/security/advisories/GHSA-c76h-2ccp-4975">https://github.com/nodejs/undici/security/advisories/GHSA-c76h-2ccp-4975</a>
(embargoed until 22-01-2025).</p>
<h2>What's Changed</h2>
<ul>
<li>fix(<a
href="https://redirect.github.com/nodejs/undici/issues/3736">#3736</a>):
back-port 183f8e9 to v6.x by <a
href="https://github.com/ggoodman"><code>@​ggoodman</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/3855">nodejs/undici#3855</a></li>
<li>fix(<a
href="https://redirect.github.com/nodejs/undici/issues/3817">#3817</a>):
send servername for SNI on TLS (<a
href="https://redirect.github.com/nodejs/undici/issues/3821">#3821</a>)
[backport] by <a
href="https://github.com/metcoder95"><code>@​metcoder95</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/3864">nodejs/undici#3864</a></li>
<li>fix: sending formdata bodies with http2 (<a
href="https://redirect.github.com/nodejs/undici/issues/3863">#3863</a>)
[backport] by <a
href="https://github.com/metcoder95"><code>@​metcoder95</code></a> in <a
href="https://redirect.github.com/nodejs/undici/pull/3866">nodejs/undici#3866</a></li>
<li>[Backport v6.x] fix: Fixed the issue that there is no running
request when http2 goaway by <a
href="https://github.com/github-actions"><code>@​github-actions</code></a>
in <a
href="https://redirect.github.com/nodejs/undici/pull/3877">nodejs/undici#3877</a></li>
<li>types: [backport] Update return type of RetryCallback (<a
href="https://redirect.github.com/nodejs/undici/issues/3851">#3851</a>)
by <a href="https://github.com/metcoder95"><code>@​metcoder95</code></a>
in <a
href="https://redirect.github.com/nodejs/undici/pull/3876">nodejs/undici#3876</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nodejs/undici/compare/v6.21.0...v6.21.1">https://github.com/nodejs/undici/compare/v6.21.0...v6.21.1</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/nodejs/undici/commit/e260e7bb173abe3399dabd61338ca4a71fcf8825"><code>e260e7b</code></a>
Bumped v6.21.1</li>
<li><a
href="https://github.com/nodejs/undici/commit/c3acc6050b781b827d80c86cbbab34f14458d385"><code>c3acc60</code></a>
Merge commit from fork</li>
<li><a
href="https://github.com/nodejs/undici/commit/2414bc9f7d651f830902af00238e1b11d9a389dc"><code>2414bc9</code></a>
Update return type of RetryCallback (<a
href="https://redirect.github.com/nodejs/undici/issues/3851">#3851</a>)
(<a
href="https://redirect.github.com/nodejs/undici/issues/3876">#3876</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/be8cd0afa0cf8207d8849026f2ee6fdc6dc9dcec"><code>be8cd0a</code></a>
[Backport v6.x] fix: Fixed the issue that there is no running request
when ht...</li>
<li><a
href="https://github.com/nodejs/undici/commit/ee6176cd2e09853c868bf5bc1a34bf0500963e4d"><code>ee6176c</code></a>
fix: sending formdata bodies with http2 (<a
href="https://redirect.github.com/nodejs/undici/issues/3863">#3863</a>)
[backport] (<a
href="https://redirect.github.com/nodejs/undici/issues/3866">#3866</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/a0220f14bfd2a404173eacc94aa1722829075283"><code>a0220f1</code></a>
fix(<a
href="https://redirect.github.com/nodejs/undici/issues/3817">#3817</a>):
send servername for SNI on TLS (<a
href="https://redirect.github.com/nodejs/undici/issues/3821">#3821</a>)
[backport] (<a
href="https://redirect.github.com/nodejs/undici/issues/3864">#3864</a>)</li>
<li><a
href="https://github.com/nodejs/undici/commit/353ab63188af904a17030d96018d6193247d7d18"><code>353ab63</code></a>
fix(<a
href="https://redirect.github.com/nodejs/undici/issues/3736">#3736</a>):
back-port 183f8e9 to v6.x (<a
href="https://redirect.github.com/nodejs/undici/issues/3855">#3855</a>)</li>
<li>See full diff in <a
href="https://github.com/nodejs/undici/compare/v6.21.0...v6.21.1">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=6.21.0&new-version=6.21.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-01-22 01:02:24 +00:00
Jon Ross-Perkins e393c769af Add support for testing with stdin (#4819)
In order to write language-server tests, we need some way to pass stdin
input. This adds support for a split "// --- STDIN" which will be
provided as a temp file for testing.

Note this does more stdin -> input_stream style renaming, this is just
bugging me more since I know shadowing works but it can be subtle to
read, particularly since I'm now making direct use of stdin in a handful
of spots.
2025-01-21 22:04:13 +00:00
David Blaikie 667a010ae6 Readd the missing class !members list. (#4828)
Thanks to danakj for spotting this was removed accidentally in #4732
2025-01-21 20:37:07 +00:00
Geoff Romer 943acf1ec2 Separate node kind for bindings inside var (#4822)
This is a step toward making binding pattern handling more robust, by
removing its reliance on the node stack for context.
2025-01-21 20:15:19 +00:00
Jon Ross-Perkins 4f024410f7 Add stdin to driver's streams, and refactor stream passing (#4812)
The language server needs stdin, and for tests we should be passing it
around. My intent is to pass in a faux stdin to Driver for language
server tests.

As long as I'm adding a new parameter, I was looking at also changing
the way streams are passed in to Driver for style (pointers since
they're held past construction lifetime). Since these are all stored in
DriverEnv, I thought it might be a net improvement to use the struct
directly, getting more explicit parameter names and also removing the
need for `SetFuzzing`.

I'm trying here to avoid functional changes, but there are a couple
additional fixes like removing an obsolete `find_insensitive` and
refactoring how `ValidateOptions` handles errors (because it reduces the
number of spots that operate on error_stream).
2025-01-21 16:52:05 +00:00
Jon Ross-Perkins 41b6bb5688 Update TODO for semantic checking (#4821)
I believe `check_syntax` is already controlling the semantic vs
syntactic merge, added in #4149. Other parts of the TODO are clarified
per discussion. But this is tested, e.g. errors with the bool flipped:

```
 impl i32 as I {
+  // CHECK:STDERR: method.carbon:[[@LINE+6]]:14: error: redeclaration syntax di
ffers here [RedeclParamSyntaxDiffers]
+  // CHECK:STDERR:   fn F[self: i32](other: i32) -> i32 = "int.sadd";
+  // CHECK:STDERR:              ^~~
+  // CHECK:STDERR: method.carbon:[[@LINE-7]]:14: note: comparing with previous
declaration here [RedeclParamSyntaxPrevious]
+  // CHECK:STDERR:   fn F[self: Self](other: Self) -> Self;
+  // CHECK:STDERR:              ^~~~
   fn F[self: i32](other: i32) -> i32 = "int.sadd";
 }
```
2025-01-21 16:50:25 +00:00
Boaz Brickner 6636baf392 Remove comment about inst_id not being poisoned (#4827)
`InstId` cannot be poisoned since #4764.
Part of #4622.
2025-01-21 16:34:46 +00:00
Calvin a664801608 Reformat CompilationUnit function definitions out-of-line (#4825)
The `Driver::CompilationUnit` class is defined with multiple long
function definitions inline. This change moves those definitions
out-of-line.
2025-01-21 16:27:00 +00:00
Boaz Brickner c304e73857 When adding a namespace, explicitly unpoison an optimistically poisoned name (#4826)
Part of #4622
2025-01-21 16:18:49 +00:00
Boaz Brickner d30957fc65 Remove extra SemIR:: qualification in NameScope since it's already in SemIR namespace (#4823) 2025-01-20 15:44:14 +00:00
Boaz Brickner 30c1530261 Support multiple import Cpp library in a single unit (#4814)
Instead of compiling the imported file, generate a C++ header that
includes all `Cpp` import files.
Part of #4666
2025-01-20 09:44:45 +00:00
Jon Ross-PerkinsandGeoff Romer 4c4c4a4d2c Add RawStringOstream for slightly simpler streaming to strings (#4817)
This adds a RawStringOstream. Versus TestRawOstream, which is
consolidated over to RawStringOstream, it uses a string for storage
instead of a vector, mainly to support move-to-string semantics. Versus
llvm::raw_string_ostream, it owns the string and supports pwrite (which
is needed for driver and its fd_ostream compatibility requirement).

This converts most uses of llvm::raw_string_ostream, leaving behind a
few in InstNamer that explicitly cannot own the string, such as:

```
     llvm::raw_string_ostream(name)
          << "_" << tree.tokens().GetColumnNumber(token);
```

I have this as its own library so that it can use CHECK.

Yes this doesn't save much code, but it's code we repeatedly write.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2025-01-18 01:11:44 +00:00
Richard SmithandCarbon Infra Bot ef6e035e7d Website: exclude files that would cause problems for prebuild or jekyll (#4810)
Exclude some files from the website and prebuild steps that aren't part
of the git repository, but may exist in a checkout, and if present will
cause the website prebuild or build to misbehave or break.

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-01-17 20:47:52 +00:00
Geoff RomerandRichard Smith 13434f0e8a Model var as a pattern operator (#4720)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-01-17 17:51:34 +00:00
Jon Ross-Perkins 6572da7314 Add dwblaikie as a toolchain reviewer (#4820) 2025-01-17 16:51:53 +00:00
David BlaikieandJon Ross-Perkins e6c1f0630a Add a newline after diagnostic output when testing (#4818)
This removes some churn when adding new diagnostic cases to test files
(where previous to this change the newly added newline would cause the
previous diagnostic CHECKs to be updated including changes to the line
number because the CHECK for the blank line meant an extra line between
CHECK and source line).

A few alternatives discussed here:
https://discord.com/channels/655572317891461132/655578254970716160/1329573358475673723

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-16 23:23:57 +00:00
a8b46cf561 Add SemIR Vtable instruction and usage (#4732)
Add a Vtable typed inst with a type_id (of the type this vtable applies
to) and list of virtual function decls (or import refs to function
object constants).

This doesn't add lowering/emission of the vtable, or usage when
initializing objects of the type.

Some questions in case they're interesting to discuss:
* is it right/worth having the type_id in the vtable? (probably makes it
easier to emit - using the type to get the class name to figure out the
mangled name for the vtable) perhaps it should be a ClassId?
* I'm thinking the logic in CheckCompleteClassType could be the place we
handle diagnostics for mismatched keywords (virtual/abstract for a
function that's already virtual/abstract, maybe checking for non-virtual
functions with the same name in a base class, or derived class functions
without `impl`, etc) - but we could move some of that to the moment we
walk the function decl, and record our findings in the function decl
(record the base function it overrides, or the index of the vtable to
slot to use when building the vtable at the end of the class)
* the Vtable typed inst has `constant_kind = InstConstantKind::Always`
and `is_lowered = false`, I think I added that in to workaround/address
some failures in lowering. And seems correct for this intermediate step
- I'll add lowering in a follow-up patch. But the constant_kind - what
should this be? We can just say all vtables are of VtableType (in which
case the `Always` constant kind sounds right to me) or we could have
them introduce a type with each virtual function as a named member,
even?

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-16 20:19:22 +00:00
Jon Ross-Perkins e348119feb Update a few faq questions which are showing their age (#4813)
Struck me I hadn't looked through this recently, although it feels it's
mostly held together.
2025-01-16 01:27:42 +00:00
Richard Smith a058f30f3a Fix rendering of https://docs.carbon-lang.dev/proposals/p2188.html (#4802)
Per https://kramdown.gettalong.org/syntax.html#html-blocks, kramdown
doesn't render markdown inside HTML tags by default. Enable this
globally to get results more similar to Github-Flavored Markdown.
2025-01-15 22:38:11 +00:00
Dana Jansens 6aba386eeb Move the complete_witness_type above the !members label. (#4808)
When printing a Class, the complete_type_witness was printed last but
this gave a somewhat misleading representation as it appeared to be part
of the !members label. Move it above the label so that the label more
clearly refers to everything below it.
2025-01-15 22:13:19 +00:00
Jon Ross-Perkins f7269482fe Remove node_stack Peek templating where possible (#4801)
The "templated for consistency" variants felt a little confusing when I
was working on #4795, so suggesting to remove templating where it's not
helpful to instantiate (particularly when there were both templated and
non-templated variants). Note this leaves a `PeekIs<IdT>` because
there's indirection there, but that's more the exception than the rule.
2025-01-15 22:12:22 +00:00
Richard Smith e0f9c40f47 Switch some codeblocks to recognized languages. (#4811)
Fix syntax highlighting for these code blocks.
2025-01-15 21:49:14 +00:00
Boaz Brickner 28d6aedbbb Add Support for #include in cpp files imported from Carbon (#4809)
Propagate `FileSystem` to `buildASTFromCodeWithArgs`().
Part of #4666
2025-01-15 21:27:58 +00:00
Boaz Brickner aa23e9e2d8 Update LLVM (#4807) 2025-01-15 17:32:42 +00:00
Jon Ross-Perkins d958caaff3 Refactor CheckIsAllowedRedecl and stop function definition merging (#4800)
Rename `CheckIsAllowedRedecl` to `DiagnoseIfInvalidRedecl` to try to
better document behavior, and clean up comments.

This extends the no-merge-if-defined behavior to functions. It was
already the case for class/interface, and just added for impl, so if
anything functions were now inconsistent. I was kind of tempted to make
a helper for it, but I didn't think of a great structure/name to get
there: `DiagnoseRedef` isn't always called when it's a redefinition, for
example due to `extern` diagnostics, it's hard to combine.

Cleans up `is_defined` calls to rely more on `has_definition_started`,
removing some code paths that are unused since definitions aren't
merged.
2025-01-14 21:13:21 +00:00
Boaz Brickner 5b70a3ea91 Generate AST when importing a cpp file (#4790)
Ignore the AST and support a single Cpp import, for now.
Report cpp compilation errors and warnings.
Part of #4666
2025-01-14 20:45:50 +00:00
Richard Smith f5f6ae214d Fix PR links in two proposals. (#4799)
Remove a leading 0 from another one for consistency with the rest of the
three-digit proposals; the link works either way.
2025-01-14 18:46:35 +00:00
Richard Smith 6bc36b045f Rearrange name poisoning logic to do a little less work. (#4766)
Insert the poison at the same time we do the name lookup to avoid doing
two hash table lookups into each scope. This adds a bit of complication
because import logic now needs to cope with importing a name that is
already poisoned, but the complexity seems worthwhile to reduce the
number of name lookups performed.

This incidentally fixes a bug where we wouldn't poison any name scopes
if we found the name in an enclosing lexical scope, leading to one extra
diagnostic in existing tests.

Part of #4622
2025-01-14 17:34:33 +00:00
Jon Ross-Perkins 9dc450e0af Stop merging invalid impl redefinitions (#4798)
Fixes a crash, see the new regression test in
toolchain/check/testdata/impl/no_prelude/generic_redeclaration.carbon.
Stopping merging seems like the most straightforward way to prevent
references to generic regions with the incorrect block.
2025-01-14 00:58:58 +00:00
Jon Ross-PerkinsandRichard Smith a3e66d6116 Fix short option error (#4796)
"unsigned char" prints as an integer, not a char

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-01-14 00:44:41 +00:00
Jon Ross-Perkins 2faff26f92 Add newline to vlog message (#4797)
Tiny, minor, almost invisible fix
2025-01-14 00:35:52 +00:00
josh11bandJosh L 3a44b65b95 Support importing associated constant declarations (#4794)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-01-13 19:20:28 +00:00
Jon Ross-Perkins 6f6e46ef57 Migrate tree-sitter support to MODULE.bazel (#4783)
The WORKSPACE file is deprecated; support is already off by default, and
it'll be removed in the next major bazel release. Our main dependency is
tree-sitter, and I'm trying to address that here.

We're currently using https://github.com/elliottt/rules_tree_sitter, but
that hasn't been updated in a couple years, meaning it lacks
MODULE.bazel support. In the registry, there's
https://registry.bazel.build/modules/tree-sitter-bazel, but this is only
the *parser* libraries of tree-sitter, not the *generator*. I'm using it
for that much, at least.

For the *generator*, which transforms grammar.js to parser.c/h, I'm just
requiring a non-hermetic invocation (i.e., people who want to work on it
will need to install tree-sitter; see the README.md updates). I tried
running it manually, but parser.c is about 600 KB; pre-commit rejects
files that large and I don't think an exception makes sense to override
for this (it'd probably also grow substantially if the grammar were
updated to cover more syntax). In order to make the non-hermetic call
not break "bazel build //..." for most developers, I'm marking most
targets in the package as manual.

Note, I did look long and hard at using `aspect_rules_js`/`rules_nodejs`
to invoke npm. This took a lot of time, and I have a commit that's
mostly working, except I hit a point where it uses `declare_symlink`
which we disallow for compatibility reasons (commit "Lots of work for
figuring out rule_js uses declare_symlink" on the PR). As a consequence,
I think we can't use the primary supported ways to have hermetic npm
calls.

Also, `treesitter` -> `tree_sitter` because it's generally called
`tree-sitter`, two words. We even had a `treesitter/src/tree_sitter`
directory so it's a bit inconsistent.

As far as bugs here, the parser library breaks bazel queries, e.g. the
error:
```
ERROR: Evaluation of query "somepath(//..., @llvm-project//third-party/unittest:gtest)" failed: preloading transitive closure failed: no such package '@@[unknown repo 'platforms' requested from @@tree-sitter-bazel+]//': The repository '@@[unknown repo 'platforms' requested from @@tree-sitter-bazel+]' could not be resolved: No repository visible as '@platforms' from repository '@@tree-sitter-bazel+'
```

I'm just excluding tree_sitter from queries where I can to work around
the error.
2025-01-13 19:04:10 +00:00
Richard Smith 0d70091bda Fix introduction of class and interface names in local scopes. (#4793)
When declaring a class (or interface), we create a scope that covers the
entire class declaration. If the class was declared in a lexical scope,
we would declare the class name in the innermost scope, which was the
class's own scope instead of the enclosing lexical scope.

Fix this by instead adding the name to the lexical scope at the start of
the class declaration, not the lexical scope created to hold the class.
For now, we reject if the class name would have been shadowed by a name
that has already been declared within its scope, such as a generic
parameter, so we only ever need to modify the end of the list of lexical
lookup results for the class name.

This appears to be sufficient to make local declarations and definitions
of classes and interfaces work properly throughout check, though testing
is pretty minimal so far.
2025-01-13 18:55:26 +00:00
Richard Smith bb6ffc3dbc Rename parameters in int conversions. (#4791)
As requested in review of #4753.
2025-01-13 18:25:43 +00:00
230a8ee598 Support associated constants in impl witnesses (#4770)
With this change, we now support impl of interfaces with non-function
associated constants.

Also:
* Make impl diagnostics use more consistent names
* Make some impl tests "no_prelude"

Still to do:
* Facet type resolution as a separate, reusable step
* Using the assigned values of associated constants (see
`fail_todo_use_assoc_const.carbon`)

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-01-11 01:59:06 +00:00
Richard Smith fb1a9ba20f Use explicit conversion between integer types in examples. (#4792) 2025-01-11 01:46:32 +00:00
Richard Smith b1230218d5 Make fingerprinting stable across compatible source changes. (#4789)
Include the index rather than the name in the fingerprint of a symbolic
binding. While both the index and the name contribute to the canonical
identity, using either one of them in the fingerprint is sufficient to
ensure that distinct entities get different fingerprints. Changing the
name of a symbolic binding should ideally not result in fingerprint
changes, so exclude the name from the fingerprint when we have an index.

Use the canonical type and constraint when fingerprinting an impl, so
that uses of names in `name_ref` instructions aren't considered, only
the entity the name resolves to, and different ways of spelling the same
type have the same fingerprint. This similarly allows compatible changes
to be made to impls without changing the fingerprint.

Exclude the declaration block when determining the fingerprint of a
declaration. The declaration block contains the declarations of
parameters of the declaration, which do affect whether two declarations
are identical, but not whether they denote the same entity, because it
would be invalid to have different declaration blocks for declarations
with the same name in the same scope. Therefore changes to the
declaration block are compatible, and it's useful for such changes to
not affect the fingerprint.

This is not easy to test in isolation with our current testing
machinery. However, a follow-on PR will change the name of a parameter
in the prelude, and with this in place, will not cause any changes to
occur elsewhere in the toolchain tests.
2025-01-10 22:30:22 +00:00
Geoff RomerandJon Ross-Perkins 4f10735751 Track params in the parser (#4777)
This change splits `NodeKind::IdentifierName` into separate node kinds
depending on whether the identifier is followed by parameters, and
similarly splits `NameQualifier` based on whether the qualifier has
parameters. This enables us to only push a pattern block when it's
actually needed, rather than "defensively" pushing one when it might be
needed.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-10 22:11:07 +00:00
Jon Ross-Perkins 8f685b6953 Change how diagnostics are ordered (#4778)
This change deliberately breaks away from the line/column ordering, and
instead focuses on a last byte offset corresponding to the final token
processed as part of producing the message. Where that's equal, this
maintains stable ordering in order to reflect the order that diagnostics
were produced.

The intent of this approach is that lex, parse, and check diagnostics
are interleaved based on where they are produced, but that
subexpressions still have diagnostics emitted prior to containing
expressions. In particular, the prior line/column sort essentially
sorted on the _start_ of where a diagnostic was associated, and this is
closer to sorting based on the _end_. As a consequence, something like
`F(1 2)` will have the error for `1 2` emitted _before_ a diagnostic for
`F(1 2)` not matching parameters, instead of _after_.

In check, we track the last handled node. This provides a
last_byte_offset _separate_ from where a diagnostic is associated. The
intent is that this creates an ordering of diagnostics which may be
associated with earlier code, to cause the diagnostics to be emitted
later. An example consequence of this is the change in ordering of
modifier diagnostics: we are diagnosing those from the same place, but
they have the same last_byte_offset, so we print them out in the order
produced.

I've added similar tracking to parse, but cannot identify any test which
is affected by it (note the separate commit, I thought about this late).
I'm not sure whether we have good out-of-order errors we could produce
for this.

A significant number of tests have reordered diagnostics as a
consequence of this change, so this change does not add further testing.
2025-01-10 18:36:24 +00:00
Jon Ross-Perkins be85a5092d Fill in videos and slides for talks (#4788)
NDC has published Chandler's video now, and I spent a little time
backfilling slides.
2025-01-10 17:59:05 +00:00
Richard Smith d42128ef9a Parse all kinds of declarations at function scope. (#4779)
These don't fully work in check and beyond yet, because they're not
added into lexical lookup, but already mostly do the right thing.

Per #3407, disallow namespace declarations anywhere other than at file
scope for now.

We don't treat statements starting with a packaging introducer keyword
(`package`, `library`, `import`) as declarations because they're
sufficiently unlikely to occur that the error recovery doesn't seem
important, and this avoids needing to disambiguate `package.` at the
start of an expression.
2025-01-10 07:03:10 +00:00
Jon Ross-Perkins 1e5e2bc7e2 Update clang-tidy and compile-commands git commits (#4785)
Just noticed the versions were old while I was updating tcmalloc in
#4784. I've tested and it doesn't seem to introduce issues; the compile
commands may actually work a little better.
2025-01-10 01:28:43 +00:00
Jon Ross-Perkins 81dfb2b29b Remove the libprotobuf_mutator BUILD (#4782)
Missed in #4731, noticed while looking at removing woff2
2025-01-10 01:28:12 +00:00
Jon Ross-Perkins 43e68751c6 Remove woff2 from third_party (#4781)
Bazel's WORKSPACE file is deprecated, and we haven't worked on the woff2
example in ages. Rather than investing time into keeping it around,
remove it and we can revive it when we're ready.
2025-01-10 01:27:40 +00:00
Jon Ross-Perkins 82a346730a Fix clang-tidy issues (#4786)
Both of these I noticed from testing #4785, but they occur at head.

```
(elided)/execroot/_main/common/raw_hashtable.h:532:40: error: do not use nested 'std::max' calls, use an initializer list instead [modernize-min-max-use-initializer-list,-warnings-as-errors]
  532 |   static constexpr ssize_t Alignment = std::max<ssize_t>(
      |                                        ^
  533 |       {alignof(MetadataGroup), alignof(StorageEntry<KeyT, ValueT>)});
      |        ~~~~~~~~~~~~~~~~~~~~~~  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |        static_cast<long>(alignof(MetadataGroup)) static_cast<long>(alignof(StorageEntry<KeyT, ValueT>))

(elided)/execroot/_main/toolchain/install/busybox_info_test.cpp:259:8: error: unused local variable 'usr_prefix' of type 'std::filesystem::path' [bugprone-unused-local-non-trivial-variable,-warnings-as-errors]
  259 |   auto usr_prefix = MakeInstallTree(dir_ / "usr");
      |        ^
(elided)/execroot/_main/toolchain/install/busybox_info_test.cpp:260:8: error: unused local variable 'usr_local_prefix' of type 'std::filesystem::path' [bugprone-unused-local-non-trivial-variable,-warnings-as-errors]
  260 |   auto usr_local_prefix = MakeInstallTree(dir_ / "usr/local");
      |        ^
```

The std::max diagnostic seems a little confused, but the initializer
list seems like it can be dropped without any loss. The unused locals
diagnostic is correct.

Neither of these seem like they should be newer than my last clang-tidy
pass, maybe I just missed them in other sweeps.
2025-01-10 00:22:04 +00:00
Jon Ross-Perkins 670de353c7 Remove clangd Function.h include, fix Protocol.h location (#4787)
The Function.h include was simply unused, I was partly dropping the bits
that would've depended on it. Protocol.h is used, but it should really
be included from handle.h.
2025-01-09 22:59:27 +00:00
Richard Smith d31fc9ad02 Support array types with dependent bounds. (#4751)
Given `N:! i32`, the type `[T; N]` is a valid but dependent array type.
2025-01-09 22:46:22 +00:00
Jon Ross-Perkins 3a6fd0306e Get the tcmalloc build fix (#4784)
I fixed the build issue in
https://github.com/google/tcmalloc/commit/b6563dbdc7905f7b0b31c97256c83e7c9b2f08c2
2025-01-09 21:48:47 +00:00
Dana Jansens 21998f6a65 Allow Worklist construction with an initial InstBlockId (#4776)
This makes InstFingerprinter::GetOrCompute for InstId and InstBlockId
more similar, in that they just construct a Worklist and call Run.
    
The Worklist::Run method differentiates if the next todo item is an
InstBlockId and in that case it adds everything in the block to its
todo list and continues processing.
    
We only use the fingerprint of an InstBlockId if its at the bottom of
the todo stack, which is the case when it's placed there initially by
InstFingerprinter::GetOrCompute. We could cache it but we currently
do not. If we did, we could also cache other InstBlockIds found
inside instructions, but at the moment we skip through them and
add their instructions rather than adding the InstBlockId to the
todo stack.
2025-01-09 15:40:10 +00:00
Richard Smith 9a5f2d734b Include a fingerprint of the specific arguments in mangled names. (#4771)
Instead of including the raw index of the specific, which is unstable
across files and across unrelated changes, use a fingerprint of the
constant values of the specific arguments. This is a placeholder until
we decide on how we want to mangle specific functions.
2025-01-08 20:23:12 +00:00
Dana Jansens ab12da7d03 Rename BoundMethod::function_id to function_decl_id (#4775)
The InstId in this field is to an instruction that declares the
function, rather than the function itself, so that diagnostics can print
where the function is coming from. The type of the function (the
FunctionType instruction) is the type (the type_id) of the
function_decl_id. So we rename the field to help make this distinction
more clear.

Followup to #4739
2025-01-08 19:08:56 +00:00
Boaz Brickner 7d92aa7bbf Add a test that shows names are not poisoned when lookup fails (#4774)
#4622
2025-01-08 16:59:26 +00:00
Chandler Carruth f52ae6afa7 Fix clang-tidy to run on the merge queue (#4773)
Without this, the merge queue blocks on results but they never get
triggered and show up. This will need to merge before we re-enable
`clang-tidy` enforcement on the trunk branch.
2025-01-08 16:44:53 +00:00
Dana JansensandJon Ross-Perkins bf5c891540 Explain BoundMethod and function_id a bit more (#4739)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-08 08:37:50 +00:00
Richard Smith f6d0cdabf8 Slightly simplify int value lowering. (#4767)
Refactor to use the new `GetAtWidth` function.
2025-01-08 08:37:50 +00:00
Boaz Brickner 74395ce693 Change name poisoning implementation to allow better diagnostics (#4764)
Change the implementation to use an explicit `is_poisoned` bit instead
of `InstId::PoisonedName` value.
Zero behavior change.
This would allow to more easily change the API to support accessing the
poisoning declaration so we can have better name poisoning diagnosis.
#4622
2025-01-08 08:36:14 +00:00
Richard Smith 246ec785df Add support for converting between integer types (#4753)
Add a builtin `"int.convert"` supporting unchecked conversions between
different integer types. This performs a truncation, zero-extension, or
sign-extension, depending on the widths of the operands and the
signedness of the source type. Add explicit `As` support to the prelude.
No implicit conversions are supported yet as we don't have a way to
express the constraint that we can only implicitly convert to wider
types.
2025-01-08 08:25:20 +00:00
Jon Ross-Perkins 96d836f965 Refactor the language server structure. (#4721)
I'm trying to make the LSP look more like the rest of the toolchain. I'm
trying to separate the handlers from the transport layer, and remove the
multiple inheritance aspect. Also fixing some style issues, switching to
`Map`, and removing an unnecessary copt.

I'm using `Context` for the central object for consistency with other
portions of the toolchain. In order to get the `handle_*` files working,
I'm using LLVM's registry class. It has a quirk that I can't register
two registries in the same cpp file, so there are two one-line cpp
files.

In order to help show the delta (or lack thereof) for actual
implementation, I've copied server.cpp over handle_* and undone that in
two commits. See the third and fourth commits on the PR history for
that.
2025-01-08 06:01:51 +00:00
Jon Ross-Perkins aaef516600 Fix job name for clang tidy (#4760)
I think this will affect the name GH shows in some action UIs; this will
more clearly disambiguate from tests.yaml actions.
2025-01-08 00:08:41 +00:00
ottmar-zittlau 7ed3b986b9 Fix unchecked optional access in compile subcommand (#4756)
Hi,

I fixed a small issue that I found inside the "compile subcommand"
component:
The program can be crashed by running ```bazel run -- toolchain:carbon
compile --dump-mem-usage "non-existing-file.carbon"``` - i.e. by
activating the memory usage dump flag and passing a non-existing file.

Best regards,
oz
2025-01-08 00:04:16 +00:00
Richard Smith 13c121c56c Address clang-tidy findings from #4763. (#4768) 2025-01-07 23:33:44 +00:00
josh11bandJosh L 1d379ff7f8 Syntactic impl declaration matching updates (#4762)
* Implement ignoring the difference between `Self as` and `as`, as well
as `where` clauses at the end of an `impl` declaration when checking
whether `impl` declarations match, from #3763.
* Allow impl declarations with different constraint ids to match, as
long as the facet type of the constraint has the same interface_id and
specific_id.
* Add some TODOs reflecting future facet type resolution.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-01-07 23:31:31 +00:00
Jon Ross-Perkins 8cac0c398a Enable as many bazel incompatible flags as possible. (#4761)
Uses bazel 8 flags since there's the update in #4729. bazelisk was used
to generate the list of flags (see bazelrc comment). The overall
approach is trying to do our best to follow
https://bazel.build/release/backward-compatibility, in particular since
`--incompatible_strict_action_env` had come up (essentially just
adopting as much as we can now).

The default visibility changes in `carbon_rules/BUILD` and
`cc_toolchains/BUILD` files are for
`--incompatible_config_setting_private_default_visibility`. That's
enough for fastbuild, but we use tcmalloc in opt, and it has an issue.

In `clang_toolchain.BUILD` it's for
`--incompatible_check_visibility_for_toolchains`, even though
`rules_shell` then breaks on it. `manifest/defs.bzl` changes are for
`--incompatible_disable_target_default_provider_fields` which
`rules_pkg` breaks on. Even though these flags are off, I'm keeping the
changes since we should eventually enable the flags.

I'm still looking at the tree sitter rules due to the WORKSPACE issue,
but I think that needs more substantial work.
2025-01-07 22:10:42 +00:00
Richard SmithandDana Jansens 19182f08aa Compute a fingerprint for constants and import_ref instructions. (#4763)
Use it in the instruction namer to make instruction names more stable
across unrelated changes to the toolchain or the prelude.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-01-07 20:41:44 +00:00
Jon Ross-Perkins 05b272703e Add danakj to autoassign (#4765)
I'm glad to see you're grabbing PRs to review. Have some automagically.
:-P
2025-01-07 20:15:18 +00:00
Richard SmithandJon Ross-Perkins d2d5c5520b Solutions for advent of code, day 4 - 13. (#4750)
A collection of additional Carbon examples demonstrating current
language capabilities and some limitations of the current state of the
toolchain.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-07 19:42:40 +00:00
Geoff Romer 9b28d3ad78 Late response to comments on #4698 (#4758) 2025-01-07 17:44:34 +00:00
josh11bandJosh L fa9a07b6cc Add Make...Id functions for debugging (#4759)
In practice, I am unable to call constructors like `SemIR::InstId` from
a debugger. I first tried to use
https://clang.llvm.org/docs/AttributeReference.html#noinline to make
some non-inline calls to the constructor, but that didn't work:

```
toolchain/sem_ir/dump.cpp:245:23: error: 'noinline' attribute is ignored because there exists no call expression inside the statement [-Werror,-Wignored-attributes]
  245 |   [[clang::noinline]] return InstId(inst);
      |          
```

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-01-07 01:10:21 +00:00
Jon Ross-Perkins ccf51cef23 Update to bazel 8.0.0 (#4729)
This updates to bazel 8.0.0, also updating bazel mod deps and tools to
make that function. The release is a couple weeks old, and we haven't
updated in a while, and it's a major release. Note it includes some
incompatible flag flips that this is trying to update with respect to.
I'll try generally enabling incompatible support separately.

The most visible bazel behavior change here will be the change from `~`
to `+` in repo path names. (If you're curious,
https://github.com/bazelbuild/bazel/issues/23127 indicates this fixes a
Windows performance issue)

Note that this is building on top of both the action env update in #4728
(which got me started down this path) and the proto removal in #4731
(which would add significant work to this update). Only the commit
starting at "Work towards bazel 8.0.0" is specifically part of this PR.
2025-01-06 23:50:12 +00:00
Jon Ross-Perkins bc637bdd7a Fix redundant void return (#4757)
Caught by more recent tidy versions:
https://clang.llvm.org/extra/clang-tidy/checks/readability/redundant-control-flow.html
2025-01-06 19:32:15 +00:00
josh11bandJosh L 7edb0b8f59 Add more Dump methods for debugging (#4747)
Follow-on to #4669 . Did some manual testing, but may have not exercised
all code paths.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-01-06 17:26:28 +00:00
Dana JansensandRichard Smith c59ceb1f7b Support builtin conversions of adapter classes (#4655)
When creating a tuple or struct type object/value, we will walk each of
the tuple's or struct's parts, respectively, and Convert() each of them.
This allows (T, T) to convert to (U, U) and so forth. It also performs
the conversion from value to initialization even for the same types,
such as converting from a value of (T, T) to an object of (T, T).

Classes need to define their own conversions but when the target and
source types are the same, there is no conversion of types taking place.
If the class adapts a tuple or struct then walk each of the tuple's or
struct's parts, respectively, and Convert() each of them in order to
initialize the parts of the target.

For copyable types, the conversion implies a copy in the initialization,
and for non-copyable types, an error is emitted.

This supports copying a class value to a class object when it is an
adapter of a tuple or struct.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-01-06 16:23:32 +00:00
Boaz Brickner 72e594dfd0 Do not try to recover from using impl outside class error (#4755)
This prevents crashing when the wrongly used `impl` uses a poisoned
name.
#4622
2025-01-03 20:20:35 +00:00
Boaz Brickner fa9d838270 Fix CC1Main setting trigger undefined behavior (#4714)
This is caused by setting a temporary lambda to a `llvm::function_ref`.
The fix is to assign the lambda into a variable that outlives the
`llvm::function_ref`.
2025-01-03 11:34:28 +00:00
725e80f0d3 Fix a bug importing declarations in generics (#4752)
Imported declarations that are contained within a generic, such as an
`impl forall...` would be given an abstract symbolic constant value
instead of a concrete generic value in some cases where the function was
used in an api file and impl file of the same library. This caused #4679
to fail using `ImplicitAs.Convert` transitively imported from the
prelude.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-01-02 23:56:43 +00:00
c5fd8f42b8 ImplWitness (#4679)
* Change `InterfaceWitness` -> `ImplWitness`
* Include a `SpecificId` in the `ImplWitness`. This allows the
`InstBlock` it contains to have its own identity, allowing it to be
changed as the impl is processed. Evaluation only updates the specific.
* Create the `ImplWitness` at the start of the impl definition. In the
future, this will be populated with the values of non-function
associated constants. For now, it starts full of invalid instruction
ids.
* Implements the model suggested in #4672 .

Note that the non-SemIR testdata changes are to these file:
* `toolchain/check/testdata/impl/lookup/fail_todo_undefined_impl.carbon`
* `toolchain/check/testdata/struct/import.carbon`
* `toolchain/check/testdata/tuple/import.carbon`

The last two are due to an import of generics bug exposed by this PR,
which will be fixed in a follow-on.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-01-02 23:03:11 +00:00
Richard Smith 4a7aefefaa Add support for operators on Core.IntLiteral. (#4716)
Fixes integer builtins to produce the correct values (and not
CHECK-fail) when used on integer literals. Also adds impls to the
prelude to use the new builtins to perform operations on integer
literals.

Perhaps most importantly, this allows directly initializing `i32` values
with negative numbers, as the negation operation on integer literals now
works.

For testing I've added tests for use of literals with one operator in
each class (addition, multiplication, ordering, bitwise, etc) for which
there are distinct rules or overflow behavior, rather than exhaustively
testing all the combinations. This is aimed at finding a good tradeoff
between maintainability of the tests and thorough test coverage.

Also fixes lowering of heterogeneous shifts and comparisons. These are
currently disabled when one of the operands is an integer literal, but
we may want to allow that when the integer literal operand has a known
constant value.
2024-12-31 06:36:43 +00:00
624950c62c Store hash in the probed_indices array in common/raw_hashtable.h to avoid its recomputation. (#4726)
Store hash in probed_indices array to avoid its recomputation.

Benchmarks on ARM (altra, aarch64).
```
name                                                  old CYCLES/op        new CYCLES/op        delta
BM_MapInsertSeq<Map<int, int>>/1                         119 ± 2%             119 ± 1%     ~     (p=0.961 n=55+54)
BM_MapInsertSeq<Map<int, int>>/2                         133 ± 1%             134 ± 1%     ~     (p=0.342 n=56+57)
BM_MapInsertSeq<Map<int, int>>/3                         150 ± 1%             150 ± 1%     ~     (p=0.856 n=56+57)
BM_MapInsertSeq<Map<int, int>>/4                         167 ± 2%             167 ± 2%     ~     (p=0.430 n=56+57)
BM_MapInsertSeq<Map<int, int>>/8                         234 ± 5%             234 ± 3%     ~     (p=0.957 n=57+57)
BM_MapInsertSeq<Map<int, int>>/16                        368 ± 4%             368 ± 4%     ~     (p=0.762 n=57+57)
BM_MapInsertSeq<Map<int, int>>/32                        650 ± 4%             650 ± 4%     ~     (p=0.955 n=57+57)
BM_MapInsertSeq<Map<int, int>>/64                      1.93k ± 4%           1.98k ± 4%   +2.35%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/256                     9.68k ± 5%           9.85k ± 3%   +1.74%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/4096                     177k ± 3%            163k ± 2%   -8.17%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/65536                   3.99M ± 3%           3.87M ± 4%   -3.12%  (p=0.000 n=56+56)
BM_MapInsertSeq<Map<int, int>>/1048576                 90.5M ± 5%           91.3M ± 6%   +0.87%  (p=0.025 n=55+55)
BM_MapInsertSeq<Map<int, int>>/16777216                2.77G ± 8%           2.74G ± 9%     ~     (p=0.076 n=57+57)
BM_MapInsertSeq<Map<int, int>>/56                      1.05k ± 5%           1.05k ± 5%     ~     (p=0.727 n=57+57)
BM_MapInsertSeq<Map<int, int>>/224                     6.29k ± 5%           6.37k ± 4%   +1.32%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/3584                     124k ± 4%            109k ± 3%  -12.46%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/57344                   2.67M ± 4%           2.50M ± 4%   -6.40%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/917504                  65.3M ± 6%           65.8M ± 6%   +0.89%  (p=0.050 n=55+56)
BM_MapInsertSeq<Map<int, int>>/14680064                2.17G ±10%           2.14G ± 9%   -1.55%  (p=0.032 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/1                       122 ± 1%             122 ± 1%     ~     (p=0.415 n=56+56)
BM_MapInsertSeq<Map<int*, int*>>/2                       136 ± 1%             136 ± 1%     ~     (p=0.861 n=56+57)
BM_MapInsertSeq<Map<int*, int*>>/3                       153 ± 1%             153 ± 1%     ~     (p=0.607 n=56+57)
BM_MapInsertSeq<Map<int*, int*>>/4                       170 ± 2%             174 ± 3%   +2.34%  (p=0.001 n=56+57)
BM_MapInsertSeq<Map<int*, int*>>/8                       238 ± 4%             242 ± 3%   +1.59%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/16                      382 ± 4%             383 ± 4%     ~     (p=0.977 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/32                      701 ± 7%             682 ± 5%   -2.69%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/64                    2.13k ± 6%           2.09k ± 3%   -1.89%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/256                   10.3k ± 3%           10.2k ± 3%   -0.94%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/4096                   184k ± 2%            179k ± 2%   -2.62%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/65536                 3.63M ± 2%           3.68M ± 3%   +1.22%  (p=0.000 n=54+57)
BM_MapInsertSeq<Map<int*, int*>>/1048576                129M ±10%            129M ±10%     ~     (p=0.874 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/16777216              3.27G ±11%           3.24G ±10%     ~     (p=0.451 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/56                    1.18k ± 9%           1.10k ± 5%   -6.52%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/224                   6.76k ± 5%           6.59k ± 4%   -2.55%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/3584                   117k ± 2%            115k ± 3%   -1.93%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/57344                 2.22M ± 3%           2.24M ± 2%   +0.87%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/917504                95.0M ± 8%           94.8M ± 9%     ~     (p=0.894 n=55+57)
BM_MapInsertSeq<Map<int*, int*>>/14680064              2.42G ±14%           2.40G ±13%     ~     (p=0.852 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/1             124 ± 1%             124 ± 1%     ~     (p=0.604 n=56+55)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/2             140 ± 1%             140 ± 1%     ~     (p=0.181 n=56+56)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/3             158 ± 1%             158 ± 3%     ~     (p=1.000 n=56+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/4             176 ± 2%             176 ± 3%     ~     (p=0.125 n=56+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/8             247 ± 4%             247 ± 2%     ~     (p=0.614 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/16            391 ± 3%             391 ± 2%     ~     (p=0.993 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/32            690 ± 3%             691 ± 3%     ~     (p=0.224 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/64          2.17k ± 3%           2.22k ± 3%   +1.94%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/256         11.1k ± 3%           11.3k ± 3%   +1.58%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/4096         204k ± 2%            193k ± 2%   -5.65%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/65536       5.19M ± 3%           5.09M ± 3%   -2.05%  (p=0.000 n=56+56)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/1048576      124M ±10%            123M ± 6%     ~     (p=0.626 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/16777216    3.30G ± 9%           3.25G ± 8%   -1.39%  (p=0.019 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/56          1.12k ± 3%           1.12k ± 3%     ~     (p=0.482 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/224         7.04k ± 4%           7.14k ± 3%   +1.36%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/3584         138k ± 2%            126k ± 2%   -8.89%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/57344       3.48M ± 4%           3.34M ± 4%   -3.93%  (p=0.000 n=56+56)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/917504      84.4M ± 7%           84.9M ± 6%     ~     (p=0.159 n=56+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/14680064    2.42G ± 9%           2.40G ±10%     ~     (p=0.300 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/1             168 ± 0%             168 ± 0%     ~     (p=0.555 n=56+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/2             208 ± 0%             208 ± 0%     ~     (p=0.722 n=52+53)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/3             248 ± 0%             248 ± 0%     ~     (p=0.248 n=53+54)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/4             288 ± 0%             288 ± 0%     ~     (p=0.185 n=54+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/8             457 ± 0%             457 ± 0%     ~     (p=0.665 n=53+53)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/16            867 ± 1%             867 ± 1%     ~     (p=0.174 n=47+52)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/32          1.61k ± 3%           1.62k ± 4%     ~     (p=0.402 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/64          4.96k ± 9%           4.89k ± 5%   -1.37%  (p=0.046 n=57+54)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/256         26.9k ± 8%           26.5k ± 8%   -1.51%  (p=0.004 n=56+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/4096         600k ± 3%            588k ± 2%   -2.07%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/65536       13.9M ± 3%           13.5M ± 2%   -2.99%  (p=0.000 n=55+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/1048576      407M ± 7%            393M ± 5%   -3.27%  (p=0.000 n=56+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/16777216    10.2G ± 8%            9.9G ± 5%   -3.50%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/56          2.81k ± 5%           2.81k ± 4%     ~     (p=0.809 n=56+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/224         17.9k ± 6%           17.6k ± 5%   -1.20%  (p=0.035 n=57+52)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/3584         374k ± 3%            367k ± 3%   -1.80%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/57344       8.64M ± 3%           8.53M ± 2%   -1.29%  (p=0.000 n=55+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/917504       247M ± 6%            244M ± 5%   -1.19%  (p=0.021 n=56+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/14680064    6.81G ± 8%           6.64G ± 6%   -2.46%  (p=0.000 n=57+57)
```

Benchmarks on x86
```
name                                                  old cpu/op   new cpu/op   delta
BM_MapInsertSeq<Map<int, int>>/1                      32.9ns ± 3%  32.6ns ± 3%   -0.84%  (p=0.027 n=54+51)
BM_MapInsertSeq<Map<int, int>>/2                      35.9ns ± 3%  35.7ns ± 4%     ~     (p=0.123 n=54+54)
BM_MapInsertSeq<Map<int, int>>/3                      39.7ns ± 3%  47.4ns ± 4%  +19.40%  (p=0.000 n=55+56)
BM_MapInsertSeq<Map<int, int>>/4                      52.7ns ± 3%  52.1ns ± 4%   -1.22%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/8                      78.1ns ± 3%  78.3ns ± 3%     ~     (p=0.141 n=50+57)
BM_MapInsertSeq<Map<int, int>>/16                      135ns ± 3%   135ns ± 4%     ~     (p=0.936 n=53+57)
BM_MapInsertSeq<Map<int, int>>/32                      249ns ± 3%   241ns ± 3%   -3.28%  (p=0.000 n=55+57)
BM_MapInsertSeq<Map<int, int>>/64                      631ns ± 3%   618ns ± 3%   -2.21%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/256                    2.62µs ± 3%  2.36µs ± 4%  -10.02%  (p=0.000 n=52+53)
BM_MapInsertSeq<Map<int, int>>/4096                   39.2µs ± 3%  37.9µs ± 4%   -3.40%  (p=0.000 n=57+56)
BM_MapInsertSeq<Map<int, int>>/65536                   972µs ± 3%   955µs ± 3%   -1.76%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/1048576                16.2ms ± 4%  16.3ms ± 5%     ~     (p=0.231 n=52+54)
BM_MapInsertSeq<Map<int, int>>/16777216                651ms ± 3%   648ms ± 2%   -0.42%  (p=0.048 n=57+56)
BM_MapInsertSeq<Map<int, int>>/56                      418ns ± 3%   401ns ± 3%   -4.10%  (p=0.000 n=54+57)
BM_MapInsertSeq<Map<int, int>>/224                    1.79µs ± 3%  1.61µs ± 3%  -10.20%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, int>>/3584                   26.0µs ± 3%  24.9µs ± 4%   -4.13%  (p=0.000 n=57+56)
BM_MapInsertSeq<Map<int, int>>/57344                   560µs ± 3%   549µs ± 3%   -2.11%  (p=0.000 n=56+57)
BM_MapInsertSeq<Map<int, int>>/917504                 10.4ms ± 3%  10.4ms ± 3%     ~     (p=0.805 n=56+56)
BM_MapInsertSeq<Map<int, int>>/14680064                422ms ± 2%   421ms ± 3%     ~     (p=0.269 n=57+56)
BM_MapInsertSeq<Map<int*, int*>>/1                    33.7ns ± 3%  33.7ns ± 3%     ~     (p=0.620 n=55+55)
BM_MapInsertSeq<Map<int*, int*>>/2                    36.7ns ± 3%  36.5ns ± 3%     ~     (p=0.160 n=55+56)
BM_MapInsertSeq<Map<int*, int*>>/3                    41.1ns ± 2%  41.0ns ± 4%     ~     (p=0.284 n=54+56)
BM_MapInsertSeq<Map<int*, int*>>/4                    45.0ns ± 3%  53.9ns ± 4%  +19.70%  (p=0.000 n=57+56)
BM_MapInsertSeq<Map<int*, int*>>/8                    77.1ns ± 3%  80.9ns ± 4%   +4.98%  (p=0.000 n=55+57)
BM_MapInsertSeq<Map<int*, int*>>/16                    130ns ± 3%   136ns ± 4%   +4.42%  (p=0.000 n=56+57)
BM_MapInsertSeq<Map<int*, int*>>/32                    244ns ± 3%   246ns ± 4%   +0.95%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/64                    620ns ± 3%   674ns ± 3%   +8.83%  (p=0.000 n=55+57)
BM_MapInsertSeq<Map<int*, int*>>/256                  2.93µs ± 3%  2.88µs ± 3%   -1.73%  (p=0.000 n=56+56)
BM_MapInsertSeq<Map<int*, int*>>/4096                 54.0µs ± 3%  50.8µs ± 4%   -6.01%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/65536                1.18ms ± 2%  1.17ms ± 4%     ~     (p=0.083 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/1048576              28.9ms ± 4%  29.1ms ± 5%   +0.91%  (p=0.007 n=55+56)
BM_MapInsertSeq<Map<int*, int*>>/16777216              914ms ± 2%   919ms ± 3%   +0.56%  (p=0.015 n=56+57)
BM_MapInsertSeq<Map<int*, int*>>/56                    404ns ± 3%   427ns ± 4%   +5.60%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/224                  1.88µs ± 3%  1.87µs ± 4%   -0.68%  (p=0.013 n=55+53)
BM_MapInsertSeq<Map<int*, int*>>/3584                 34.2µs ± 3%  32.9µs ± 4%   -4.02%  (p=0.000 n=56+57)
BM_MapInsertSeq<Map<int*, int*>>/57344                 768µs ± 3%   756µs ± 3%   -1.53%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int*, int*>>/917504               16.4ms ± 5%  16.5ms ± 7%     ~     (p=0.303 n=56+57)
BM_MapInsertSeq<Map<int*, int*>>/14680064              607ms ± 2%   613ms ± 3%   +0.92%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/1          34.1ns ± 3%  34.2ns ± 4%     ~     (p=0.288 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/2          37.4ns ± 3%  37.5ns ± 3%     ~     (p=0.316 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/3          41.8ns ± 4%  49.1ns ± 3%  +17.45%  (p=0.000 n=57+56)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/4          54.6ns ± 3%  53.9ns ± 5%   -1.35%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/8          81.4ns ± 3%  81.4ns ± 4%     ~     (p=0.956 n=56+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/16          139ns ± 3%   139ns ± 3%     ~     (p=0.754 n=57+56)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/32          256ns ± 3%   250ns ± 4%   -2.32%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/64          705ns ± 4%   687ns ± 3%   -2.56%  (p=0.000 n=53+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/256        2.95µs ± 5%  3.05µs ± 3%   +3.42%  (p=0.000 n=52+55)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/4096       49.6µs ± 3%  50.8µs ± 4%   +2.44%  (p=0.000 n=55+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/65536      1.39ms ± 3%  1.40ms ± 3%   +0.65%  (p=0.004 n=57+56)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/1048576    37.7ms ± 4%  38.1ms ± 4%   +1.07%  (p=0.001 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/16777216    1.20s ± 3%   1.20s ± 3%   +0.50%  (p=0.040 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/56          432ns ± 3%   414ns ± 3%   -3.99%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/224        1.92µs ± 4%  1.89µs ± 4%   -1.48%  (p=0.000 n=52+55)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/3584       31.5µs ± 4%  32.1µs ± 4%   +1.89%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/57344       757µs ± 3%   748µs ± 3%   -1.28%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/917504     21.9ms ± 4%  22.1ms ± 5%     ~     (p=0.096 n=57+57)
BM_MapInsertSeq<Map<int, llvm::StringRef>>/14680064    735ms ± 3%   737ms ± 3%     ~     (p=0.208 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/1          41.5ns ± 3%  41.4ns ± 4%     ~     (p=0.790 n=54+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/2          50.6ns ± 4%  50.6ns ± 5%     ~     (p=0.684 n=53+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/3          59.7ns ± 4%  59.4ns ± 4%     ~     (p=0.277 n=55+53)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/4          68.5ns ± 5%  68.2ns ± 5%     ~     (p=0.623 n=54+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/8           107ns ± 5%   107ns ± 9%     ~     (p=0.359 n=54+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/16          200ns ± 6%   200ns ± 6%     ~     (p=0.772 n=56+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/32          373ns ± 8%   371ns ± 7%     ~     (p=0.541 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/64         1.11µs ± 9%  1.09µs ± 8%   -2.09%  (p=0.003 n=56+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/256        5.61µs ± 5%  5.48µs ± 7%   -2.42%  (p=0.000 n=54+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/4096        153µs ± 4%   147µs ± 6%   -3.80%  (p=0.000 n=54+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/65536      3.24ms ± 3%  3.10ms ± 3%   -4.19%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/1048576     100ms ± 2%    98ms ± 3%   -1.97%  (p=0.000 n=56+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/16777216    2.45s ± 2%   2.40s ± 3%   -2.09%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/56          637ns ± 8%   630ns ± 8%     ~     (p=0.101 n=56+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/224        3.77µs ± 6%  3.68µs ± 6%   -2.42%  (p=0.000 n=56+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/3584       92.1µs ± 7%  88.4µs ± 6%   -4.04%  (p=0.000 n=57+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/57344      1.99ms ± 4%  1.92ms ± 3%   -3.47%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/917504     62.1ms ± 4%  60.9ms ± 3%   -1.93%  (p=0.000 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/14680064    1.53s ± 3%   1.50s ± 3%   -1.85%  (p=0.000 n=57+57)
```

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-12-31 05:44:37 +00:00
Vitaly Goldshteyn 384e1cbb92 Update Read*To* to improve operation dependency graph. (#4746)
Benchmarks for StringRef key seem slightly positive.

```
name                                                               old CYCLES/op        new CYCLES/op        delta
BM_MapContainsHit<Map<llvm::StringRef, int>>/1/256                   24.2 ± 0%            23.9 ± 0%  -1.14%        (p=0.000 n=54+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/2/256                   24.2 ± 0%            23.9 ± 0%  -1.15%        (p=0.000 n=53+54)
BM_MapContainsHit<Map<llvm::StringRef, int>>/3/256                   24.2 ± 0%            23.9 ± 0%  -1.15%        (p=0.000 n=53+54)
BM_MapContainsHit<Map<llvm::StringRef, int>>/4/256                   24.2 ± 0%            23.9 ± 0%  -1.14%        (p=0.000 n=56+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/8/256                   25.4 ± 3%            26.3 ± 4%  +3.61%        (p=0.000 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/16/256                  29.1 ± 2%            29.0 ± 2%  -0.28%        (p=0.030 n=56+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/32/256                  29.2 ± 2%            29.0 ± 1%  -0.59%        (p=0.000 n=57+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/64/256                  30.1 ± 2%            30.0 ± 2%  -0.43%        (p=0.045 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/256/256                 30.5 ± 1%            30.3 ± 1%  -0.56%        (p=0.000 n=56+56)
BM_MapContainsHit<Map<llvm::StringRef, int>>/256/64                  29.2 ± 1%            29.2 ± 2%    ~           (p=0.513 n=55+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/256/128                 29.6 ± 1%            29.5 ± 1%  -0.34%        (p=0.002 n=55+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/4096/256                32.0 ± 2%            31.9 ± 2%    ~           (p=0.082 n=55+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/4096/1024               37.8 ± 2%            37.8 ± 1%    ~           (p=0.751 n=57+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/4096/2048               45.3 ± 2%            45.5 ± 2%  +0.46%        (p=0.001 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/65536/256               34.3 ± 2%            34.2 ± 2%  -0.46%        (p=0.000 n=57+56)
BM_MapContainsHit<Map<llvm::StringRef, int>>/65536/16384             72.4 ± 3%            72.3 ± 2%    ~           (p=0.458 n=54+50)
BM_MapContainsHit<Map<llvm::StringRef, int>>/65536/32768             77.7 ± 3%            77.6 ± 3%    ~           (p=0.774 n=56+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/1048576/256             34.9 ± 1%            34.8 ± 2%    ~           (p=0.051 n=56+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/1048576/262144           115 ± 5%             115 ± 5%    ~           (p=0.660 n=57+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/1048576/524288           145 ± 4%             145 ± 5%    ~           (p=0.917 n=57+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/16777216/256            36.5 ± 2%            36.5 ± 2%    ~           (p=0.250 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/16777216/4194304         288 ± 3%             287 ± 4%    ~           (p=0.058 n=56+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/16777216/8388608         303 ± 2%             302 ± 3%  -0.47%        (p=0.044 n=53+54)
BM_MapContainsHit<Map<llvm::StringRef, int>>/56/256                  29.1 ± 3%            29.0 ± 3%    ~           (p=0.147 n=56+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/224/256                 30.7 ± 2%            30.6 ± 2%    ~           (p=0.140 n=56+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/3584/256                31.4 ± 1%            31.3 ± 1%  -0.42%        (p=0.003 n=53+54)
BM_MapContainsHit<Map<llvm::StringRef, int>>/3584/896                35.8 ± 2%            36.0 ± 2%  +0.58%        (p=0.000 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/3584/1792               43.5 ± 1%            43.6 ± 2%  +0.21%        (p=0.032 n=51+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/57344/256               34.3 ± 2%            34.1 ± 1%  -0.43%        (p=0.003 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/57344/14336             67.1 ± 2%            66.8 ± 2%    ~           (p=0.057 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/57344/28672             72.8 ± 3%            72.5 ± 3%  -0.45%        (p=0.032 n=57+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/917504/256              34.7 ± 2%            34.6 ± 2%    ~           (p=0.065 n=56+57)
BM_MapContainsHit<Map<llvm::StringRef, int>>/917504/229376            104 ± 4%             104 ± 5%    ~           (p=0.853 n=55+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/917504/458752            114 ± 6%             114 ± 5%    ~           (p=0.643 n=56+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/14680064/256            36.4 ± 2%            36.2 ± 2%  -0.58%        (p=0.001 n=56+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/14680064/3670016         271 ± 2%             271 ± 4%    ~           (p=0.632 n=55+55)
BM_MapContainsHit<Map<llvm::StringRef, int>>/14680064/7340032         285 ± 3%             285 ± 3%    ~           (p=0.658 n=57+55)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/1                      19.3 ± 1%            19.3 ± 2%    ~           (p=0.201 n=55+57)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/2                      19.4 ± 1%            19.3 ± 1%    ~           (p=0.191 n=56+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/3                      19.4 ± 1%            19.4 ± 2%    ~           (p=0.422 n=55+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/4                      19.4 ± 1%            19.4 ± 1%    ~           (p=0.179 n=56+57)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/8                      19.5 ± 2%            19.5 ± 1%    ~           (p=0.148 n=54+57)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/16                     19.7 ± 2%            19.6 ± 2%    ~           (p=0.204 n=54+57)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/32                     20.0 ± 3%            20.0 ± 3%    ~           (p=0.917 n=56+54)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/64                     19.8 ± 3%            19.8 ± 3%    ~           (p=0.245 n=57+54)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/256                    20.1 ± 3%            20.1 ± 3%    ~           (p=0.307 n=57+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/4096                   20.1 ± 3%            20.2 ± 2%    ~           (p=0.070 n=57+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/65536                  20.5 ± 3%            20.5 ± 3%    ~           (p=0.174 n=56+57)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/1048576                20.9 ± 2%            20.8 ± 3%    ~           (p=0.476 n=53+55)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/16777216               22.2 ± 4%            22.2 ± 3%    ~           (p=0.807 n=57+57)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/56                     24.9 ±28%            23.9 ±16%    ~           (p=0.058 n=57+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/224                    27.1 ±19%            26.6 ±19%    ~           (p=0.122 n=57+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/3584                   28.9 ±10%            28.7 ±10%    ~           (p=0.405 n=56+57)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/57344                  30.5 ± 7%            31.2 ± 7%  +2.32%        (p=0.000 n=57+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/917504                 31.8 ± 7%            31.7 ± 7%    ~           (p=0.713 n=57+56)
BM_MapContainsMiss<Map<llvm::StringRef, int>>/14680064               33.4 ± 9%            33.5 ± 7%    ~           (p=0.921 n=56+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/1/256                     49.3 ± 0%            48.2 ± 0%  -2.17%        (p=0.000 n=55+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/2/256                     49.3 ± 0%            48.2 ± 0%  -2.17%        (p=0.000 n=56+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/3/256                     49.3 ± 0%            48.2 ± 0%  -2.17%        (p=0.000 n=54+55)
BM_MapLookupHit<Map<llvm::StringRef, int>>/4/256                     49.3 ± 0%            48.2 ± 0%  -2.17%        (p=0.000 n=54+53)
BM_MapLookupHit<Map<llvm::StringRef, int>>/8/256                     49.0 ± 0%            48.0 ± 0%  -2.02%        (p=0.000 n=51+51)
BM_MapLookupHit<Map<llvm::StringRef, int>>/16/256                    51.8 ± 1%            51.3 ± 1%  -0.89%        (p=0.000 n=50+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/32/256                    51.8 ± 1%            51.3 ± 1%  -1.07%        (p=0.000 n=56+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/64/256                    52.4 ± 1%            51.8 ± 1%  -1.12%        (p=0.000 n=57+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/256/256                   54.6 ± 1%            54.1 ± 1%  -0.94%        (p=0.000 n=53+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/256/64                    51.9 ± 1%            51.4 ± 1%  -0.95%        (p=0.000 n=55+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/256/128                   52.5 ± 1%            52.0 ± 1%  -1.07%        (p=0.000 n=57+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/4096/256                  62.0 ± 3%            61.6 ± 3%  -0.62%        (p=0.002 n=55+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/4096/1024                 74.6 ± 1%            73.5 ± 1%  -1.38%        (p=0.000 n=56+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/4096/2048                 80.9 ± 1%            79.8 ± 1%  -1.34%        (p=0.000 n=57+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/65536/256                 72.0 ± 2%            71.4 ± 2%  -0.77%        (p=0.000 n=56+55)
BM_MapLookupHit<Map<llvm::StringRef, int>>/65536/16384                145 ± 4%             145 ± 3%    ~           (p=0.662 n=57+55)
BM_MapLookupHit<Map<llvm::StringRef, int>>/65536/32768                155 ± 4%             156 ± 4%    ~           (p=0.541 n=57+54)
BM_MapLookupHit<Map<llvm::StringRef, int>>/1048576/256               73.1 ± 2%            72.5 ± 2%  -0.73%        (p=0.000 n=56+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/1048576/262144             281 ± 7%             283 ± 5%    ~           (p=0.284 n=57+49)
BM_MapLookupHit<Map<llvm::StringRef, int>>/1048576/524288             342 ± 5%             342 ± 5%    ~           (p=0.684 n=57+53)
BM_MapLookupHit<Map<llvm::StringRef, int>>/16777216/256              77.5 ± 2%            76.9 ± 2%  -0.74%        (p=0.000 n=55+54)
BM_MapLookupHit<Map<llvm::StringRef, int>>/16777216/4194304           750 ± 3%             749 ± 3%    ~           (p=0.458 n=57+53)
BM_MapLookupHit<Map<llvm::StringRef, int>>/16777216/8388608           802 ± 2%             801 ± 3%    ~           (p=0.518 n=57+55)
BM_MapLookupHit<Map<llvm::StringRef, int>>/56/256                    51.9 ± 1%            51.3 ± 1%  -1.10%        (p=0.000 n=57+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/224/256                   54.0 ± 1%            53.5 ± 1%  -1.01%        (p=0.000 n=56+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/3584/256                  58.8 ± 2%            58.1 ± 2%  -1.28%        (p=0.000 n=56+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/3584/896                  69.7 ± 2%            68.7 ± 1%  -1.35%        (p=0.000 n=57+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/3584/1792                 77.1 ± 1%            76.0 ± 1%  -1.45%        (p=0.000 n=55+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/57344/256                 71.3 ± 2%            70.7 ± 3%  -0.85%        (p=0.000 n=55+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/57344/14336                128 ± 3%             128 ± 3%    ~           (p=0.556 n=57+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/57344/28672                140 ± 4%             140 ± 3%    ~           (p=0.735 n=57+51)
BM_MapLookupHit<Map<llvm::StringRef, int>>/917504/256                72.8 ± 2%            72.3 ± 2%  -0.76%        (p=0.000 n=57+57)
BM_MapLookupHit<Map<llvm::StringRef, int>>/917504/229376              242 ± 7%             243 ± 6%    ~           (p=0.303 n=57+55)
BM_MapLookupHit<Map<llvm::StringRef, int>>/917504/458752              264 ± 7%             264 ± 6%    ~           (p=0.823 n=57+55)
BM_MapLookupHit<Map<llvm::StringRef, int>>/14680064/256              76.4 ± 2%            75.8 ± 3%  -0.78%        (p=0.000 n=57+56)
BM_MapLookupHit<Map<llvm::StringRef, int>>/14680064/3670016           696 ± 3%             698 ± 3%    ~           (p=0.189 n=56+53)
BM_MapLookupHit<Map<llvm::StringRef, int>>/14680064/7340032           749 ± 3%             750 ± 3%    ~           (p=0.266 n=55+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/1/256                     34.9 ± 0%            35.0 ± 0%  +0.36%        (p=0.000 n=56+50)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/2/256                     34.9 ± 0%            35.0 ± 0%  +0.35%        (p=0.000 n=55+53)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/3/256                     34.9 ± 0%            35.0 ± 0%  +0.35%        (p=0.000 n=55+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/4/256                     34.9 ± 0%            35.0 ± 0%  +0.36%        (p=0.000 n=56+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/8/256                     37.5 ± 3%            37.6 ± 2%    ~           (p=0.081 n=57+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/16/256                    39.4 ± 1%            39.5 ± 2%    ~           (p=0.054 n=55+57)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/32/256                    40.0 ± 3%            39.9 ± 4%    ~           (p=0.449 n=56+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/64/256                    40.0 ± 1%            40.1 ± 2%    ~           (p=0.796 n=54+54)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/256/256                   41.1 ± 2%            41.2 ± 2%    ~           (p=0.061 n=53+50)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/256/64                    39.6 ± 2%            39.6 ± 2%    ~           (p=0.695 n=55+52)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/256/128                   40.2 ± 2%            40.1 ± 2%    ~           (p=0.507 n=53+49)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/4096/256                  43.4 ± 2%            43.5 ± 2%    ~           (p=0.300 n=53+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/4096/1024                 50.9 ± 2%            51.8 ± 2%  +1.79%        (p=0.000 n=56+57)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/4096/2048                 58.2 ± 1%            58.3 ± 1%    ~           (p=0.072 n=57+57)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/65536/256                 46.1 ± 1%            46.1 ± 2%    ~           (p=0.197 n=54+53)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/65536/16384               88.1 ± 5%            88.9 ± 4%  +0.90%        (p=0.011 n=57+57)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/65536/32768               92.4 ± 3%            93.6 ± 3%  +1.35%        (p=0.000 n=57+57)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/1048576/256               46.6 ± 2%            46.7 ± 2%    ~           (p=0.687 n=51+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/1048576/262144             144 ± 7%             145 ± 6%    ~           (p=0.130 n=57+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/1048576/524288             181 ± 4%             182 ± 4%    ~           (p=0.057 n=56+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/16777216/256              48.9 ± 2%            48.7 ± 2%  -0.30%        (p=0.042 n=56+53)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/16777216/4194304           351 ± 2%             350 ± 3%    ~           (p=0.287 n=57+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/16777216/8388608           368 ± 3%             367 ± 3%    ~           (p=0.710 n=57+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/56/256                    39.7 ± 3%            39.6 ± 3%    ~           (p=0.572 n=57+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/224/256                   41.7 ± 2%            41.6 ± 3%    ~           (p=0.233 n=55+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/3584/256                  42.6 ± 2%            42.5 ± 2%    ~           (p=0.309 n=54+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/3584/896                  49.1 ± 1%            49.8 ± 1%  +1.51%        (p=0.000 n=57+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/3584/1792                 57.0 ± 1%            57.1 ± 2%  +0.30%        (p=0.022 n=56+57)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/57344/256                 46.1 ± 2%            46.0 ± 1%  -0.28%        (p=0.013 n=55+53)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/57344/14336               82.0 ± 2%            82.6 ± 2%  +0.71%        (p=0.000 n=57+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/57344/28672               88.7 ± 2%            89.8 ± 2%  +1.22%        (p=0.000 n=57+53)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/917504/256                46.5 ± 1%            46.5 ± 2%    ~           (p=0.961 n=53+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/917504/229376              126 ± 5%             128 ± 5%  +1.64%        (p=0.000 n=57+54)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/917504/458752              140 ± 5%             141 ± 6%    ~           (p=0.162 n=57+55)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/14680064/256              48.5 ± 2%            48.3 ± 2%    ~           (p=0.094 n=55+54)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/14680064/3670016           328 ± 4%             328 ± 3%    ~           (p=0.925 n=57+56)
BM_MapUpdateHit<Map<llvm::StringRef, int>>/14680064/7340032           345 ± 3%             345 ± 3%    ~           (p=0.489 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/1/256                76.0 ± 0%            75.9 ± 0%  -0.03%        (p=0.006 n=54+47)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/2/256                71.3 ± 1%            72.1 ± 5%    ~           (p=0.750 n=52+54)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/3/256                70.9 ± 2%            70.7 ± 2%    ~           (p=0.095 n=54+52)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/4/256                70.4 ± 2%            70.6 ± 3%    ~           (p=0.458 n=47+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/8/256                75.0 ± 1%            74.2 ± 1%  -1.16%        (p=0.000 n=52+54)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/16/256               80.5 ± 3%            79.0 ± 3%  -1.88%        (p=0.000 n=51+53)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/32/256               83.2 ± 4%            82.3 ± 5%  -1.01%        (p=0.009 n=56+57)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/64/256               80.6 ± 3%            79.4 ± 4%  -1.48%        (p=0.000 n=52+54)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/256/256              83.6 ± 3%            82.6 ± 5%  -1.23%        (p=0.000 n=54+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/256/64               79.1 ± 6%            78.8 ± 8%    ~           (p=0.359 n=55+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/256/128              81.1 ± 6%            80.3 ± 9%  -1.04%        (p=0.010 n=55+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/4096/256             85.5 ± 5%            84.1 ± 4%  -1.61%        (p=0.000 n=54+57)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/4096/1024            95.7 ± 3%            95.2 ± 2%  -0.47%        (p=0.033 n=56+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/4096/2048             101 ± 2%             101 ± 1%  -0.68%        (p=0.000 n=56+54)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/65536/256            90.5 ± 4%            88.1 ± 4%  -2.57%        (p=0.000 n=56+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/65536/16384           134 ± 3%             133 ± 2%  -0.71%        (p=0.002 n=57+57)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/65536/32768           142 ± 3%             141 ± 2%  -0.90%        (p=0.000 n=57+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/1048576/256          91.2 ± 3%            89.3 ± 4%  -2.08%        (p=0.000 n=56+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/1048576/262144        209 ± 5%             208 ± 5%    ~           (p=0.170 n=57+54)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/1048576/524288        243 ± 5%             240 ± 5%  -1.05%        (p=0.020 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/16777216/256         94.3 ± 3%            92.5 ± 5%  -1.91%        (p=0.000 n=55+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/16777216/4194304      542 ± 3%             537 ± 4%  -1.02%        (p=0.000 n=57+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/16777216/8388608      566 ± 3%             561 ± 4%  -1.01%        (p=0.000 n=57+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/56/256               83.7 ±10%            81.3 ± 8%  -2.84%        (p=0.000 n=55+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/224/256              88.7 ± 8%            86.6 ± 9%  -2.40%        (p=0.001 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/3584/256             94.0 ± 5%            91.3 ± 4%  -2.83%        (p=0.000 n=56+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/3584/896              118 ± 4%             118 ± 5%    ~           (p=0.930 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/3584/1792             143 ± 4%             141 ± 4%  -1.10%        (p=0.002 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/57344/256             102 ± 4%             100 ± 4%  -2.31%        (p=0.000 n=56+57)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/57344/14336           191 ± 2%             190 ± 1%  -0.32%        (p=0.024 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/57344/28672           197 ± 2%             197 ± 1%    ~           (p=0.059 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/917504/256            103 ± 4%             101 ± 4%  -1.99%        (p=0.000 n=57+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/917504/229376         280 ± 3%             279 ± 3%    ~           (p=0.145 n=57+52)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/917504/458752         298 ± 4%             296 ± 3%    ~           (p=0.116 n=57+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/14680064/256          107 ± 4%             104 ± 4%  -2.11%        (p=0.000 n=55+56)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/14680064/3670016      613 ± 3%             612 ± 2%    ~           (p=0.224 n=57+55)
BM_MapEraseUpdateHit<Map<llvm::StringRef, int>>/14680064/7340032      637 ± 2%             635 ± 1%    ~           (p=0.075 n=56+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/1                          132 ± 0%             132 ± 0%  -0.26%        (p=0.000 n=47+41)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/2                          160 ± 0%             161 ± 4%  +0.57%        (p=0.001 n=45+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/3                          188 ± 2%             189 ± 3%    ~           (p=0.327 n=54+54)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/4                          217 ± 3%             218 ± 5%    ~           (p=0.240 n=54+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/8                          342 ± 5%             341 ± 4%    ~           (p=0.282 n=53+54)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/16                         640 ± 3%             648 ± 8%  +1.26%        (p=0.023 n=49+54)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/32                       1.20k ± 8%           1.20k ± 8%    ~           (p=0.423 n=53+54)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/64                       3.57k ± 8%           3.55k ± 6%    ~           (p=0.557 n=57+54)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/256                      18.6k ± 5%           18.6k ± 6%    ~           (p=0.799 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/4096                      492k ± 4%            491k ± 3%    ~           (p=0.378 n=56+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/65536                    10.5M ± 2%           10.4M ± 1%    ~           (p=0.143 n=57+48)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/1048576                   323M ± 2%            322M ± 3%    ~           (p=0.098 n=56+56)
BM_MapInsertSeq<Map<ll::StringRef, int>>/16777216                 7.07G ± 3%           7.05G ± 4%    ~           (p=0.195 n=56+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/56                       2.04k ± 8%           2.03k ± 7%    ~           (p=0.124 n=52+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/224                      12.0k ± 5%           12.0k ± 4%    ~           (p=0.467 n=57+55)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/3584                      294k ± 5%            292k ± 4%    ~           (p=0.188 n=56+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/57344                    6.40M ± 2%           6.39M ± 1%    ~           (p=0.381 n=57+56)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/917504                    199M ± 3%            199M ± 3%    ~           (p=0.977 n=57+57)
BM_MapInsertSeq<Map<llvm::StringRef, int>>/14680064                 4.56G ± 3%           4.55G ± 3%    ~           (p=0.129 n=55+56)
```
2024-12-31 04:32:52 +00:00
ezbr 9d09061301 Avoid misaligned loads from StaticRandomData in the size [4, 8] hashing case. (#4743)
Avoid misaligned loads from StaticRandomData in the size [4, 8] hashing
case. We can use aligned loads in this case for lower latency. We
introduce the SampleAlignedRandomData function for this purpose.
2024-12-31 04:32:13 +00:00
Richard Smith 4bbc189d55 Don't produce a follow-on error message if we try to perform an impl lookup during error recovery. (#4749) 2024-12-31 03:30:35 +00:00
ezbr afdf846636 Align StaticRandomData to cacheline size. (#4741)
Align StaticRandomData to cacheline size to ensure the whole array is on
the same cacheline.
2024-12-31 02:34:30 +00:00
Richard Smith d41668350b Suppress testing SemIR in int builtin tests. (#4748)
Add `EXTRA-ARGS:` support to file_test, to add arguments without
overriding the default arguments. Use `EXTRA-ARGS: --no-dump-sem-ir` to
turn off SemIR dumping and thus SemIR testing in the int builtin tests,
which validate correct behavior through diagnostics instead.

This doesn't get us any closer to supporting more targeted SemIR dumping
/ testing, but this seems to be a generally useful feature anyway. Most
existing
tests using `ARGS` have been switched over to using `EXTRA-ARGS`.

Requested in review of #4716.
2024-12-31 00:35:39 +00:00
josh11bandJosh L 89df77707b Drop references to deleted explorer fuzzer (#4745)
Follow up to delete that happened in #4731 .

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-28 02:09:40 +00:00
Richard Smith 7d8d59cb7e Make snegate / unegate overflow handling consistent with other builtins. (#4744)
Make `int.snegate` ignore the signedness of its operand and
unconditionally check for signed overflow like all the other `int.s*`
builtins do. Fix the prelude implementation of unary `-` for `Core.UInt`
to use `int.unegate` instead of `int.snegate`.

Fix the test for unsigned negate to actually test negating unsigned
integers, and add some tests that unary `-` also works.
2024-12-26 22:07:47 +00:00
Dana Jansens 724fc7623e Fix the forty_two.carbon example in getting started (#4736)
The Core.Print function has moved into the "io" library, so it needs to
be imported into scope.

Part of issue #4734
2024-12-26 00:37:42 +00:00
Dana Jansens 9290ee2bcf Use unsigned arithmetic builtins for UInt(N) operations (#4740)
We were mistakenly using the signed builtins, which produce the same
lowering for add/multiply right now, but don't for division and modulus.

When manually flipping SignedOverflowIsUB on, the signed version of add
gains the nsw (no signed wrap) flag, while the unsigned version
(correctly after this change) does not:
```
// CHECK:STDOUT: define i32 @_Cadd_i32.Main(i32 %a, i32 %b) !dbg !4 {
// CHECK:STDOUT: entry:
// CHECK:STDOUT:   %int.sadd = add nsw i32 %a, %b, !dbg !7
// CHECK:STDOUT:   ret i32 %int.sadd, !dbg !8
// CHECK:STDOUT: }
// CHECK:STDOUT:
// CHECK:STDOUT: define i32 @_Cadd_u32.Main(i32 %a, i32 %b) !dbg !9 {
// CHECK:STDOUT: entry:
// CHECK:STDOUT:   %int.uadd = add i32 %a, %b, !dbg !10
// CHECK:STDOUT:   ret i32 %int.uadd, !dbg !11
// CHECK:STDOUT: }
```
2024-12-26 00:36:33 +00:00
josh11bandJosh L 1a5107efa4 Clarify the logic for invalid impl redeclarations (#4738)
Follow up to #4179, specifically re:
https://github.com/carbon-language/carbon-lang/pull/4719#discussion_r1894364691
.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-23 23:05:12 +00:00
Dana Jansens f8e60a8ec1 Fix path to carbon binary in nightly builder (#4737)
The path moved from ./bazel-bin/toolchain/install/run_carbon to
./bazel-bin/toolchain/carbon in 13502b7c89.

Part of issue https://github.com/carbon-language/carbon-lang/issues/4734
2024-12-23 22:54:30 +00:00
Richard Smith 28602a87c2 Fix handling of repeated tuple indexing. (#4733)
Per [the
design](https://docs.carbon-lang.dev/docs/design/lexical_conventions/),
`x.1.2` should lex as `(x.1).2`, not as `x.(1.2)`.
2024-12-21 06:57:14 +00:00
Jon Ross-Perkins 266fd6aa75 Remove explorer's proto fuzzer and proto dependencies (#4731)
As part of migrating to the latest bazel configurations in #4729, I'm
running into proto toolchain issues. For example:
"Error: <target @@protobuf+//:cc_toolchain> (rule
'proto_lang_toolchain') doesn't contain declared provider
'ProtoLangToolchainInfo'"

Although we may eventually want more use of proto, right now the only
use is for the explorer fuzzer. The explorer codebase is essentially
frozen, so continuing to run it isn't gaining us much (in fact, we've
already disabled autofuzzing for it).

So, rather than trying to fix the proto setup, this change:

1. Deletes `explorer/fuzzing`
2. Removes proto portions of `testing/fuzzing`, which were only in-use
by the explorer
3. Removes some ancillary proto support, which would otherwise break
from the bazel changes and would be difficult to validate as "still
working"

This change is partly isolated in order to make it easier to revive bits
of (3).
2024-12-20 23:55:06 +00:00
josh11bandJosh L 01ca9f05dd has_definition_started accessor for entities (#4730)
Note that I left some calls to `is_defined()` where I thought they were
interchangeable.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-20 22:29:50 +00:00
Jon Ross-Perkins 9b72b0eb1a Enable strict action env (#4728)
Doing this due to questions about rebuilds. But it now has me looking at
incompatible flags in general.

I believe we should have the specific action_env settings due to the use
in toolchain setup.
2024-12-20 22:23:37 +00:00
josh11bandJosh L 5169a1862e Require a definition in the same file as an impl declaration (#4719)
This PR detects the failures that #4709 fixes.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-20 17:00:53 +00:00
josh11bandJosh L 661ba36119 Remove stale comment (#4727)
Comment became out of date with #4698 . Seems better to delete instead
of update this comment.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-20 16:58:39 +00:00
Dana Jansensandjonmeow 6cb660f5ad Avoid recursion in InstNamer::CollectNamesInBlock (#4706)
Use a deque to maintain the set of instructions to be walked over. so
that the loop can append more instructions (with their related scope)
during iteration without requiring recursion.

---------

Co-authored-by: jonmeow <jperkins@google.com>
2024-12-20 16:12:06 +00:00
Chandler Carruth aca862ceff Fix a clang-tidy issue (#4723) 2024-12-20 07:18:59 +00:00
josh11bandJosh L c130fe8d51 Fix VSCode language extension configuration instructions (#4725)
The instructions did not match the example. The VSCode settings suggests
the example is the correct one.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-20 07:16:35 +00:00
Chandler CarruthandDanila Kutenin 3ae968a74c Teach the SIMD metadata group match to defer masking (#4595)
When using a byte-encoding for matched group metadata we need to mask
down to a single bit in each matching byte to make the iteration of a
range of match indices work. In most cases, this mask can be folded into
the overall match computation, but for Arm Neon, there is avoidable
overhead from this. Instead, we can defer the mask until starting to
iterate. Doing more than one iteration is relative rare so this doesn't
accumulate much waste and makes common paths a bit faster.

For the M1 this makes the SIMD match path about 2-4% faster. This isn't
enough to catch the portable match code path on the M1 though.

For some Neoverse cores the difference here is more significant (>10%
improvement) and it makes the SIMD and scalar code paths have comparable
latency. Still not clear which is better as the latency is comparable
and beyond latency the factors are very hard to analyze -- port pressure
on different parts of the CPU, etc.

Leaving the selected code path as portable since that's so much better
on the M1, and I'm hoping to avoid different code paths for different
Arm CPUs for a while.

---------

Co-authored-by: Danila Kutenin <danilak@google.com>
2024-12-20 04:40:58 +00:00
Jon Ross-Perkins e85125c3d7 Extension version bump and npm update for a release of #4527 (#4722) 2024-12-20 00:59:49 +00:00
Chandler CarruthandJon Ross-Perkins 13502b7c89 Replace #4505 with a different set of workarounds (#4527)
This restores the symlinks for the installation, but teaches the busybox
info search to look for a relative path to the busybox binary itself
before walking through symlinks. This let's it find the tree structure
when directly invoking `prefix_root/bin/carbon` or similar, either
inside of a Bazel rule or from the command line, and mirrors how we
expect the installed tree to look. This works even when Bazel resolves
the symlink target fully, and potentially to something nonsensical like
a CAS file.

In order to make a convenient Bazel target that can be used with `bazel
run //toolchain`, this adds an override to explicitly set the desired
argv[0] to use when selecting a mode for the busybox and a busybox
binary. Currently, the workaround uses an environment variable because
that required the least amount of plumbing, and seems a useful override
mechanism generally, but I'm open to other approaches.

This should allow a few things to work a bit more nicely:
- It should handle sibling symlinks like `clang++` to `clang` or
  `ld.lld` to `lld`, where that symlink in turn points at the busybox.
  We want to use *initial* `argv[0]` value to select the mode there.
- It avoids bouncing through Python (or other subprocesses) when
  invoking the `carbon` binary in Bazel rules, which will be nice for
  building the example code and benchmarking.

It does come at a cost of removing one feature: the initial symlink
can't be some unrelated alias like `my_carbon_symlink` -- we expect the
*first* argv[0] name to have the meaningful filename for selecting
a busybox mode.

It also trades the complexity of the Python script for some complexity
in the busybox search in order to look for a relative `carbon-busybox`
binary. On the whole, I think that tradeoff is worthwhile, but it isn't
free.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-12-20 00:33:29 +00:00
josh11bandJosh L 85ea848879 Fix syntactic match of impl decl to definition (#4709)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-20 00:31:38 +00:00
Richard Smith 6fe8e0b5aa Provide generic impls for Core.Int and Core.UInt operations. (#4693)
Instead of providing operations only for `i32`, provide them for all
`iN` and `uN` types.

For now, this excludes the `*Assign`, `Inc` and `Dec` interfaces,
because the implementations for those are defined as Carbon functions
rather than builtins, and we can't yet lower definitions for specific
functions, so converting those to be generic breaks the build for our
examples.
2024-12-19 22:02:18 +00:00
Richard Smith de41a4b1b3 Fix a protected data member in a test. (#4717) 2024-12-19 22:01:18 +00:00
Geoff RomerandRichard Smith a112cbde5c Model type expressions as regions (#4698)
This is a precondition for enabling the new pattern-matching subsystem
to support binding patterns that have `if` expressions in the type
position.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-19 21:41:06 +00:00
David Blaikie 95c9634c60 Enable libc++ and LLVM pretty printers for gdb (#4715) 2024-12-19 18:53:21 +00:00
Richard Smith a536dbd8d9 Solution for advent of code day 3. (#4713) 2024-12-19 18:23:50 +00:00
Richard Smith 0fa699641a Solution for advent of code day 2. (#4708) 2024-12-19 17:18:19 +00:00
Richard Smith b54a27e9e7 Fix incorrect lowering of mixed constant / non-constant aggregate initialization. (#4704)
We defer lowering initialization with constant values, because the use
of the constant can itself be part of a larger constant that we don't
want to emit. However, when the initialization is for an element of a
non-constant aggregate, we do need to initialize the constant portion.
2024-12-19 01:13:29 +00:00
Jon Ross-Perkins ee4746c41c Add documentation for running GDB and LLDB (#4710)
After lots of fidgeting, LLDB seems to work. Not sure how reliable this
will be though -- fission seems a little hit and miss.
2024-12-19 00:32:25 +00:00
Jon Ross-Perkins cb4686bf21 Enable misc-non-private-member-variables-in-classes and adjust style to match (#4702)
Pursuant to discussion regarding #4699, turn on
`misc-non-private-member-variables-in-classes` using the
`IgnoreClassesWithAllMemberVariablesBeingPublic` flag (the check treats
structs as classes, so we need this for structs with all-public
members). Updates the style guide notes to match, which should be pretty
minor due to the scoping of test fixtures.

Also fixes some underscore uses in test files on the way. Basically this
is keeping the style for [class data member
naming](https://google.github.io/styleguide/cppguide.html#Variable_Names)
even while making them public.
2024-12-19 00:31:41 +00:00
Jon Ross-Perkins f67a4a5bcb Do a pass on vscode development instructions (#4703) 2024-12-19 00:31:24 +00:00
Jon Ross-Perkins ecda309c12 Change Dump functions to static where appropriate. (#4712)
Verified under LLDB these still appear callable; I'm expecting GDB to be
the same. My concern about debugger calls to static functions was just
wrong.
2024-12-18 23:58:01 +00:00
Jon Ross-Perkins a85160087b Undo formatting changes for clang-tidy-16 compatibility. (#4707) 2024-12-18 17:47:38 +00:00
Jon Ross-Perkins a651ce1961 Fix default for Carbon Path (#4705)
The extension.ts tries to provide a default, but it's not working the
way I expect. So in addition, provide it in properties, which seems to
work better.
2024-12-18 17:43:47 +00:00
Richard Smith c1590f886a Add equality comparison support for bool. (#4701) 2024-12-18 00:47:03 +00:00
David Blaikie 4d0a6db49b Abort checking when encountering an invalid parse node (#4700)
Short term solution/block for #4689
2024-12-18 00:19:12 +00:00
Nirmal Patel b69f97d1f3 Fix Devcontainer build errors (#4647)
Devcontainer Dockerfile has been updated to use Ubuntu 24.04 as the
base. Now devcontainer builds without errors. Tested with Podman on
Linux and Docker Desktop on Windows.

To avoid re-downloading and re-compiling whenever the container is
deleted, a named volume is mounted at /home/ubuntu/.cache.

Closes #4065
2024-12-17 23:38:17 +00:00
Jon Ross-PerkinsandGeoff Romer 2eb1c7c372 Document StepStack (#4687)
Also add underscores to member names, and make `PushSpecificId` private
since it's not used outside `PushEntityName`

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2024-12-17 22:55:43 +00:00
Jon Ross-PerkinsandRichard Smith 3f9a06aee3 Look at flipping clang-tidy's misc-* to enable-by-default (#4699)
I was wondering, instead of treating `misc` differently and enabling
specific checks, maybe we can flip that since we actually seem okay with
most of the checks?

The main check I'm enabling, with significant edits here, is
`misc-no-recursion`. But maybe this is helpful to enable, even with the
necessary NOLINTs, since we want to avoid recursion in the toolchain?
This PR shows some example fixes in subst.cpp (which are more stylistic,
since the code shouldn't actually have recursed due to its structure; I
think we could remove the warning on TryResolveInst the same way). Some
also just don't seem worth fixing, like those in tests files (I didn't
see a way to exclude files in .clang-tidy, so instead I'm using
NOLINTBEGIN). But I think we might actually want to fix inst_namer, and
there's enough in convert that I didn't look closely.

Also, I made some protected -> private style fixes based on
`misc-non-private-member-variables-in-classes` (this is also how I
noticed `class Real` versus `struct Real`). With node_stack, it looks
like the `protected` wasn't even used. [Per
style](https://google.github.io/styleguide/cppguide.html#Access_Control),
data members should be private outside tests. But since we can't
trivially exclude `protected` members in tests, I'm turning it off -- I
don't view it as offering enough benefit on the whole.

migrate_cpp issues are preexisting (I believe we just aren't monitoring
it), but changes there make `bazel build --config=clang-tidy -k //...`
work cleanly.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-17 21:20:37 +00:00
9c8773da1b Basic name poisoning support (#4654)
https://github.com/carbon-language/carbon-lang/issues/4622
When using an unqualified name, disallow declaring that name in all
scopes that would make it ambiguous in retrospect.
Doesn't include support for poisoning in `impl library` (see new test
for that with TODO).
Implemented by introduce `InstId::PoisonedName` and entries with it to
`NameScope`.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: josh11b <josh11b@users.noreply.github.com>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-12-17 21:08:26 +00:00
6b3307c520 Support StructValue in StringifyTypeExpr (#4696)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-17 19:19:52 +00:00
Geoff Romer 557c9b022a Remove CHECK from GetCurrentReturnSlot (#4688)
`GetCurrentReturnSlot` is sometimes called when there is no return slot
while checking incorrect Carbon code. This change also updates
`fail_returned_var_no_return_type.carbon` to cover one such case.
2024-12-17 19:15:27 +00:00
Boaz Brickner c99c9c41cf Do not load prelude files to the test file system in no-prelude tests (#4697)
These tests do not import prelude so the files do not need to exist, and
only make the tests more complex, as they include extra unnecessary
inputs.
2024-12-17 16:37:31 +00:00
Richard Smith 62f7345bb7 Import support for Call and BoundMethod. (#4695) 2024-12-17 08:26:18 +00:00
Jon Ross-Perkins c832d523be Update files and clang-tidy config to pass with clang-tidy-20 (#4691)
Disables three new warnings because they lean more towards style
conflicts than fixes. I've brought these up on #style.

Other than that, mostly fixing basic issues, and things that
clang-tidy-20 seems to fire where clang-tiday-16 didn't. One particular
curious case is `llvm::StringLiteral::data()` uses, which are flagged as
not strictly null-terminated; I'm switching to `const char*` in those
spots which matches `llvm::formatv`'s format argument, but feels worse.

I'm removing `run_clang_tidy.py` here because I'm observing it give
fewer warnings than `bazel build --config=clang-tidy -k
//toolchain/...`. The latter matches how we enforce in GitHub actions
(and also caches results, and suppresses output for files that have no
issues), so I'm dropping the bespoke script.
2024-12-17 01:25:53 +00:00
Jon Ross-PerkinsandChandler Carruth 08f24551ec Add bit packing to NodeImpl (#4651)
Just a small packing optimization. We currently have 222 `NodeKinds`, so
this reduces us to just 30ish more we can add without needing to pack
more. However, if we did, there would be a couple options for bringing
the count down by reusing `NodeKinds` and disambiguating based on the
token kind (the 29 infix operators as an example). Or we could just undo
this.

I'm expecting this to yield a small improvement. I'll see if I can get
better numbers since my machine's not really reliable, but here are some
basic values.

Also suggesting to draw the use of `::RawEnumType` for `TokenKind`,
since bit packing appears to work without it. Hoping the `static_assert`
is easier for people to understand the size of the field.

With the change:

```
----------------------------------------------------------------------------------------------------------------------------
Benchmark                                                 Time             CPU   Iterations      Bytes      Lines     Tokens
----------------------------------------------------------------------------------------------------------------------------
BM_CompileAPIFileDenseDecls<Phase::Parse>/256         50399 ns        50359 ns        14336 104.588M/s 3.87217M/s 21.8629M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024       237823 ns       237629 ns         3072 136.721M/s 4.11986M/s 24.2058M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096       997645 ns       996771 ns          768 142.343M/s 4.04105M/s 23.9363M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384     4020308 ns      4018319 ns          192 152.041M/s 4.05966M/s 24.0874M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    16691390 ns     16683058 ns           48 151.317M/s 3.92374M/s 23.2936M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144   75265735 ns     75233476 ns            8 135.842M/s 3.48421M/s 20.6862M/s
```

Without the change:
```
----------------------------------------------------------------------------------------------------------------------------
Benchmark                                                 Time             CPU   Iterations      Bytes      Lines     Tokens
----------------------------------------------------------------------------------------------------------------------------
BM_CompileAPIFileDenseDecls<Phase::Parse>/256         51515 ns        51480 ns        13312 102.312M/s 3.78789M/s  21.387M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024       241040 ns       240900 ns         3072 134.865M/s 4.06392M/s 23.8771M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096       985593 ns       984657 ns          768 144.094M/s 4.09077M/s 24.2308M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384     4109327 ns      4105496 ns          192 148.813M/s 3.97345M/s  23.576M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    17459655 ns     17446006 ns           48   144.7M/s 3.75215M/s  22.275M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144   80802815 ns     80737489 ns            8 126.581M/s 3.24668M/s  19.276M/s
```

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-12-17 00:58:54 +00:00
Richard Smith c04d62a7d1 Ensure that all allocas are created in the entry block. (#4685)
Non-entry-block allocas will allocate new stack memory each time they're
reached, resulting in leaking stack memory over time for allocas in a
loop. Move all such allocas to the entry block instead, and use an LLVM
intrinsic to mark when the lifetime of the variable actually begins.
2024-12-17 00:55:06 +00:00
Richard Smith 3645143e27 Add solutions for advent of code 2024 day 1 to examples/. (#4673)
In order to support these examples, this adds two new builtins to the
toolchain: `print.char` and `read.char`, which map to the libc functions
`putchar` and `getchar`.
2024-12-17 00:47:51 +00:00
josh11bandJosh L b25117b508 Do not resolve the declaration when forming a specific for use in an eval block (#4692)
When substituting into a generic in order to form a generic eval block,
we form `SpecificId`s to track the list of arguments that should
eventually be used to form a specific referenced by the eval block.
Values within that specific are not needed and won't ever be used, so
it's safe to skip forming them in the first place.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-17 00:39:48 +00:00
Jon Ross-Perkins 76055de063 Shuffle around yaml formatting in .clang-tidy (#4690)
I was looking at this again, considering how best to add new checks, and
realized we could just change the format and probably get better deltas
in the future.

This change should just be formatting, with no functional impact.
2024-12-16 23:59:06 +00:00
Richard Smith a10c79569e Model Core.Int as a class type (#4644)
Instead of treating `Core.Int` as the toolchain's builtin `IntType`,
model it as a class that adapts the builtin type. This aligns us better
with the intended language model, gives an associated library for
`impl`s involving `Core.Int` to live within, and opens the door adding
member functions to `Core.Int` if we decide that is desirable.
Remarkably it also seems to make the formatted SemIR a little smaller,
because a call to a generic class generates less IR than a call to a
function.
2024-12-16 22:19:23 +00:00
Jon Ross-PerkinsandRichard Smith f922988c8c Update the vscode language server setup (#4663)
Switches from js to ts, and starts bundling files in order to produce a
better package for deployment. Fixes the README.md to be a more
appropriate front page, moving dev content to development.md. Makes the
path to `carbon` configurable so that it's more stable than just running
in `bazel-bin`.

This is built using suggestions from samples at
https://github.com/microsoft/vscode-extension-samples/tree/main/lsp-sample
and
https://github.com/microsoft/vscode-extension-samples/tree/main/esbuild-sample.
Note the esbuild in particular comes from complaints from `vsce` to use
an option from
https://code.visualstudio.com/api/working-with-extensions/bundling-extension,
and esbuild is just the first option detailed there (I have no real
opinion on options).

I'm bumping the version, and will do a release after merging.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-16 16:05:17 +00:00
Richard Smith 7b45a28a82 Fix lowering of array indexing with an int literal. (#4686)
Such indexing operations are created by array initialization. Since we
switched integer literals to be of type IntLiteral we've been attempting
to index arrays with the (empty) representation of an IntLiteral rather
than with an actual integer value.
2024-12-14 04:47:32 +00:00
Jon Ross-Perkins 1d5d4617ca Fix mem usage tracking of semir (#4684)
The call got misplaced during refactoring.
2024-12-14 01:13:34 +00:00
Dana Jansens 18d99350a9 Add a --remote switch to new_proposal.py (#4681)
If the user's fork is not named 'origin' then the script will fail and
needs to know the user's remote name.

Fixes #1899
2024-12-13 15:46:27 +00:00
Dana Jansens c7ae2a7b18 Avoid printing enums as characters (#4676)
Given code like the following:
```
auto kind = ConversionTarget::Kind{0};
CARBON_CHECK(!loc_id.is_valid(), "hello {0} world", kind);
```

Currently we would print 'hello <the next line>', as the check string
would be treated as terminating at the '{0}', so it does not print the
rest of the string or a newline. This is because ConversionTarget::Kind
is an enum with underlying type `int8_t` which is a char, and
llvm::formatv does not look if the type is an enum and treat is
specially. So it prints it as a char rather than a number, which in this
case is a nul terminator.

With this change, the '{0}' value will be converted to a larger integer
before being passed through to llvm::formatv so that char-sized enums
will print as a number, and the result is that we will print 'hello 0
world\n' as the developer intended.
2024-12-13 14:48:05 +00:00
Jon Ross-Perkins aee098b8e2 Clean up missing library in test (#4678)
Noted in #4677
2024-12-13 00:34:57 +00:00
Jon Ross-Perkins 55c257bc93 Use a filename without a line number as a cue for autoupdate. (#4677)
This is so that diagnostics which lack a location get split file
clustering.
2024-12-13 00:05:33 +00:00
Richard Smith e71fd07dc6 Support stringifying tuple values. (#4664) 2024-12-12 23:23:44 +00:00
Richard Smith 0d835699e3 Import support for array types. (#4675) 2024-12-12 23:09:28 +00:00
Richard Smith 3e0fdd04eb Lower global variables as global definitions, not global declarations. (#4674) 2024-12-12 22:23:00 +00:00
Boaz Brickner 9ea1534535 Allow defining .h files in tests without trying to compile them as Carbon files (#4667)
This would be used to test interop with C++.
#4666
2024-12-12 22:19:24 +00:00
Jon Ross-PerkinsandDana Jansens 3ce0df67bb Add Dump functions to Check, Parse, and Lex (#4669)
- Provide `Check::Dump(context, arg)` and similar.
- gdb and lldb should do contextual lookup, and `call Dump(*this,
Lex::TokenIndex::Invalid)` has been tested with gdb.
- Since this is only for debug, keeps the functions fully separated from
code.
- Uses alwayslink to ensure objects are correctly linked, even though
there are no calls.
- `-Wno-missing-prototypes` is needed when we don't have forward
declarations.
- Code is not linked in opt builds, using `#ifndef NDEBUG`.
- This probably could be doing something in BUILD files with a
`select()`, but the `#ifndef` seemed easier.

This is based on #4620, but uses free functions instead of member
functions.

Co-authored-by: Dana Jansens <danakj@orodu.net>

---------

Co-authored-by: danakj <danakj@orodu.net>
2024-12-12 20:51:02 +00:00
Richard Smith 79ba184dab Provide a location for monomorphization failures resulting from TryToCompleteType. (#4670)
Almost all callers actually could never fail and nearly all of those
already `CHECK`-failed on failure. Add a new overload for that case, and
add a location parameter for the one remaining call.
2024-12-12 00:44:07 +00:00
Richard Smith 758b6c42ba Produce a note indicating where the specific was used from if monomorphization fails. (#4662)
Also fix a bug in `Context::GetClassType` that previously tried to
complete the class type before returning it. That's not correct --
`GetCompleteTypeImpl` is only appropriate for cases where the type can
trivially be completed and completing it can't fail -- and led to
infinite recursion with this change because we would call `GetClassType`
when producing a diagnostic if completing that class type failed.
2024-12-11 22:34:10 +00:00
Richard SmithandJon Ross-Perkins 042ac39426 Pacify CHECK failure on invalid code. (#4665)
Found by fuzzer.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-12-11 18:53:58 +00:00
Jon Ross-Perkins 61c0a8b676 Make more use of llvm STLExtras (#4668)
This is essentially the result of looking at `.begin()` uses. We also
frequently do `std::shuffle`, but unfortunately STLExtras doesn't
provide a wrapper for that.
2024-12-11 18:16:38 +00:00
Richard Smith 47285b6207 Include a fully-qualified name when stringifying types. (#4657)
For example, format the `ImplicitAs` interface as `Core.ImplicitAs`
rather than simply `ImplicitAs`.

When importing an entity in a namespace, also import a declaration of
the enclosing namespace if necessary so that we can determine its name.
2024-12-11 16:33:53 +00:00
8e8d570571 Proposal: Variadics (#2240)
Proposes a set of core features for declaring and implementing generic
variadic
functions.

A "pack expansion" is a syntactic unit beginning with `...`, which is a
kind of
compile-time loop over sequences called "packs". Packs are initialized
and
referred to using "pack bindings", which are marked with the `each`
keyword at
the point of declaration and the point of use.

The syntax and behavior of a pack expansion depends on its context, and
in some
cases by a keyword following the `...`:

- In a tuple literal expression (such as a function call argument list),
`...`
iteratively evaluates its operand expression, and treats the values as
    successive elements of the tuple.
- `...and` and `...or` iteratively evaluate a boolean expression,
combining
the values using `and` and `or`, and ending the loop early if the
underlying
    operator short-circuits.
-   In a statement context, `...` iteratively executes a statement.
- In a tuple literal pattern (such as a function parameter list), `...`
iteratively matches the elements of the scrutinee tuple. In conjunction
with
    pack bindings, this enables functions to take an arbitrary number of
    arguments.

---------

Co-authored-by: josh11b <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-12-11 01:58:40 +00:00
Richard Smith 14724a5c9a Switch from recommending a local workspace extension to recommending our published extension. (#4661) 2024-12-10 22:39:21 +00:00
Jon Ross-Perkins e98995c936 Update the vscode extension for publishing. (#4660)
A few initial fixes just so that publishing works.


https://marketplace.visualstudio.com/items?itemName=carbon-lang.carbon-vscode
2024-12-10 22:03:48 +00:00
Jon Ross-Perkins 87b3671330 Refactor single-unit checking out of check.cpp (#4649)
This is primarily moving code around, to try to create a logical split
of the code in check.cpp, makingthe API boundaries clearer.

There's one small, deliberate logic change around false returns from
`HandleParseNode`, where before there was a `CARBON_CHECK` instantiated
by the `#define` (per `NodeKind`), and now it's outside the `#define`
(done mainly because the message didn't keep up with the `Handle##Name`
-> `HandleParseNode` rename).
2024-12-10 21:00:51 +00:00
Richard Smith 92201ceb10 Rename various TryToCompleteType functions to better describe what they do. (#4658)
As requested in review of #4652.
2024-12-10 20:56:37 +00:00
Boaz Brickner fe8b42148f Mark some //common, //toolchain/driver, //‎toolchain/install tests as small per 'Test execution time' warning (#4646)
These tests only take between 0.1s and 1.4s.
2024-12-10 20:55:58 +00:00
Richard Smith d81ed4b58f Rename mutable accessor in InstBlock store. (#4659)
Mutating a block is a strange and rare operation and shouldn't have an
innocuous name like `Get`.
2024-12-10 20:23:24 +00:00
Richard Smith eabe9f117a Track complete types required by a generic. (#4652)
When a generic requires a symbolic type to be complete, add a new
`require_complete_type` instruction to the generic eval block. During
monomorphization of such an instruction, require that type to be
complete.
2024-12-10 03:00:28 +00:00
Richard SmithandGeoff Romer e75ef34591 Improve diagnostics for missing qualified names. (#4638)
Mention the scope in which the name wasn't found.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2024-12-09 23:48:46 +00:00
Dana Jansens 4e3b8c9775 Disable modernize-use-trailing-return-type on MATCHER_P (#4656)
clang-tidy gives a false positive on the use of the MATCHER_P macro.
2024-12-09 21:13:40 +00:00
josh11bandJosh L bd0f620583 Add more tests of indexing a tuple with a non-literal (#4650)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-06 23:22:21 +00:00
Boaz Bricknerandjonmeow daba2c72cf [NFC] Convert NameScope from struct to class (#4623)
This is a preparation change for adding name poisoning support
(https://github.com/carbon-language/carbon-lang/issues/4622), which is
expected to require more elaborate logic around NameScope since a name
can be not defined yet, defined, or poisoned.

The API separates looking up a name from getting the full entry since we
have cases where the entries are invalidated between the time we're
looking for the name and when we access (and sometimes modify) the
entry.

This change has the following benefits:
* `names` and `name_map` are internal to `NameScope` and are guaranteed
to match.
* `extended_scopes` and `import_ir_scopes` can not be manipulated (only
new scopes can be added).
* `inst_id`, `name_id` and `parent_scope_id` are constants.
* `has_error` can only be mutated from false to true.

---------

Co-authored-by: jonmeow <jperkins@google.com>
2024-12-06 21:50:50 +00:00
Jon Ross-Perkins e7a86b03c6 Remove offsets from InstId formatting, trying to name more (#4645)
The offsets were originally added to deal with churn from builtins in
the raw semir. In textual semir, we mostly see instruction IDs for
imports, and builtins have also settled down more.

On imports, where possible, use the `EntityNameId` for an import instead
of printing an instruction. Next, show the source location if we have a
node. Only show the instruction if there's no location.

This also exposes `Parse::Tree` and `TokenizedBuffer`, so that we can
pass a `SemIR::File` without the component parts. In particular this
allows us to get the `TokenizedBuffer` for import IRs without
substantial structural modifications. We may want to make these optional
for serialized `SemIR` later, but the nodes/tokens contain source
location, which we'd need for debug information -- so it's not clear how
much we can really make them optional without substantial information
loss.

Reduce arguments to just `File` in a few spots, as a result of the
accompanying `TokenizedBuffer` and `Parse::Tree`. Also updates style to
pass around `const File*` where the reference is maintained, instead of
`const File&`.

I was considering keeping a direct reference to the tree and tokens on
`Context`, but initially my thought was it wouldn't make much
difference. I can re-add those if desired, just as direct caching of the
`File` fields.
2024-12-06 21:17:24 +00:00
David Blaikie a2c939a2a2 Add an instruction for vptr initialization (#4633)
This fixes a crash in lowering, at least (though only initializes the
vptr to
null for now) - certainly open to naming feedback on the instruction, or
the
exact semantics (we could have a global vptr instruction that's
referenced from
the existing instructions for reading globals, for instance).

I guess we'll want one type parameter for the vptr_init instruction,
which is
the type that this is a vptr for? (can do that here or in a follow-on
patch)
2024-12-06 18:51:36 +00:00
David Blaikie 5719687438 Fix crash in lowering use of a global variable (#4631)
Actually presenting two options in this one review - if you look at the
specific
commits in this PR, the first commit represents my first attempt - and
if you
look at the overall PR change for the second attempt.

But I'm totally open to completely different approaches/ideas - these
were just
my rough guesses.
2024-12-06 17:34:29 +00:00
Richard Smith cd1ecf1297 When a builtin function expects type T also allow an adapter for T. (#4643)
Extends the set of function signatures that support being given a
builtin definition to include cases where a parameter or return type is
an adapter for a supported type. For example, if we can give a builtin
definition to `Add(a: i32, b: i32) -> i32`, then we can also give a
builtin definition to `Add(a: MyI32, b: MyI32) - >MyI32` where `MyI32`
adapts `i32`.

This is a prerequisite for changing `Core.Int` to be a class type that
adapts the builtin int type.
2024-12-06 03:13:05 +00:00
David Blaikie 2bb520718d Enable gdb_index unconditionally for gdb usage (#4642)
Also make `-gsimple-template-names` lldb-only due to it tripping up gdb
in some cases (I came across it breaking SmallVector pretty printing
where gdb wouldn't associate a simplified type named declaration with a
simplified type named definition in another translation unit - seems gdb
can associate a type decl/def when it sees both (if you step into both
translation units or otherwise trigger gdb loading/parsing them) but it
doesn't seem able to /search/ for the type definition). Filed
https://sourceware.org/bugzilla/show_bug.cgi?id=32421 for this.

A couple of other things I'd like to do, but don't know how:
* It might be nice to allow opting into or out of gdb_index (with the
  default being 'on' for gdb_flags, but you could opt out). But doesn't
  seem super important.
* We should turn off fission by default, it seems - bazel has trouble
  making the .dwo files available at the same path as is in the binary
  especially on partial rebuilds. (not sure if we can do that, I guess
  we can make fission a no-op/doesn't add any flags, even if we can't
  change the fission default in bazel itself)
* can we have gdb_flags imply/disable lldb_flags? (so you can use
  --features=gdb_flags without always having to add
  --features=-lldb_flags)
2024-12-05 23:48:12 +00:00
Jon Ross-Perkins 3ee41222e0 Add video from LLVM Dev meeting (#4641) 2024-12-05 22:34:53 +00:00
Richard Smith ead09da2d5 Remove some assumptions that the object representation for a type is that type itself. (#4640)
This slightly improves the handling of adapters, by making them copyable
in some cases when their adapted type is copyable.

Refactor some of the repeated checks for properties of value
representations.

In passing, move all the adapter tests in check/testdata/class to a
subdirectory since we now have quite a few of them.
2024-12-05 22:26:10 +00:00
Jon Ross-Perkins 1cba3328f7 Finish removing BuiltinInstKind (#4637) 2024-12-05 22:07:51 +00:00
Richard Smith e4eeacabe7 Convert unsupported qualifier test to be no_prelude. (#4639)
Stop relying on `i32` being a builtin type.
2024-12-05 20:31:43 +00:00
Jon Ross-Perkins 27275e6729 Change the IdBase operator== to fix reversed operator warnings (#4636)
I believe our flags enable the warning by default, it's just that it
doesn't catch this in clang-16 (maybe more; I reproduced with clang-18
and didn't keep digging). For example:

```
toolchain/parse/tree_test.cpp:86:28: error: ISO C++20 considers use of overloaded operator '==' (with operand types 'value_type' (aka 'Carbon::Parse::NodeIdInCategory<Carbon::Parse::NodeCategory::Decl>') and 'AnyDeclId' (aka 'NodeIdInCategory<NodeCategory::Decl>')) to be ambiguous despite there being a unique best viable function [-Werror,-Wambiguous-reversed-operator]
   86 |   EXPECT_TRUE(*any_decl_id == any_decl_id2);
      |               ~~~~~~~~~~~~ ^  ~~~~~~~~~~~~
```

The different `operator==` approach works except for with
`Parse::NodeId::Invalid`, which seems easy to replace with a
`.is_valid()` check.
2024-12-05 19:37:32 +00:00
Boaz Brickner 1409666e6a In indirect_import_member test, make the alias avoid name poisoning (#4635)
This is a preparation change for introducing name poisoning
(https://github.com/carbon-language/carbon-lang/issues/4622), which
would have broken this test.
2024-12-05 18:24:56 +00:00
Jon Ross-Perkins efab39cbd9 Remove InstId::Builtin members (#4632)
- `InstId::Builtin<Inst>` -> `<Inst>::SingletonInstId`
- `InstId::PackageNamespace` -> `Namespace::PackageInstId`
2024-12-05 18:13:46 +00:00
Richard Smith d79d9e0884 Factor out common work of determining how inty a type is. (#4634) 2024-12-05 01:49:52 +00:00
Richard Smith 1b13125d19 Avoid relying on an implicit conversion in builtin lowering test. (#4630)
This test is trying to explicitly test builtin functions, so use an
explicit call to a builtin function for the conversion too.
2024-12-05 01:33:42 +00:00
Richard Smith 9ed65775fb Add missing library declarations to test. (#4629) 2024-12-05 01:32:11 +00:00
Jon Ross-Perkins bc24a6c5d8 Refactor IdBase to provide CRTP-based printing (#4626)
This removes a lot of boilerplate `Print` functions in favor of a
CRTP-based approach that uses a `Label` field as an automatic prefix.
This `Label` is also made available for other purposes, particularly
`IdKind` crash messages in this change. In particular, for
`RequireIdKind` in node_stack.h from using numeric IdKinds (e.g., 5 and
24) to something that will print `IdKind(<label>)` (this came up
recently on #toolchain).

While I'm in here, also doing some other tinkering:

- Moving operators to be `friend` members, to reduce the extra
templating now that the base types are templated.
- Adjusts IntId diagnostics from `int [...]` to `int(...)` for
consistency with other id printing.
- Changes InstBlockId's label from "block" to "inst_block", since we
have multiple blocks now.
- Fixes StructTypeFieldsId to use "struct_type_fields" instead of
"type_block" (from `TypeBlockId`)
- Does some more adjustments from camelCase to snake_case for
consistency
2024-12-05 01:29:53 +00:00
Richard Smith a45cb86bf7 Add a compile-time check that the condition of a CHECK is not constant. (#4628)
Inspired by #4624.
2024-12-04 22:29:35 +00:00
Richard Smith 65166dc27b Filter out entities transitively imported from the prelude in test output. (#4627)
Previously we only filtered out things directly imported from the
prelude.
2024-12-04 21:55:52 +00:00
Richard Smith 80a3dc83bc Fix impl lookup to properly look in the IR containing a transitively-imported entity. (#4625) 2024-12-04 21:38:19 +00:00
josh11bandJosh L 6260f0fecf Fix bug introduced in #4613 (#4624)
Issue was not properly handling `ImportRef` instructions in
`AddAssociatedEntities` in `check/import_ref.cpp`. Using `CARBON_CHECK`
instead of `CARBON_FATAL` was hiding the error.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-04 21:16:54 +00:00
Richard Smith f8e7dad33a Include the file from which an entity was imported in formatted SemIR. (#4621) 2024-12-04 19:12:56 +00:00
Jon Ross-Perkins 0e92e6cc5a Switch TypeId::TypeType to TypeType::SingletonTypeId, and similar (#4619)
`ids.h` and `ids.cpp` are the manual edits, everything else is
search-and-replace.

The full list of things moved is:

- `TypeId::TypeType`
- `TypeId::AutoType`
- `TypeId::Error`
- `ConstantId::Error`

This is to unblock removing `InstId::Builtin*`.
2024-12-04 18:40:50 +00:00
Geoff RomerandRichard Smith 78d7a7c291 Remove return_slot_id (#4577)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-04 00:21:24 +00:00
33110d096c Facet types support rewrite (where .A =...) constraints (#4613)
* Rewrite constraints are stored in a facet type, substituted, imported,
and formatted.
* We now distinguish `.Self` from other symbolic bindings in two ways:
* `.Self` itself now has an invalid compile time binding index (since it
doesn't bind to any of the generic parameters). As a result, we no
longer need to create a generic region in `handle_where.cpp`.
* There is a new phase tracking values that are only symbolic because
they transitively depend on `.Self`. This allows us to give the result
of a `where` expression template phase as long as it doesn't use any
symbolic constants other than `.Self` or other designators.
* `AddConstant` has been removed from `check/context` since it was only
used from `eval`. This meant less plumbing of the phase change.
* Evaluation of `BindSymbolicName` now also performs substitution into
its type.
* Include a bit more information in some diagnostics.
* `StringifyTypeExpr` outputs rewrites, which required adding support
for associated entities as well.
  * Associated entities now have an entity name set when importing.
* Adds tests for some interesting cases with rewrites and uses of
`.Self` mixed with other symbolic constants.

Still to do:
* There is no validation that any particular type satisfies rewrite
constraints.
  * Access to members of a facet type do not see the rewritten values.
* Impls don't recognize whether associated constants have rewrites
setting their values.
  * No support for resolving facet types.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-03 22:44:39 +00:00
Dana JansensandJon Ross-Perkins dc5edb88fb Explain bazel is an alias to bazelisk, and recommend that for linux (#4603)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-12-03 21:30:56 +00:00
Dana Jansens 96b5b34a2a Add comments on the constants for BlockValueStore (#4605)
This allows the reader to understand their purpose without having to
find and understand BlockValueStore beforehand.
2024-12-03 20:47:58 +00:00
josh11bandJosh L 5d1b39e1f2 More instructions get named (#4615)
Goal is to reduce churn in names in test updates (by churning a lot of
them in this PR).

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-12-03 20:47:53 +00:00
Jon Ross-Perkins 48a84ca55d Restrict the Cpp package name (#4618)
We're looking at using this for imports, and it gets awkward if we allow
users to declare entries.
2024-12-03 20:47:19 +00:00
Dana JansensandRichard Smith 7005f39162 Introduce AnyRawId as a polymorphic field type in typed instructions (#4606)
The Any[...] instruction group structs have a field layout that matches
the specific typed instructions that it groups together. However those
specific instructions may have different field types, or different
numbers of fields, making it impossible for the Any[...] instruction
group to match them all at once.

In this case, it can use the AnyRawId field type to represent that the
specific typed instructions have different field types in that position,
or may not have a field at all.
    
Previously we used `int32_t` as this polymorphic placeholder type, which
was implicit and worked somewhat magically:
 - It was not listed in IdKind
 - It was was not implemented explicitly for either FromRaw or ToRaw

However it happened to work because:
 - FromRaw<T> was implemented for every T, and would build as long as T
   was constructible from the raw id value, which is int32_t.
 - In As<AnyGroupInstruction> for converting a specific instruction to a
   group instruction: For any given id field type T in the specific type
   struct, it would be converted to its raw (int32_t) value, then the
   AnyGroupInstruction field would be constructed with FromRaw<int32_t>
   since the polymorphic field type was int32_t.
 - Of course int32_t is constructible from int32_t.
 - And if the specific instruction did not have a field in the matching
   position, the AnyGroupInstruction's field would be default
   constructed, and int32_t is default constructible.

This allowed As<AnyGroupInstruction> to construct the
AnyGroupInstruction type
from each of its specific instruction types regardless of what field
types they had.

We can make this more explicit by using a type other than int32_t. We
introduce the AnyRawId specifically for the purpose of being a
polymorphic field type in Any[...] instruction groups.

The AnyRawId type _is_ part of IdKind, removing the need for a special
case in the documentation and rules about field types. And this allows
us to `require` that T is in IdKind for FromRaw<T>.
 - This also pointed out that FromRaw and ToRaw do not need to be
   implemented for BuiltinTypeKind anymore, as this is no longer a field
   type in any typed instructions, further simplifying the rules to not
   need any exceptions for what is a valid field type.

The AnyRawId type participates in FromRaw by being a member of IdKind
and being constructible from int32_t.

The AnyRawId type is default constuctible so that when the specific
typed instruction has no field in the matching position, it will be
default-constructed with the InstId::InvalidIndex value.

The AnyRawId type does _not_ participate in ToRaw, and this is
documented on the type. This is because conversion from specific typed
instruction to an instruction group is lossy (due to the polymorphism
which requires the AnyRawId type). As such conversion from the
instruction group to a specific instruction is not possible, and thus
the Any[...] instruction group does not need to support being converted
to raw id values.

This is rebased on #4604.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-03 20:43:50 +00:00
Dana Jansens 46d6b8451f Enable libc++ hardening mode in opt builds (#4609)
In llvm 17 the _LIBCPP_ENABLE_ASSERTIONS flag was split into two:
- _LIBCPP_ENABLE_HARDENED_MODE for fast checks
- _LIBCPP_ENABLE_DEBUG_MODE for expensive checks

We kept HARDENED_MODE enabled in debug, but we can also turn it on for
opt builds.

In llvm 18, the _LIBCPP_ENABLE_HARDENED_MODE was further split into 4
settings, NONE, FAST, EXTENSIVE, DEBUG. As seen in the recent blog post
https://security.googleblog.com/2024/11/retrofitting-spatial-safety-to-hundreds.html
the FAST hardening mode is indeed very fast and has minimal impact,
while helping to catch a lot of bugs.

So we enable the FAST checks in opt builds, and EXTENSIVE checks in
debug builds.

The EXTENSIVE checks are the same that Chrome enables in every build
configuration, so we could consider enabling it in opt builds as well:
https://source.chromium.org/chromium/chromium/src/+/main:build/config/compiler/BUILD.gn;l=1127;drc=a8260dee097dde71ca4464c0c8d897a80c353db2
2024-12-03 20:28:21 +00:00
f45cbc6028 Add framework for singleton instructions. (#4582)
Adds a singleton framework, and converts `File` and `InstId::Print` to
demonstrate functionality. Moves various functions from `ids.h` to
`ids.cpp` because `Inst::Print` needs the file if `singleton_insts.h` is
split out, so the small bit of cleanup feels consistent.

I added `Inst::MakeSingleton` because getting the type of the
instruction to make from an `InstKind` felt too hard. Singleton
instructions follow a basic structure, so I'm just putting that
instruction structure into `Inst`. Previously we required macros to do
this, and I'm trying to remove macro dependencies.

I'm trying to remove builtin/singleton-related functionality from
`InstId` in order to get a clearer boundary for the functionality. The
other builtin functions should be removed as part of the bigger
migration, but I'm trying to carefully scope changes to verify agreement
on the singleton approach in use first.

This provides `InstT::SingletonInstId` because that'll often be written
as `SemIR::TypeType::SingletonInstId`. The alternative of something like
`SemIR::SingletonInstId<SemIR::TypeType>` is just a little more verbose
due to the repeated `SemIR`, and it's more consistent with
`TypeType::Kind`.

An alternative I considered was consolidating singleton information to
`InstKind`. This felt challenging because of the
`InstId::BuiltinTypeType` and similar values. Maintaining those would
turn into something like `InstKind::IsSingleton()` and
`InstId::Singleton<TypeType>`, which didn't feel like as good a split.
`InstId::Print` remains aware of singletons, but I'm hoping to remove
other builtin-related calls from `InstId`.

Another thing I considered was adding `.is_singleton = true` to
`InstKind::Definition`. I don't think we could rely on that to get
`InstId::Singleton<TypeType>` set up as `constexpr`, though. At that
point, I think it'd mainly be _just_ a comment-like annotation, maybe
validated with `CHECK` but not having any effect on its own. So I
decided not to do that, just adding comments instead.

Sidenotes:

- "singleton" naming was discussed [on
#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1308870233729269781).
- The TODO in file.h about possibly excluding other things than
singletons seems moot. That's for raw IR, and we're much more focused on
textual IR these days.

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Boaz Brickner <brickner@google.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2024-12-03 20:03:37 +00:00
Dana JansensandRichard Smith d434828e21 Remove Parse::Node, add ElementIndex in docs for typed insts (#4604)
The documentation still referred to typed instructions having a
Parse::Node field, however that was removed and moved to the InstStore
in f197219c10.

Then GetParseNode() was renamed to GetNodeId() in 86a7c9ff45 and
then GetLocationId() in b079acd86f and finally GetLocId() in
b5d28f2c4b.

The comment in typed_inst.h mentions only three fields now, but some
types still have four, thanks to the unmentioned `ElementIndex index`
field. Normally this field comes last, after the `[...]Id` fields except
for in one case, AssociatedEntity. Rather than write ambiguously ordered
documentation, update the comment to and docs to say that the
ElementIndex comes last, and move it to the last position in
AssociatedEntity. Tests are rebased accordingly.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-12-03 19:44:54 +00:00
Dana Jansens b705be9527 Use a Timings* in place of optional<Timings>* (#4607)
The current representation has two nested presence indicatators (the
optional bool, the null pointer). Currently the pointer is never null,
but the style guide suggests that T* should be used for parameters that
may or may not be present, so we do not need the optional here.

> When passing an object's address as an argument, use a reference
> unless one of the following cases applies:
>
> - If the parameter is optional, use a pointer and document that it
>   may be null.

Once the parameter is just a pointer, the ScopedTiming field does not
need an optional either, and can just store the pointer.

It would be more preferable to have an optional representation of a
sometimes-null pointer like optional<T&> to describe a sometimes-null
pointer, as this would allow clearer runtime diagnostics when used
incorrectly (a check failure in unwrapping) and would be better
self-documenting through syntax instead of a comment. But we do not
currently have such a primitive.
2024-12-03 19:01:12 +00:00
Richard SmithandJon Ross-Perkins e4412a95dd Factor out machinery for forming int type literals. (#4616)
Use it in the remaining few places where we currently hardcode `i32`: as
the index type in array indexing, as the type for literals in `if`
expressions, and as a valid return type for `Run`.

In preparation for changing `Core.Int` to be a class.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-12-03 18:46:27 +00:00
Richard Smith cf0f504d54 Support for stringifying int values used as generic arguments. (#4614) 2024-12-03 17:56:23 +00:00
Jon Ross-Perkins 0c2ed1b14e Switch from bazeliskrc to bazelversion (#4612)
The only documentation I can find for `.bazelversion` is in
https://github.com/bazelbuild/bazelisk/blob/master/README.md. However,
`bazel` will error out if it doesn't match the `.bazelversion`. For
example:

```
╚╡/usr/bin/bazel build :all
ERROR: The project you're trying to build requires Bazel 7.3.0 (specified in [elided]/carbon-lang/.bazelversion), but it wasn't found in /usr/bin.
```

Switching to this because the `MODULE.bazel` requires tighter version
pinning in order to avoid churn, and this should help catch mistakes
early.

In `MODULE.bazel`, demote mention of the version issue because it should
only really occur now when the version is being deliberately changed, so
the connection should be more apparent.
2024-12-03 17:52:20 +00:00
Dana Jansens 74dcd1fd05 CHECK that PreCheck and GetCheckUnit are not called twice (#4608)
If they were called twice for a CompilationUnit, they would destroy
objects that they created and returned a pointer to, leaving a dangling
pointer somewhere else.
2024-12-02 21:25:13 +00:00
Dana Jansens f9ca2ea2d6 Expose InstKind::FromInt for Inst instead of InstKind::Make (#4611)
The Inst type will type erase a specific typed instruction by storing
the kind as an integer. It does this by calling InstKind::AsInt on a
runtime or compile-time InstKind. Then it returns the kind as InstKind
by reconstituting it from the integer.

Currently it does a cast to a raw enumerator and then calls
InstKind::Make. However Make is designed to be more of an internal
detail. The more clearly paired inverse operation is InstKind::FromInt,
which is documented as being intended to be exposed by derived classes
like InstKind.
2024-12-02 20:13:03 +00:00
Boaz Brickner a297eef2d5 [NFC] In DeclNameStack::AddName(), use NameScope::AddRequired() instead of duplicating its logic (#4610)
This is a pure code deduplication change.
2024-12-02 20:06:01 +00:00
Richard Smith 63ff0cca1a Include the call arguments in the location of a call. (#4602)
Underline the entire call in diagnostics, not only the portion up to the
`(`.
2024-12-02 18:51:44 +00:00
Richard Smith d0e067ac75 Fix impl lookup to look in the arguments of a specific. (#4601) 2024-12-02 18:49:30 +00:00
2ae35d569e Add a basic test for name poisoning (#4572)
Demonstrate where failures should happen.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: David Blaikie <dblaikie@gmail.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2024-12-02 17:37:11 +00:00
Richard Smith 831dd2c929 Fix importing of the complete_type_witness for a generic class. (#4600)
We need to create an instruction on import to attach the generic
constant value to.
2024-11-28 00:13:21 +00:00
Richard Smith 4a10d29b99 Include the complete type witness for a class in its SemIR output. (#4599)
This seems slightly redundant for a locally-defined class, where there
will be a complete_type_witness instruction earlier in the class, but is
important for imported classes, where we're currently doing the wrong
thing in a way that's invisible in formatted SemIR.
2024-11-27 23:45:20 +00:00
Richard SmithandJon Ross-Perkins d6ec885eb3 Track the type as written in BaseDecl and AdaptDecl. (#4564)
Represent the type as an `InstId` rather than as a `TypeId` to preserve
how it was written and better support tracking its value in a generic.
Add accessors to `Class` to get the base and adapted type to reduce code
duplication, and add `TypeStore::GetObjectRepr` to make it easier to map
from a type to its possibly-adapted object representation type. In
passing, also move `GetIntTypeInfo` and `GetUnqualifiedType` into
`TypeStore`.

This fixes specifics of generic adapters to properly look at the
specific adapted type, and also fixes importing of adapters.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-27 22:26:30 +00:00
Boaz Brickner e0db74a2a1 Add a test that verifies we prefer unqualified name lookup from a a non lexical scope over a lexical scope (#4591)
This adds missing test coverage.
See discussion in
https://github.com/carbon-language/carbon-lang/pull/4574.
2024-11-27 20:35:19 +00:00
Dana Jansens 760bdb57fb Use a switch in StringifyTypeExpr (#4598)
Get a compiler error when a case isn't handled instead of a runtime
CHECK failure.
2024-11-27 16:27:26 +00:00
josh11bandJosh L b894d4e62c Refactor StringifyTypeExpr (#4597)
* Make the step stack into a class
* Make the operations on the stack (pushing, popping, test for done)
into methods on the stack class.
* Add more kinds of steps (array bound and name).
* Rewrite cases to use the new kinds of steps. Afterward, none use
`Step::Next()` or the step index, so those get removed.
* Add another convenience method `PushTypeId`.
* Remove the `SemIR::File&` member from the steps, since it doesn't
change.

Hopefully using `step_stack.Push`... calls makes it clear that they are
resolved in the reverse order they are executed.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-27 02:20:31 +00:00
David Blaikie 14bb9dd5cf disallow impl without base (#4583) 2024-11-27 01:37:49 +00:00
Richard Smith c571b0f13b Don't print a comma in a two-item list. (#4596) 2024-11-26 22:48:00 +00:00
6468450c95 Add documentation for the three most common kinds of instruction operand (#4594)
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Dana Jansens <danakj@orodu.net>
2024-11-26 20:09:59 +00:00
4d3b962029 Symbolic aggregate access (#4590)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-11-26 19:33:44 +00:00
Jon Ross-Perkins 5880954041 Refactor command line errors to mirror diagnostic style (#4568)
This changes to an `Error` return to let the driver do the "error: "
prefix, except for one case with `help` that needs more work to change
(I'm not planning on picking up that TODO). It also changes
capitalization, backtick use, and a few minor punctuation things to try
to better match the diagnostic style.

This also adds `Error` matchers so that the changes to command line
testing are clearer.
2024-11-26 19:22:05 +00:00
David BlaikieandRichard Smith f921923b4b lazy field index (#4514)
We considered a couple of other options for this:
* https://github.com/carbon-language/carbon-lang/pull/4515 Keep the
`ElementIndex` numbering vptr-ignorant, and do +1 offsets as needed -
seems subtle/easy to miss
* https://github.com/carbon-language/carbon-lang/pull/4517 Always have a
zeroth element in the object representation, make it zero-size in the
case of no-vptr - @zygoloid was concerned this would add overhead
especially to stateless objects used in type-trait-like things.

But currently moving forward with this direction - of initializing field
indexes with an invalid value until the end of the class definition,
then assigning field indexes during construction of the class's object
representation struct type. This direction might reinforce/help avoid
premature access to the object representation before the class is
complete, and give a single place where class layout is done (at class
completion) if we want to add more options there, such as class layout
optimizations, etc.

This patch still has problems with object initialization (that #4515
does not have/does address) but does address normal `obj.member` access
correctly.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-11-26 18:16:25 +00:00
Dana Jansens 9c71151e34 Add "Whether to" in the description of 'debug-info' switch (#4592)
The switch defaults to true, so it's displayed as `--no-debug-info` in
the help. The description should be agnostic about whether the flag will
enable or disable the behaviour.
2024-11-26 17:39:09 +00:00
Chandler Carruth a2af7ad8f0 Improve hashtable prefetching (#4585)
I had removed most but not all of the hashtable prefetching during
development because I wasn't confident in the benchmarking results.
However, I never revisited this once the benchmarking infrastructure
improved and there were solid and stable results.

This factors the two interesting prefetch patterns I've seen for this
style of hashtable into helpers that are always called, and provides
macros that can be used during the build to configure exactly which
prefetch strategies are enabled.

Benchmarking these and gaining confidence is very frustrating -- even
now with the improved infrastructure, the noise is much higher than I
would like. But it seems clear that *some* prefetching is a significant
win. It also seems like enabling both results in too much prefetch
traffic. And the entry group prefetch appears to be significantly more
effective, both for the most interesting of the microbenchmarks and
maybe most importantly for our compilation benchmarks. There, AMD is
helped substantially and M1 seems to be helped some (although harder to
measure).

AMD server benchmark numbers:
```
name                                              old cpu/op   new cpu/op   delta
BM_CompileAPIFileDenseDecls<Phase::Lex>/256       35.0µs ± 2%  34.2µs ± 2%  -2.40%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/1024       156µs ± 2%   151µs ± 2%  -3.18%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/4096       625µs ± 1%   605µs ± 1%  -3.22%  (p=0.000 n=19+18)
BM_CompileAPIFileDenseDecls<Phase::Lex>/16384     2.79ms ± 1%  2.69ms ± 2%  -3.67%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/65536     12.1ms ± 1%  11.6ms ± 1%  -4.30%  (p=0.000 n=17+18)
BM_CompileAPIFileDenseDecls<Phase::Lex>/262144    56.6ms ± 1%  53.8ms ± 1%  -5.00%  (p=0.000 n=18+17)
BM_CompileAPIFileDenseDecls<Phase::Parse>/256     61.1µs ± 2%  61.7µs ± 1%  +0.87%  (p=0.000 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024     288µs ± 1%   290µs ± 1%  +0.55%  (p=0.004 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096    1.16ms ± 1%  1.16ms ± 1%  -0.54%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384   4.98ms ± 1%  4.91ms ± 1%  -1.39%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536   20.9ms ± 1%  20.5ms ± 1%  -1.86%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144  92.1ms ± 1%  90.2ms ± 1%  -2.12%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/256     1.16ms ± 2%  1.16ms ± 1%    ~     (p=0.931 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024    2.17ms ± 2%  2.16ms ± 1%    ~     (p=0.247 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096    6.07ms ± 1%  6.04ms ± 1%  -0.48%  (p=0.007 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384   22.4ms ± 1%  22.2ms ± 1%  -0.99%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536   93.3ms ± 1%  92.2ms ± 1%  -1.23%  (p=0.000 n=20+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144   400ms ± 1%   391ms ± 1%  -2.15%  (p=0.000 n=20+18)
```
2024-11-26 10:14:14 +00:00
4ba6a6efc1 Link to video for 2024 CppNorth talk (#4578)
* Change format:
  * previously there was a single link per talk, the video if available
  * now there are separate "video" and "slide" links
* Adds link to video for 2024 CppNorth talk
* Adds link to slides for 2024 LLVM Developers' Meeting
* Restores links to slides from past years

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-11-26 02:03:54 +00:00
josh11bandJosh L 01ea408d75 Simplify logic in StringifyTypeExpr using push_string (#4561)
Follow-on to #4511.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-26 01:59:55 +00:00
Richard Smith c0faa81961 Switch most of ImportRefResolver to non-member functions (#4584)
In preparation for further refactoring, switch away from member
functions for most of `ImportRefResolver`.

Split `ImportRefResolver` into a context class that exposes the value
stores for the source and destination files, and a derived class that
maintains a worklist. The idea is to statically enforce that functions
that take `ImportContext` cannot accidentally add new work, because they
don't have access to the work queue.
2024-11-26 01:44:59 +00:00
josh11bandJosh L ed80cd2f15 Facet member access (#4371)
Adds `FacetAccessWitness` instruction and uses it in `member_access.cpp`
to support accessing members of facets. Still to do: interface witness
access is producing runtime values when it should produce symbolic
values.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-26 01:12:46 +00:00
josh11bandJosh L 0b209c3fbc Make facet type deduction more restrictive and correct (#4589)
Previously it would allow interface mismatches. We only need to support
the case where there is a single interface, though, which makes checking
much more straightforward.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-25 23:50:56 +00:00
josh11bandJosh L d5e022d53c Mark instructions that can be deduced through in typed_insts.h (#4588)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-25 23:50:41 +00:00
Dana JansensandRichard Smith 2cb6507392 Update idioms.md with changes to match the code now (#4587)
- Rename TypedInstArgsInfo references to InstLikeTypeInfo. The type was
renamed in 07efa026de.
- Update and correct the link to search for ValueStore (and similar) in
the Context class. We must avoid the google-doc-style checks rewriting
`repo:` to `repository:` in the URL.
- Mention the existance of many types of Store collections now.
- Remove pre-C++20 idioms in Field detection. Correct the concept based
idioms to work.
- Fix code indenting consistency.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-11-25 20:09:17 +00:00
Dana Jansens dcfdf12315 Refresh the ValueStore api description in idioms.md (#4586)
There is no `Set` method, so remove that, and include `AddDefaultValue`
instead.
2024-11-25 17:54:54 +00:00
Dana Jansens e09bf82d36 Update links to the DiagnosticConsumers (#4580)
The ConsoleDiagnosticConsumer and ErrorTrackingDiagnosticConsumer have
moved to new places.
2024-11-25 05:52:38 +00:00
David Blaikie b15875e302 element index init with vptr (#4565)
Not sure if this is the most robust way to do it - I guess the
alternative is doing name lookup into the dest struct fields too?
2024-11-23 01:02:43 +00:00
Jon Ross-Perkins 0278973bbf Remove vim swap files (#4581)
Trying to make the .gitignore a little more broad. Accidentally added in
#4553, I'm guessing as part of the force-push.
2024-11-22 21:05:00 +00:00
Geoff RomerandJon Ross-Perkins 4f816dd03f Remove param_refs and implicit_param_refs (#4479)
This introduces `calling_convention_param_ids`, a single block that
consolidates all the information that was being used by consumers of
`param_refs` and `implicit_param_refs`, in a form that's easier to
produce and typically easier to consume.

See also [this Discord
discussion](https://discord.com/channels/655572317891461132/655578254970716160/1300545448909738125)
regarding the decision to keep the return slot last in the SemIR calling
convention, even though it goes first in the LLVM calling convention.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-22 18:34:21 +00:00
Jon Ross-Perkins 17272cf93c Change how CheckParseTrees receives NodeLocConverters (#4563)
This is really a set of closely related changes:

1) We really shouldn't be creating a Check::Unit for _Lower_. This fixes
that by storing the diagnostic converter for reuse.
2) Rather than passing in node converters to Check as their own array,
pass diagnostic converters as part of Check::Unit.
3) To support creating the converters early, pass SemIR::File
pre-constructed.
4) Since SemIR::File construction was used to track "checked", add
`is_checked` for that.
5) Clarifies a subtle edge case around `input_filename_` use with `-`.

Note the key consequence of this change, where I actually started, is
that `Check` only has one array of `Check::Unit` instead of receiving
`NodeLocConverter` as a separate array.
2024-11-22 16:51:10 +00:00
Dana Jansens 77689c4a72 Suppress unused-includes in clangd for false positives (#4573)
clangd-17 reports includes as being unused when they are used, such as
in common/ostream.h. There it says the `<concepts>` include is unused
but `std::derived_from` is present in the same file (and clangd points
out that it is coming from `<concepts>` on hover).
2024-11-22 16:32:46 +00:00
Chandler Carruth b08fefc896 Change the test timeouts for the benchmarks to moderate. (#4570)
After some poking, it would take a more significant change to
restructure the string generation to take less time when run under ASan,
and it's not worth it at the moment.

For future reference, nearly half the time here is in building the
global data structures of random string contents, not in the actual
benchmark functions. If/when we want to improve this, we should switch
to a growing pool of random strings similar to what `SourceGen` uses.
That lets it not allocate the full size of data when just testing that
the benchmark doesn't crash.

I thought about having these benchmarks switch to use `SourceGen`, but
I'd like to keep them stand-alone if easy, and there are some important
differences that would have to be adapted around which wouldn't be
trivial. I'd rather come back in with a better generation strategy than
re-use the source code one here.
2024-11-22 16:26:54 +00:00
Boaz Brickner bbd8b55be2 Clarify what specific name in the Core package is looked for when diagnosing that the Core package is not found (#4571)
I believe this makes the error easier to understand.
2024-11-22 15:48:18 +00:00
d870e0bd7c Remove links to weekly sync and open discussion as these docs weren't updated for 2 years and link the Minutes folder instead (#4554)
These docs do not seem to be the standard entries anymore given than
it's been 2 years since they were used.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-11-22 10:51:16 +00:00
Jon Ross-Perkins be5db6e1cd Remove labels from the builtin inst kind macro (#4558)
This is stamping out the per-instruction structs, similar to what we do
elsewhere. `BuiltinInstKind::label` then finishes shifting to
`InstKind::ir_name`.
2024-11-22 00:59:49 +00:00
josh11bandJosh L e42b377cf6 Fix comment in test (#4569)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-22 00:48:50 +00:00
Chandler Carruth 637539726d Switch to our custom benchmark main. (#4567)
I'm working on speeding up the benchmark tests and noticed they weren't
using our main, seemed worth cleaning that up.
2024-11-22 00:46:09 +00:00
67f2c9ce26 Add a FacetValue instruction (#4545)
The new `FacetValue` instruction represents `C as I` for some type `C`
and facet type `I`. It is named `FacetValue` instead of just `Facet` to
parallel the `FacetType` instruction.

This PR uses this instruction represent the facet value `Self` in an
`impl` declaration. This instruction will be used in the future to also
support things like:

* `C as I` where `C` is a class; and
* forming a specific for a generic with a `T:! I` parameter where `T` is
being given a concrete value.

(Here `I` is an interface or other non-`type` facet type.)

Also do some renaming and add some comments to make things a bit more
clear.

* `FacetTypeAccess` -> `FacetAccessType` to clarify this is not access
of a facet type, but access of the type of a facet
* `.facet_id` -> `.facet_value_inst_id` to parallel the `FacetValue`
instruction

`FacetAccessWitness` will be in a future PR.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-11-21 22:29:53 +00:00
Richard Smith 5e4038048b Import the full list of extended scopes. (#4562)
Replace the special case adding the base class to the list of extended
scopes with a fully general approach. We use an ImportRef to lazily
import the extended scopes on first lookup.
2024-11-21 20:56:39 +00:00
Dana Jansens 4cf2c07f7d Explain more on the difference of where constraints (#4551)
This adds language to explain where the types of constraints can or can
not appear (attached-to an impl-as vs in-a type expression). And
describes the impact of using a rewrite vs same-type constraint inside
the body of the affected code, and thus why a rewrite is preferable when
the constraint is of a single facet type.
2024-11-21 18:33:17 +00:00
Jon Ross-Perkins 79b9180eff Adds per-builtin instructions, removing BuiltinInst (#4556)
Adds per-builtin instructions, removing `BuiltinInst`. This collapses
`builtin_inst_kind.def` into `inst_kind.def` so that we have a single
place for all macro uses. I still want to remove `BuiltinInstKind`, but
it's something I think is better separated from the `BuiltinInst`
removal.

I'm collapsing the build targets `ids` and `inst_kind` into one because
they both have links to builtin kind information now. It's hard to
separate without a cycle. I'm using the `typed_insts` name because that
seems like the actual most significant thing there, and more interesting
relative to the `inst` target.
2024-11-21 00:48:24 +00:00
David BlaikieandJon Ross-Perkins ffbcfc4dfc Reject/error on base declarations that appear after field declarations (#4553)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-20 23:46:39 +00:00
Jon Ross-Perkins 16bf3f710e Split deferred node traversal out from check.cpp (#4559)
I'm looking at adding more significant logic to checking, particularly
for interop. But check.cpp is getting large, and I think just adding
more logic will make it harder to reason about, so I'm looking at
splitting it up. This moves out NodeIdTraversal and
DeferredDefinitionWorklist because they're already independent from the
other code, and are reasonably sized to have their own files.
2024-11-20 20:58:58 +00:00
Jon Ross-Perkins 493d766a97 Have sh_test directly invoke benchmarks (#4552)
These tests typically take 10-20s, but I'm seeing some timeouts
[here](https://github.com/carbon-language/carbon-lang/actions/runs/11899548036/job/33158400417).
This seemed particularly suspicious due to the _absence_ of output
(copied below). That got me looking, and maybe the subprocessing tickles
a cpu bottleneck, so proposing this approach to remove the exec. Even if
this doesn't solve the flakiness, I think it's a simpler implementation.

Note I believe this is intended to work. The `sh` rules rely on shebangs
(as noted at https://bazel.build/reference/be/shell#sh_test), and are
essentially just subprocessing to the input. Note this could've also had
`args` on a `cc_test` rule, but I'd expect the same args to be passed to
`run` where instead the benchmark behavior should be default (and I'm
assuming you'd rather not have args there). Fundamentally this becomes a
symlink:

```
bazel-bin/common/map_benchmark_test -> .../execroot/_main/bazel-out/k8-fastbuild/bin/common/map_benchmark
```

Copying snippet from timeout below:

```
==================== Test output for //common:map_benchmark_test:
      /private/var/tmp/_bazel_runner/e591f63ed099023de1f206992dfce127/execroot/_main/bazel-out/darwin_arm64-fastbuild/testlogs/common/map_benchmark_test/test.log
-- Test timed out at 2024-11-18 19:32:13 UTC --
INFO: From Testing //common:map_benchmark_test:
================================================================================
```
2024-11-20 19:00:37 +00:00
Jon Ross-Perkins 4a80d6758d Rename the builtin FloatType to LegacyFloatType, Error to ErrorInst (#4555)
This is for more clearly distinct names, and to make it a clearer
transition from `BuiltinInst` for name conflicts. `FloatType` is also an
instruction, and we have `Carbon::Error` (common/error.h). This avoids
affecting tests, although the name is embedded in the builtin test.

In `LegacyFloatType`, `Legacy` because I was having trouble coming up
with a more appropriate name. I'm not clear this is a `FloatLiteralType`
at present, it needs some work to mirror `IntLiteralType`.

In `ErrorInst`, the suffix `Inst` was discussed as good and similar to
`BuiltinInst` (although I'm trying to get rid of that).
2024-11-19 20:37:39 +00:00
Richard SmithandJon Ross-Perkins e2ae5f212c Remove the special case for i32. (#4543)
For the few remaining uses of the builtin `i32` type, manually build an
`IntType(Signed, 32)` value instead. These are:

- The return type of `Run`.
- The type that int literals in an `if` expression are converted into.
- The type of an array index expression.

We should consider converting those three cases away from `i32` over
time.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-18 23:19:36 +00:00
Jon Ross-Perkins b5368b3078 Change prettier to a direct node use. (#4550)
The prettier pre-commit mirror is no longer supported
(https://github.com/pre-commit/mirrors-prettier). This switches to a
direct call, and updates to 3.3.3. And I'm now specifying types for it
to apply to, rather than letting it ignore unknown files; overall just
trying to separate out which linter sees what.

To comment on formatting changes:

- In most cases, seems to be getting confused by `[]` use in markdown
when it's not part of a link. This looks like a regression, but not one
we're broadly affected by.
- p0107.md - caught an issue with a malformed broken bad link which I've
tried to fix.
- p3720.md - looks like a fix.

Note, prettier has a 4.0.0 alpha release. As best as I could tell, that
only affected the .prettierrc.yaml processing. I changed the glob there
for forwards compatibility.
2024-11-18 23:02:10 +00:00
Jon Ross-Perkins 4eb955bf42 Drop std:: on size_t in various spots. (#4546)
We predominantly omit the `std::` in these cases already. This is for
style: "Prefer to omit the std:: prefix for these types, as the extra 5
characters do not merit the added clutter."
(https://google.github.io/styleguide/cppguide.html#Integer_Types)
2024-11-18 22:28:57 +00:00
Jon Ross-Perkins d8ecc72d9d Update pre-commit config (#4549)
Skipping prettier because the relevant repo is archived and not working
well. Issues being fixed are from codespell.
2024-11-18 21:29:30 +00:00
josh11bandJosh L 47bfa375af Propagate llvm::vfs::FileSystem from driver_env to Clang (#4537)
As discussed in #4530 . This required switching to using
`llvm::IntrusiveRefCntPtr` in a number of places.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-18 18:24:19 +00:00
Dana Jansens 825714f06b Use a single = in 'impl as where' to assign an associated constant (#4548)
This was written as `==` but is inconsistent with the rest of the
documentation for assigning associated constants.
2024-11-18 17:22:17 +00:00
Dana Jansens f2479321fc Correct name of ComparableFromDifference in Generics details (#4547)
The name ComparableFromDifferenceFn comes from the next example. In this
example ComparableFromDifference is the name of the class that will be
implictly cast to a Facet matching Comparable.
2024-11-18 17:18:59 +00:00
Dana Jansens cb94609889 Suppress readability-redundant-member-init (#4538)
This initializes the DriverResult::per_file_success field explicitly
with `= {}` in order to encode that DriverResult can be constucted via
aggregate initialization while omitting the per_file_success field. This
prevents -Wmissing-designated-field-initializers from firing in newer
clang versions when constructing DriverResult like:
```
return {.success = false};
```

Newer clang-tidy warns that the `= {}` is redundant however it is not,
as its marking which fields need to be explicitly initialized. So we
suppress it.
2024-11-18 16:38:46 +00:00
Richard Smith 145f878ce8 Allow extend adapt of non-class types. (#4544)
Stop rejecting `extend adapt` of non-class types such as struct and
tuple. These don't actually work just yet because name lookup into
struct and tuple types is a special case that doesn't handle adapters,
but this gets us a bit closer.

This also slightly improves error recovery for name lookup into an
invalid scope.
2024-11-18 16:01:44 +00:00
Richard Smith bc395eb889 Represent integer literals as IntLiteral not as i32. (#4532)
When an `IntLiteral` appears as an operand of an `if` expression,
convert it to `i32` for now, so that we don't reject things like `if
cond then 1 else 2` due to having a non-constant value of type
`IntLiteral`.

For tuple indexing expressions such as `(a, b).0`, convert the index to
type `IntLiteral`, not to type `i32`. This isn't strictly necessary to
do in this PR, but avoids the need to provide an `IntLiteral` -> `i32`
implicit conversion for `no_prelude` tests using this syntax.
2024-11-15 23:24:15 +00:00
Richard Smith 980ce6b25a Convert array bounds to IntLiteral. (#4526)
Instead of leaving array bounds as whatever integer type they arrive as,
convert them to the `IntLiteral` type as part of forming an `ArrayType`.
This ensures that array types canonicalize properly even when the bounds
are specified with different types.

Create an empty generic definition for a generic builtin function to
avoid this causing "use of undefined generic function" errors.
2024-11-15 22:09:31 +00:00
Dana Jansens a65cde6ae2 Use llvm::any_of instead of std::ranges::any_of (#4542)
We do not intend to use std::ranges in the Carbon implementation due to
concerns of compile time cost, largely due to implicit instantiation of
types involved in calling and typechecking the functions and their
requires clauses.

In #4539, we converted std::any_of to std::ranges::any_of, but this
replaces that with llvm::any_of from llvm/ADT/STLExtras.h.

This conversion was suggested by the modernize-use-ranges clang-tidy
check. We can keep the check on, and use it to guide conversion to llvm
helpers that do similar things (as was done in this CL now). If it's
being too confusing, then it can be disabled as well.
2024-11-15 21:59:32 +00:00
Jon Ross-Perkins 86a057b820 Add blank lines betweeen EntityWithParamsBase members. (#4536)
This is at a point where it's getting difficult to read, and #4479 is
adding a large block comment. In order to more clearly delineate
members, add blank lines between.
2024-11-15 21:53:36 +00:00
Richard Smith ff530305d1 Add prelude support for implicit conversion between integer literals and sized integer types. (#4525)
In preparation for changing integer literals to be of `IntLiteral` type.
Conversions from the integer literal type are only permitted when the
value fits within the destination type.

For now, if conversion cannot be checked because the source value is a
symbolic constant, produce a symbolic constant representing the
conversion rather than rejecting it.
2024-11-15 21:46:14 +00:00
Jon Ross-Perkins c2ff865700 Reconstruct rational for disabled clang-tidy checks. (#4541)
Commenting on danakj's clang-tidy PRs, it would've been helpful to just
have a quick reference for older checks. So while I've been getting
comments for new things, go back and comment the ones that predate
adding per-check comments.

I did this mainly by running clang-tidy and seeing whether we could
re-enable them, thus also fixing the clang-tidy wrapper script.

Adding backticks to try to make it easier to scan.
2024-11-15 21:17:27 +00:00
4ee65ef58a Reduce the size of formatted SemIR. (#4534)
- Do not include entities imported from files that we are not dumping.
- Do not include constants and import_refs that are not referenced by
something that we are including in the formatted output.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-11-15 21:00:26 +00:00
Dana Jansens 3c18a6c477 Suppress readability-enum-initial-value in clang-tidy (#4540)
This warns unhelpfully on enums like:

```
enum Kind: int8_t {
  Value,
  ValueOrRef,
  ...
  FullInitializer,
  Last = FullInitializer
};
```

It claims that all enum values should have explicit values if any of the
values do, but that's not what we would want to write here.
2024-11-15 20:02:03 +00:00
Dana Jansens 9112053cee Use std::ranges::any_of instead of std::any_of (#4539)
This is suggested by clang-tidy's modernize checks, and is a safer
coding practice.
2024-11-15 19:51:21 +00:00
Jon Ross-Perkins 1d8c7ffe89 Add support for scoped timings. (#4533)
I think there are a few related ways to do this. I considered
llvm::make_scope_exit, but the return type is difficult to work with. I
particularly was thinking I could encapsulate the duration logic this
way.
2024-11-15 16:57:33 +00:00
Jon Ross-Perkins fe5d3cecbd Try running 'bazel cquery //...' before target-determinator (#4531)
Trying to improve robustness against failures such as
[here](https://github.com/carbon-language/carbon-lang/actions/runs/11845529962/job/33011203628):

```
WARNING: Download from https://ftp.gnu.org/gnu/m4/m4-1.4.18.tar.xz failed: class java.net.ConnectException Connection refused
```

Which is coming from the target-determinator invocation:

```
subprocess.CalledProcessError: Command '['/home/runner/.cache/carbon-lang-scripts/target-determinator', '--bazel=/usr/local/bin/bazelisk', 'a720921dfb99c21f08832663c91a1f9e48a1bcc4']' returned non-zero exit status 1.
```

My thought is that the `bazel cquery` should trigger equivalent
downloads (equally though, I'd thought the `bazel mod deps` would do
that, so I don't want to give the impression of confidence).

It's harder to inject this into the target-determinator command line,
since we'd need something that retries by default.
2024-11-15 01:01:24 +00:00
josh11bandJosh L 93169c30b1 Update LLVM (#4530)
Includes updates to reflect these LLVM changes:
* https://github.com/llvm/llvm-project/pull/112517
* https://github.com/llvm/llvm-project/pull/113331

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-15 00:09:10 +00:00
Jon Ross-Perkins b2ea19f269 Add a small lowering test with an imported argument. (#4529)
We don't have much import coverage at present, but this seems worth a
tiny bit of validation. I believe the LLVM IR is currently correct.
2024-11-14 21:16:46 +00:00
Jon Ross-Perkins a720921dfb Test an absolute symlink (#4528) 2024-11-14 18:48:26 +00:00
Jon Ross-Perkins c59faea0e8 Fix up busybox detection for relative symlinks (#4522)
Handling for relative symlinks is new (comment talks about relative
symlinks). Relocated to add tests though, to do extra checking of logic.
2024-11-14 17:13:01 +00:00
Richard Smith cbd88e5c72 Add builtin for performing checked conversion between integer types. (#4523)
As a prerequisite for switching the type of int literals to be the
`IntLiteral` type, add support for performing conversions of in-bounds
integer constant values to other integer types in which they fit.

This incidentally is our first compile-time-only builtin function, so
add very minimal support for compile-time-only functions while we're
here.
2024-11-14 00:27:40 +00:00
josh11bandJosh L abd12c18c7 Support extended scopes that are parameterized types (#4524)
* The `extended_scopes` in a `NameScope` were represented by a
`NameScopeId`. Replace that with an `InstId` of an instruction returning
the type that is extending this name scope.
* `Context::LookupQualifiedName` now can take multiple scopes to look
in.
* `GetAsLookupScope` was moved out of `member_access.cpp` and is now
`Context::AppendLookupScopesForConstant`

This PR also fixes some existing issues that were revealed as part of
writing and testing this PR:
* Additional validation and handling of invalid ids.
* `extend impl` in a class is not properly imported yet, but at least
now it doesn't crash.

The change to use an `InstId` also allowed some diagnostics and
formatting to be improved.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-13 23:48:02 +00:00
Jon Ross-Perkins 5e293ad97f Fix bazel-bin invocations of run_tool (#4521)
SCRIPT_LOCATION contains `bazel-out`, so this drops the portions shared
between the script and tool locations before removing the suffix.
2024-11-13 18:16:49 +00:00
Chandler Carruth f17939e252 Follow-up to #4487 to fix file names (#4520)
This switches from `int_store*` to `int*` as this file contains both the
ID and the store for integers.

This was supposed to be added to #4487 before merging, apologies for
missing that.
2024-11-13 18:10:52 +00:00
Jon Ross-Perkins fa95892a37 Add diagnostic coverage, remove possibly-unreachable unary op diagnostic (#4519)
I'm working to make sure remaining diagnostics have coverage, at least
the ones I'd previously added a TODO for. Note in particular that I
couldn't figure out a repro for UnaryOperatorRequiresWhitespace; if you
have one, I can add a test, but otherwise maybe it's actually
unreachable due to being diagnosed through infix logic (or, maybe
this'll let fuzzing tell me an example).
2024-11-13 18:04:25 +00:00
3ba4997855 Canonicalize away bit width and embed small integers into IntIds (#4487)
The first change here is to canonicalize away bit width when tracking
integers in our shared value store. This lets us have a more definitive
model of "what is the mathematical value". It also frees us to use more
efficient bit widths when available, such as bits inside the ID itself.

For canonicalizing, we try to minimize the width adjustments and
maximize the use of the SSO in APInt, and so we never shrink belowe
64-bits and grow in multiples of the word bit width in the
implementation. We also canonicalize to the signed 2s compliment
representation so we can represent negative numbers in an intuitive way.

The canonicalizing requires getting the bit width out of the type and
adjusting to it within the toolchain when doing any kind of math, and
this PR updates various places to do that, as well as adding some
convenience APIs to assist.

Then we take advantage of the canonical form and embed small integers
into the ID itself rather than allocating storage for them and
referencing them with an index. This is especially helpful for the
pervasive small integers such as the sizes of types, arrays, etc. Those
no longer require indirection at all. Various short-cut APIs to take
advantage of this have also been added.

This PR improves lexing by about 5% when there are lots of `i32` types.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-13 09:36:20 +00:00
josh11bandJosh L 39ed62dad7 Add facet_types() accessor to Check::Context (#4518)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-13 01:20:07 +00:00
Sam EstepandJon Ross-Perkins e0e305536e Collect timing data per unit for each phase (#4512)
This PR adds a `--dump-timings` flag to the `compile` subcommand
(similar to the existing `--dump-mem-usage` flag), which collects timing
data per compilation unit for each compilation phase. For example, on my
2020 M1 MacBook:

```
$ bazel build -c opt //toolchain
$ bazel-bin/toolchain/install/run_carbon compile --phase=lower --dump-timings examples/sieve.carbon | tail
...
---
filename:        'examples/sieve.carbon'
nanoseconds:
  lex:             30792
  parse:           25458
  check:           226625
  lower:           1136958
  Total:           1419833
...
```

Most of the changes are pretty straightforward. There were a couple I
wasn't sure about though; let me know if I should change:

- new `Timings` class in its own file, pretty similar to the existing
`MemUsage` class
- added a `timings_` field to the `CompilationUnit` class
- added a `timings` field to the `Check::Unit` struct
- renamed `CheckParseTree` function to `CheckParseTreeInner` for ease of
timing with early `return`

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-12 20:47:08 +00:00
josh11bandJosh L 3824c5fd30 Look in libraries associated with the interface (#4510)
This was broken by #4499 .

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-12 20:35:32 +00:00
josh11bandJosh L ada9564077 Add missing #include (#4513)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-12 16:53:41 +00:00
David Blaikie 79c5c47911 Preserve the is_dynamic property of classes when importing them (#4501)
The test update shows a class derived from an imported base class with a
vptr, and without this change the derived class got its own vptr, with
this change the derived class can see the base is dynamic, so the
derived doesn't need to add a vptr and can rely on the base class's vptr
instead.
2024-11-12 16:11:19 +00:00
Richard Smith 0a6321f492 Include the arguments for a generic class or interface in diagnostics. (#4511)
This can lead to us trying and failing to print certain kinds of
constant value, but we can fix that in future changes.

Note that `StringifyType` should probably be substantially refactored.
For this change I'm trying to leave the overall structure relatively
intact, but hopefully this additional formatting support will help guide
future refactorings.
2024-11-12 01:47:33 +00:00
Richard Smith de9b7d282a Fix use-after-free printing the name of an interface that might have been invalidated by lazy import. (#4509)
While here, also change the diagnostic emission to pass the interface
type rather than the interface name. This prepares us to include the
arguments in the diagnostic.
2024-11-12 00:50:10 +00:00
josh11bandJosh L 4f474fafb5 Remove some single-interface restrictions from some uses of facet types (#4508)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-12 00:43:45 +00:00
Richard Smith 2c1d02d991 Don't eagerly materialize an initializing expression used as the object in a compound member access. (#4496)
Instead, wait until we know whether it is used as a value or reference
expression. This allows us to avoid materializing a temporary if it is
used as a value and the initializing representation holds a copy of a
value representation.
2024-11-11 21:32:33 +00:00
a69c2630f9 Replace InterfaceType with FacetType (#4499)
This does a few things:
* Replaces the single `TypeId` in the `FacetTypeInfo` struct with a
vector of `InterfaceId`, `SpecificId` pairs (sorted in id order)
representing the set of interface requirements of the facet type. This
will later be used to support facet types with multiple interface
requirements (as in `I & J` or `I where .Self impls J`).
* Replace `InterfaceType` instructions (used as the type of an
`InterfaceDecl` instruction) with `FacetType` instructions (introduced
in #4460) with a (newly introduced) `FacetTypeFromInterface()` function.
* Replace code that consumed `InterfaceType` values with code that
consumed `FaceType` values. I've generally left the assumption in the
code that it is dealing with a single interface, using the (newly
introduced) `FacetTypeInfo::TryAsSingleInterface`, and producing an
error otherwise. There isn't yet support for the `&` operator or `where
.Self impls`, so this is generally a good assumption for now, except you
can get a facet type with no associated interfaces from a `type
where`... expression. In some cases, the facet type value is pulled from
the evaluation of an `InterfaceDecl` instruction, where the single
interface assumption will hold permanently.
* Some related cleans up: nicer stringification and formatting of facet
types, suppression of some errors when there already was an error.

There is still a lot left to do, including:
* Type `type` should be a facet type with a reserved id, replacing the
built-in instruction.
* Code using `TryAsSingleInterface` should generally be upgraded to
handle more than (or less than) one interface. Name lookup should be
particularly exciting.
* Operator `&` should be defined on facet types, unioning their
interface and other requirements.
* Requirements from a `where` clause don't do anything yet.
* Impls and impl lookup need to resolve facet types, and do things like
determine if all the associated constants are given values.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2024-11-11 18:01:50 +00:00
Jon Ross-Perkins 6dce164c49 Change the bazel-out structure to avoid busybox symlinks. (#4505)
As described in symlink_helpers.bzl, copied here for visibility:

Symlinking busybox things needs special logic.

This is because Bazel doesn't cache the actual symlink, resulting in
essentially resolved symlinks being produced in place of the expected
tool. As a consequence, we can't rely on the symlink name when dealing
with busybox entries.

An example repro of this using a local build cache is:

    bazel build //toolchain
    bazel clean
    bazel build //toolchain

We could in theory get reasonable behavior with
`ctx.actions.declare_symlink`, but that's disallowed in our `.bazelrc`
for cross-environment compatibility.

The particular approach here uses the Python script as a launching pad
so that the busybox still receives an appropriate location in argv[0],
allowing it to find other files in the lib directory. Arguments are
inserted to get equivalent behavior as if symlink resolution had
occurred.

The underlying bug is noted at:
https://github.com/bazelbuild/bazel/issues/23620
2024-11-08 22:08:50 +00:00
Geoff Romer db43bb1b42 Replace FIXME with TODO in toolchain code (#4506) 2024-11-08 21:10:30 +00:00
Geoff RomerandRichard Smith 5759ad8b42 Remove forward references from binding patterns (#4494)
This is primarily to free up space in the BindingPattern insts, but as a
side effect it moves the link between BindingPattern and its BindName
out of the SemIR, and into a transient data structure in Context.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-11-08 20:18:22 +00:00
Jon Ross-Perkins 10e256a241 Name empty tuples distinctly in SemIR. (#4503)
Building on #4502, give empty tuple values a distinct name, and also
explicitly name tuple types (previously values but not types were
named).
2024-11-08 17:14:52 +00:00
josh11bandJosh L bbeb66b5fe Test class with multiple extend (#4504)
Adds coverage for an existing diagnostic. Code appears to work without
modification.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-08 16:29:53 +00:00
Jon Ross-Perkins cab7818df8 Make empty ids for all block types (#4502)
Adding empty IDs to all block types. This is primarily for
TypeBlockId::Empty, which allows me to disambiguate empty tuple types,
which I think might yield a SemIR readability improvement (PR
forthcoming). I'm splitting PRs so that the limited test impact here is
clear.
2024-11-07 22:46:22 +00:00
josh11bandJosh L caba03d27e Support deduction of the types of struct fields (#4500)
Follow-on to #4492 .

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-07 21:25:49 +00:00
Jon Ross-Perkins 138ecf108f Remove verbose formatting of instructions on crash messages. (#4495)
Undoes a chunk of #4125 because nobody's really in favor of keeping the
formatting, and it's occasionally caused a crash in Formatter to
dominate output (and even when working, it can be verbose; the source
location in (5) is often more helpful).

Basically goes back to:

```
4.	Check::Context
          NodeStack:
            0. LetIntroducer: no value
            1. BindingPattern: inst+15
            2. LetInitializer: no value
            3. StructLiteralStart: no value
          inst_block_stack_:
            0.	block<invalid>	{inst+0, inst+1, inst+6, inst+7, inst+8, inst+9, inst+10, inst+11, inst+12}
            1.	global_init	{}
          pattern_block_stack_:
            0.	block<invalid>	{}
          param_and_arg_refs_stack:
            0.	block<invalid>	{}
          args_type_info_stack_:
            0.	block<invalid>	{}
5.	alias_of_alias.carbon:15:12: checking StructLiteral
          let d: c = {};
                     ^~
```

Fixes #4145
2024-11-07 16:22:36 +00:00
Jon Ross-Perkins be56ff87c6 Convert StructTypeField to a specific type. (#4492)
This converts `StructTypeField` from an instruction to a dedicated type,
with its own store. This had originated from discussing how
`.GetAs<SemIR::StructTypeField>` was more prevalent than for other
instructions, but is probably more interesting for the storage savings
(16 bytes StructTypeField + 4 byte LocId + 4 byte InstId -> 8 byte
StructTypeField).

Due to the different structure, these now have their own stack during
construction, reducing (but not eliminating) `args_type_info_stack_`
use-cases.

The test changes of different InstIds is expected because structs and
classes generate fewer instructions now. Other than that, results should
remain the same.

I'm generally trying to avoid unrelated cleanup here due to the PR size,
though I did scrutinize the `VerifyOnFinish` calls, adding one and
commenting others (putting them in member order because that's how I was
checking what was verified and what wasn't).
2024-11-06 21:38:27 +00:00
Jon Ross-Perkins 7977a9cddc Fix the command used for nightly release versions. (#4498) 2024-11-06 21:04:30 +00:00
David Blaikie d79a374ad4 Skip vptr when performing object initialization (#4490)
The cehck for vptr could be done differently (is this class dynamic and
its base class non-dynamic), and if we change the layout (to put the
vptr after any base) then this code will break (could add an assertion
that the vptr isn't present apart from at the start of the field list if
that'd seem worthwhile).

There's still later issues with lowering (if this patch causes crashes
in lowering, do they result in fuzz failures/need to be avoided before
this change is submitted?)
2024-11-06 18:27:40 +00:00
Richard Smith fcabeb6725 Don't create instructions for implicit constants. (#4497)
When an instruction is created as part of an implicit call to an
interface member, we generated a bunch of constants for naming the
interface, finding the corresponding specific, accessing its member
function, and so on. This led to significant bloat in SemIR.

Instead, we now track whether an instruction is created implicitly in
its location, and where relevant, we use the constant value of the
instruction directly instead of storing a new `Inst`.

This doesn't reduce the amount of work we need to do, but does make the
representation in SemIR smaller and more readable.
2024-11-06 15:44:56 +00:00
Jon Ross-Perkins 9aae9de43c Clean up some CopyOnWriteBlock details (#4493) 2024-11-06 02:23:51 +00:00
Richard Smith a68acb1975 Fix crash lowering an imported impl method. (#4489)
While we don't need a lookup table for an imported impl from a different
library, we do still need to import the name scope so we can compute the
parent scope for mangling purposes.
2024-11-05 20:38:26 +00:00
Richard Smith 2bcd4659f3 Don't copy maps and sets when computing their memory usage. (#4491)
Also use the `Impl` base class to type-erase the small size of
`SmallVector`. (I'd like to do the same for `Map` and `Set` by using
`MapView` and `SetView`, but that runs into ambiguities due to
`BumpPtrAllocator`'s unconstrained converting constructor.)
2024-11-05 20:37:22 +00:00
Dana Jansens 361efa90a8 Always call MemUsage::Collect to collect metrics from a field (#4480)
Previously Collect() was used for types that implemented
CollectMemUsage() but otherwise Add() was used. This required the caller
to think about the type of the field and know/decide which method to
use.

Now, the caller always uses Collect() unless they are adding specific
byte values, in which case Add is used. Typically then, Add will only be
used to implement the CollectMemUsage() function.

To do this we require all Collect() methods to be templates so that they
all be a single overload set. The Collect on BumpPtrAllocator is
converted to a template that checks
`std::same_as<llvm::BumpPtrAllocator, T>`.
2024-11-05 19:31:14 +00:00
Sam Estep f03bd6a89b Set .python-version to 3.10 for pyenv users (#4456)
The contribution docs for macOS say to install Python 3.10:


https://github.com/carbon-language/carbon-lang/blob/957599b2ab036d01b325aa6e82edea0fce7b4c53/docs/project/contribution_tools.md#L118-L124

For people who are using [pyenv](https://github.com/pyenv/pyenv) instead
of Homebrew Python, this PR adds a `.python-version` file to specify
Python 3.10 for pyenv to use.

However, I also see that later in the same document, the docs only say
that Python >=3.9 is required:


https://github.com/carbon-language/carbon-lang/blob/957599b2ab036d01b325aa6e82edea0fce7b4c53/docs/project/contribution_tools.md?plain=1#L162

So in that case, feel free to just close this PR. I also saw that #778
specifically moved Carbon away from pyenv, so if pyenv is discouraged in
general, also feel free to just close this.
2024-11-05 17:37:15 +00:00
josh11bandJosh L 534100e87b Add test coverage for ImplOfUndefinedInterface diagnostic (#4484)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-05 16:31:32 +00:00
josh11bandJosh L 4febf7c459 Add capitilization and punctuation to TODO comments (#4486)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-05 16:31:00 +00:00
Richard Smith 9c8ca2f6e9 Don't track generic insts created while importing an impl. (#4485)
Fixes a crash when we unexpectedly find a symbolic binding is created in
a non-generic entity.
2024-11-05 02:55:17 +00:00
Richard Smith d1733c6aa7 Abort rather than exiting "normally" if an autoupdate step crashes. (#4483)
This avoids producing an LSan leak report for the objects that got
leaked by the crash, which would otherwise scroll all the useful
information about the crash off the terminal.
2024-11-05 01:15:48 +00:00
Jon Ross-Perkins 2841e9a67e Require that InvalidParse nodes must have an error (#4482)
Unifies some boilerplate AddLeafNode calls for InvalidParse, and checks
has_error in AddNode.
2024-11-05 00:40:08 +00:00
Jon Ross-Perkins 26e58b4587 Refactor subcommand addition for sharing. (#4474)
Trying to standardize the setup a little more.
2024-11-04 22:42:57 +00:00
josh11bandJosh L ea0b0b4b48 Add facet type values and an instruction that produces them (#4460)
Still to do:
* Represent facet type values in a canonical form
* Produce & consume facet type values instead of interface values
* `type` should be associated with a canonical facet type value
* Support `&` on facet type values
* Type check and enforce requirements in facet types

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-04 21:43:55 +00:00
josh11bandJosh L 607522c7de Fix a case of InvalidParse with has_error = false (#4481)
Introduced in #4470.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-04 21:22:50 +00:00
Dana Jansens fcd611406a Correct typo in p0144 Numeric literal semantics (#4478)
This was already corrected in the design at

https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/expressions/literals.md#implicit-conversions

The text means to say "rejected" but says "represented".
2024-11-04 18:24:57 +00:00
Jon Ross-Perkins bd2fa3ace7 Remove CalleeParamsInfo (#4452)
I'm seeing three issues with CalleeParamsInfo:

1. Although ResolveCalleeInCall had been extracted out and the
EntityWithParamsBase could be used directly, that had not been cleaned
up.
2. implicit_param_refs_id is unused; param_refs_id was only used by
ResolveCalleeInCall. The factoring as a struct seems to be obscuring
what's used and what isn't (creating unnecessary copies).
3. On #4446, CalleeParamsInfo seemed to be obfuscating what
ConvertCallArgs actually worked with (a Function, not a generic entity).

I'm thinking that just removing CalleeParamsInfo is the best resolution
here, it looks like it's tripping people up more than it's helping.

Note, I think Function used to be named Callable, which was where the
"callable" name originally came from (I might be wrong about this). But
"function" seems clearer about the type now.
2024-11-04 16:47:40 +00:00
Jon Ross-Perkins dd43bb92b5 Refactor struct literal parse nodes. (#4470)
Split StructComma into StructLiteralComma and StructTypeLiteralComma in
order to easily differentiate handling (remains the same in this PR).

Add "Literal" to StructField and StructTypeField because it feels
inconsistent versus the other non-shared things. StructFieldDesignator
remains shared between value literals and type literals.

Note I probably would've made StructFieldDesignator non-shared too, but
that'd require either a lookahead of 2 (to see the separator`) or a
writeback after parsing the separator, neither of which felt especially
crucial for this, when what I'm really trying to do is split type
literal handling a little further.
2024-11-04 16:06:57 +00:00
Richard Smith 26d7717d60 Insert a value_of_initializer after a call to ImplicitAs where possible. (#4473)
This avoids going through memory when performing an implicit conversion
to a type with a by-copy value representation, such as i32.
2024-11-04 16:06:19 +00:00
Jon Ross-PerkinsandChandler Carruth 9af06cc988 Adjust some build troubleshooting notes (#4471)
Came up due to [libc++ install
issues](https://discord.com/channels/655572317891461132/655577725347561492/1302023663155023905)

We've discussed clang version verification, and adding that as long as
I'm in here. The more significant bit is the libc++ check, which if it's
not installed should fail like:

```
(tons of output)
ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/lib/llvm-16/lib/clang/16/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
/usr/local/google/home/jperkins/.cache/bazel/_bazel_jperkins/85deb7d9d96f7e0e80b42618a55969d7/external/_main~clang_toolchain_extension~bazel_cc_toolchain/_temp:6:2: error: "No libc++ install found!"
#error "No libc++ install found!"
 ^
1 error generated.
ERROR: Analysis of target '//toolchain:toolchain' failed; build aborted: Analysis failed
INFO: Elapsed time: 0.265s, Critical Path: 0.08s
INFO: 1 process: 1 internal.
ERROR: Build did NOT complete successfully
```

pre-commit runs bazel, and GitHub runners have an old clang by default
(caught by the new check), so I'm installing here for a consistent
version.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-11-04 16:03:09 +00:00
Chandler Carruth 4148161e24 Refactor value store code to use separate files. (#4477)
This is in anticipation of making the integer value store be customized
heavily. I'd like to extract it from the common code when doing that, so
first disentangling them here without any intended change in
functionality or behavior to enable that.

I've tried to update `#include`s to be as minimal as I can and added a
few missing includes spotted in the process.

I've split the test for value store to include what was easy focused on
just the value store templates rather than the unified shared value
stores.

This might surface some opportunities for adding more tests, but for
this PR, just doing the minimal restructuring.
2024-11-04 04:00:17 +00:00
Chandler Carruth 1b2eb42c5a Start avoiding parse diagnostics on error tokens (#4431)
An invalid parse due to an error token isn't likely a great diagnostic
as it will already have been diagnosed by the lexer. A common case to
start handling that is when the parser encounters an invalid token when
expecting an expression.

This removes a number of unhelpful diagnostics after the lexer has done
a good job diagnosing.

This also means that there may be parse tree errors that aren't
diagnosed when there are lexer-diagnosed errors, so track that.

Follow-up to #4430 that almost finishes addressing its diagnostic TODO.
2024-11-02 05:53:27 +00:00
Richard Smith 44fe65fbe5 Rename BigInt to IntLiteral. (#4476)
In preparation for changing the type of integer literals to
`IntLiteral`.
2024-11-02 02:09:10 +00:00
Richard Smith db76e81630 Rename IntLiteral to IntValue. (#4475)
This instruction represents integer values, whether they come from
literals or calculations, so it the old name is inaccurate. I also plan
to rename `BigInt` to `IntLiteral` based on recent discussion and this
change aims to avoid confusion stemming from the same name being used
for two different things.

I'm not renaming `FloatLiteral` because recent discussion suggests we
may want distinct `FloatLiteral` versus `FloatValue` representations in
SemIR.
2024-11-02 01:19:39 +00:00
Richard Smith 261fe38508 Fix use-after-free in return statement handling. (#4472)
Initialization can import a function and thus invalidate the reference
we're holding to the enclosing function. Don't use the reference after
initialization completes.
2024-11-01 23:11:27 +00:00
Geoff RomerandRichard Smith ac5cc33da4 Model return slot as parameter in lowering (#4457)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-11-01 21:48:09 +00:00
Jon Ross-Perkins 145c44b66c Move the language server into toolchain's busybox. (#4469)
Removes the separate language server binary; I'm not sure we need to
provide it. Instead, `carbon language-server` is added as a subcommand.

Moves //language_server to //toolchain/language_server. Splits into a
trivial language_server.h, and a substantive server.h. I wasn't sure
about a better name, but wanted the split similar to check/check.h,
lex/lex.h, etc. At the same time, the class is probably going to be a
little big so not a good fit to through into just a cpp file.

This fixes some style issues with the language server class, but
generally I'm trying to not address things here in order to keep it
simpler.
2024-11-01 19:49:39 +00:00
Chandler Carruth 954441c358 Exempt the clang subcommand when fuzzing. (#4468)
This teaches the driver library to track when its being used with
fuzzing and disables the `clang` subcommand from actually running Clang.

The Clang libraries have a large backlog of fuzzer-found issues that
isn't being actively reduced, so we can't productively fuzz into it.
This lets us more productively fuzz at the top level.

This is also available on the command line itself, which should be
useful if anyone wants to fuzz Carbon from the command line using tools
like AFL -- they can inject this flag to avoid getting noise from the
fuzzer hitting known issues in Clang.
2024-11-01 15:35:29 +00:00
Richard Smith 32e5212daa Fix lowering of a conversion from a type with a pointer value representation to a type with a copy value representation. (#4467)
We previously generated a `value_bind` instruction of the wrong type,
resulting in lowering building bad LLVM IR.

Also fix another issue exposed by this change, where we would import
constants without marking their types as complete, and then crash in
lowering while trying to lower them. This happens in particular for the
`FunctionType`s of functions in `ImplDecl`s. Address this by skipping
lowering for constants with incomplete types.
2024-11-01 14:52:57 +00:00
Richard Smith fab07726c9 Add import support for int_type. (#4466) 2024-10-31 23:05:25 +00:00
Richard Smith 3192cfc776 Add import support for specific_function constants. (#4465)
These can currently only be imported as part of the eval block for a
generic, because they only show up as the callee of a call instruction.
2024-10-31 20:13:05 +00:00
Richard Smith e2ab97672d Fix lowering of specific_functions referring to methods. (#4464)
In this case, the callee may be non-constant because it includes a
reference to `self`, so we need to be able to lower a non-constant
`specific_function`.
2024-10-31 20:07:30 +00:00
Jon Ross-Perkins 99e96605bf Don't create a compile time binding after CompileTimeBindingInVarDecl (#4463)
Related to #4461, more generally try not to produce a compile-time
binding when the code shouldn't be able to do so.
2024-10-31 18:27:43 +00:00
Jon Ross-Perkins 57c9a2ed4a Switch eval of ArrayIndex to use CARBON_KIND (#4462)
Just a minor cleanup.
2024-10-31 18:23:54 +00:00
Jon Ross-Perkins f70221c040 Fix deduction crash for function with missing parameters. (#4461)
This is because `var x:! () = ();` modifies the binding index, which
causes `A` to be generic, which causes the params to be used, which
crashes. There may be another issue to fix here so that the invalid
binding doesn't modify the binding index, but at least
`param_patterns_id` should probably be set consistently with
`params_id`.
2024-10-31 17:12:49 +00:00
Jon Ross-Perkins 85f6bf32b5 Switch tar verification to a manifest comparison. (#4458)
This removes the install marker-relative path checks, and replaces it
with bidirectional verification: previously, files in the tar file had
to be in install data, but there was no check that files in install data
were all in the tar.
2024-10-30 22:49:19 +00:00
Jon Ross-Perkins d944347e7b Elide prelude components in the IR formatter. (#4453)
This is in particular to avoid churn from changes such as #4370. I think
the import list can be helpful (particularly to understand what the
library is aware of), but it's a different trade-off for the prelude
package due to the implicit imports.
2024-10-30 22:45:26 +00:00
Jon Ross-Perkins fe23a4fe1f Refactor run_tool (#4459)
Removes the python script, should get equivalent results in the current
setup.
2024-10-30 22:39:12 +00:00
Jon Ross-Perkins 957599b2ab Implement a basic busybox for carbon/clang. (#4406)
For reference, we're going down the busyboxing route because Carbon
depends on Clang, and we want both to be available as binaries.
Busyboxing allows this while avoiding duplicating symbols between
multiple binaries.

I'm removing the `cc_binary` for `driver:carbon` because I want to avoid
a significant increase in binary outputs; `bazel run //toolchain` still
works great.

This still doesn't have great test coverage (but non-zero:
`//examples:sieve` still builds/runs, for example). The problem is that
we want to avoid subprocessing for performance, but this mainly deals
with subprocessing. I'm still thinking about good approaches for that,
since we'll probably want more significant testing for `clang`
interaction... the solution might involve busyboxing `file_test` too.

Note development on this ran into the argv issue being fixed in #4405
2024-10-30 17:07:55 +00:00
Jon Ross-Perkins 69d1d344bc Replace dict.update call with explicit dict (#4455)
https://bazel.build/rules/lib/core/dict#update indicates it returns
`None`. Maybe this hasn't worked for a long time, and was missed due to
the issue fixed by #4363
2024-10-30 17:00:16 +00:00
Geoff RomerandJon Ross-Perkins e20e8bfbea Consolidate caller match in one function call (#4446)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-10-29 23:31:50 +00:00
Brymer MenesesandJon Ross-Perkins 89eed4220f Expose indexing as a language interface (#4370)
This PR makes it so that types can implement the `IndexWith` interface
so that they can provide their custom indexing behavior.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-10-29 21:25:02 +00:00
josh11bandJosh L c30b1d1124 Fix where crash when empty decl_name_stack (#4451)
Bug found by fuzzer.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-29 19:38:02 +00:00
Richard Smith df68bf9f71 Switch to using Core.BigInt as the type of the size of a type literal. (#4450)
This removes one of the few ways in which `i32` is special and gets us
closer to removing it as a special case.
2024-10-28 23:35:08 +00:00
Jon Ross-Perkins 7ec8ceac73 Try working around xcrun failures (#4449)
I expect the change here will try rerunning a couple times, then fail if
it's a permanent failure.

I've seen similar failures, and believe this is flaky. Here's the
specific example that caused me to try a workaround:

https://github.com/carbon-language/carbon-lang/actions/runs/11560505812/job/32177497296

I don't see a difference in the runner information between failing and
passing runs, which might've indicated a canary. That's why I'm doing
this as a trivial retry.
2024-10-28 21:44:30 +00:00
dependabot[bot] 2c7166b2c9 Bump rexml from 3.3.6 to 3.3.9 in /website in the bundler group across 1 directory (#4448)
Bumps the bundler group with 1 update in the /website directory:
[rexml](https://github.com/ruby/rexml).

Updates `rexml` from 3.3.6 to 3.3.9
<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.3.9 - 2024-10-24</h2>
<h3>Improvements</h3>
<ul>
<li>Improved performance.
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/210">GH-210</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>
<p>Fixed a parse bug for text only invalid XML.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/215">GH-215</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
<li>
<p>Fixed a parse bug that <code>&amp;#0x...;</code> is accepted as a
character
reference.</p>
</li>
</ul>
<h3>Thanks</h3>
<ul>
<li>NAITOH Jun</li>
</ul>
<h2>REXML 3.3.8 - 2024-09-29</h2>
<h3>Improvements</h3>
<ul>
<li>SAX2: Improve parse performance.
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/207">GH-207</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>Fixed a bug that unexpected attribute namespace conflict error for
the predefined &quot;xml&quot; namespace is reported.
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/208">GH-208</a></li>
<li>Patch by KITAITI Makoto</li>
</ul>
</li>
</ul>
<h3>Thanks</h3>
<ul>
<li>
<p>NAITOH Jun</p>
</li>
<li>
<p>KITAITI Makoto</p>
</li>
</ul>
<h2>REXML 3.3.7 - 2024-09-04</h2>
<h3>Improvements</h3>
<ul>
<li>Added local entity expansion limit methods
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/192">GH-192</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/202">GH-202</a></li>
<li>Reported by takuya kodama.</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.3.9 - 2024-10-24 {#version-3-3-9}</h2>
<h3>Improvements</h3>
<ul>
<li>Improved performance.
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/210">GH-210</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>
<p>Fixed a parse bug for text only invalid XML.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/215">GH-215</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
<li>
<p>Fixed a parse bug that <code>&amp;#0x...;</code> is accepted as a
character
reference.</p>
</li>
</ul>
<h3>Thanks</h3>
<ul>
<li>NAITOH Jun</li>
</ul>
<h2>3.3.8 - 2024-09-29 {#version-3-3-8}</h2>
<h3>Improvements</h3>
<ul>
<li>SAX2: Improve parse performance.
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/207">GH-207</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>Fixed a bug that unexpected attribute namespace conflict error for
the predefined &quot;xml&quot; namespace is reported.
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/208">GH-208</a></li>
<li>Patch by KITAITI Makoto</li>
</ul>
</li>
</ul>
<h3>Thanks</h3>
<ul>
<li>
<p>NAITOH Jun</p>
</li>
<li>
<p>KITAITI Makoto</p>
</li>
</ul>
<h2>3.3.7 - 2024-09-04 {#version-3-3-7}</h2>
<h3>Improvements</h3>
<ul>
<li>Added local entity expansion limit methods
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/192">GH-192</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/202">GH-202</a></li>
<li>Reported by takuya kodama.</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/38eaa86ac7abe0d31cf49d8df57ad239fdeb80e9"><code>38eaa86</code></a>
Add 3.3.9 entry</li>
<li><a
href="https://github.com/ruby/rexml/commit/ce59f2eb1aeb371fe1643414f06618dbe031979f"><code>ce59f2e</code></a>
parser: fix a bug that &amp;#0x...; is accepted as a character
reference</li>
<li><a
href="https://github.com/ruby/rexml/commit/a09646d395a07399cbf9bc3bc8d6d8bb1d13ecea"><code>a09646d</code></a>
test: fix indent</li>
<li><a
href="https://github.com/ruby/rexml/commit/cf0fb9c9ca3dc0d725c8e4644aa0e728025f42ce"><code>cf0fb9c</code></a>
Fix <code>IOSource#readline</code> for <code>@pending_buffer</code> (<a
href="https://redirect.github.com/ruby/rexml/issues/215">#215</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/1d0c362526f6e25e2abcd13e2fcefcc718c20e78"><code>1d0c362</code></a>
Optimize <code>IOSource#read_until</code> method (<a
href="https://redirect.github.com/ruby/rexml/issues/210">#210</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/622011f25ac1519fd553d6c56da52d7eba14a787"><code>622011f</code></a>
Bump version</li>
<li><a
href="https://github.com/ruby/rexml/commit/036d50851ce091c797db0b9ba3ed8e5a39c3918c"><code>036d508</code></a>
test: avoid using needless non ASCII characters</li>
<li><a
href="https://github.com/ruby/rexml/commit/4197054a19e65511fb51983518a134a5c65aa840"><code>4197054</code></a>
Add 3.3.8 entry</li>
<li><a
href="https://github.com/ruby/rexml/commit/78f8712dccad773a51dc5eef31c02d523e994570"><code>78f8712</code></a>
Fix handling with &quot;xml:&quot; prefixed namespace (<a
href="https://redirect.github.com/ruby/rexml/issues/208">#208</a>)</li>
<li><a
href="https://github.com/ruby/rexml/commit/2e1cd64f2f9c0667a840a0e31f9bb99f9e1c2b33"><code>2e1cd64</code></a>
Optimize SAX2Parser#get_namespace (<a
href="https://redirect.github.com/ruby/rexml/issues/207">#207</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/ruby/rexml/compare/v3.3.6...v3.3.9">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.6&new-version=3.3.9)](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>
2024-10-28 20:11:03 +00:00
Richard Smith a0609b9155 Don't eagerly import all impls. (#4447)
Instead, eagerly import only the impls from the api file corresponding
to the current file, if any, because we need those for impl
redeclaration lookup. For all other cases, load only the impls in
libraries that are referenced as part of an impl lookup query.
2024-10-26 00:38:24 +00:00
Jon Ross-Perkins 0ca0d0d4f5 Small refactoring to Extract for compile time. (#4444)
AFAICT https://github.com/carbon-language/carbon-lang/pull/4363 made
builds of extract.cpp go from ~15s to ~35s. I'm not sure how to really
improve on this, short of adding boilerplate to the types in order to
reduce template use (e.g., instead of using struct reflection to return
fields, we could have something that directly returns fields). But, this
switch to `MaybeTrace` seems to be about a 20% build time improvement
(down to ~30s), with `noinline` accounting for a part of that.
2024-10-25 23:08:28 +00:00
Chandler Carruth 577fda1ca2 Speed up type literal lexing and make it more strict. (#4430)
This rejects type literals with more digits than we can lex without
APInt's help, and using a custom diagnostic. This is a pretty arbitrary
implementation limit, I'm wide open to even more strict rules here.

Despite no special casing and a very simplistic approach, by not using
APInt this completely eliminates the lexing overhead for `i32` in the
generated compilation benchmark where that specific type literal is very
common. We see a 10% improvement in lexing there:
```
BM_CompileAPIFileDenseDecls<Phase::Lex>/256        39.0µs ± 4%  34.8µs ± 2%  -10.86%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/1024        180µs ± 1%   158µs ± 2%  -12.22%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/4096        731µs ± 2%   641µs ± 1%  -12.31%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/16384      3.20ms ± 2%  2.86ms ± 2%  -10.47%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/65536      13.8ms ± 1%  12.4ms ± 2%   -9.78%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/262144     64.0ms ± 2%  58.4ms ± 2%   -8.70%  (p=0.000 n=19+18)
```

This starts to fix a TODO in the diagnostic for these by giving a
reasonably good diagnostic about a very large type literal. However, in
practice it regresses the diagnostics because error tokens produce noisy
extraneous diagnostics from parse and check currently. Leaving the TODO
there, and I have a follow-up PR to start improving the extraneous
diagnostics.
2024-10-24 21:43:35 +00:00
Geoff Romer b67d03126e Separate inst kind for out params (#4442) 2024-10-24 15:22:32 +00:00
Jon Ross-PerkinsandGeoff Romer 06f4eec91e Modify lex yaml output to elide FileStart/End in tests. (#4433)
Trying to make split file tests of lex functionality shorter and easier
to read. numeric_literals.carbon in particular has an example of why I'm
interested in this (at the bottom). This also switches from `[]` list
format to `-` list format so that the trailing `]` is removed.

Trimming comments in tokenized_buffer.h because (1) it feels like it's
giving too much detail about what's printed, which has drifted slightly
and (2) it also feels like it's trying to justify YAML output, when
that's just what we're doing in general.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2024-10-23 18:56:41 +00:00
Céline Dedaj d1c6f0152e Update CODE_OF_CONDUCT.md (#4441)
Deleted conduct team member list from this page to avoid duplicate
information: the list is already on the conduct team page, referenced
here.
2024-10-23 18:19:35 +00:00
Jon Ross-Perkins e58ce3e1bb Add coverage testing for parse node kinds. (#4436)
This refactors the diagnostic kind coverage check into something that
also works for node kinds. Then, since this points out a few node kinds
that aren't having their parse verified, I'm adding minor tests for
those.
2024-10-23 18:16:32 +00:00
Jon Ross-Perkins 03ddeb576b Fix use of runfiles (#4440)
I was looking at the documentation again, and I realized that while this
works, I think the intention is that `runfiles` is set _instead_ of both
fields (I was a little confused by the error I was getting when setting
`runfiles` _with_ `default_runfiles`)

I believe I've verified this works in necessary situations.
2024-10-23 18:01:14 +00:00
Richard Smith 2e63da1a40 Move diagnostic kind name to the end of the diagnostic. (#4437)
Also surround it in square brackets rather than parentheses. This
matches the format used by Clang and GCC, and means diagnostics will
still match the `file:line:col: error: ` pattern used by some IDE tools.

Before:
```console
fail_builtins.carbon:11:11: error(AliasRequiresNameRef): alias initializer must be a name reference
```

After:
```console
fail_builtins.carbon:11:11: error: alias initializer must be a name reference [AliasRequiresNameRef]
```

Also tighten up test regex to only match on `STDERR` lines that list a
file name.
2024-10-23 16:56:23 +00:00
Jon Ross-Perkins f206072216 Add data_runfiles to manifests (#4438)
This is trying to help systems that don't use
--incompatible_always_include_files_in_data
2024-10-23 16:54:52 +00:00
Geoff Romer 9266f867f9 Model the return slot as an output parameter (#4432)
Also fix `Param` insts to have meaningful names in pretty-printing, to
help clarify relationship with return slot.
2024-10-23 16:53:34 +00:00
Jon Ross-Perkins 5038218cea Pass the manifest path by flag. (#4439)
This is just a cleanup to remove the hardcoded path, since it's not
really necessary in context.
2024-10-23 16:52:52 +00:00
Richard SmithandJon Ross-Perkins e68e54dae4 Issue a diagnostic if we try to parse a source file that is too large. (#4429)
Previously in an optimized build we'd produce bogus tokens, such as
tokens with incorrect IdentifierIds, and in a debug build we would try
to CHECK-fail -- but actually wouldn't, because we're incorrectly
checking for `2 << bits` instead of `1 << bits`. I hit this while I was
trying to do some profiling and was seeing some very strange
diagnostics.

The diagnostic is pointed at the first token that is beyond the limit to
help people determine where to split their files.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-10-22 23:21:35 +00:00
Richard Smith af816cda90 Move impl lookup out into its own file. (#4435)
In preparation for adding more logic here. This code doesn't belong in
member access.
2024-10-22 17:19:21 +00:00
josh11bandJosh L 17bf9f1454 Delete Function::ParamInfo::GetNameId (#4434)
No longer used as of #4422 .

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-22 16:10:09 +00:00
Jon Ross-Perkins c25177658a Add more compile benchmark stats (#4408)
I was discussing some details of cross-compiler lex performance. Since
we were talking about LoC initially, and lex performance especially will
differ based on bytes and tokens being lexed, throwing in some stats for
how we're processing those. Here's some example output:

```
----------------------------------------------------------------------------------------------------------------------------
Benchmark                                                 Time             CPU   Iterations      Bytes      Lines     Tokens
----------------------------------------------------------------------------------------------------------------------------
BM_CompileAPIFileDenseDecls<Phase::Lex>/256           31828 ns        31798 ns        22528  165.64M/s 6.13247M/s 34.6249M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/1024         147513 ns       147434 ns         5120 220.363M/s 6.64025M/s  39.014M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/4096         611530 ns       610985 ns         1280  232.22M/s 6.59264M/s 39.0501M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/16384       2645671 ns      2643411 ns          320 231.122M/s 6.17119M/s  36.616M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/65536      11593324 ns     11587201 ns           64 217.864M/s 5.64934M/s 33.5378M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/262144     60338069 ns     60313976 ns           16 169.444M/s 4.34607M/s 25.8032M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/256         53355 ns        53308 ns        13312 98.8029M/s 3.65798M/s 20.6535M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024       253979 ns       253818 ns         3072 128.001M/s  3.8571M/s 22.6619M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096      1052984 ns      1052427 ns          768 134.815M/s 3.82734M/s 22.6705M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384     4364730 ns      4362756 ns          192 140.038M/s 3.73915M/s 22.1857M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    19419562 ns     19413505 ns           48 130.035M/s 3.37188M/s 20.0175M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144   89023213 ns     88979387 ns            8 114.856M/s 2.94595M/s 17.4905M/s
BM_CompileAPIFileDenseDecls<Phase::Check>/256        676254 ns       675605 ns         1024 7.79597M/s  288.63k/s 1.62965M/s
BM_CompileAPIFileDenseDecls<Phase::Check>/1024      1412608 ns      1411876 ns         1024 23.0112M/s 693.404k/s 4.07401M/s
BM_CompileAPIFileDenseDecls<Phase::Check>/4096      4333665 ns      4331240 ns          256 32.7581M/s 929.988k/s 5.50858M/s
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    16566625 ns     16553982 ns           64 36.9065M/s 985.443k/s 5.84699M/s
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    68609701 ns     68542189 ns           16 36.8304M/s 955.032k/s 5.66963M/s
BM_CompileAPIFileDenseDecls<Phase::Check>/262144  302899379 ns    302596672 ns            8 33.7739M/s 866.265k/s 5.14313M/s
```

Also note, this is the discussion that led to [me looking at bytes per
token](https://discord.com/channels/655572317891461132/655578254970716160/1295803122844700786)
2024-10-22 00:22:46 +00:00
Jon Ross-Perkins 9fefef162f Add tests to catch untested diagnostics. (#4426)
Use the diagnostic kind printing in #4425 to catch when we have
diagnostics with no tests.

This merges a couple other use-cases of filegroup manifests into a
common rule.

Note I do add a few tests for things, and also some things are
_actually_ unit tested (just not in the file_test structure). But I
stopped when I realized that dealing with merge conflicts is going to be
a pain. I might end up reverting test changes (as part of merge conflict
resolution) and doing narrow test additions in a separate PR, after both
this and #4425 are merged.
2024-10-21 20:16:18 +00:00
Jon Ross-Perkins 249709cb49 Split out clang-tidy to not run in merge (#4428)
Because clang-tidy is slow (and I'm not sure we can make it really
fast), trying to run it slightly less. Also, I noticed we can shave a
few minutes by disabling apt removal without losing too much free space.

Note that since this removes the old clang-tidy, I'll need to change the
branch protections before merging.
2024-10-21 19:59:40 +00:00
Geoff Romer 223c5cb04b Restructure handling of runtime parameters (#4422)
- Generate runtime indices as part of pattern matching, rather than as a
separate postprocessing/rewriting step.
- In contexts where runtime parameters aren't permitted, avoid emitting
insts for them to begin with, rather than trying to detect the problem
and rewrite the IR to remove them later on.
2024-10-21 19:53:38 +00:00
Jon Ross-PerkinsandGeoff Romer 302aa1bb30 Remove uses of StringLiteral in format strings. (#4416)
Building on #4411, avoid using StringLiteral in format strings. This
includes a diagnostic check to prevent regressions (which is also how I
gathered issues).

Note, I haven't looked at `std::string` uses yet, but we might need
things like that to be able to pass strings in code back to the user.
StringLiteral though means that it's literally written down in the
toolchain, at which point it should probably be written in the format
string instead of separately.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2024-10-21 19:39:53 +00:00
Jon Ross-Perkins 62c36eceda Support printing the diagnostic kind for verification. (#4425)
This is to help identify which diagnostics we're actually using.

Note that driver/testdata still has tests which don't pass this flag,
and so continue to test the kind-less (default) behavior.
2024-10-18 22:33:56 +00:00
Jon Ross-Perkins e3950298cf Update for llvm::formatv changes (#4427)
dwblaikie changed this upstream:
https://github.com/llvm/llvm-project/pull/112625
2024-10-18 20:26:15 +00:00
Richard Smith 684cda3d53 Don't deduce values for explicitly-specified generic bindings. (#4415)
Distinguish between deduction against a symbolic binding pattern and
deduction against a symbolic binding name. In the former case, the value
is being explicitly specified and must be constant. In the latter case
we encountered a use of the binding name as a subexpression, and should
deduce against it if it's not explicitly specified.
2024-10-18 15:33:10 +00:00
Jon Ross-PerkinsandRichard Smith b5a837aa89 Refactor modifier formatting to remove string passing. (#4418)
I'm taking the approach of making DiagnosticBase an API so that we can
pass similar diagnostics as parameters. An alternative would be to do
the function_ref approach we've done elsewhere, but these felt more
boilerplate to me.

Note I'm also modifying messages here. Let me know if you'd like
different changes and/or just keeping current formatting (keeping
current formatting would also allow removing some of the templating I've
added, but it felt helpful putting explicit tokens where possible). But
also, things like "`protected` not allowed on `interface` declaration at
file scope" were part of the phrasing issue, I think.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-10-17 22:47:40 +00:00
Geoff Romer 5a795db0de More focused diagnostic notes for parameters (#4420) 2024-10-17 21:47:20 +00:00
Jon Ross-Perkins 2a36ff611d Remove a couple std::string uses in diagnostics. (#4421)
We can't completely remove std::string from diagnostics because it's
probably better to provide a string than something like a
StringLiteralValueId or NameId (because those may be opaque for someone
trying to present the diagnostic). So this change is just playing
whackamole on another couple things that could easily use the new format
providers.
2024-10-17 21:39:21 +00:00
Jon Ross-Perkins 7c22348461 Add s plural format to IntAsSelect (#4423)
Per discussion on #toolchain, add "s" as a special-case for the common
plural format.

Note this removes periods from a few diagnostics; the periods shouldn't
be there per message style. Also, while I'm ignoring llvm::StringLiteral
uses, those should be addressed as #4416 -- this'll probably conflict
and make me clean up one or the other.
2024-10-17 19:51:52 +00:00
Jon Ross-Perkins 780dd3addc Remove mistaken asserts and add regression test (#4424) 2024-10-17 18:49:31 +00:00
Jon Ross-Perkins 5bdeb010c8 Clean up format_provider uses (#4417)
Building on https://github.com/carbon-language/carbon-lang/pull/4411,
replace format_provider uses (other than `TokenKind`, which is more on
the okay side of things)

Also does some edits to `ClassMemberDefinition` to try to better match
diagnostic style
2024-10-17 18:47:29 +00:00
Richard Smith a02dfe0226 Superficial support for Core.BigInt type (#4414)
Add a `Core.BigInt` type and a corresponding builtin type in the
toolchain. See [corresponding section of the
design](https://docs.carbon-lang.dev/docs/design/expressions/literals.html#defined-types).

So far this type is not used for anything, and there is no way to create
an instance of it.
2024-10-16 23:27:01 +00:00
Jon Ross-Perkins 96964ee534 Implement basic bool and int formatting for diagnostics (#4411)
Note, this supports plurals, but doesn't apply it anywhere. I'm mainly
doing that to demonstrate the approach regarding syntax. See
format_providers.h for details.
2024-10-16 22:46:15 +00:00
Jon Ross-Perkins a5ba0eed6a Drop macos-12 runners due to shutdown (#4412)
macos-12 is being shut down; it will have outages in November, and will
be fully removed in December:
https://github.com/actions/runner-images/issues/10721
2024-10-16 21:52:28 +00:00
David BlaikieandRichard Smith dfed743de2 Add vtable pointers to class layout (#4407)
A small step to virtual functions - adding vtable pointers to the
layout, but not initializing or otherwise using them at this stage.

A few open design questions I'd love feedback on:

* Is this the right/good enough SemIR representation for now? This patch
adds a `is_dynamic` attribute to `SemIR::Class` and populates/flags it
based on the flag of the base class, or if any virtual function is
declared in the class (or, at least that's my intent). Some other
options include:
* Each `Class` could store a `ClassId` (or `TypeId`?) of the (possibly
indirect, possibly self) base class that is the first one that is
dynamic/has a vtable pointer
* Could make the property narrower, like `has vtable pointer` and have
it `true` only on the type that introduces the vtable - then derived
classes would have to walk their base classes to check if they're the
one that needs to define the vtable pointer or not
* Should the vtable be the first element in the type? If there's a
non-dynamic base type, we could have a layout that's `{<non-dynamic base
type>, vtable ptr, <derived members>}`? Derived types would still be
able to uniquely identify where their vtable pointer is just fine... -
and the vtable pointer is, in a sense, a member of that intermediate
type, so it does seem a bit strange to force it to the front - but I
guess it's probably more efficient in some ways?

Open to any other suggestions/advice/thoughts on the direction, etc.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-10-16 21:26:17 +00:00
Jon Ross-Perkins 3c58fb7ec5 Adjust libpfm4 dep to use git instead of the tar. (#4413)
The .tar.gz link is currently broken (I think wget used to work, now it
doesn't); not sure if that's deliberate since it's a download page. I'm
hoping the new location remains more reliable.

Note I tried using SourceForge's git directly. That works locally, but
on the action runners it seems to be blocked:

```
fatal: unable to access 'https://git.code.sf.net/p/perfmon2/libpfm4/': Failed to connect to git.code.sf.net port 443 after 5 ms: Connection refused
```
2024-10-16 20:07:33 +00:00
Geoff RomerandJon Ross-Perkins 9d942f4633 Generate parameter pattern-match IR from pattern IR (#4388)
Also propagate the pattern IR along with the pattern-match IR, and use
it where appropriate.

Strictly speaking, some parts of the pattern-match IR are allocated
eagerly, while traversing the pattern's parse tree, but they still
aren't actually emitted until we traverse the associated pattern insts.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-10-16 19:15:29 +00:00
Jon Ross-Perkins 4a73b36688 Switch back to the system llvm-symbolizer. (#4410)
Undoes most of #4347, because of [performance
complaints](https://discord.com/channels/655572317891461132/707150492370862090/1295527235133898772).
With a 30-ish frame stack trace and `-c dbg`, my installed
`llvm-symbolizer` still seems slow (~6s), but the hermetic
`llvm-symbolizer` adds ~4s (i.e., ~10s total). I don't think we can
easily force the hermetic version to build in opt configuration, so I'm
backing it out.
2024-10-16 18:32:11 +00:00
Jon Ross-Perkins 77facdd775 Remove unused benchmark_main.h (#4409)
This was refactored to Testing::GetExePath, but apparently the header
was missed.
2024-10-15 20:43:26 +00:00
Jon Ross-Perkins e2256516e8 Fix InitLLVM argv (#4405)
`args_.push_back(nullptr);` can resize `args_`, invalidating `argv`. The
order needs to be switched.
2024-10-13 17:47:57 +00:00
David BlaikieandRichard Smith d491387a98 Disallow creating instances of abstract classes (#4381)
A good first-pass, at least. (abstract adapters are rejected with this
change, though pending further language design discussion)

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-10-12 15:17:42 +00:00
Jon Ross-Perkins bafddd8711 Use @bazel_tools//tools/cpp:malloc instead of defining a library (#4404)
@bazel_tools//tools/cpp:malloc is equivalent and comes from
https://bazel.build/reference/be/c-cpp#cc_binary.malloc. This also
avoids some confusion in the documentation, since while system_malloc
_can_ be used with `malloc`, it has no effect when it's used with
`--custom_malloc`. But, rather than trying to adjust that, maybe we can
just use @bazel_tools//tools/cpp:malloc
2024-10-11 21:11:11 +00:00
josh11bandJosh L 8ecf844ba5 Fix missing ` (#4403)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-11 20:43:51 +00:00
josh11bandJosh L 4994e13068 Document that extend base must appear early in a class definition (#4401)
Note: some of this is from the principle of information accumulation,
and some is from [proposal
#2760](https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p2760.md#class-inheritance).

Also: change terminology from "virtual override keywords" to "virtual
modifier keywords", to be consistent with our other modifier keywords.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-11 19:51:15 +00:00
josh11bandJosh L b0cde707f8 Rename "partial facet" and to "partial class type" (#4402)
See [2024-10-01 discussion on #typesystem in
Discord](https://discord.com/channels/655572317891461132/708431657849585705/1290774105498325122).

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-11 18:25:18 +00:00
Richard Smith 851ef2c517 Initial, very rough lowering for calls to specific functions and specific function declarations. (#4399)
Generate declarations of specific functions on demand. Definitions are
not emitted yet, and I'm using a temporary, known-broken scheme for name
mangling.
2024-10-10 23:37:16 +00:00
Jon Ross-Perkins df55b89e08 Implement some token-based formatting structure. (#4386)
Here I'm trying to add some simple formatting based on the token kind,
aiming mainly to keep the implementation short for now.

This approach won't generalize to arbitrary structures (e.g., it doesn't
discern between braces for a function body and a struct literal). I
think we'll probably want to build a parse tree and associate parse
kinds with tokens in order to format, additionally doing something less
linear. But my essential goal at present is to just get a
proof-of-concept that the basics can yield something that looks okay.
2024-10-10 23:18:38 +00:00
josh11bandJosh L c721a020a7 Store pointer not reference in ConstantStore (#4398)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-10 22:30:10 +00:00
Jon Ross-PerkinsandChandler Carruth 0db96ebc52 Stitch together adjacent comments using the indent. (#4397)
This is improving the comment production to produce fewer distinct
comments.

At present, comment processing uses strict prefix matching. It either
expects `// ` (with a space) for valid comments, or just `//` (without a
space) for invalid comments that lacked the space.

As a consequence, the following would be three comments:

```
// Comment 1
//
//
// Comment 4
```

This is because a 3-character prefix is used for valid comments. The
prefix switches between lines 1 and 2, and again between lines 3 and 4,
each resulting in a separate comment.

For contrast, this is one comment because only a 2-character prefix is
used:

```
//Comment 1
//
//
//Comment 4
```

That's because all lines lack a suffix space.

Additionally, with SIMD 16-byte boundaries, further splits can occur if
processing needs to transition to non-SIMD.

Here, I'm trying to just address all of this by:

1. Stitching together adjacent comments. Since a lexed comment starts at
the `//` excluding the indent, the delta from the prior comment must be
precisely the indent.
2. Adding support for switching from SIMD to non-SIMD on file
boundaries.

I considered trying to have a separate `//\n` prefix for SIMD processing
of `// `, but I wasn't sure about the tradeoff of doing both at the same
time (in particular, it'd require constructing a string for the
different prefix), thus this stitch approach. This does mean multiple
passes will be required for a typical long comment structure using blank
comment lines to separate paragraphs (for performance reasons, I will
recommend engineers not write comm... nevermind).

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-10-10 22:25:41 +00:00
9e5e33082c Update instructions for adding a SemIR instruction. (#4348)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-10-10 21:57:29 +00:00
Richard Smith 1a1bfd2eb2 Track and resolve the specific callee in a call to a generic function (#4395)
Add a new `specific_function` instruction that represents a generic
function plus its deduced argument list as a callee in a function call.
The new instruction can only appear as the immediate operand of a call
instruction, so we give it a builtin placeholder type.

At the end of each file, require definitions for all specific functions
used in that file. Resolve the generic with the argument list to produce
those specific function definitions as needed, and diagnose if the
generic doesn't have a definition available.

A few tests are updated in cases where they declared and used generic
functions but didn't previously provide a function definition.
2024-10-10 20:52:46 +00:00
Céline Dedaj bb874f21f7 Update conduct team member list (#4394)
deleted @flysand7 from the conduct team member list after they left the
team
2024-10-10 20:02:05 +00:00
Jon Ross-Perkins 0f350255ce Refactor compile-related tests to share construction. (#4396)
Note in particular that this fixes an issue where SharedValueStore had
been shared across files, when they should be per-file. This is only
visible when doing multiple compilations in a single test, which was
rare before.

This also moves these tests into the Testing namespace. My memory of the
various namespacing changes is that we'd generally agreed to have tests
in Testing so that we'd see SemIR:: and similar, same as we would in a
lot of the implementation.
2024-10-10 19:43:31 +00:00
David Blaikie b1014bf9f5 Disallow abstract or base on class declarations (that are not definitions) (#4378)
Per:
[p3762](https://docs.carbon-lang.dev/proposals/p3762.html#modifier-keywords:~:text=Other%20class%2C%20impl%2C%20and%20interface%20modifiers%20%28abstract%2C%20base%2C%20final%29%20exist%20only%20on%20the%20definition%2C%20not%20on%20the%20forward%20declaration):
"Other class, impl, and interface modifiers (`abstract`, `base`,
`final`) exist only on the definition, not on the forward declaration."
2024-10-10 17:41:38 +00:00
Jon Ross-Perkins 1338f9e0ad Add tracking of lexed comments, with skeletal formatting. (#4385)
In order to format comments, it's helpful if they're tracked. This
tracks them separately from tokens in order to avoid interfering with
parse; it'd be inconvenient if comment tokens could show up in arbitrary
locations, albeit possible to support.

This additionally extracts out the TokenIterator support into a template
in order to generally have it available for IndexBase types. I'm only
adding it for CommentInfo, not sure if we'll want it elsewhere, but this
structure still felt like a good fit.
2024-10-09 21:05:53 +00:00
Richard Smith efb5d6d25a Assign locations to instructions in a generic eval block. (#4393)
The locations point to the first instruction in the generic that needed
the relevant constant value or type.

For now, this must makes the formatted SemIR a bit more useful, but in
the future it will also provide locations for diagnostics caused by
monomorphization failure.
2024-10-09 19:03:15 +00:00
Céline Dedaj b1366f3e4e Update CoC team members (#4392)
deleted @flysand7 from the conduct team member list, as requested by
@flysand7
2024-10-09 18:48:53 +00:00
Jon Ross-Perkins e9a6b9dfcc Add AUTOUPDATE-SPLIT to help with format tests. (#4384)
Since formatting covers comments, and the CHECK lines are in comments,
it can create recursive behaviors. This introduces AUTOUPDATE-SPLIT as a
way of formally designating a split to exclusively be used for
autoupdate output.
2024-10-09 18:47:03 +00:00
Jon Ross-Perkins 434173b016 Add skeletal format subcommand. (#4383)
This extracts out the SourceBuffer handling of `-` in order to trivially
share it.

Note this still has a number of TODOs, it's just setting up the
essential subcommand infrastructure, with some tests demonstrating that
it at least does something.
2024-10-09 17:33:29 +00:00
Chandler Carruth 33954d1f20 Improve -c dbg, enabling Split DWARF and other enhancements (#4382)
This should substantially reduce the total build size of `-c dbg`
builds, and especially improve cache hits during incremental
development. I'm seeing over 50% reduction total on Linux in just the
raw size of a complete debug build. Even on macOS where we can't use
split DWARF there are substantial reductions.

Note that LLDB and GDB want slightly different flags to have the best
experience with split debug information, and so the build and
documentation have been updated to enable LLDB's flags by default but
provide clear instructions for switching to GDB's flags, and they are
structured so that this can be done persistently for an individual
developer.
2024-10-09 03:58:47 +00:00
Richard Smith 8650f1c173 Remove out-of-date TODO (#4390) 2024-10-09 01:41:14 +00:00
Richard SmithandJon Ross-Perkins 6410d6e140 Add support for deduction of most kinds of type constant. (#4389)
This adds deduction in all the cases where we can match the instruction
fields of the parameter against the corresponding instruction fields of
the argument. This handles all current type constants except for struct
types, for which we would want to match by field name.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-10-09 00:42:53 +00:00
Richard Smith 9fadfb5e82 Basic support for argument deduction in generic impls. (#4380)
Refactor the current function call deduction logic to make it reusable.
Call into it from `impl` deduction. Also build a generic region for the
definition portion of a generic `impl` and substitute into it before
accessing the witness in a specific `impl`.

This is enough to get simple uses of generic `impl`s to work. The main
blocker for more complex cases is that we have very little support for
non-trivial deduction, so while we can deduce `forall [T:! type] T as
I`, we can't deduce `forall [T:! type] C as I(T)` yet.
2024-10-08 22:17:37 +00:00
Richard Smithandjosh11b b274622228 Improve infrastructure for formatting types in diagnostics. (#4374)
Instead of stringifying types in the caller in some cases, add new types
to represent:

- `InstIdAsType`: an `InstId` diagnostic argument that represents a type
expression that should be included in the diagnostic
- `InstIdAsTypeOfExpr`: an `InstId` diagnostic argument that represents
an expression whose type should be included in the diagnostic

For these cases, we can produce more user-friendly descriptions of a
type than we can with a canonicalized `TypeId`. Add comments to
discourage using `TypeId` diagnostic arguments when one of the above can
be used, and move over existing uses where it's straightforward to do
so.

Move type stringification code to its own files and out of `SemIR::File`
to make `File` smaller and to further discourage the direct use of the
stringification logic.

Also update type printing to include the `` ` `` delimiters surrounding
the type. The intent is that we will eventually want to include other
information when formatting a type, like Clang does when printing a
typedef (`'string' (aka 'std::basic_string<char>')`), and such
formatting requires that the diagnostic machinery produces the `` ` ``s
itself.

There are a couple of cases where we really want to format valid Carbon
type syntax directly into a diagnostic, rather than an `aka` or similar,
because the diagnostic text includes part of the type itself, for
example: ``"consider using `partial {0}`"``. For such cases, a `Raw`
form of the diagnostic argument types is added: `TypeIdAsRawType` and
`InstIdAsRawType`. In principle we could instead use ``"consider using
`partial {0:raw}`"``, but our diagnostic machinery isn't set up for
that.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-10-07 22:55:26 +00:00
Geoff Romer 6439f9065d Handle block scopes in compile-time binding check (#4379)
This fixes a fuzzer-found crash when a compile-time binding occurs
inside a block (which is represented by an invalid inst ID).
2024-10-07 22:53:22 +00:00
Chandler Carruth 284b14981d Fix our default fastbuild Bazel config (#4363)
Causes the default development (`fastbuild`) Bazel build and test to
both use ASan, minimal optimizations, and produce good backtraces with
source locations.

This also fixes all of the non-host configs that were deeply broken for
the latest releases of Bazel going back quite some time.

The intent of our our Bazel toolchain config was for a minimally
optimized, minimal debug info, and ASan + UBSan configuration to be the
`fastbuild`, or the default development build of the project. This
matches its inclusion of asserts, etc.

At some point quite some time ago, all of this stopped working. Bazel no
longer has a `nonhost` feature. This was disabled a long time ago,
briefly argued to be re-enabled, but has persistently been removed.
However, since then the host and non-host features have been separated
including the compilation mode, and so none of that is needed now.
Instead, we can use a much simpler and more principled approach to all
of the feature configuration now which this PR implements.

However, we added TCMalloc _after_ all of the ASan stuff became broken,
and so we never saw that it is fundamentally incompatible with ASan. So
this PR also reworks how TCMalloc is used to only apply to `-c opt`
builds on Linux, and it also explicitly disables it when using
`--config=asan`. I've not found a convenient way to tie the malloc
library choice to a toolchain feature in Bazel, so this relies on the
config being used rather than the feature in isolation.

Last but not least, with this change `fastbuild` creates substantially
larger output and so this change also passes several new flags to reduce
the size costs. One is a general improvement from outlining ASan
instrumentation. The others are in a special feature as they reduce the
error message quality for two of the more expensive UBSan checks in
favor of small generated code size. Keeping these last two separate
allows disabling this locally if needed to debug a failure.
2024-10-07 18:19:49 +00:00
Chandler Carruth 55d8edcdc7 Some trivial check-phase inlining. (#4362)
When profiling, these jumped out as good inline candidates that happened
to be out-of-line, this just moves them inline so that they're
available. I think as much as 10% improvement in check-phase from this,
but I haven't run detailed before/after measurements as these changes
seemed minimally disruptive.

Also switched from `CHECK` to `DCHECK` in one place that seems
especially hot and where the check itself seems reasonable to only do in
debug builds. Left a comment since we rarely need to remove these any
more.
2024-10-07 17:31:22 +00:00
josh11bandJosh L c1b871f361 Add link to video for C++Now variadics talk (#4377)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-07 17:30:32 +00:00
David Blaikie 0b5d1101f9 Remove redundant optional wrapping llvm::function_ref (#4367)
llvm::function_ref (like std::unique_ptr, for instance) already has a
null/empty state, so use that to avoid confusion/duplication of empty
states between optional and the nested function_refs.
2024-10-07 17:25:35 +00:00
Chandler Carruth e38ad83bfd Disable the Bazel disk cache on CI. (#4375)
This should free up quite a bit of space and even make our builds faster
by avoiding duplicating every output. The syntax for this flag is
counter intuitive, so I've left a comment explaining it.
2024-10-06 18:02:30 +00:00
josh11bandJosh L 6dbeda612a where check stage, step 3: some type checking (#4364)
With this, we now check:

* The left argument to `where` is a facet type
* The right argument of a rewrite (`=`) requirement converts to the type
of the left argument.
* The left argument of an `impls` requirement is a type and the right
argument is a facet type.

No checking is done for `==` constraints yet.

In addition, make the "is facet type" query into its own function and
fix some comments noticed as part of this change.

This change reveals that accessing the members of a facet, like `.Self`,
isn't doing the right thing, and will have to be fixed in a follow-on
PR. Some tests have been adjusted or disabled as a result.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-05 01:03:43 +00:00
Richard Smith 17411c5e78 Assign a name to interface_type instructions. (#4369)
This matches what we do for `class_type` and `function_type`.
2024-10-04 23:06:24 +00:00
82937e1a3c Change how to get info for a parameter (#4366)
Updates `SemIR::Function::GetParamFromParamRefId` to return more
information in the form of a new `ParamInfo` struct. This struct has a
method for getting the `NameId` from the name binding instruction. The
callers previously got it from the `Param` instruction, but the plan is
for that instruction to no longer be associated with a name.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2024-10-04 16:30:00 +00:00
Richard Smith 568ad197d1 Track the instruction used to name the type and constraint in an impl. (#4368)
This is necessary in order to have access to the specific versions of
their constant values in a generic impl.

Stub out impl deduction.
2024-10-04 00:06:55 +00:00
David Blaikie eab5dd6112 Reject abstract function definitions (#4350)
Not sure about error recovery options - can/should we drop the
definition as a means of recovery when building the SemIR? I guess
probably not, so I guess this change is about right.

Phrasing of the error message I'm certainly open to.
2024-10-03 22:50:46 +00:00
josh11bandJosh L 8f547365f5 Increase test timeout to unblock submit (#4365)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-03 21:19:53 +00:00
josh11bandJosh L d6d70bf80d Handle runtime implicit parameters, and self outside of methods (#4361)
Closes #4356, #4359

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-03 20:24:28 +00:00
Geoff Romer e617d64939 Remove parameter-constant arrays from import_ref (#4360)
This makes the code more resilient to changes in the structure of
parameter insts, and could help avoid bugs by making the
ImportRefResolver's data structures the single source of truth.
2024-10-03 19:39:12 +00:00
David Blaikie afbea6a9ec Disallow base virtual in adapter (#4343)
According to
https://docs.carbon-lang.dev/docs/design/generics/details.html#adapting-types:
> You can add any declaration that you could add to a class except for
declarations that would change the representation of the type. This
means you can add methods, functions, interface implementations, and
aliases, but not fields, base classes, or virtual functions. The
specific implementations of virtual functions are part of the type
representation, and so no virtual functions may be overridden in an
adapter either.
So, let's check/reject that.

Checking at the end of the class ensures that no matter the order of
methods and adapt statements, the issue will still be correctly
diagnosed.
2024-10-02 18:38:00 +00:00
josh11bandJosh L 49e0c186fc Add comma between the arguments to the bind_symbolic_name instruction (#4358)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-01 23:58:30 +00:00
josh11bandJosh L 958279c869 Update instructions for running tests (#4357)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-10-01 21:29:40 +00:00
Richard Smith 4ca711c175 When converting an expression to type type, retain the resulting instruction as well as the TypeId. (#4355)
The `TypeId` is lossy, as it represents only the canonical type, and not
the specific computation that produced it.
2024-10-01 01:49:39 +00:00
Richard SmithandJon Ross-Perkins 9d5ec52232 Use more compact storage for impl lookup buckets. (#4351)
If the bucket is of size zero or one, which is expected to be the common
case, then store it directly. For the remaining cases, use a side table
of lookup buckets.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-29 17:31:53 +00:00
Richard Smith 5ab957d012 Make ImplDecls evaluate to themselves. (#4352)
Change ImplDecls so they evaluate to themselves in general, rather than
having a special case in import handling that pretends that they do.
2024-09-27 22:39:56 +00:00
Jon Ross-Perkins 9d1d8d75be Replace llvm_symbolizer with a cc_env_data() array. (#4354)
This is a minor adjustment to make it easier to modify (or omit) data
where needed. Also, makes it pair better with cc_env().
2024-09-27 21:50:59 +00:00
Richard SmithandJon Ross-Perkins 2f3ad26f0e Basic support for declaring generic impls. (#4336)
Update impl handling to more closely match other kinds of declaration,
including support for declaring and defining gneeric `impl`s.

When of performing redeclaration lookup for impls by looking for the
self and constraint type, produce a list of impls rather than a single
impl because it's possible for there to be multiple impls with different
deduced parameters but the same self type and constraint. Following
#3763, only consider impls to be redeclarations if they're spelled the
same, not just if they have the same self and constraint types.

No support yet for impl selection to deduce the arguments of a generic
impl.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-27 21:18:24 +00:00
Jon Ross-Perkins 74d6fc0b9f Update LLVM and use a hermetic llvm-symbolizer (#4347)
This only sets the symbolizer for our more used targets; not sure if
there's a great way to set it everywhere (I suppose I could try wrapping
cc_binary etc rules if there's a strong preference).

There is a downside here, symbolizing a fastbuild crash seems to take
about 3s. Not sure if there's a good way to get a faster llvm-symbolizer
execution...?

I tried running with the new LLVM update without the
LLVM_SYMBOLIZER_PATH, and it looks like that's insufficient. With the
settings, I now get readable crashes:

```
 #9 0x000055dc007d1724 void Carbon::Internal::CheckFail<Carbon::TemplateString<5>{"FATAL"}, Carbon::TemplateString<27>{"toolchain/driver/driver.cpp"}, 84, Carbon::TemplateString<0>{}, Carbon::TemplateString<3>{"err"}>() (/usr/local/google/home/jperkins/.cache/bazel/_bazel_jperkins/85deb7d9d96f7e0e80b42618a55969d7/sandbox/linux-sandbox/9383/execroot/_main/bazel-out/k8-fastbuild/bin/toolchain/testing/file_test.runfiles/_main/toolchain/testing/file_test+0x2894724)
```

Note the LLVM update is for
https://github.com/llvm/llvm-project/pull/109021
2024-09-27 20:41:55 +00:00
Jon Ross-PerkinsandChandler Carruth 4332d8239d Fix invocation issues with clang runner (#4353)
`ToolContext` should be explicitly initialized.

`-c` can still require a valid, writable `-o` path.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-09-27 20:33:11 +00:00
Richard Smith 42bda1e38f Don't substitute into the targeted instructions of an associated constant. (#4342)
When an instruction makes an absolute reference to another instruction,
such as when `assoc_const` refers to the declaration of the associated
constant in an interface, substitution into that instruction should not
substitute into the referenced instruction.

Mark the corresponding `InstId` fields in the typed instructions as
being absolute by giving them a distinct ID type that `Subst` doesn't
substitute into. This formation of unnecessarily complicated SemIR that
could in some cases lead to a CHECK failure when printing formatted
SemIR because the same instruction ends up in multiple scopes.
2024-09-27 17:41:05 +00:00
Jon Ross-Perkins 73c6f67378 Add support for capturing console output to FileTest. (#4339)
One of the things that ClangRunnerTest is doing is capturing
stderr/stdout because clang prints to it directly. This adds support for
that to FileTest.

I'm renaming the current `capture_output` field to `dump_output` because
the name is ambiguous after this change, and the flag is already named
`--dump_output`. It's still not great, but at least it's more distinct.

Note ClangRunner still doesn't use the vfs; that still needs work. I'm
just moving the NoArgs test over as a trivial test of the functionality.
2024-09-27 16:10:44 +00:00
bdbd1079a6 where check stage, step 2: SemIR (#4349)
The check stage now produces SemIR instructions to represent a `where`
clause. It still does not check types.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-27 01:41:56 +00:00
Jon Ross-Perkins 4c9ffb0dee Fix TryEvalInstInContext to be static (#4346)
Also noticed `MakeIntTypeResult` should be static.
2024-09-27 00:22:11 +00:00
Jon Ross-Perkins b1f93d0881 Remove declare_symlink use (#4345)
We're trying to remain compatible with an environment where
`declare_symlink` is (apparently) disallowed.
`--allow_unresolved_symlinks=false` will prevent regressions.
2024-09-26 18:03:11 +00:00
Jon Ross-Perkins 98e0d22b60 Refactor InstallPaths API and comments a little. (#4341)
Stemming from #4331, trying to break apart InstallPaths class comments
into three parts:

- Construction semantics, staying in the class comment
  - Trying to refer to methods with more detailed  documentation.
- Install prefix contents, now on `prefix_`
- Install structure, consolidating on `install_dirs`

For code refactoring, `driver()` and `prefix()` were only used by the
install paths test. Rather than having a comment not to use `prefix()`,
this instead extracts it out to a TestPeer model (which we have
elsewhere with `TypedNodesTestPeer`, thus my choice in approaches).
2024-09-26 16:16:53 +00:00
Richard Smith 7f22a289b9 Push a generic region when handling a where expression. (#4340)
This fixes a crash in the case where a `where` expression appears
outside of any generic.
2024-09-26 00:24:38 +00:00
Jon Ross-Perkins ee383638bc Flush pending diagnostics on crash. (#4337)
This risks diagnsotic formatting crashing, but I think we more
frequently see cases where it'd be interesting to know what diagnostics
were being delayed as part of the default sorting.
2024-09-25 21:00:36 +00:00
Geoff RomerandJon Ross-Perkins dc32aa2690 Initial support for binding patterns in SemIR (#4221)
Introduces the `BindingPattern` and `SymbolicBindingPattern` insts, and
a separate stack of pattern blocks that they are emitted into. The
intent is to generate the corresponding pattern-matching insts (like
`BindName`) from them in a separate pass, but that is deferred to future
PRs.

See
[here](https://docs.google.com/document/d/1U_vQH17V893J9aF1LJXUnFYBNSs2MjKl4bJPaWCB2zo/edit?usp=sharing&resourcekey=0-w0xGYZ0An31Kpz-wvzSXwQ)
for the design this is based on, but note that during review we have
chosen to deviate from that design by putting the patterns in separate
blocks, and omitting the "forward references" from a `BindingPattern` to
its corresponding `BindName`. This in turn necessitates having separate
inst kinds for symbolic and non-symbolic binding patterns.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-25 19:12:58 +00:00
Jon Ross-PerkinsandRichard Smith 87678cc374 Disallow compile time bindings where they aren't clearly supported. (#4338)
This is resolving a fuzz-discovered crash related to function suspends
and compile time bind indices. Although the crash originally came from
clearly invalid syntax (missing the `=` inside a `class` decl), the
syntax with a value should also be valid but has the same crash.

This approach disallows compile-time bindings in contexts that can
create ambiguous results, particularly class declarations. These are an
issue because a suspended function can have let declarations after it.
I'm allowing them in function bodies and interface scopes.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-09-25 17:06:09 +00:00
49a8efbe1b where check stage, step 1: designators (#4329)
Right now, there is no checking of `where` requirements. The result of a
where expression is just the type on the left-hand side. It does now
introduce `.Self` so that it is available in expressions on the
right-hand side, in addition to designators corresponding to the members
of type on the left-hand side. Note, though, that diagnostics could
still be improved significantly.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-25 02:44:12 +00:00
Jon Ross-PerkinsandChandler Carruth bba4f8aa20 Refactor install structure to make changes easier. (#4332)
Instead of separately constructing file information for `filegroup` and
`pkg_filegroup`, this instead creates a single structure which is used
to generate both. Additionally, I'm unifying the `llvm_link_data` and
`install_lib_data` targets (though the `llvm_link_data` target is
problematic for busyboxing, I don't think it can keep working as it does
right now).

Note I'm also stopping reuse of llvm's binary_alias. We need to be able
to symlink non-binary files, so I'm going to just share logic there.
(plus, I admit I find the name "binary_alias" confusing since it's not
an alias in bazel terms)

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-09-24 17:19:44 +00:00
Richard Smith 8d45530c5f Add a note: prefix to all notes. (#4330)
Omit the `note: ` prefix and the snippet from the "in import" note that
precedes a diagnostic.

This makes our diagnostic output more closely match that of Clang and
GCC.
2024-09-23 23:59:25 +00:00
Jon Ross-PerkinsandChandler Carruth c107aaad13 Add a clang subcommand. (#4322)
This makes something like `bazel run :toolchain -- clang -- -c test.cpp`
work, because that can be run in-process. Note that `bazel run
:toolchain -- clang -- test.cpp` still requires subprocessing, and does
not work.

Note, the vision here is that we are trying to align how clang and
carbon compile c++ code. This is work towards intertwining command
execution.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-09-23 23:21:20 +00:00
Jon Ross-Perkins c7057eff89 Improve install_paths handling for relative paths. (#4331)
Because install_paths is not presently validated, and it's resolved
after the `SetWorkingDirForBazel` call, if a relative path is used with
bazel then it would fail silently. This starts making the driver share
install path errors, and starts changing how `//toolchain` launches
`carbon`.

Note the implementation is still brittle and will break with symlinks.
That's something I plan to address as part of busyboxing.
2024-09-23 22:26:53 +00:00
Jon Ross-Perkins edc6ed3d10 Clean up comment about node ID. (#4335)
Without researching, I think this just predates the templating. Also
refactoring the body since there's not really a benefit to having each
line be its own expression, and the `arg.loc_id.node_id()` is a little
indirect when `node_id` is an argument.
2024-09-23 22:18:10 +00:00
Jon Ross-PerkinsandChandler Carruth 434ee32515 Style notes on passing and storing object addresses (#4310)
[Context](https://discord.com/channels/655572317891461132/821113559755784242/1283516297686286377).
Some relevant Google C++ style is at [Inputs and
Outputs](https://google.github.io/styleguide/cppguide.html#Inputs_and_Outputs).
#4301 is an example application of the style.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-09-20 23:53:02 +00:00
Jon Ross-Perkins 9b0519d236 Convert CommandLine member references to pointers (#4301)
This follows up on a [style
question](https://discord.com/channels/655572317891461132/821113559755784242/1283516297686286377)
about whether to prefer reference members or pointers. This PR converts
to pointers as a demonstration of that style choice.

Note, I'm trying to update constructors to match use of `*` based on
whether they keep a reference. I'm removing a few `const&` uses where no
reference was kept (i.e., it was just copied, and didn't seem worth a
move).

I'm changing `AddArgImpl` to return an `Arg*` because it just gets
passed to a constructor, seems simpler this way.
2024-09-20 20:30:04 +00:00
864c832971 Lambdas (#3848)
This document proposes a path forward to add lambdas to Carbon. It
further proposes augmenting function declarations to create a more
continuous syntax between the two categories of functions. In short,
both lambdas and function declarations will be introduced with the `fn`
keyword. The presence of a name distinguishes a function declaration
from a lambda expression, and the rest of the syntax applies to both
kinds. By providing a valid lambda syntax in Carbon, migration from from
C++ to Carbon will be made easier and more idiomatic. In C++, lambdas
are defined at their point of use and are often anonymous, meaning
replacing them solely with function declarations would create an
ergonomic burden compounded by the need for the migration tool to select
a name.

Associated discussion docs:

* [Lambdas Discussion
1](https://docs.google.com/document/d/1rZ9SXL4Voa3z20EQz4UgBMOZg8xc8xzKqA1ufPQdTao/)
* [Lambdas Discussion
2](https://docs.google.com/document/d/14K_YLjChWyyNv3wv5Mn7uLFHa0JZTc21v_WP8RzC8M4/)
* [Lambdas Discussion
3](https://docs.google.com/document/d/1VVOlRuPGt8GQpjsygMwH2B7Wd0mBsS3Qif8Ve2yhX_A/)
* [Lambdas Discussion
4](https://docs.google.com/document/d/1Sevhvjo06Bc6wTigNL1pK-mlF3IXvzmU1lI2X1W9OYA/)

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-09-20 02:08:59 +00:00
Richard SmithandJon Ross-Perkins 50bce0c865 Adopt new diagnostic conventions in handle_class.cpp (#4327)
Doing this to a couple of diagnostics was suggested in review comments
on #4320, so I've applied the suggestions across the whole file.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-20 00:25:15 +00:00
Jon Ross-PerkinsandRichard Smith e7aebbe581 Update basic diagnostic capitalization/punctuation (#4328)
This is a primarily automated change:

- Search & replace for capitalization
-
`(CARBON_DIAGNOSTIC\((?:\n\s+)?\w+,(?:\n\s+)?\s\w+,(?:\n\s+)?\s")([A-Z])`
    - `$1\L$2`
- Search & replace for period
-
`(CARBON_DIAGNOSTIC\((?:\n\s+)?\w+,(?:\n\s+)?\s\w+,(?:\n\s+)?\s"(?:[^)]|\n)+)\.("[,)])`
    - `$1$2`
- Limited search & replace for `ERROR: ` -> `error: ` in streamed things
- Leaving a TODO for command_line because there's more cleanup that can
be done there
- Modify diagnostic_consumer.cpp
    - ERROR -> error
    - WARNING -> warning

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-09-19 21:32:53 +00:00
Geoff Romer 7f6d684b29 Add usage tips to NOAUTOUPDATE tests (#4324)
These tips are especially valuable in these cases, because you can't use
`autoupdate_testdata.py` to identify the output difference, so dumping
the output is pretty much the only option.
2024-09-19 21:00:21 +00:00
josh11bandJosh L db78450c61 Fix singular/plural mismatch in design README (#4326)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-09-19 20:58:57 +00:00
Jon Ross-Perkins f7304b21ac Iterate on diagnostic structure (#4321)
Part of this is also a plan to change "ERROR:" -> "error:" in
diagnostics. I think I'm the odd one out on sentence casing. The rest is
mostly trying to figure out advice that I think we can live with.

Note I'm not immediately planning to rewrite all diagnostics (unless
maybe there's a simple regex). I'm more trying to redirect style a
little to where preferences lie, particularly for new diagnostics.
2024-09-19 20:35:50 +00:00
Richard Smith 2044366652 Support initialization of specific classes from struct literals (#4320)
Add support for initializing types like `GenericClass(i32)` from a
struct literal. A new kind of instruction, `complete_type_witness`, is
added to the class definition to track the object representation type so
that it's visible to the generics machinery. Accesses to the object
representation of a class have all been updated to pass in the class's
`SpecificId` so that the types of the fields of the specific class are
used instead of the types of the fields of the generic class in places
that look at the object representation -- primarily class
initialization.
2024-09-19 19:18:32 +00:00
dependabot[bot] d3df61e354 Bump google-protobuf from 4.27.3 to 4.27.5 in /website in the bundler group across 1 directory (#4325)
Bumps the bundler group with 1 update in the /website directory:
[google-protobuf](https://github.com/protocolbuffers/protobuf).

Updates `google-protobuf` from 4.27.3 to 4.27.5
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/protocolbuffers/protobuf/commits">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=google-protobuf&package-manager=bundler&previous-version=4.27.3&new-version=4.27.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 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>
2024-09-19 16:43:01 +00:00
David BlaikieandJon Ross-Perkins 4631767943 Stop name mangling at an imported package name (#4294)
To ensure the outer package name is not mangled into imported names.

With this change I can successfully link/run a two-file example:
```
package Mod;
fn HelloWorld() {
  Core.Print(42);
}
```
```
import Mod;
fn Run() -> i32 {
  Mod.HelloWorld();
  return 0;
}
```
```
$ carbon compile mod.carbon main.carbon
$ carbon link mod.o main.o --output=a.out
$ ./a.out
42
```
\o/

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-18 22:01:08 +00:00
ff1cc43f44 Apply is_closed_import to imported namespaces (#4312)
Spin off from
https://github.com/carbon-language/carbon-lang/pull/4294#discussion_r1752916451

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-09-17 20:56:09 +00:00
Brymer Meneses 7f930d0f58 Use TupleAccess instead of TupleIndex (#4318)
This change removes the `TupleIndex` instruction, and instead
consolidate it with the `TupleAccess` instruction, per this
[discussion](https://discord.com/channels/655572317891461132/655578254970716160/1271195835975204946).
This change, in turn removes `AnyAggregateIndex`.
2024-09-17 20:26:48 +00:00
Brymer Meneses da40c8b076 Improve access checking code (#4317)
This change accomplishes the TODOs for access checking. More
specifically it,
- makes `SemIR::AccessKind` formattable using `llvm::formatv`.
- makes use of `LookupUnqualifiedName` to find `Self`.
2024-09-17 20:26:07 +00:00
Chandler Carruth 1d904556ef Remove [[clang::preserve_most]] (#4319)
These appear to be causing some subtle misinteractions with MSan that we
don't understand, and may be a compiler bug. =/ Fortunately, they
weren't essential to the performance gains so just remove them for now.
When benchmarked on an x86 server, where I would expect this to be more
important due to relatively few named registers, the performance change
appears to be either an improvement or in the noise.

Huge credit to Jon for tracking down that this is related to the MSan
issues.
2024-09-16 22:55:55 +00:00
Chandler Carruth 06344aeb7c Do some tactical inlining across lexer and parser. (#4307)
These are based on looking at our compilation benchmark and looking at
function bodies that seem surprising to not get inlined.

Note that this will have a bit more impact on x86 where function call
overhead (especially due to pushing and popping registers) is a bit
higher than Arm.

For a recent AMD server, this makes parsing around 15% faster, and full
"check" phase 5% faster.

Benchmark results:
```
name                                               old cpu/op   new cpu/op   delta
BM_CompileAPIFileDenseDecls<Phase::Lex>/256        40.2µs ± 2%  37.8µs ± 1%   -5.89%  (p=0.000 n=19+17)
BM_CompileAPIFileDenseDecls<Phase::Lex>/1024        190µs ± 2%   181µs ± 2%   -4.93%  (p=0.000 n=19+18)
BM_CompileAPIFileDenseDecls<Phase::Lex>/4096        779µs ± 1%   745µs ± 2%   -4.29%  (p=0.000 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/16384      3.44ms ± 1%  3.32ms ± 3%   -3.32%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/65536      14.6ms ± 2%  14.3ms ± 3%   -2.46%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/262144     66.7ms ± 2%  65.0ms ± 4%   -2.52%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/256      85.7µs ± 2%  71.3µs ± 2%  -16.77%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024      421µs ± 2%   352µs ± 2%  -16.38%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096     1.71ms ± 2%  1.44ms ± 2%  -15.89%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384    7.19ms ± 2%  6.10ms ± 2%  -15.24%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    29.8ms ± 2%  25.3ms ± 2%  -14.91%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144    127ms ± 2%   109ms ± 2%  -14.28%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/256       785µs ± 1%   752µs ± 1%   -4.13%  (p=0.000 n=20+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024     1.71ms ± 1%  1.62ms ± 1%   -5.17%  (p=0.000 n=20+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096     5.28ms ± 1%  4.97ms ± 1%   -6.04%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    20.2ms ± 1%  19.0ms ± 2%   -5.98%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    83.8ms ± 1%  78.9ms ± 2%   -5.84%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144    354ms ± 1%   335ms ± 1%   -5.41%  (p=0.000 n=19+20)
```
2024-09-15 23:48:19 +00:00
580e84513c Brief documentation for the current name mangling scheme (#4286)
Documents the scheme thus far, as implemented in
a548eff0bb

---------

Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-14 04:30:38 +00:00
josh11bandJosh L 7611aac355 Clarify what was missing in binding pattern errors (#4314)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-09-14 03:31:43 +00:00
Jon Ross-Perkinsandjosh11b c029931910 Refactor link and compile into subcommand objects. (#4303)
Note the purpose here is to make it simpler to add more subcommands,
without adding a lot of things to Driver.

This creates a copy of CodegenOptions, but it was double-registered at
present which felt odd. It's also fairly small right now. If this
becomes an issue, maybe we can look into using optional for delayed
initialization, or just go back to straight sharing.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-09-14 03:16:53 +00:00
Richard Smith 5d481877f1 Omit a trailing SpecificId by default when formatting instruction arguments. (#4315) 2024-09-13 23:15:59 +00:00
David Blaikie 02950e46d3 Ignore the .gdb_history that's created next to the project-specific .gdbinit (#4313) 2024-09-13 21:37:57 +00:00
Richard Smith 0354efa1fc Rework how we check calls to support deduced implicit parameters (#4302)
Instead of the `call` instruction having a block with one argument per
explicit argument, preceded optionally by `self` and followed optionally
by a return slot, change the `call` to store only the *runtime*
arguments. Store an index on the runtime parameters to make it easier to
determine the correspondence between arguments and parameters in a call.
Compile-time parameters, whether implicit or explicit, are no longer
included in the call argument list. Instead, they're tracked only in the
`specific_id` on the callee.

For calls to generic classes and generic interfaces, it no longer makes
sense to form a `call` instruction, given that the entirety of the
result is determined by the `specific_id`, which is now formed when
checking the call. Instead, the `call` instruction now only models
function calls, and not calls to other kinds of parameterized entity
names, and we create a `class_type` or `interface_type` instead of a
`call` instruction to model these kinds of calls. Notionally the model
here is that we're following the #3720 approach for calls, but for now
we inline the `Call.Op` function when forming SemIR.

We now also track the enclosing specific for a generic class or generic
interface that appears within an enclosing generic. This is necessary in
order for deduction of the inner generic parameters to not get confused
by the outer generic parameters being absent.

In order to not regress diagnostics, the template argument deduction
mechanism has been extended to specify the name of the parameter we're
deducing against when possible, and call arity mismatch errors are now
diagnosed before performing deduction rather than afterwards.
2024-09-13 21:31:43 +00:00
Jon Ross-Perkins 8b92b996b1 Move 'core' directory prefix (#4311)
This fixes a bit of sloppiness from #4305, the prefix should really be
specified in one place.
2024-09-13 18:52:10 +00:00
Jon Ross-PerkinsandGeoff Romer 1b956e68fe Extract subcommand options from the driver file. (#4300)
I'm separating the options out so that it's easier to review. They
include a lot of boilerplate text that I think won't change much, and
makes it harder to review changes.

To explain filename differences, whereas `CodegenOptions` is shared (by
link and compile), `LinkOptions` and `CompileOptions` are
subcommand-specific. I'm planning to separate out the subcommands, so
I'm putting those in respective subcommand files. I'm still going to try
to use the `.h` to declare the interface, `.cpp` for bigger
implementation details (for better or worse, including comments on
options).

I'm also moving out corresponding Driver members to help shrink deltas
when refactoring. That is, the bodies aren't changing here, but a
refactoring of commands will make some changes. By moving the code to
different files now, it should be easier to identify what's changing
later.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2024-09-13 16:17:51 +00:00
Chandler Carruth 02c263294c Move the constants in the precedence table into the header. (#4308)
Getting the basic constants is actually quite hot in the parser, and is
spending all of its time in memory stalls due to touching the call stack
just to return a constant when these are out-of-line.

This alone is worth another 8% improvement in parsing, and 2% in syntax
checking:
```
name                                               old cpu/op   new cpu/op   delta
BM_CompileAPIFileDenseDecls<Phase::Lex>/256        37.7µs ± 1%  37.5µs ± 2%  -0.58%  (p=0.019 n=19+18)
BM_CompileAPIFileDenseDecls<Phase::Lex>/1024        181µs ± 1%   179µs ± 2%  -0.95%  (p=0.001 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/4096        743µs ± 1%   736µs ± 2%  -0.85%  (p=0.001 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/16384      3.30ms ± 1%  3.25ms ± 2%  -1.48%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/65536      14.2ms ± 1%  13.9ms ± 2%  -1.95%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/262144     64.7ms ± 2%  63.8ms ± 2%  -1.30%  (p=0.000 n=18+18)
BM_CompileAPIFileDenseDecls<Phase::Parse>/256      71.0µs ± 1%  65.2µs ± 2%  -8.20%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024      351µs ± 1%   320µs ± 1%  -9.02%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096     1.43ms ± 2%  1.31ms ± 2%  -8.41%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384    6.08ms ± 2%  5.57ms ± 1%  -8.49%  (p=0.000 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    25.2ms ± 1%  23.2ms ± 1%  -8.08%  (p=0.000 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144    109ms ± 1%   101ms ± 1%  -6.93%  (p=0.000 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/256       752µs ± 1%   744µs ± 1%  -1.07%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024     1.62ms ± 1%  1.59ms ± 1%  -1.88%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096     4.97ms ± 2%  4.85ms ± 1%  -2.43%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    19.0ms ± 2%  18.5ms ± 2%  -2.32%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    78.8ms ± 2%  76.9ms ± 2%  -2.50%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144    334ms ± 1%   327ms ± 2%  -2.29%  (p=0.000 n=20+20)
```
2024-09-13 10:03:21 +00:00
David Blaikie ec63d2be21 Assert that the llvm::Function is created with the same name as requested (#4306)
This will catch some cases of bugs in the name mangling logic - if
within a single file we incorrectly mangle two distinct entities to the
same name, llvm::Function will assign a new name to the second copy
showing one of the two entities should have a distinct name/is missing
something in their mangling.
2024-09-13 00:33:29 +00:00
88f3b3470f Improve error recovery in binding patterns (#4309)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-09-12 21:12:04 +00:00
Jon Ross-Perkins a8d4f068e3 Switch to ctx.label.package for rule, and adjust relative path handling (#4305)
build_file_path works with bazel but I'd missed it's
[deprecated](https://bazel.build/rules/lib/builtins/ctx#build_file_path).

Relative path handling also could use some improvements.

Both of these are really to support non-standard environments,
essentially.
2024-09-12 16:52:59 +00:00
4845f40dff Switch CARBON_CHECK to a format string API (#4285)
This switches `DCHECK` and `FATAL` as well.

The goal is to reduce the code size impact of these assertions so that
we can keep more of them enabled. Currently, the largest cost I see from
`CHECK` is not the actual check or the cold code itself, but actually
the failure to inline trivial functions due to the presence of the cold
code. This means that our goal isn't to reduce apparent code size in the
final binary but the LLVM IR cost assessed for these routines in the
inliner, which closely correlates with code size but is a bit different.

As discussed in #4283, experimentation shows that a single function call
with a minimal number of arguments is the lowest cost model for these.
This is easily achieved with a format-string API that internally uses
`llvm::formatv`. This PR is essentially the `CHECK` version of #4283.

However, the check macros are substantially harder to make work with
both format strings and streaming because they also take a condition.
Also, unexpectedly, I was very successful at devising a regular
expression based automated rewrite from the streaming to the format
string form with only low 10s of manual fixes. This includes compacting
strings broken up across lines, etc. Given how well that went, I've
prepared this PR which just directly switches to the format string API
and migrate everything to use it.

One nice side-effect is that the format string approach ends up greatly
simplifying the implementation here as well.

This is ... *shockingly* effective. Parsing speeds up by more than 3%
with just this change. And checking speeds up by **8%** with this change
alone:
```
BM_CompileAPIFileDenseDecls<Phase::Parse>/256      86.3µs ± 1%  82.9µs ± 1%  -3.94%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024      431µs ± 1%   415µs ± 1%  -3.76%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096     1.77ms ± 1%  1.71ms ± 1%  -3.18%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384    7.44ms ± 1%  7.17ms ± 2%  -3.56%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    30.7ms ± 1%  29.7ms ± 1%  -3.15%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144    131ms ± 1%   127ms ± 1%  -2.81%  (p=0.000 n=18+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/256       878µs ± 2%   800µs ± 1%  -8.91%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024     1.88ms ± 2%  1.72ms ± 1%  -8.56%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096     5.78ms ± 2%  5.28ms ± 1%  -8.70%  (p=0.000 n=20+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    21.9ms ± 1%  20.1ms ± 1%  -8.02%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    90.4ms ± 2%  83.1ms ± 1%  -8.04%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144    381ms ± 2%   352ms ± 1%  -7.79%  (p=0.000 n=19+19)
```

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-09-12 16:42:08 +00:00
josh11bandJosh L 35dfa5f03c Only allow designators when parsing where __ = ... (#4304)
Implements
[TODO](https://github.com/carbon-language/carbon-lang/pull/4275/files#r1751000646)
introduced in #4275 . Note that this enforces the restriction
syntactically in parse, following the
[design](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/generics/details.md#rewrite-constraints).

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-09-12 01:39:22 +00:00
Jon Ross-Perkins de57c9988c Break out driver environment info into its own type. (#4299)
I want to split commands out so that we don't keep piling onto driver
(particularly as I'm eyeing clang-related commands). This extracts out
the DriverEnv so that it can be easily shared, with the CompilationUnit
as an example.

CARBON_VLOG_TO is to remove the vlog_stream_ requirement of CARBON_VLOG.
2024-09-12 00:06:31 +00:00
d6b2fb1736 Add parse support for multiple requirements after where separated by and (#4298)
Follow on to #4275 that added `where` parse support.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-09-11 21:36:55 +00:00
Brymer Meneses 6bfaa888e8 add additional testdata for access checks (#4297)
I just realized that
https://github.com/carbon-language/carbon-lang/pull/4248 should now
correctly enforce compound member access. This change adds tests for
this functionality.
2024-09-11 16:59:36 +00:00
Jon Ross-Perkins 37a70dfa79 Update the talk list (#4279)
The LLVM Developers' meeting agenda was [just
published](https://discourse.llvm.org/t/announcing-the-2024-llvm-developers-meeting-program/81108),
so add that.
2024-09-11 16:30:31 +00:00
Chandler Carruth 0c8ab663c9 Migrate all CARBON_VLOG to the format string variant. (#4284)
This mostly uses a hilarious set of regular expressions to mechanically
switch all but two uses, and then manually fixed the last two. There
weren't too many.

Also simplifies the `vlog` implementation now that it's all going
through a format string.

This alone has a nice impact on parse and check of about 2% and 1%
respectively. The impact on lex in my timings looks like noise (no
change in instruction count, unlike the other phases).
```
name                                               old cpu/op   new cpu/op   delta
BM_CompileAPIFileDenseDecls<Phase::Lex>/256        39.1µs ± 3%  38.1µs ± 2%  -2.42%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Lex>/1024        187µs ± 3%   183µs ± 1%  -2.30%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/4096        776µs ± 4%   756µs ± 1%  -2.62%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/16384      3.36ms ± 1%  3.33ms ± 1%  -0.90%  (p=0.000 n=18+18)
BM_CompileAPIFileDenseDecls<Phase::Lex>/65536      14.4ms ± 2%  14.2ms ± 1%  -1.41%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Lex>/262144     65.7ms ± 1%  65.2ms ± 2%  -0.86%  (p=0.002 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/256      87.5µs ± 1%  86.3µs ± 1%  -1.43%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024      438µs ± 2%   431µs ± 1%  -1.54%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096     1.81ms ± 2%  1.77ms ± 1%  -2.12%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384    7.54ms ± 1%  7.43ms ± 1%  -1.44%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    31.2ms ± 1%  30.6ms ± 1%  -2.03%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144    133ms ± 1%   130ms ± 1%  -1.85%  (p=0.000 n=20+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/256       882µs ± 1%   878µs ± 1%  -0.52%  (p=0.001 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024     1.90ms ± 2%  1.88ms ± 1%  -1.17%  (p=0.000 n=19+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096     5.85ms ± 2%  5.76ms ± 1%  -1.43%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    22.2ms ± 2%  21.9ms ± 2%  -1.20%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    91.2ms ± 2%  90.3ms ± 1%  -1.00%  (p=0.000 n=20+19)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144    382ms ± 1%   380ms ± 1%  -0.51%  (p=0.003 n=18+19)
```
2024-09-11 12:11:23 +00:00
e48101b608 Switch CARBON_VLOG to support a format string API. (#4283)
The goal is to replace our stream operator APIs with format string APIs
that can be made to have much less impact on inlining and other
optimizations of the performance critical path through the code.

Several experiments show that the most compact representation we can
arrange for is one that calls an uninlined function and passes a minimal
number of arguments to it. It doesn't help to do any work to minimize
the arguments such as building a lambda -- the cost of extra code to
merge the arguments is likely to outweigh the benefit.

Initial experiments showed that switching a hot but uninlined function
to this new API enabled inlining and the subsequent performance
improvement.

This also adds a 'TemplateString` utility that allows using a string
literal as a template parameter. This is useful to remove the format
string itself from the arguments passed to the function by passing it as
a template argument instead.

Currently, support is left in place for both APIs because with
`CARBON_VLOG` we can detect whether or not any message was provided
expecting a format string. This should allow incrementally migrating
code to this API. I've added some test coverage in this PR, but I'll
separate out any switching of parts of the codebase over.

The goal is to eventually replace all the usages and remove the
streaming support entirely.

This PR doesn't update `CARBON_CHECK` in the same way because it is
substantially more complex to switch. I have a few experimental PRs
looking at that and will discuss how best to approach this with the
specific challenges check presents separately. But the goal is for all
of the macro-based output APIs to move to format strings rather than
streams.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-09-11 10:38:59 +00:00
c33c9a02f6 Parse support for where operator (#4275)
Includes support for the `impls`, `=`, and `==` requirement operators to
the right of a `where`, but `and` to allow multiple requirements is
still a TODO.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-09-11 03:17:07 +00:00
josh11bandJosh L 8fa173b58a Add explicit to match style, appease clang-tidy (#4296)
Introduced by https://github.com/carbon-language/carbon-lang/pull/4290

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-09-11 00:03:25 +00:00
Brymer Meneses 63ebc3df17 docs: add missing syntax highlighting (#4289) 2024-09-10 22:59:30 +00:00
Jon Ross-Perkins 19f6cd2023 Split if expressions out of handle_expr (#4292)
Just a small factoring thing. The `if` logic is sizeable, and there's no
need for it to be in handle_expr (we do also have handle_brace_expr,
handle_index_expr, etc)
2024-09-10 22:57:32 +00:00
Jon Ross-Perkins d4c7743d18 Update tests to use [[@TEST_NAME]] (#4293)
Applies #4278 TEST_NAME substitution to tests. Note I've tried to
structure commits as:

1. Do all the replacements.
2. autoupdate (nothing else) -- this shows incorrect updates.
3. Fix up manually, including autoupdates to get back to original
output.
2024-09-10 22:52:23 +00:00
David BlaikieandJon Ross-Perkins b8f61a712e Add KeywordModifierSet helper for conversion to (likely SemIR) enums (#4290)
(based on
https://github.com/carbon-language/carbon-lang/pull/4272#discussion_r1751001345)

Could haggle over the name "ToEnum" probably avoids the debate over
"enumeration" (the type being returned) v "enumerator" (the value being
returned)

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-10 22:01:21 +00:00
Jon Ross-Perkins 6311552fcc Generate and use a manifest for prelude files. (#4291)
This removes the directory crawl because bazel doesn't remove files from
execroot when the rule generating them would no longer generate them.

Fixes #4288
2024-09-10 20:59:49 +00:00
Jon Ross-Perkins 2e299f5fc4 Make the 'library' lines in tests use a substitution. (#4278)
This opens the door for replacing all `library ...` lines in toolchain
test files with `library "[[@TEST_NAME]]";`. That's technically more
typing in a lot of cases, but OTOH means we can just do some copy-paste
boilerplate and stop carefully writing library names.

Also cleans up the test setup, because it's getting messy. I'm trying to
make it easier to see the divisions of tests and the output associated
with them. StringSwitch looked like a way to do this, with a few edits
to make it work nicely.
2024-09-10 20:24:11 +00:00
David BlaikieandJon Ross-Perkins 5806d8385d Add SemIR support for virtual functions (#4272)
I guess this technically would also allow code to pass check that hasn't
before, and that isn't covered by tests (since it's masked by other
failures in the tests that already test this functionality) - should I
add another test/add some code to a valid test case?

Also, this'll miscompile in lowering, since there's no support there yet
- should I do anything about that to make lowering fail in some way? Or
is it acceptable that some things just silently mis-lower? (I could add
a currently-miscompiling test case too, to demonstrate this? (not sure
if the autogenerated tests leave space for comments that would explain
that the currently-tested behavior is incorrect?))

Is the addition to EntityWithParamsBase suitable? of course not all
functions can be virtual, so it's a wasted bit at the moment for all
those cases (though it's free, since it's bitpacked - but as we want to
add more bits in there it might not be a scalable solution)?

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-10 18:16:59 +00:00
Brymer Meneses 8ac9c80e87 Enforce private and protected access modifiers for class member access (#4248)
Print diagnostics for invalid class member access. This doesn't take
into account compound member access.
2024-09-10 16:35:07 +00:00
Jon Ross-Perkins 43c6259fb2 Update LLVM and fix formatv issues. (#4282)
https://github.com/llvm/llvm-project/pull/105745 increased validation of
formatv requirements, this fixes a couple issues.

Note the CommandLine case was untested, and caught separately.
2024-09-09 23:54:35 +00:00
Chandler Carruth f641cb95d2 Manually free up disk space on macOS (#4287)
This should mitigate the effects of a GitHub regression that reduced
space on these runners:
https://github.com/actions/runner-images/issues/10511

After this, we're mostly fine, but builds that happen to compile enough
of the codebase can bump past it. With this PR we have over 50 GiB of
space which is more than we need.

See a test run here:
https://github.com/carbon-language/carbon-lang/actions/runs/10780743574
2024-09-09 20:42:06 +00:00
Richard Smith a4fe9be2e4 Resolve the definition of the self specific when re-entering its scope for an inline method definition. (#4281)
This fixes a crash if an inline method definition attempts to access a
member of the enclosing generic scope directly.

Fixes #4229.
2024-09-06 23:23:40 +00:00
a548eff0bb Rudimentary name mangling support (#4267)
This seems to be enough to avoid naming collisions for functions in any
of the current test cases (verified by asserting that the name of the
`llvm::Function` matches the name passed to create it - not triggering
LLVM's numbering that happens when names collide)

It currently implements mangling for namespace scopes, class scopes, and
impls.
Nothing generic is mangled yet - haven't looked at how that works,
though evidently it's not covered by existing testing, I guess.

Follow-up change will document the current mangling algorithm in
`toolchain/docs/lower.md`

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-09-06 23:10:21 +00:00
Geoff Romer 49f2136325 Remove default from ComputeIdKindTable switch (#4280)
I've repeatedly struggled with very obscure build errors that turned out
to be caused by a newly-introduced node kind getting inappropriately
defaulted to `Id::Kind::Invalid`. Dropping the default will turn those
mistakes into much more straightforward "missing case in switch" errors.
2024-09-06 20:10:00 +00:00
c43fa3a8a5 Bit-pack the lexer's token info (#4270)
This makes each token info consist of 8 bytes of data:
- 1 byte of the kind
- 1 bit for whitespace tracking
- 23 bits of payload
- 32 bits for byte offset in the file

This builds directly on representing the location of the token as
a single 32-bit offset, now compressing the rest of the data into
a single 32-bit bitfield.

This adds some implementation limits: we can no longer lex more than
2^23 tokens in a single source file. Nor can we have more than 2^23
string literals, integer literals, real literals, or identifiers. Only
the first of these is even close to an issue, and even then seems
unlikely to ever be a problem in practice.

The memory efficiency here is great and the motivating goal. But to make
this work well, we also need to streamline how we create the tokens.
Otherwise, all the bit fiddling can end up erasing our gains. This PR
adds a number of APIs to manage creating and accessing the now
significantly more complex storage of token infos to try and help with
this.

One big change required to simplify the writes here is to switch from
computing whether a token has trailing space after-the-fact to
pre-computing whether a token will have leading space. That lets us have
the leading space information available immediately when forming the
token, and avoids doing a single bit flip afterward.

Another change that helps with this representation is to minimize the
updating of groups after-the-fact. The code now tries to set the opening
index directly when creating the closing token and only updates the
opening group afterward. Because of the bit packing, this is a reduction
of 0.5% of dynamic instructions in the compile benchmark, and has
dramatic improvements for the grouping symbol focused benchmarks.

All combined, this is a significant improvement on the lexer-focused
benchmarks despite the added complexity, and a significant win on our
compile time benchmarks due to both the lexer improvements and
downstream memory density improvements: 5-12% reduction in lex time,
growing larger as files get larger. About a 4.5% reduction in parse
time, and even a 1-2% reduction in total check time. =D

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2024-09-06 16:22:36 +00:00
Richard SmithandJon Ross-Perkins 187a3608df Use As and ImplicitAs interfaces for conversions. (#4209)
Add these interfaces to the core library. For now, they're two separate
interfaces because we don't yet support one interface extending another.

This collapses a lot of the layering in check: for example, the call
building logic depends on implicit conversions, conversions now depend
on the overloaded operator machinery, and that machinery depends on
building calls.

In passing, improve the diagnostics for failing to find a name required
from the prelude. Also convert all the transitively-called code from
`NodeId` to `LocId` given the latter is what the conversion machinery
has available.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-05 23:39:58 +00:00
Richard SmithandJon Ross-Perkins 2d650f7d16 Improve diagnostics for the case where some or all of the prelude is missing. (#4276)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-05 21:35:53 +00:00
Richard Smith ddfd4ad60d Fix use-after-free bug in call argument conversion. (#4277)
Conversion can trigger new entities to be imported, which can invalidate
the reference it holds to an EntityWithParamBase. Instead of holding
such a reference, pull the information we need out of the entity early
and only pass that into ConvertCallArgs.

I couldn't find a good standalone way to test this, but this fixes the
test failure we otherwise see on MacOS after #4209, so it will be tested
once that PR lands.
2024-09-05 21:30:24 +00:00
Jon Ross-Perkins e382e6fd97 Refactor FindPreludeFiles into InstallPaths (#4268)
From the driver's perspective, `FindPreludeFiles` is closely tied to
`compile`. This makes it difficult to refactor commands without
affecting the test dependencies on `FindPreludeFiles`. `InstallPaths`
seems like a decent home since it is responsible for the install
structure.

I'm switching to an `Error` return to allow callers to choose how to
handle it (e.g., in file tests, we typically don't want the direct error
stream).
2024-09-04 22:22:48 +00:00
Jon Ross-PerkinsandDavid Blaikie 1412ecd3f4 Handle unknown lines in DebugInfo (#4252)
Mainly, changes the default from -1 to 0 in DiagnosticLoc, still trying
to keep reusing that. Nothing except for the lowered output is affected,
so I think this is fine.

Also, have lowering consistently call GetDiagnosticLoc.

Pulls in one of the CHECKs suggested from #4251 

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2024-09-04 21:25:02 +00:00
Chandler CarruthandJon Ross-Perkins 97e98bcc5a Shrink the lexer's token location and line data structures. (#4269)
First, this replaces the separate line index and column index in the
token information with a single 32-bit byte offset of the token. This is
then used to compute line and column numbers with a binary search of the
line structure and then using that to compute the column within the
line. In practice, this is _much_ more efficient:

- Smaller token data structure. This will hopefully combine with a
subsequent optimization PR that shrinks the token data structure still
further.
- Fewer stores to form each token's information in the tight hot loop of
the lexer.
- Less state to maintain while lexing, fewer computations while lexing.

We only have to search to build the line and column information off the
hot lexing path, and so this ends up being a significant win and shrinks
some of the more significant data structures.

Second, this shrinks the line start to a 32-bit integer and removes the
line length. Our source buffer already ensures we only have 2 GiB of
source with a nice diagnostic. I've just added a check to help document
this in the lexer. The line length can be avoided in all of the cases it
was being used, largely by looking at the next line's start and working
from there. This also precipitated cleaning up some code that dated from
when lines were only built during lexing rather than being pre-built,
which resulted in nice simplifications.

With this PR, I think it makes sense to re-name a bunch of methods on
`TokenizedBuffer`, but to an extent that was already needed as these
methods somewhat predate the more pervasive style conventions. I avoided
that here to keep this PR focused on the implementation change, I'll
create a subsequent PR to update the API to both better nomenclature and
remove deviations from our conventions.

There may also be a way to de-duplicate the binary search in the
diagnostic location conversion and the main line accessor binary search,
but it wasn't obvious to me that it would be a net savings, so left it
alone for now.

The performance impact of this varies quite a bit...

The lexer's benchmark improves pretty consistent across the board on
both x86 and Arm. For x86, where I have nice comparison tools, it
appears 3% to 20% faster depending on the specific pattern. For Arm
server CPUs at least it seems a much smaller but still an improvement.

The overall compilation benchmarks however don't improve much with these
changes alone on x86. Significant reduction in instruction count
required for lexing, but the overall performance is bottlenecked
elsewhere in the overall compilation it seems. However, on Arm, despite
the more modest gains in special cases of lexing, this shows fairly
consistent 1-2% improvements in overall lexing performance on our
compilation benchmark. And the expectaiton is these improvements will
compound with subsequent work to further compact our representation.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-09-03 23:56:44 +00:00
Jon Ross-PerkinsandChandler Carruth 8b0154ce85 Getting commit access (#4246)
Establish a process for getting commit access. We will:

-   Grant access based on a developer's commit history.
- Someone with commit access should nominate, and a contributor may ask.
    -   A lead will approve nominations. Only one lead is needed.
-   Remove commit access once someone is idle for 6 months.
- "Idle" means no significant project activity on any of GitHub,
Discord,
        or in meetings.
    -   Access removed due to being idle will be restored on request.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-09-03 23:41:22 +00:00
Jon Ross-PerkinsandGeoff Romer a24816a1f4 Move toolchain architecture to markdown (#4242)
Note I'm mostly trying to capture [the
docs](https://docs.google.com/document/d/1RRYMm42osyqhI2LyjrjockYCutQ5dOf8Abu50kTrkX0/edit?resourcekey=0-kHyqOESbOHmzZphUbtLrTw&tab=t.0)
as they exist today, not fixing issues with the docs. I think the doc
itself hasn't changed much lately (i.e., for months). Trying to organize
it a little better though, particularly so that it shows up reasonably
when looking in github or the website.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2024-09-03 23:13:49 +00:00
David Blaikie 2971e129ad Add TODO breadcrumb from for design to semantics proposal (#4271) 2024-09-03 19:17:37 +00:00
Richard SmithandJon Ross-Perkins 891c7d8368 Enforce that the parse node for an instruction has the kind specified in the instruction definition (#4264)
Remove `ReusingLoc` and add enforcement that even for imported
locations, the kind of the parse node for an instruction matches the
kind specified in the instruction definition.

Change the node kind for a few instructions to `NodeId`:

- A couple of instructions had a typed node but could be created
implicitly with any node as part of a builtin implicit conversion. This
happened for `AddrOf`, `ArrayIndex`, and `Deref`.
- A bunch of instructions had `InvalidNodeId` as their associated parse
node kind but were actually always created with a location.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-08-29 21:10:14 +00:00
Richard Smith dada4fc29f Make the nightly instructions work without modification. (#4266)
Compute the date rather than including a placeholder for it. Also
include a command to download the release, taken from Carbon Copy #4.
2024-08-29 05:37:42 +00:00
Jon Ross-Perkins d5f0be08e0 Cleanup unused node_subtree_size (#4262) 2024-08-28 23:36:01 +00:00
Richard Smith 16fd645663 Add source locations to interface_witness and interface_witness_access instructions. (#4265) 2024-08-28 23:30:00 +00:00
David Blaikie 67b287a2f2 DebugInfo: Add the name as-written, separate from the mangled name (#4253)
There's not much mangling happening yet - but Run -> main (and some
overloading numbering happening, maybe LLVM is doing that 'helpfully'
under the hood?) is enough to demonstrate this improvement/fix.

Ah, here it is:
```
#0  llvm::ValueSymbolTable::makeUniqueName (this=0x50287fe5b6c0, V=0x50287fe827e8, UniqueName="F") at external/_main~llvm_project~llvm-project/llvm/lib/IR/ValueSymbolTable.cpp:45
#1  0x000055555c40f964 in llvm::ValueSymbolTable::reinsertValue (this=0x50287fe5b6c0, V=0x50287fe827e8) at external/_main~llvm_project~llvm-project/llvm/lib/IR/ValueSymbolTable.cpp:100
#2  0x000055555c2a91df in llvm::SymbolTableListTraits<llvm::Function>::addNodeToList (this=0x50287fd16f18, V=0x50287fe827e8) at external/_main~llvm_project~llvm-project/llvm/lib/IR/SymbolTableListTraitsImpl.h:75
#3  0x000055555c2a90e5 in llvm::iplist_impl<llvm::simple_ilist<llvm::Function>, llvm::SymbolTableListTraits<llvm::Function> >::insert (this=0x50287fd16f18, where=..., New=0x50287fe827e8)
    at external/_main~llvm_project~llvm-project/llvm/include/llvm/ADT/ilist.h:166
#4  0x000055555c27fef2 in llvm::iplist_impl<llvm::simple_ilist<llvm::Function>, llvm::SymbolTableListTraits<llvm::Function> >::push_back (this=0x50287fd16f18, val=0x50287fe827e8) at external/_main~llvm_project~llvm-project/llvm/include/llvm/ADT/ilist.h:250
#5  0x000055555c27faeb in llvm::Function::Function (this=0x50287fe827e8, Ty=0x50287fd43058, Linkage=llvm::GlobalValue::ExternalLinkage, AddrSpace=0, name="F", ParentModule=0x50287fd16f00) at external/_main~llvm_project~llvm-project/llvm/lib/IR/Function.cpp:521
#6  0x0000555559441f95 in llvm::Function::Create (Ty=0x50287fd43058, Linkage=llvm::GlobalValue::ExternalLinkage, AddrSpace=0, N="F", M=0x50287fd16f00) at external/_main~llvm_project~llvm-project/llvm/include/llvm/IR/Function.h:175
#7  0x000055555c27ebac in llvm::Function::Create (Ty=0x50287fd43058, Linkage=llvm::GlobalValue::ExternalLinkage, N="F", M=...) at external/_main~llvm_project~llvm-project/llvm/lib/IR/Function.cpp:398
#8  0x0000555558ce7bb5 in Carbon::Lower::FileContext::BuildFunctionDecl (this=0x7fffffffc438, function_id=...) at toolchain/lower/file_context.cpp:257
```

That's where LLVM decides to make a new name (name.number) when asked to
create a new global with the same name as an existing global.

It's not a valid mangling scheme - since the name won't be stable
between different compilations, but it is enough to make
single-compilation code build/run for now.
2024-08-28 19:18:54 +00:00
Jon Ross-Perkins b72826c431 Fix parse to use the error tracking consumer for has_errors_. (#4261)
This is how we are setting has_errors_ in other stages; this should only
make parse consistent.

Fixes #4259
2024-08-28 18:41:36 +00:00
702d0d8a53 Parsing of designators like .x or .Self (#4254)
These appear in `where` clauses, as in:

```
U:! InterfaceB where .C = Vector(.D)
V:! type where Vector(.Self) impls Sortable
```

`.Self` can additionally appear in type expressions in a binding pattern
such as `T:! InterfaceA(.Self)`.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-08-28 16:26:23 +00:00
Jon Ross-Perkins b9e9e66cee Update group documentation (#4250)
I'm trying to use this just to document the de facto state. This is
linked to #4246, but I'm trying to keep the two arranged to allow
independent merges.
2024-08-28 08:10:56 +00:00
Jon Ross-Perkins 1614091da4 Fix match code to consistently diagnose invalid parses. (#4260)
This is a minimal fix to consistently diagnose when producing erroneous
nodes. Leaving a TODO in handle_match

Caught while investigating #4259
2024-08-27 23:49:22 +00:00
Jon Ross-Perkins dfe992f1bc Rename DotOrArrow to PeriodOrArrow (#4263)
We generally say Period (this is the only "Dot" in code), so this seems
more consistent.

Also renames a few struct tests that had "dot" in the name.
2024-08-27 23:46:07 +00:00
Jon Ross-PerkinsandRichard Smith bed5fdcbbe Fix indirect import handling for functions. (#4258)
The particular test this focused on is indirect_two_file in
toolchain/check/testdata/function/definition/no_prelude/extern_library.carbon.

This removes `parent_scope_id_for_new_inst` because I think it's
returning unhelpful results. The use was at the root of incorrect
results for the indirect import chain. `name_id_for_new_inst` is
actually wrapping a union, so it's more important.

The merging of `is_extern` and `first_owning_decl_id` in
`handle_function.cpp` feels like it's less correct with the changes
that've been made to `extern`. This ripples in tests, because the error
recovery shifts.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-08-27 20:26:23 +00:00
David Blaikie 2a7c2c5df2 Add test coverage for lowering raw identifiers in function names (#4257) 2024-08-27 19:49:18 +00:00
David Blaikie 4c9021cbc8 Change branch-to-fatal to check condition (#4256) 2024-08-27 18:09:54 +00:00
David Blaikie 5177ebbe2a Fix crash when disabling debug info (#4249)
The source line debug info generation assumed that the function would
have debug info. Check for a non-null di_subprogram_ to ensure we are
emitting debug info for the function.

Rather than checking the di_builder_ - this way if we implement
`nodebug` function attributes, it'll fall out naturally (by creating a
null di_subprogram_) rather than having to come back and change this
from "is debug info enabled" to "is debug info enabled for this
function" later on.
2024-08-26 21:13:39 +00:00
David Blaikie 0ae2a3907e Add line-level debug info (#4247)
Seems to work with lldb ( https://pastebin.com/igKkNECm ), though gdb
has /some/ trouble with the paths (they aren't complete - just using the
filename directly, not providing the working directory - might be some
quick hacks that can help there).
2024-08-26 15:49:31 +00:00
5d73743971 Add link for coherence appendix to Swift forums (#4241)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-08-24 19:44:07 +00:00
Chandler Carruthandjosh11b d9cd3851cf Teach source generation to reference more interesting types. (#4244)
This teaches our source generation tool to create interesting type
references. This include both referencing a weighted distribution of
explicitly specified types, and referencing types that are being defined
in the generated file.

Generating more interesting explicit types will exercise more of
Carbon's prelude, but because C++ doesn't have an automatic prelude with
fundamental types like `int64_t` or tuples, we include some minimal
headers when generating the C++ analog. This likely makes the comparison
more fair rather than less fair as Carbon's toolchain isn't processing
just the generated source, but also its prelude.

The current set of fixed types is based primarily on the set of types
that the toolchain currently implements and a set that seems reasonably
interesting to exercise for compile time performance. We want to try to
cover things that should be optimized in the toolchain, even if a single
source file might not typically hit all of them.

The weights of everything are completely arbitrary, based on intuition
and some hand inspection of some random source files. There is also an
intentional bias towards non-zero coverage and so the tail is much
larger than it should be in reality. The result is that the weights more
reflect the _priority_ of optimizing compile time than the _observed_
distribution in practice. We can refine the weighting scheme in the
future though, potentially with multiple modes to separate coverage from
maximally representative weights, etc. The goal is just to have a
starting point.

The scheme for referencing the defined types requires some care and
complexity to avoid referencing types before they are defined while
still referencing all of the types defined and ensuring the number of
references is stable even as the order is randomized to avoid fixed
patterns in the source code.

All of this also triggered some minor refactoring of the state used to
generate class definitions in the source generator. There are probably
some good follow-on refactoring opportunities, but I'd prefer to leave
those to future work.

I don't have any tests here because most of how this is observable is
already tested -- the existing tests ensure the file sizes remain
consistent and that the generated code is compiled correctly. But if
folks have any ideas of useful tests here, happy to add them.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-08-24 05:13:08 +00:00
Chandler Carruth 5d0ec91c20 Collection of minor tweaks to get approx. 10-15% compile time (#4245)
Most of these are about enabling inlining, in a couple of cases moving
code to a header and throughout switching to `CARBON_DCHECK`. The code
size of `CARBON_CHECK` seems to make inliing quite unreliable. I'm going
to think about whether there are ways to improve this, but a reasonably
small number of these seem worth switching for now to get some compile
time savings.

Also moves VLOG out of the hot path which helps a bit as well.

All combined, this net a bit over 10%, although it varies a bit exactly
how much. We're now pretty consistently over 800k lines/second for check
in the compilation benchmark for files >=4k lines, which makes me happy.
That's remarkably close to our original target.

Not really planning to keep optimizing here, just was glancing at the
profile and many of these stood out to me and were easy to fix.
2024-08-23 14:43:54 +00:00
David BlaikieandJon Ross-Perkins c5ada29ba9 Add filename and line number to function debug info metadata (#4243)
Refactors a bunch of the SemIRDiagnosticConverter to be able to use that
from Lower to access source locations there to use in debug info.

I assume some of this is a bit jank/would need to be fixed/improved in
the future - like the context functor that's passed into ConvertLoc?
(not totally clear what that's for/what the debug info will be missing
out on in its absence, I could throw a FIXME in there if you like)

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-08-23 00:05:26 +00:00
935715e704 Implement new precedence from #4075 (#4236)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2024-08-22 22:32:19 +00:00
dependabot[bot] 2174e5088f Bump rexml from 3.3.5 to 3.3.6 in /website in the bundler group across 1 directory (#4240)
Bumps the bundler group with 1 update in the /website directory:
[rexml](https://github.com/ruby/rexml).

Updates `rexml` from 3.3.5 to 3.3.6
<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.3.6 - 2024-08-22</h2>
<h3>Improvements</h3>
<ul>
<li>
<p>Removed duplicated entity expansions for performance.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/194">GH-194</a></li>
<li>Patch by Viktor Ivarsson.</li>
</ul>
</li>
<li>
<p>Improved namespace conflicted attribute check performance. It was
too slow for deep elements.</p>
<ul>
<li>Reported by l33thaxor.</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>
<p>Fixed a bug that default entity expansions are counted for
security check. Default entity expansions should not be counted
because they don't have a security risk.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/198">GH-198</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/199">GH-199</a></li>
<li>Patch Viktor Ivarsson</li>
</ul>
</li>
<li>
<p>Fixed a parser bug that parameter entity references in internal
subsets are expanded. It's not allowed in the XML specification.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/191">GH-191</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
<li>
<p>Fixed a stream parser bug that user-defined entity references in
text aren't expanded.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/200">GH-200</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
</ul>
<h3>Thanks</h3>
<ul>
<li>
<p>Viktor Ivarsson</p>
</li>
<li>
<p>NAITOH Jun</p>
</li>
<li>
<p>l33thaxor</p>
</li>
</ul>
</blockquote>
</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.3.6 - 2024-08-22 {#version-3-3-6}</h2>
<h3>Improvements</h3>
<ul>
<li>
<p>Removed duplicated entity expansions for performance.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/194">GH-194</a></li>
<li>Patch by Viktor Ivarsson.</li>
</ul>
</li>
<li>
<p>Improved namespace conflicted attribute check performance. It was
too slow for deep elements.</p>
<ul>
<li>Reported by l33thaxor.</li>
</ul>
</li>
</ul>
<h3>Fixes</h3>
<ul>
<li>
<p>Fixed a bug that default entity expansions are counted for
security check. Default entity expansions should not be counted
because they don't have a security risk.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/198">GH-198</a></li>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/199">GH-199</a></li>
<li>Patch Viktor Ivarsson</li>
</ul>
</li>
<li>
<p>Fixed a parser bug that parameter entity references in internal
subsets are expanded. It's not allowed in the XML specification.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/191">GH-191</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
<li>
<p>Fixed a stream parser bug that user-defined entity references in
text aren't expanded.</p>
<ul>
<li><a
href="https://redirect.github.com/ruby/rexml/issues/200">GH-200</a></li>
<li>Patch by NAITOH Jun.</li>
</ul>
</li>
</ul>
<h3>Thanks</h3>
<ul>
<li>
<p>Viktor Ivarsson</p>
</li>
<li>
<p>NAITOH Jun</p>
</li>
<li>
<p>l33thaxor</p>
</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ruby/rexml/commit/95871f399eda642a022b03550479b7994895c742"><code>95871f3</code></a>
Add 3.3.6 entry</li>
<li><a
href="https://github.com/ruby/rexml/commit/7cb5eaeb221c322b9912f724183294d8ce96bae3"><code>7cb5eae</code></a>
parser tree: improve namespace conflicted attribute check
performance</li>
<li><a
href="https://github.com/ruby/rexml/commit/6109e0183cecf4f8b587d76209716cb1bbcd6bd5"><code>6109e01</code></a>
Fix a bug that Stream parser doesn't expand the user-defined entity
reference...</li>
<li><a
href="https://github.com/ruby/rexml/commit/cb158582f18cebb3bf7b3f21f230e2fb17d435aa"><code>cb15858</code></a>
parser: keep the current namespaces instead of stack of Set</li>
<li><a
href="https://github.com/ruby/rexml/commit/2b47b161db19c38c5e45e36c2008c045543e976e"><code>2b47b16</code></a>
parser: move duplicated end tag check to BaseParser</li>
<li><a
href="https://github.com/ruby/rexml/commit/35e1681a179c28d5b6ec97d4ab1c110e5ac00303"><code>35e1681</code></a>
test tree-parser: move common method to base class</li>
<li><a
href="https://github.com/ruby/rexml/commit/6e00a14daf2f901df535eafe96cc94d43a957ffe"><code>6e00a14</code></a>
test: fix indent</li>
<li><a
href="https://github.com/ruby/rexml/commit/df3a0cc83013f3cde7b7c2044e3ce00bcad321cb"><code>df3a0cc</code></a>
test: fix indent</li>
<li><a
href="https://github.com/ruby/rexml/commit/fdbffe744b38811be8b1cf6a9eec3eea4d71c412"><code>fdbffe7</code></a>
Use loop instead of recursive call for Element#namespace</li>
<li><a
href="https://github.com/ruby/rexml/commit/6422fa34494fd4145d7bc68fbbe9525d42becf62"><code>6422fa3</code></a>
Use loop instead of recursive call for Element#root</li>
<li>Additional commits viewable in <a
href="https://github.com/ruby/rexml/compare/v3.3.5...v3.3.6">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.5&new-version=3.3.6)](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>
2024-08-22 22:23:28 +00:00
David Blaikie a17480133f Remove excess use of auto on initializers (auto x = Y(z) -> Y x(z)) (#4239) 2024-08-22 20:29:35 +00:00
David Blaikie 1e1034ee81 Enable debug info by default (#4232)
Discussed in the toolchain meeting today - we'd like to try having this
on by default and see if the cost isn't too high.

The nodebug test is a bit verbose, because it doesn't have the
`--exclude-dump-file-prefix` that test_file would usually add. Is there
a nicer way I could write this test to verify that --no-debug-info does
what it's meant to?
2024-08-22 20:27:45 +00:00
David Blaikie 5a11048c34 Remove some explicit (Mutable)ArrayRef constructions (#4238)
Rely on implicit conversion in call sites and initialization.

Removing the explicit conversions is only code simplication.
Moving from `auto x = Y(z)` to `Y x = z;` helps ensure that only
implicit constructors/conversions are happening (whereas the prior
syntax allows explicit conversions) which can help with readability
since implicit conversions are generally "less
complex"/risky/attention-requiring.
2024-08-22 19:40:54 +00:00
David BlaikieandJon Ross-Perkins ea8ad22a17 Add function debug info descriptions (#4233)
Still doesn't have line tables, so of limited value (at least now
this'll be enough that LLVM really generates debug info into the
resulting object file (whereas with only the compilation unit metadata,
LLVM will consider it empty and avoid emitting any of it)) - but another
step along the path.

This also doesn't attach the right source location to the functions -
I'll do that in a follow-up change because I think it'll require the
majority of the refactoring between driver and check to extract the
essential functionality sem_ir_diagnostic_converter, I think, to allow
retrieving source locations during lowering.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-08-22 17:19:30 +00:00
Brymer Meneses 435ee44e4c Report invalid parse on var x: i32 = {.7 = 8} (#4237) 2024-08-22 16:21:46 +00:00
Jon Ross-Perkins 4293c9f25f Switch python syntax to use Path.parents (#4235)
I think `paths.parents[2]` is easier to read than
`path.parent.parent.parent`, just applying uniformly. I'd noticed this
while looking at #4227

Also remove a couple `resolve()` calls that shouldn't be necessary since
`__file__` is absolute (elsewhere in the same files, `resolve()` is used
to resolve potentially relative paths)
2024-08-22 08:29:04 +00:00
Jon Ross-Perkinsandjosh11b 89be57ffc3 Add documentation for entity declaration design work (#4230)
Trying to pull in key elements of #3762, #3763, and #3980 (decl matching
and `extern`, essentially). These aren't specific to any particular
declaration type, but are common to entities, so suggesting a new doc
oriented on that.

There's probably more that could be said here, I'm just focused on
getting the recent formal discussion mirrored into the design.

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-08-21 22:21:07 +00:00
Chandler Carruth f75cbea7ce Minor updates to support newer Clang versions. (#4234)
A flag was renamed after LLVM 18, and a warning caught a couple more
trivially fixed issues.
2024-08-21 15:29:45 +00:00
d57aa57215 Add rudimentry debug info metadata emission (#4225)
This adds just the debug info metadata for Compilation Units (the top
level container of debug info) - but without anything in them, LLVM
won't emit them at all, so while this is testable at the IR level, it
isn't observable at the object level until more debug info is added.

A couple of starting points in this patch:
* A flag (`--debug-info`, seems to match the naming/style of other flags
in the carbon driver, though this is different from the naming
conventions of clang/gcc) that enables debug info when lowering. Open to
other names/approaches (on by default? historically debug info's been to
large/expensive to do this, so sticking with that precedent for now).
* Enabling that flag by default in the lowering tests - I do find the
churn on golden tests a bit rough, and adding more features to all the
tests means more churn, but it seems consistent with the approach so far
- keep an eye on this and perhaps revisit this if the churn gets too
annoying

---------

Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-08-20 20:00:35 +00:00
Jon Ross-PerkinsandChandler Carruth b6396e97f8 Build a website. (#4189)
Demo site: https://jonmeow.carbon-lang.dev/

I'm trying to keep work under the `/website` subdirectory so that the
misc files don't interfere with unrelated views of the repository. The
`prebuild.py` script does some work to move things around and add
frontmatter, helping the jekyll generation.

I'm using the "just-the-docs" theme because I think it's a decent match
for what we want, and getting jekyll up and running with it wasn't too
difficult. Note #1526 proposed using Docusaurus; I started out there,
but was having trouble getting it working with newer versions. The
plugins in particular I got stuck trying to make work, which sent me
looking for options that we could have working with less customization.
I do lean towards jekyll though, because it's what GH uses so hopefully
we can get a more consistent experience.

Having a website has been approved for a while under #1492, but hasn't
been a priority. I'm mainly doing this because I want to just be able to
point people to carbon-lang.dev and have easy links that way.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-08-20 17:53:06 +00:00
R B 61e87c3a88 Lower global variables (#4228) 2024-08-19 22:43:07 +00:00
Jon Ross-Perkins 2d3842fc06 Implement 'extern library' support for functions. (#4220)
Support for types (particularly classes) is left as a TODO.

There's also an issue I'm observing with a "define in impl" test, but
this is probably an issue with resolving the prior declaration which is
imported indirectly. The PR was already feeling big, so I'm choosing to
cut here.

Note, this does not implement the rule "The owning library's API file
must import the `extern` declaration, and must also contain a
declaration."
2024-08-19 22:12:21 +00:00
Jon Ross-PerkinsandChandler Carruth 0a4b0f33e3 Add docs for raw identifier syntax. (#4223)
Feature approved in #3797

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-08-19 21:50:13 +00:00
Jon Ross-PerkinsandChandler Carruth d5ac724266 Document the export keyword (#4224)
This was approved in #3938

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-08-19 20:51:37 +00:00
R B 6414ca9344 Modify toolchain/autoupdate_testdata.py to use scripts/scripts_utils.py (#4227)
The current `toolchain/autoupdate_testdata.py` script assumes the
correct bazel version is already installed. This change uses
`scripts/scripts_utils.py` to fallback to `bazelisk`.
2024-08-19 17:18:34 +00:00
Brymer Meneses 34ae2b001b move tuple testdata from index/ to tuple/access (#4226) 2024-08-19 16:47:14 +00:00
Jon Ross-Perkins 64204d9182 Factor library names into their own ID structure. (#4219)
This supports distinguishing between unset, Default, and "incorrect but
already diagnosed, do not use" for `extern library` logic.
2024-08-16 23:46:38 +00:00
Jon Ross-Perkins 696668ccb0 Fix bumper labeling for accessibility (#4222) 2024-08-16 23:41:22 +00:00
Brymer Meneses c353f6bd78 change tuple index (#4218)
This changes the tuple index from tuple[0] to tuple.0 in accordance with
the accepted propsal
https://github.com/carbon-language/carbon-lang/pull/3646

I messed up syncing to trunk on my original PR
https://github.com/carbon-language/carbon-lang/pull/4186, that's why I'm
starting on a blank state. Please let me know if I missed incorporating
a change from my prior PR.
2024-08-15 16:06:02 +00:00
Jon Ross-Perkins 3f7af842a3 Adjust check's node formatting in crash output. (#4217)
I'm trying to make the line of code more clearly nested in crash output
(the way it is, I sometimes forget about it). Also,
`Check::HandleFunctionDecl` is the old naming scheme, it's now all
`Check::HandleParseNode`, so I'm replacing that.

Before:

```
3.	extern_library_owner.carbon:6:1: Check::HandleFunctionDecl
extern fn F();
^~~~~~~~~~~~~~
 #0 0x0000564c0057ef1d llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) ...
```

After:

```
3.	extern_library_owner.carbon:6:1: checking FunctionDecl
          extern fn F();
          ^~~~~~~~~~~~~~
 #0 0x00005629029ffd9d llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) ...
```
2024-08-14 21:01:14 +00:00
Chandler Carruth 72cb9d0d06 Refactor testing exe path and benchmark main handling. (#4216)
Consolidates both main libraries into `//testing/base`, and factors out
the exe path handling for benchmarks and unit tests into a common
library to remove duplication. Refactors how that logic is managed to be
cleaner and avoid a confusing bool that came up in code review.

Updates all the tests and benchmarks that use these. I still need to
update other benchmarks to use the same main, but I wanted to keep this
PR somewhat minimal.

This also fixes a bug noticed in passing that the compilation benchmark
didn't have the required dependency on the benchmark library itself,
just the benchmark main library.
2024-08-14 17:50:08 +00:00
a9c815c9f4 Introduce a source generator and end-to-end compile benchmarks (#4124)
The big addition here is a very, very rough and very early skeleton of a
source code generator framework. This builds upon the lexers identifier
synthesis logic, improving on its framework and wiring it up with the
most rudimentary of source file generation. This is just enough to
roughly replicate my "big API file" source code benchmarks.

The source generation works *very* hard to both vary the structure and
content of the source as much as possible while ensuring the same
*total* amount of each construct is in use, from bytes in identifiers to
line breaks, parameters, etc. This lets us generate randomly structure
inputs that should consistently take the exact same amount of total work
to compile.

The complex identifier synthesis logic from the lexer's benchmark is
moved over here and the lexer uses APIs in the source generator for
identifiers. The other source synthesis in the lexer's benchmark isn't
yet moved over, but should likely be slowly absorbed here as it can be
refactored into a more principled and re-usable form. Some bits may stay
of course if they're just too lexer-specific.

Next, this adds a simple end-to-end compile benchmark for the driver
that directly and much more clearly reproduces all the measurements I've
done manually up until now. It should also be easy to extend to more
patterns over time as we add support to the source generator to produce
those patterns.

Last but not least, I've added a tiny CLI to the source generator so
that you can generate source code manually. This is especially nice for
generating demo source code to actually run through the driver or look
at in an editor. The CLI can also generate C++ source code which lets us
do some minimal comparative benchmarking between Carbon and C++/Clang.

There are huge number of TODOs in the source generation framework. This
is going to be a large ongoing effort I suspect.

There are also a bunch of rough edges I've left to try and get this out
for review sooner. I've left TODOs for refactorings that really need to
be done here, but hoping these can maybe be follow-ups. If not, please
flag and I'll try to layer them on here.

Sample compile benchmark output, nicely showing where we are w.r.t. our
goal speeds (2x behind on lex and check, 5x on parse) at least on a
recent AMD server CPU:
```
------------------------------------------------------------------------------------------------------
Benchmark                                                 Time             CPU   Iterations      Lines
------------------------------------------------------------------------------------------------------
BM_CompileAPIFileDenseDecls<Phase::Lex>/256           29420 ns        29419 ns        22860 6.62847M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/1024         146130 ns       146128 ns         4840 6.69959M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/4096         601584 ns       601577 ns         1020 6.69573M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/16384       2547578 ns      2547313 ns          280   6.404M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/65536      10816591 ns     10816389 ns           80 6.05193M/s
BM_CompileAPIFileDenseDecls<Phase::Lex>/262144     52191320 ns     52189828 ns           20 5.02261M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/256        101706 ns       101698 ns         6900 1.91745M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024       512161 ns       512162 ns         1380  1.9115M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096      2078426 ns      2078430 ns          340   1.938M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384     8795786 ns      8795583 ns          100 1.85468M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    35073596 ns     35072973 ns           20 1.86639M/s
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144  151100688 ns    151097370 ns           20 1.73483M/s
BM_CompileAPIFileDenseDecls<Phase::Check>/256        957059 ns       957049 ns          740 203.751k/s
BM_CompileAPIFileDenseDecls<Phase::Check>/1024      1956134 ns      1955985 ns          360 500.515k/s
BM_CompileAPIFileDenseDecls<Phase::Check>/4096      5797864 ns      5797417 ns          120 694.792k/s
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    21219608 ns     21217584 ns           40 768.843k/s
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    96311116 ns     96302334 ns           20 679.734k/s
BM_CompileAPIFileDenseDecls<Phase::Check>/262144  371637963 ns    371609964 ns           20 705.387k/s
```

Lest someone think this is *bad*, the fact that we're already within 2x
of our rather audacious goals makes me quite happy. =D

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-08-13 19:37:55 +00:00
Jon Ross-Perkins e62973a8ef Address the LocIdAndInst::ReusingLoc TODO (#4211)
The TODO for switching to ReusingLoc (previously Untyped) had been there
for a while, so I'm trying to address it here. The intent had been to be
clearer about when the construction is validated, particularly so that
we aren't accidentally accepting an incorrect NodeId. Note, this does
fix an incorrect use of InvalidNodeId where NoLoc should've been called.

Since this changes the semantics of when `Parse::NodeId` is helpful in
`typed_nodes.h`, I'm doing a pass to either refine or switch to
`Parse::InvalidNodeId` where it compiles. I think most remaining
`Parse::NodeId` examples are things we _should_ be able to refine with a
little more work (versus before where `Parse::NodeId` also indicated
`LocId` construction might be used).

I'm also changing context.h to use `requires` that match what
`LocIdAndInst` has, I think it makes the diagnostics a little better.
And note I do add an overload for `ImportIRInstId`, also matching
`LocIdAndInst`, and widely used for import refs.
2024-08-13 18:52:24 +00:00
Jon Ross-Perkins a3a4c14960 Error on non-constant parameters to a type. (#4215)
At present, this is a crash bug. I don't know whether this is the best
fix, but I figure it'll work until zygoloid has a chance to look.
2024-08-13 18:35:10 +00:00
Jon Ross-Perkins 23545bbece Update bazel version and zlib dep (#4213)
Bazel 7.3.0 includes a dependency change onto zlib 1.3.1.bcr.3 (didn't
dig into why, it's just what I'm seeing). Updating to keep in sync.
2024-08-13 18:10:39 +00:00
Jon Ross-Perkins 56332fcfac Fix a couple fn declarations in generics details (#4214)
I think this is just a typo.
2024-08-13 18:09:59 +00:00
josh11bandJosh L bfe0fc7cc8 Update to a recent LLVM version and the changes to LLVM IR. (#4212)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-08-12 22:29:33 +00:00
Jon Ross-Perkins 0feb757de0 Add fields for extern to EntityWithParamsBase (#4206)
This adds fields to `EntityWithParamsBase` to reflect the intention with
`extern library` design. I'm renaming `decl_id` because it shouldn't be
expected to be assigned anymore. import_ref.cpp I'm deliberately keeping
on `first_owning_decl_id` (which will break when importing `extern
library` declarations). Most other cases are for diagnostics, and I'm
using `latest_decl_id` to try and get the closest declaration to the
error. Note I'm partly splitting out this PR to show the test effect,
which apparently we don't test related cases.
2024-08-12 19:50:15 +00:00
c5b5d36e8b Change operator precedence (#4075)
Update the operator precedence to achieve a few goals:

-   Form operators into groups which behave similarly
- Make the group of operators ("top-level operators") that capture
everything to the right, like `if`...`then`...`else`, behave similarly
to the left, so that rearranging expressions won't change how they
group.
- Add the `where` operator, used to specify constraints on facet types,
to the precedence chart, to define how it interacts with other
operators.
- Make the operator precedence diagram prettier, so that it eventually
can be made into a poster that Carbon programmers can hang on their
walls.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-08-10 00:15:37 +00:00
Richard Smith 4a21b6af9b Basic support for implementing and using a parameterized interface. (#4203)
The main change here is to form a specific when checking an interface
function against an impl function, instead of just substituting the
`Self` type.
2024-08-09 01:05:03 +00:00
Richard Smith b2a13afb73 Defer resolving the eval blocks and value blocks of generics and specifics until we've finished other resolution work. (#4202)
This avoids import cycles, and reduces the number of temporary vectors
we build (and potentially throw away on retry). Import the self specific
when importing a generic, now that there's no risk that will introduce
cycles.

Note that we could take the same approach to import classes, interfaces,
and so on, instead of the current third phase of resolution for those
instructions, but in this PR I'm just addressing the import cycle I'm
currently seeing in a work-in-progress PR.
2024-08-09 00:21:24 +00:00
Jon Ross-PerkinsandChandler Carruth 0ac47114ac Singular extern declarations (#3980)
Each entity is restricted to one, optional `extern` declaration. If
used, it must be imported by the defining library. The defining library
annotates the existence of an `extern` with the `has_extern` modifier.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-08-08 23:13:28 +00:00
josh11bandJosh L ca161ad0fb Comment fix: AssociatedConstantDecl isn't just for associated types (#4207)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-08-08 23:07:45 +00:00
Brymer Meneses a227ea8074 add syntax highlighting for x-macro files (#4205)
This tells Github to detect files having the extension .def as C++
files, which ensures that these files get syntax highlighted prpperly.

I'm not sure whether more files like these are present throughout the
repo. FWIW, it can also be configured to do other things, such as detect
generated, vendored files and exclude these from the Github stats.

See
https://github.com/github-linguist/linguist/blob/master/docs/overrides.md.
2024-08-08 19:03:03 +00:00
Richard Smith cfed18a6a5 Add indentation to yaml test failure output to make it easier to read. (#4201) 2024-08-07 22:41:28 +00:00
Richard Smith 3c4c234d01 Treat the empty inst block as being canonical. (#4199)
TryEvalInst was assuming this to be the case when forming canonical
constants, but it previously wasn't.

This fixes an issue where we can end up with two identical-looking
constants for an empty struct value: one with an `Empty` block and
another with the canonical empty block.
2024-08-07 21:58:28 +00:00
Jon Ross-Perkins 3d13b8f71c Fix handling of interface redefinitions. (#4198)
The prior code crashed when trying to find the function's `Self`
parameter, I believe. `fail_redefine_with_dependents.carbon` handles
this case. It wasn't caught by the prior case because the `F` didn't
have any dependent parameters.

Note this also ran into a formatter crash, with invalid constants. I'm
fixing that here, but will also note it on #4145 (the crash in
FinishGenericDecl was muddled by a crash in Formatter code).
2024-08-07 21:30:44 +00:00
Jon Ross-Perkins 0d106fbf90 Rename check/testdata/tuples to remove the plural (#4200)
This is just odd since other dirs aren't plural (struct, not structs),
and we do have parse/testdata/tuple
2024-08-07 21:05:11 +00:00
Richard Smith 91f56f72a5 Fix importing of generic types. (#4196)
Ensure we don't lose the symbolic constant value by mapping through to
the underlying inst ID.
2024-08-07 19:12:00 +00:00
Richard Smith f0fd1d2342 Clean up: use across-decl comparison comparing interface. (#4195)
This doesn't seem to be observable because we don't support
parameterized impls. But it's consistent with how we compare the type
portion of the impl.
2024-08-07 16:21:40 +00:00
Richard Smith 2a06c964b5 Fix formatting for imported impls. (#4194)
`impl`s may be defined even if they have no scope if they were imported.
2024-08-07 15:58:53 +00:00
josh11bandJosh L ab5fa938ab Fix typo introduced in #4167 (#4197)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-08-07 02:22:15 +00:00
Jon Ross-Perkins 17abaa2bca Fix stray quote in action (#4193) 2024-08-06 23:31:44 +00:00
Jon Ross-Perkins b73387fc84 Update workflows for security hardening. (#4192)
Also a small pass on workflow names.

Note, I'm a little concerned that the test/nightly release/pre-commit
endpoints may be fragile. At the same time, it's also where it may be
most useful, to prevent network access by arbitrary test code. I think
this is imperfect, but maybe we can try it out and see if it's much of
an issue.

Note, the discord wiki action is currently broken, this should fix it.
2024-08-06 23:14:23 +00:00
Richard SmithandJon Ross-Perkins 1705347375 Perform an extra pass to import a generic for a symbolic constant less often. (#4182)
Instead of always forcing an extra pass when we need to import a generic
ID for a generic that isn't already imported, attempt to import the
rest of the instruction in the same pass. There are then three
possibilities:

- The instruction needs a retry anyway to form its constant value, and
  we avoid an extra pass.
- The instruction produces its constant value on the first pass but
  still needs a retry. In this case, the handler for that instruction
  is expected to retry itself, before building its constant value. The
  third pass in this case can't be avoided.
- The instruction succeeds on its first pass. We still need an extra
  pass; track the constant produced by resolution separately.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-08-06 20:27:47 +00:00
Richard Smith f6ff5b11b5 Distinguish between whether an entity has its own parameter lists and whether it is generic. (#4191)
It's actually possible to get into all four combinations of having
parameter lists versus being generic:

- An entity nested within a generic, such as a member class, can be
generic even if it has no parameters.

- As a corner case, an entity with an *empty* parameter list has
parameter lists, but isn't a generic because it doesn't have any generic
parameters.
2024-08-06 15:50:27 +00:00
Richard Smith 8a8c227163 Track an interface type, not an interface ID, on an associated entity. (#4188)
This prepares us for modeling associated entities of parameterized
interfaces.

We don't use the interface parameters when type-checking `impl`s or uses
of interface members yet, but we do now check interface arguments during
`impl` lookup.
2024-08-05 20:45:14 +00:00
Chandler Carruth 183c8c0ccf Re-enable TCMalloc on Linux builds. (#4187)
This tripped up the Compiler Explorer sandbox, but we think that is now
fixed:
https://github.com/compiler-explorer/compiler-explorer/issues/6734

Removing the workaround here, and once it's live and not crashing we can
close #4176 as fixed (and without a temporary workaround).
2024-08-05 14:28:02 +00:00
Jon Ross-Perkins d9a550a7d5 Support 'bazel run //examples:sieve' (#4185)
#4076 changed the rule setup and incidentally stopped supporting `bazel
run`. This should make `bazel run` work again.
2024-08-04 03:00:40 +00:00
Richard Smith b3fcaf9969 Initial rough support for deducing generic arguments in a call to a generic function. (#4184) 2024-08-02 22:44:51 +00:00
David Blaikie d72b4e4151 Remove supurfluous/confusing {} around a temporary (#4183)
This was failing to build for me locally with some arbitrary Clang HEAD
host compiler:
```
migrate_cpp/rewriter.cpp:225:3: error: call to member function 'SetReplacement' is ambiguous
  225 |   SetReplacement(expr, {OutputSegment(std::move(text))});
      |   ^~~~~~~~~~~~~~
./migrate_cpp/rewriter.h:141:8: note: candidate function [with T = clang::IntegerLiteral]
  141 |   auto SetReplacement(const T* node, std::vector<OutputSegment> output_segments)
      |        ^
./migrate_cpp/rewriter.h:150:8: note: candidate function [with T = clang::IntegerLiteral]
  150 |   auto SetReplacement(const T* node, OutputSegment segment) -> void {
      |        ^
```
No idea if that's a bug in clang HEAD, but it seemed like removing the
{} simplified the code anyway - so here's that.
2024-08-01 22:32:57 +00:00
Richard Smith a9b43a222f When importing symbolic constants and types, also import the associated generic and index. (#4180)
A symbolic constant has an instruction to compute the constant value, as
well as potentially also having a generic ID and an index within that
generic to indicate where corresponding values can be found in a
specific. Import those pieces of information when importing such a
constant.

We try to import the generic before we start the main work of importing
the constant, and retry the import process if importing the generic adds
work to the worklist. This means that the first time we import anything
within a generic, we can now perform three passes calling
`TryResolveInst` instead of two, but the first pass is very lightweight
and only looks up and adds a single instruction, so the added overhead
of the extra pass should be minimal.

To avoid introducing cycles when importing a generic function, make the
import of a function declaration build the new `Function`,
`FunctionDecl`, and `FunctionType` in the first pass, like classes and
interfaces do.
2024-08-01 21:02:46 +00:00
Richard Smith 3c8fc714a8 Import support for generics and specifics (#4179)
Import generics and specifics when they are referenced by imported
entities.

When importing a generic, we import the symbolic constants required by
its eval block, and then rebuild the eval block itself given the list of
constants it needs to compute. This is likely a bit less efficient than
directly importing the contents of the eval block, but avoids needing to
either extend the importer code to be able to import the instructions
that can appear in the eval block or extend the evaluator to cope with
instructions from a different `SemIR::File`.

Importing a symbolic constant is unaffected, and does not yet preserve
the associated generic and index within that generic, so uses of a
generic from an imported IR still don't pick up values from the
specific, but the improved functionality can be seen in the changes to
the SemIR in the testcases.
2024-07-31 23:53:14 +00:00
Jon Ross-Perkins f67791cfee Separate subtree size information from parse nodes. (#4174)
Move subtree sizes over to TreeAndSubtrees, using the different
structure to represent the additional parse work that occurs, as well as
making it clear which functions require the extra information. My intent
is to make it hard to use this by accident.

The subtree size is still tracked during Parse::Tree construction. I
think a lot of that can be cleaned up, although we use it during
placeholder assignment so it may take some work. I wanted to see what
people thought about this before taking action on such a change.

I'm using a 1m line source file generated by #4124 for testing. Command
is `time bazel-bin/toolchain/install/prefix_root/bin/carbon compile
--phase=check --dump-mem-usage ~/tmp/data.carbon`

At head, what I'm seeing is:

```
...
parse_tree_.node_impls_:
  used_bytes:      61516116
  reserved_bytes:  61516116
...
Total:
  used_bytes:      447814230
  reserved_bytes:  551663894
...
1.43s user 0.14s system 99% cpu 1.565 total
```

With `Tree::Verify` disabled completely, it looks like:
```
parse_tree_.node_impls_:
  used_bytes:      41010744
  reserved_bytes:  41010744
...
Total:
  used_bytes:      427308858
  reserved_bytes:  531158522
...
1.20s user 0.13s system 99% cpu 1.332 total
```

Re-enabling just the basic verification (what is now `Tree::Verify`),
I'm seeing maybe 0.05s slower, but that's within noise for my system. I
do see variability in my timing results, and overall I think this is a
0.2s +/- 0.1s improvement versus the earlier (always testing `Extract`
code) implementation. That's opt; debug builds will be unaffected,
because the same checking occurs as before.

Note, the subtree size is a third of the node representation, which is
why I'm showing the decrease in memory usage here.
2024-07-31 19:39:45 +00:00
Richard Smith e6e61e14ae Fix incorrect value_id and location in imported BindSymbolicName. (#4178)
Instead of updating the `value_id` on the canonical constant
`BindSymbolicName` to refer to some particular instance of that
constant, create a new instruction, and attach the proper location to
it.
2024-07-31 16:38:56 +00:00
Jon Ross-Perkins c31c03acb3 Temporarily disable tcmalloc due to compiler-explorer crash (#4177)
Per @axsaucedo on #4176, tcmalloc expects cpu information that
compiler-explorer is lacking in its sandboxing. There's probably a
better fix to be had, this is intended to be temporary.
2024-07-29 15:50:57 +00:00
Jon Ross-Perkins 43c0b0a1f2 Refactor some check-phase postorder iterator use. (#4175)
Allow directly constructing a PostorderIterator, to get rid of
`tree.postorder(node_id).end()` indirect construction. For ranges that
don't need tree data, make it clearer that they're not validated.

Note, this subtly gets rid of a subtree size use in the
`tree.postorder(node_id).end()` case (to get the discarded `begin()`
value).
2024-07-27 02:15:56 +00:00
Jon Ross-Perkins 66147dee4f Refactor some commonality in formatter. (#4171)
Also tries to add comments for things. Note, I'm trying to improve
understandability here, so if you don't think this is helping I can undo
things.
2024-07-26 21:00:50 +00:00
Jon Ross-Perkins ae675e61bd Add initial parsing for 'extern library' (#4173) 2024-07-26 20:47:25 +00:00
Richard Smith 37a8bfa488 Refactor ReturnTypeInfo and InitRepr. (#4169)
Rename `ReturnInfo` to `ReturnTypeInfo`. Move it and `InitRepr` into
`type_info.h` alongside `ValueRepr`. Replace `ReturnSlot` with
`InitRepr`, and extend `InitRepr` to be able to represent the
incomplete-type case instead of CHECK-failing. Remove `has_return_slot`
from `InitRepr` and instead only provide that as part of
`ReturnTypeInfo`.
2024-07-25 21:41:33 +00:00
Richard Smith 2ef1d1f8b9 Move definition of member of Function to function.cpp where it belongs. (#4170) 2024-07-25 21:22:07 +00:00
Jon Ross-Perkins fbb1cd36c0 Only produce a name scope for a namespace when not merged (#4168)
Addresses the comment on
https://github.com/carbon-language/carbon-lang/pull/4153#discussion_r1690292168
(although maybe with somewhat quirky results, since contents get printed
each time)
2024-07-25 21:05:10 +00:00
Jon Ross-Perkins 1fc488da10 Improve notes on MODULE.bazel.lock changes (#4167)
I admit I'm tempted to make a MODULE.bazel.md for these comments, so
that modifying them doesn't trigger a lockfile update, but I don't
really want it at the top level.
2024-07-25 20:35:30 +00:00
Richard Smith a9e835f3dc Remove caching of return slot usage. (#4163)
The caching isn't buying us much, and is adding complexity and
divergence between the codepaths for generic and non-generic functions.

This means we no longer suppress diagnostics for the second or
subsequent time we call a function with an incomplete return type. If we
want to add that back, it might be worth considering moving the
suppression to `TryToCompleteType` and only diagnosing that a type is
incomplete once, regardless of why we're requiring it to be complete.
2024-07-25 20:29:59 +00:00
Brymer Meneses bf1106fc34 fix: clangd: -32001: invalid AST (#4164)
Ignore the `-march=*` in `compile_commands.json` which causes issues in
Neovim on Apple M2. This fix is from this
[comment](https://github.com/clangd/clangd/issues/1582#issuecomment-1500031372)
2024-07-25 16:51:31 +00:00
Richard Smith 3cb769a053 Rename "generic instance" to "specific" throughout the toolchain. (#4165)
As discussed in toolchain meeting, we want to avoid overloading the
meaning of "instance", and "specific" was the best name we found. It's a
little unorthodox and inventive, but hopefully over time will become as
unsurprising as the term "generic" is.
2024-07-25 16:42:01 +00:00
Brymer Meneses 70c20be91b docs: add a note on setting up clangd (#4135)
This PR adds a note on how to generate `compile_commands.json` which is
necessary for having `clangd` generate accurate diagnostics
2024-07-25 16:40:27 +00:00
Jon Ross-Perkins bf89652a4d Move common entity fields to a 'base' struct. (#4161)
I'd considered moving DeclParams uses over, but when handling qualified
names, there's a parse node instead of an instruction. I did try to
unify a couple other uses though, including adding MergeDefinition. I
expect `interface` will use a little more once it's more completely
implemented, but maybe I'm wrong about that.
2024-07-24 23:26:00 +00:00
Richard Smith a0973f4f47 When reentering an interface scope, reintroduce the Self parameter. (#4162)
This is not easy to test right now, because it should only really be
visible through `default fn` declarations, which we don't support
properly yet.
2024-07-24 22:31:24 +00:00
Richard Smith 07bad72d86 Support for calling non-generic methods in a specific class. (#4156)
Use the specific parameter types for checking, and the specific return
type as the type of the call.
2024-07-24 20:27:01 +00:00
Jon Ross-PerkinsandRichard Smith 7ded56ef35 Improve namespace handling in imports. (#4153)
This implements a few closely related features:

- Starts merging namespaces discovered inside imports.
- Stores results of cross-package name lookup as an entry inside the
scope.
  - Note this is particularly visible with `i32`.
- Moves more of the imported instructions to the import scope.

Note this is primarily for executing the namespace TODO in check.cpp,
which is removed here.
`testdata/namespace/merging_with_indirections.carbon` tests key
behavior.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-07-24 19:56:17 +00:00
Chandler CarruthandJon Ross-Perkins 55f3f48707 Add a mention of our nightly builds to our README.md. (#4158)
This provides an example of downloading and using the nightly buildings
of the toolchain. I've tried to provide appropriate caveats about the
fact that this is very early and not something that's really reliable.
But I wanted folks to know how they can play with the nightly releases
if they're interested.

I've also focused the source build instructions on the toolchain where
we'd be interested in contributions, and the first paragraph on trying
out Carbon in the browser with CE.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-07-24 19:30:40 +00:00
Richard Smith d625607510 Convert EvalContext into a class. (#4160) 2024-07-24 15:45:06 +00:00
Richard Smith 83157f3d24 Remove overeager CHECK. (#4159)
When evaluating within the context of a specific, we can encounter uses
of bindings that are nested within that specific, for example parts of
the declaration of a nested generic. Those bindings should evaluate to
the canonical form of themselves, as they would when evaluating outside
the context of the specific.

Fixes #4157.
2024-07-23 23:21:47 +00:00
Richard Smith fc8e686607 Rebuild all constants in the eval block. (#4155)
Instead of reusing instructions from the generic entity in the eval
block, rebuild constants in the same way we rebuild types. The previous
attempt to not rebuild these constants assumed that every constant used
in a generic would be built in that generic, and not referenced directly
or referenced from some enclosing scope, which isn't true in practice
and is a fragile assumption in any case.

We could add back some reuse of instructions from the generic -- if we
happen to see the right instruction to build a constant, we could
opportunistically reuse it -- but given the complexity added by doing
so, I'm not pursuing that here.

Now that the eval block for a generic consists of instructions uniquely
owned by that generic, rather than often being shared with another
entity, include the generic in the formatted SemIR output. I'm using the
same scope name for the generic object itself as for the parameterized
class / function / interface, because there are very frequently
references between them and this keeps the IR simpler and more readable,
and avoids needing to invent a second name for the scope.
2024-07-23 21:51:08 +00:00
Jon Ross-Perkins db022658c6 Implement syntactic merge checks for parameters. (#4149)
Note this isn't implementing checking through imports. The parse node
there is harder to access through the context, so would require
examining the entity in order to get the import declaration, to get at
the ImportIR. We also don't have a parse tree attached in that case, and
would need to add one to SemIR::File. But I believe we do want to add
that, so it's explicitly a TODO.

Note GetTokenText re-lexes literal values, so there's a bit of potential
overhead there. Not sure if we want a more efficient manner for
comparing in cases like this.
2024-07-23 20:32:24 +00:00
Jon Ross-PerkinsandGeoff Romer 07c286e3cb Use the package/library name in ImportIRId formatting. (#4154)
Also adds import_ir_scope to namespace formatting. I'd done this as an
aid for #4153, and am splitting it out.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2024-07-22 22:43:36 +00:00
Jon Ross-Perkins 000d6d63ef Remove already-done no_prelude todo. (#4148) 2024-07-22 21:41:35 +00:00
Richard Smith 4a8a7bf6aa Remove declaration of function deleted in #4150. (#4151) 2024-07-22 17:26:58 +00:00
Geoff Romer 326609857d Rename BindNameInfo to EntityName (#4090) 2024-07-19 22:43:50 +00:00
Jon Ross-Perkins 4c6dc2eade Remove irregular digit placement check from NumericLiteral. (#4150)
This changed in #1983 and although we updated explorer, we missed
toolchain.
2024-07-19 20:46:25 +00:00
Jon Ross-Perkins 7b1a5dfc58 Try some crash recovery in autoupdate threads. (#4147)
At present, I think if we crash from multiple threads in parallel, it
can lead to the stack trace not being printed out. Using
CrashRecoveryContext here seems to more successfully print a stack trace
on errors, which I'm hoping will ease debugging.

i.e., before:

```
-----------------------------------------------------------------------------
.Please report issues to https://github.com/carbon-language/carbon-lang/issues and include the crash backtrace.
Stack dump:
0.	performing autoupdate for toolchain/check/testdata/alias/no_prelude/import_order.carbon
1.	Program arguments: compile --phase=check --dump-sem-ir --no-prelude-import --exclude-dump-file-prefix=/usr/local/google/home/jperkins/.cache/bazel/_bazel_jper.kins/85deb7d9d96f7e0e80b42618a55969d7/execroot/_main/bazel-out/k8-fastbuild/b.in/toolchain/install/prefix_root/lib/carbon/../../lib/carbon/core a.carbon b.carbon
.CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
external/bazel_tools/tools/test/test-setup.sh: line 328: 1151859 Aborted                 "${TEST_PATH}" "$@" 2>&1
```

(EOF)

after:

```
-----------------------------------------------------------------------------
Please report issues to https://github.com/carbon-language/carbon-lang/issues and include the crash backtrace.
Stack dump:
0.	performing autoupdate for toolchain/check/testdata/alias/no_prelude/import_order.carbon
1.	Program arguments: compile --phase=check --dump-sem-ir --no-prelude-import --exclude-dump-file-prefix=/usr/local/google/home/jperkins/.cache/bazel/_bazel_jperkins/85deb7d9d96f7e0e80b42618a55969d7/execroot/_main/bazel-out/k8-fastbuild/bin/toolchain/install/prefix_root/lib/carbon/../../lib/carbon/core a.carbon b.carbon
..CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
......CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
.....................................................................................CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
.CHECK failure at ./toolchain/sem_ir/ids.h:140: is_valid()
............................ #0 0x000056045ee22d7d llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/usr/local/google/home/jperkins/.cache/bazel/_bazel_jperkins/85deb7d9d96f7e0e80b42618a55969d7/execroot/_main/bazel-out/k8-fastbuild/bin/toolchain/testing/file_test.runfiles/_main/toolchain/testing/file_test+0x731dd7d)
```

(elided the full stack trace)
2024-07-18 21:36:29 +00:00
Jon Ross-Perkins e76b6a61b4 Abbreviate instruction as inst in formatter. (#4146)
This is just consistency with other abbreviating we're doing.
2024-07-18 19:34:01 +00:00
Chandler Carruth 44c85e0872 Reserve memory for the identifiers hashtable. (#4107)
This uses a heuristic reserve to greatly reduce hashtable growth of the
identifiers hashtable. The design of the hashtable itself is optimized
around compact memory use and is especially slow to grow and so this has
an outsized impact.

The heuristic was computed using `scripts/source_stats.py` and looking
at C++ codebases. We may want to periodically re-evaluate it as Carbon
code emerges and we have better data on its distributions of tokens.

This also required fixing the `Reserve` method on `CanonicalValueStore`
that wasn't actually used anywhere and so didn't even compile correctly.
I added it to the relevant unit test so it is at least compiled locally
to its definition.
2024-07-18 15:41:21 +00:00
Richard Smith 1ed58895bc Basic testing for generic methods using Self. (#4143) 2024-07-17 23:27:40 +00:00
Richard Smith 3cc90f9017 Move GetTypeInInstance from Check to SemIR. (#4144)
In preparation for this function being used by other parts of `SemIR`
and by lowering.
2024-07-17 23:27:14 +00:00
Richard Smith dde0bd0ffe Change TypeId to be a thin wrapper around ConstantId. (#4140)
This better follows the principle that types are simply constants of
type `type`, and allows more uniform treatment of types as just another
kind of constant from generics handling.

Use a hash table to map from `TypeId` to information about the complete
type. This makes basic operations on types a bit simpler, and operations
that actually need to access the complete class information a bit more
complex.
2024-07-17 22:46:03 +00:00
Jon Ross-Perkins 65d6e3e221 Use verbose formatting of instructions on crash messages. (#4125)
Changes crash messages to start printing verbose forms of instructions,
rather than just the ID. Fixes some indentation issues with stacks. Also
switches unexpected inst formatting, because now there are lots, and
it'd be helpful to know where they are.

This uses a pimpl pattern for Formatter due to the number of member
functions on Formatter. Maybe we should refactor that, but this didn't
feel like a good place to do so.

Note, I have two concerns about this change... to note them here, to
make sure others are considering them when evaluating the
implementation:

1. Some instructions are very verbose to print, as evidenced by the
fn_decl printing (which includes function params) or scope printing
(which includes scope members).
- I'm not sure whether there's a way to simply reduce this, as it seems
essential to the requested printing of instructions.
- Long-term, we may at least want to limit the number of lines printed
here. However, I've already spent a fair amount of time here and I think
it's in a good state to evaluate.
2. Increased complexity in the crash handler may result in crash
messages failing to generate.
- For example, a crash in Formatter (and its deps, such as InstNamer or
location handling) prevents a stack from being printed. I'm pretty sure
I've written crashes in Formatter before.

Here's an example crash snippet (generated by adding a crash inside
`return` handling) before:

```
2.	NodeStack:
	0.	FunctionDefinitionStart -> function2
	1.	ReturnStatementStart -> no value
	2.	IntLiteral -> inst+26
inst_block_stack_:
	0.	block<invalid>	{inst+0, inst+1, inst+2, inst+23}
	1.	block9	{inst+26}
param_and_arg_refs_stack:
args_type_info_stack_:
```

And after:

```
2.	Check::Context
          NodeStack:
            0. FunctionDefinitionStart: function2
            1. ReturnStatementStart: no value
            2. IntLiteral:
              unexpected.inst+26.loc12_10: i32 = int_literal 0 [template = constants.%.2]
          inst_block_stack_:
            0. block<invalid> {
                package: <namespace> = namespace [template] {
                  .Core = unexpected.inst+2
                  .F = unexpected.inst+23.loc11_22
                }
                unexpected.inst+1 = import Core
                unexpected.inst+2: <namespace> = namespace unexpected.inst+1, [template] {}
                unexpected.inst+23.loc11_22: %F.type = fn_decl @F [template = constants.%F] {
                  unexpected.inst+9.loc11_9: init type = call constants.%Bool() [template = bool]
                  unexpected.inst+10.loc11_9: type = value_of_initializer unexpected.inst+9.loc11_9 [template = bool]
                  unexpected.inst+11.loc11_9: type = converted unexpected.inst+9.loc11_9, unexpected.inst+10.loc11_9 [template = bool]
                  unexpected.inst+12.loc11_6: bool = param b
                  @F.%b: bool = bind_name b, unexpected.inst+12.loc11_6
                  unexpected.inst+19.loc11_18: init type = call constants.%Int32() [template = i32]
                  unexpected.inst+20.loc11_18: type = value_of_initializer unexpected.inst+19.loc11_18 [template = i32]
                  unexpected.inst+21.loc11_18: type = converted unexpected.inst+19.loc11_18, unexpected.inst+20.loc11_18 [template = i32]
                  @F.%return: ref i32 = var <return slot>
                }
              }
            1. block9 {
                unexpected.inst+26.loc12_10: i32 = int_literal 0 [template = constants.%.2]
              }
          param_and_arg_refs_stack:
          args_type_info_stack_:
```
2024-07-17 22:05:19 +00:00
Richard Smith e6860d9930 Mark some leaf classes final to suppress -Wnon-virtual-dtor. (#4141) 2024-07-17 16:48:06 +00:00
Chandler Carruth 579cd3b5aa Directly use TCMalloc rather than the system malloc on Linux. (#4133)
This improve the toolchain's performance by about 10%.

It will also allow us to leverage TCMalloc's extensions to do heap
profiling and get other information about how efficiently we're using
the heap.

Note that currently this causes all of our builds to produce a warning
due to an issue with `rules_python` and multiple modules registering
python toolchains:
https://github.com/bazelbuild/rules_python/issues/1818

This is also only enabled on Linux as there is no support for other OSes
at the moment.
2024-07-17 16:08:13 +00:00
Chandler Carruth 8694ca6a38 Enable the more effective version of -Wnon-virtual-dtor. (#4142)
Most of this is enabled by default, but there is some that needs an
explicit flag.

Avoiding `-Wnon-virtual-dtor` itself for now because that warning can
require changes that carry overhead such as having an extra, unused
destructor entry in the vtable. Hopefully we don't have too many folks
who need our code to be `-Wnon-virtual-dtor` clean.
2024-07-17 05:34:42 +00:00
Richard Smith fe359b1a08 Substitute into generic class and interface definitions when we require them to be fully defined. (#4139)
When referring to a constant within a specific, such as a field of a
generic class, use that specific version of the constant's value.
2024-07-17 01:39:25 +00:00
Gıyaseddin Tanrıkulu 5edd2358e8 Do not query interface's self_param_id unless defined when importing (#4137)
Querying a local constant with an invalid instruction triggers a crash,
this will prevent self_param_id to be used unless it is defined.

Closes #4071 and #4080

This will only fix the crash. The scenario where a declaration-only
interface is imported then defined still gives an error message, but it
won't crash this time.
2024-07-16 23:20:26 +00:00
Jon Ross-Perkinsandjosh11b f1190a4792 Add basic output of where memory is stored after a compile. (#4136)
The output is really basic, I'm just adding this to help track how
memory is allocated.

```
---
filename:        'check/testdata/expr_category/in_place_tuple_init.carbon'
source_:
  used_bytes:      8057
  reserved_bytes:  8057
tokens_.allocator_:
  used_bytes:      0
  reserved_bytes:  0
tokens_.token_infos_:
  used_bytes:      1040
  reserved_bytes:  2032

(eliding)

value_stores_.string_literals_.set_:
  used_bytes:      320
  reserved_bytes:  320
Total:
  used_bytes:      20609
  reserved_bytes:  29437
...
```

---------

Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-07-16 23:11:01 +00:00
cd7c10b8e2 Rebuild the type of constants during evaluation. (#4138)
When evaluating in a generic context, a constant with a symbolic type
might evaluate to a constant with a concrete type (or a more specific
symbolic type). This can't actually happen yet given the current state
of the toolchain, as far as I can determine, so this is more just a
refactoring for now, but will be relied upon by future generics work.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-07-16 22:58:17 +00:00
Richard Smith 5006838f1c Build an evaluation block for the definition region of a generic. (#4131) 2024-07-16 00:16:48 +00:00
Richard SmithandJon Ross-Perkins efea072be3 Compute specific constant values. (#4128)
When forming a specific (previously called a generic instance), evaluate
the eval block of the generic to determine the values of any constants
used in that specific. The majority of the work here is updating
eval.cpp so that it can use the results of prior evaluations in the same
block when computing later values.

Include the computed results in the formatted SemIR output.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-07-15 23:59:23 +00:00
Richard Smith be94782eda Remove unused member. (#4134) 2024-07-15 18:55:07 +00:00
Jon Ross-Perkins 407b9e4dcd Add a run_bazelisk wrapper script for linux. (#4129)
I was considering making a "/bazel" alias for this, but I'm really on
the fence about whether that's a good choice. However, I do think this
is good to have to simplify installs.

Fixes #3071 and #3896
2024-07-15 17:18:18 +00:00
Chandler Carruth 547c8a6b00 Remove support for beta and alpha versions. (#4132)
With this our infrastructure should match the final form of proposal
#4105 that established our versioning scheme.
2024-07-15 14:44:21 +00:00
Chandler CarruthandRichard Smith 2fcff24100 Establish toolchain and language versioning (#4105)
Proposal for how Carbon version numbers work:

- A single version across language, standard library, compiler, linker,
etc.
-   Semantic Versioning (SemVer) based
- Details of how SemVer criteria for major, minor, and patch should
apply to
    Carbon
- Details of how we will operate before 1.0 and how this connects to
Carbon's
    milestones
- Directional guidance for future work including post-1.0 versions, LTS
    versions, and standardization

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-07-14 06:28:46 +00:00
Jon Ross-Perkins 99696b9812 Rename check handlers to HandleParseNode overloads. (#4121)
This is for consistency with #4120. Similar to that, we can use
overloads on the typed NodeId rather than individually named handlers.
There isn't the same caller benefit here though, since the calls from
check.cpp are already boilerplate.
2024-07-12 22:38:06 +00:00
Jon Ross-Perkins bb8417c810 Refactor tool fetching for easier updates. (#4127)
Adds scripts/calculate_release_shas.py to print the versions, and
updates tool versions. Consolidates target-determinator logic with the
other tool logic.

This is also intended to make it easier to add more tools.
2024-07-12 22:32:49 +00:00
Jon Ross-Perkins 006e31238e Adjust driver references to use the install version. (#4126)
Also makes an alias so that this is easier to find. Verified that
running the alias still finds prelude files.

Note the actual target is printed when building (although a symlink is
also created, using that symlink confuses file-finding).

```
╚╡bazel build :carbon
...
Target //toolchain/install:prefix_root/bin/carbon up-to-date:
  bazel-bin/toolchain/install/prefix_root/bin/carbon
```
2024-07-12 22:06:55 +00:00
Richard SmithandJon Ross-Perkins 50d56aa7c9 Add an instruction to represent a use of a dependent value from a generic instance. (#4122)
We can't use the instruction from the generic directly, because it
doesn't have the right constant value. Instead add an instruction that
models the transition from the constant value in the generic to the
constant value in the generic instance.

Also start associating the self generic instance with unqualified
lookups that find results in an enclosing generic, so that we track the
information necessary to create the new instruction.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-07-12 14:59:01 +00:00
Jon Ross-Perkins 6d2d1cf7ca Refactor lower handlers to use overloads. (#4120)
Renames Lower::Handle* to Lower::LowerFunctionInst. This allows writing
a templated handler for instructions, moving code out of the macro
expansion and removing some of the redundancy in things like
`HandleAddrOf(..., SemIR::AddrOf inst)`
2024-07-11 22:12:04 +00:00
Jon Ross-Perkins bb27a4f97b Add a convenience method for dumping the formatted SemIR file. (#4123) 2024-07-11 21:40:29 +00:00
Jon Ross-Perkins 469f1c8e64 Refactor InstKind to move metadata from macros to the type. (#4119)
This adds `DefinitionInfo` for `Define`-based configuration so that
parameters are optional. It also makes it easier to provide the
equivalent functions on both `Definition` and `Define`.

A common pattern used here is to change from a `switch` with in-line
`case`s to instead have `case`s that call an overloaded function. What's
happening here is that the instruction type is used to select an
overload, and if an overload is not defined, a compiler error would
result. Meanwhile, clusters of overloads are being defined using
`requires`-based templating, so that equivalent implementations are not
copied. This addresses a limitation of a vanilla `switch` approach where
it's hard to have redundant cases using conditional logic, while also
getting compiler errors when adding new `InstKind` entries, which had
been a significant part of why we used macros previously.

This starts hitting some odd clang-format edge cases causing
`CARBON_KIND_SWITCH(inst){` (missing space), which I haven't seen
before. Adding `CARBON_KIND_SWITCH` to .clang-format works around it.
2024-07-11 21:39:25 +00:00
Jon Ross-Perkins 6682241ea0 Refactor whether a function is lowered into InstKind::Define (#4117)
This is to remove all the FatalIfEncountered handlers in handle.cpp.
They just feel like noise when reading the file. Plus it's one less bit
of boilerplate to add for instructions that don't lower.

Note that I left HandleParam/HandleAddrPattern. I'd be happy to change
those to just set lowered=false too, but was hesitant to given the
separate logic.

Also, I'm separately considering migrating the macro logic into similar
constexpr things. If I do, I might switch Define to take in a struct.
But for how this particular parameter works, the overload felt
reasonable, particularly since is_lowered is not used in combination
with TerminatorKind.
2024-07-11 19:54:09 +00:00
Jon Ross-Perkins a81d67c629 Rename Builtin to BuiltinInst, particularly to get BuiltinInstKind (#4115)
I'm trying to increase the distinction between BuiltinKind and
BuiltinFunctionKind. BuiltinKind is for instructions,
BuiltinFunctionKind is for function definitions. To get to this point,
I'm doing a few changes:

- BuiltinKind -> BuiltinInstKind
    - builtin_kind.* -> builtin_inst_kind.*: filename consistency
- Builtin -> BuiltinInst: mainly for consistency with the above
- Builtin::builtin_kind -> BuiltinInst::builtin_inst_kind: somewhat
repetitive but seems like a consistent edit
- Function::builtin_kind -> Function::builtin_function_kind: seems a
useful distinction

I'm leaving alone things like (and mentioning in case there's a desire
for more renames):

- InstId::BuiltinError, InstId::ForBuiltin: these I think are more
apparent because they're directly associated with Inst.
- GetBuiltinICmpPredicate in lowering: maybe builtin function handling
should be in its own file, but these local names don't feel problematic
to me.
- GetBuiltinType, BuildBuiltinValueRepr, PerformBuiltinIntComparison:
similar to the above, names don't feel too problematic
2024-07-11 18:24:17 +00:00
Richard Smith 6d3c915bbf When performing name lookup, determine the generic instance within which the lookup result was found. (#4118)
Require types into which qualified lookup is performed to be completely
defined. Eventually this will trigger substitution into the definition
for generic types.
2024-07-10 18:35:55 +00:00
Jon Ross-Perkins a4ef5dd591 Move Lower::HandleCall out to its own file. (#4116)
This is over half of handle.cpp right now, due to builtin function
logic.
2024-07-09 21:46:54 +00:00
Jon Ross-PerkinsandRichard Smith cb674a12cf Add comments for instructions that lack it. (#4112)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-07-09 21:44:07 +00:00
Jon Ross-Perkins b6031c265d Update the conference talk list for EuroLLVM videos (#4114)
Also reorder links so that the future/most recent items are first,
putting older videos lower down.

Noting the lightning talk because it's there, but also that it's a
lightning talk because most of the others are 40m/1h, so 5m is very
short by comparison (I was tempted to label the length of everything,
but not sure how valuable others view that).
2024-07-09 19:30:41 +00:00
Jon Ross-Perkins f3a4178083 Remove SemIR::RealLiteral (#4113)
I think this was obsoleted around #3897, it's essentially unused.
2024-07-09 18:38:57 +00:00
Richard Smith 7322a1e220 Build a list of dependent constants to recompute in each instance of a generic. (#4110)
For each generic, build a list of instructions describing the
computations we need to do when resolving an instance of the generic:
this is a list of the instance-specific constants and types that the
generic uses. Another way of viewing this list is as a block of Carbon
SemIR code that is evaluated in order to form an instance of the generic
-- this is referenced in the code as the "eval block" for the generic.

For each instruction in the generic whose type or value is a symbolic
constant, replace that type or constant value with a symbolic reference
that says "to find the actual type or value, look at index N in the list
of values for the generic instance".

For an instruction with a symbolic constant value, we can just add that
instruction to our list. For an instruction with a symbolic constant
type, however, we may not have a corresponding instruction computing the
type within the generic and may need to build a new instruction, but
will reuse one where possible. In the case where we build a new
instruction, we use the existing substitution code to build the type
within the eval block.

For now, this transformation is only done in the declaration region of
the generic, not in the definition region. Also, we map back from the
symbolic references to the underlying constant value in a few places
where we will eventually need to do a lookup into a generic instance, in
order to avoid regressing the tests.
2024-07-08 22:29:37 +00:00
dependabot[bot] 809920d391 Bump certifi from 2023.11.17 to 2024.7.4 in /github_tools in the pip group across 1 directory (#4111)
Bumps the pip group with 1 update in the /github_tools directory:
[certifi](https://github.com/certifi/python-certifi).

Updates `certifi` from 2023.11.17 to 2024.7.4
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/certifi/python-certifi/commit/bd8153872e9c6fc98f4023df9c2deaffea2fa463"><code>bd81538</code></a>
2024.07.04 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/295">#295</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/06a2cbf21f345563dde6c28b60e29d57e9b210b3"><code>06a2cbf</code></a>
Bump peter-evans/create-pull-request from 6.0.5 to 6.1.0 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/294">#294</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/13bba02b72bac97c432c277158bc04b4d2a6bc23"><code>13bba02</code></a>
Bump actions/checkout from 4.1.6 to 4.1.7 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/293">#293</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/e8abcd0e62b334c164b95d49fcabdc9ecbca0554"><code>e8abcd0</code></a>
Bump pypa/gh-action-pypi-publish from 1.8.14 to 1.9.0 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/292">#292</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/124f4adf171e15cd9a91a8b6e0325ecc97be8fe1"><code>124f4ad</code></a>
2024.06.02 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/291">#291</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/c2196ce5d6ee675b27755a19948480a7823e2c6a"><code>c2196ce</code></a>
--- (<a
href="https://redirect.github.com/certifi/python-certifi/issues/290">#290</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/fefdeec7588ff1c05214b85a552afcad5fdb51b2"><code>fefdeec</code></a>
Bump actions/checkout from 4.1.4 to 4.1.5 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/289">#289</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/3c5fb1560b826a7f83f1f9750173ff766492c9cf"><code>3c5fb15</code></a>
Bump actions/download-artifact from 4.1.6 to 4.1.7 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/286">#286</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/4a9569a3eb58db8548536fc16c5c5c7af946a5b1"><code>4a9569a</code></a>
Bump actions/checkout from 4.1.2 to 4.1.4 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/287">#287</a>)</li>
<li><a
href="https://github.com/certifi/python-certifi/commit/1fc808626a895a916b1e4c2b63abae6c5eafdbe3"><code>1fc8086</code></a>
Bump peter-evans/create-pull-request from 6.0.4 to 6.0.5 (<a
href="https://redirect.github.com/certifi/python-certifi/issues/288">#288</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/certifi/python-certifi/compare/2023.11.17...2024.07.04">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=certifi&package-manager=pip&previous-version=2023.11.17&new-version=2024.7.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>
2024-07-06 07:02:22 +00:00
Jon Ross-Perkins efa158d496 Refactor InstBlockStack to use ArrayStack. (#4104)
The use of ArrayStack here is intended to simplify the logic, and also
make better use of the inst heap allocations. Prior changes #4101 and
#4103 removed the less related logic from InstBlockStack, although #4103
is the actual part that blocked using ArrayStack.

BTW, note the PrintForStackDump implementation was incorrect because it
didn't apply size_. This simplification fixes the issue.
2024-07-03 19:19:57 +00:00
Jon Ross-Perkins 9581a1867d Move import refs to their own block. (#4103)
This executes on a TODO in AddImportRef to add instructions to their own
block instead of the File block. This has an important consequence of
removing a pattern from InstBlockStack that added to blocks not
currently at the top, cleaning up an issue for ArrayStack. The delta
here is then mostly in different formatting of the import refs, a
consequence of the separation.
2024-07-03 18:21:12 +00:00
Chandler Carruth 00a1559c01 Add a few percentiles to histogram output. (#4108) 2024-07-03 18:07:36 +00:00
Jon Ross-Perkins cf389bf5d3 Split global init out from InstBlockStack. (#4101)
Creates a `GlobalInit` class for storing relevant values, pulling
functions off `InstBlockStack` and `Context`. Adds a `Context` pointer
just so that it doesn't need to be passed in on each call (`Finalize` in
particular uses several members).

Note we have several different `InstBlockStack` instances, so several
copies of the relevant members were simply unused.
2024-07-03 17:49:47 +00:00
Jon Ross-Perkins 5ebcbae2e8 Add a location to indirect imports. (#4098)
By adding an `ImportDecl` instruction, this creates something that can
be referenced through `ImportIRInst`.
packages/no_prelude/implicit_imports_entities.carbon is getting a test
of this (import_conflict and import_conflict_reverse).

Also re-packs ImportIR from 24 bytes to 16 on 64-bit, since I'm touching
everywhere that makes one anyways.
2024-07-03 17:34:39 +00:00
Jon Ross-PerkinsandChandler Carruth d437e4bffe Create an array stack type for a shared use-case (#4100)
Based on discussion around the region handling in generic_region_stack,
create a generic structure for the stack-of-vectors support. I also want
to add this to InstBlockStack, but that's a little more complex due to
GlobalInit, so cutting a PR here to check with review.

My work here is how I noticed #4099; I want to be sure that I'm correct
about the issue, but it's the difference between being able to use
PeekArray or not.

Note in scope_stack.h, I believe we could remove next_compile_time_index
and make it just based on elements_size(). However, I want to verify
with you before I make further changes there.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2024-07-03 16:58:47 +00:00
Chandler Carruth e71e6ca07f Use separate value stores for identifiers and string literals (#4106)
This undoes a previous change to unify them, and I think at my advice.
=[ Sorry about that, I think I was just wrong.

Specifically, I think I had suggested that it would be more efficient to
have a single shared hashtable of strings. The more I look at profiles
of the toolchain, the less likely that seems. Specifically for
identifiers and string literals it seems especially problematic.

Using a single, joint hashtable is likely a good idea when all of the
different querying code paths are equally likely, the strings follow the
same distribution of sizes, and either there is no clustering of access
to different sets of strings or none of the sets are meaningfully small
enough to fit into a lower level of resident cache.

I think essentially none of these predicates actually hold for
identifiers vs. string literals:
- Identifiers are *much* more hot
- They have wildly different size distributions.
- The access patterns are very clustered

Sorry for the misleading advice on that one.

While splitting them, I've worked to simplify the code a bit by building
a way to have the `StringRef` holding canonical value stores not require
specializations, and so we get a pretty large code cleanup in the
process here.
2024-07-03 15:54:04 +00:00
Chandler CarruthandJon Ross-Perkins 8992d22ab3 Port the toolchain to use the new Carbon hashtable (#4097)
This works to leverage the capabilities of the hashtable as much as
possible, for example using the key context in the value stores.
However, there may still be opportunities to refactor more deeply and
use the functionality even better. Hopefully this is at least
a reasonable start and gets us a clean baseline.

On an Arm M1, this is a 15% improvement on my large lexing stress test,
but ends up a wash on my x86-64 server. This is a smaller benefit than
I expected, and it's because we're using a set-of-IDs and looking up
values with a key context for things like identifiers. This pattern has
a surprising tradeoff. The new hashtable uses significantly less memory,
a 10% peak RSS reduction just from the hashtable change. But indirecting
through the vector of values makes growing the hashtable dramatically
less cache-friendly: it causes growth to randomly access every key when
rehashing. On x86, everything gained by the faster hashtable is lost in
even slower growth. And even on Arm, this eats into the benefits.

But I have a plan to tweak how identifiers specifically work to avoid
most of the growth, and so I suspect this is the right tradeoff on the
whole. It gives us significant working set size reduction and we can
likely avoid the regressed operation (growth with rehash) in most cases
by clever reserving and if necessary by adding a hash caching layer to
the table infrastructure.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-07-03 01:10:44 +00:00
Jon Ross-Perkins f5f8342542 Fix drop_back call in scope_stack (#4099)
I found this through inspection, looking at an array stack data type.
Tests pass either way, not sure what a good test would be for
regressions (tests do fail if the size doesn't match, but either
approach gets an appropriate size). But this is followed by
`truncate(remaining_compile_time_bindings)`, so it seems like
`drop_back` is a better match than `drop_front`.
2024-07-03 01:07:40 +00:00
Richard Smith 6ecf4ce9a7 Store additional information for symbolic constants. (#4102)
When forming a `ConstantId` for a symbolic constant, add storage to
track the generic in which the constant was formed and the index within
that generic. These fields are not yet populated.
2024-07-02 22:38:19 +00:00
Chandler Carruth a8748f3e2d Key context improvements (#4095)
This injects a customization point for hashtable-specific equality
testing that the key context uses by default. While this is rarely
needed, there are LLVM types where it is necessary and it seems a good
general tool to have to avoid unnecessary complexity from custom key
contexts when a simple customization of equality is all that is
required.

This also adds a CRTP mixin for implementing a common pattern of key
contexts where the context provides translation of some key types into
another type, potentially using state. Rather than having to implement
the entire key context API, code can derive from this template and
simply provide a set of overloads for the types it wants to translate.
Any key types used which can be passed to one of those overloads will
get translated before following the same logic as the default key
context. While this updates the only usage so far of this pattern, a
subsequent PR will add several more users making the pattern worth
abstracting here.
2024-07-02 21:20:14 +00:00
bf736e6b03 A collection of hashing improvements from using hashtables. (#4094)
LLVM's `APInt` and `APFloat` need specialized handling to be used
effectively in hashtables. We can't inject overrides into LLVM so we
need to handle them in our hashing routine.

There were also problematic limits on hashing pairs and tuples. First,
the unique-object-representation hashing of pairs was more restricted
than tuples which was a problematic asymmetry and isn't needed. But the
larger issue is that we didn't support recursively hashing when
necessary. That requires a careful predicate to avoid infinite recursion
but lets us handle important use cases for hashtables with a tuple as a
key.

Also added support for hashing arrays that recurse in addition to arrays
where we can hash the raw storage, and added overloads to redirect to
common array handling from various array-like types.

Last but not least, re-worked the constraint model for hashing as raw
data to not override custom hashing functions.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-07-02 20:53:48 +00:00
Richard Smith fa11050961 Track a list of dependent instructions created within a generic (#4092)
When checking a declaration or definition of a generic, track a list of
created instructions that depend on the generic's parameters in some
way, along with information on how they depend on the parameters. This
will eventually be used to determine what information we need to compute
when creating instances of the generic, but for now we're just building
the list.

Information is tracked separately for the declaration region and the
definition region of the generic, because in general these may be first
provided in separate declarations, and they should be substituted into
at different times.
2024-07-01 20:33:44 +00:00
Chandler Carruth 177663551b Hack in a unique IDs counter to source stats. (#4096)
This is awkward to track... Probably it would be best done by tracking
the ratio of unique IDs to lines as a floating point and plot them and
see what a best fit distribution curve looks like. But none of the
histogram printing or stats tracking stuff already in use here makes it
easy to do any of that...

So this does what I hope is a reasonable rough approximation by counting
the ceiling of unique identifiers per 10 lines of code, and plotting
that discreet histogram. Shape of the histogram is exactly what I would
expect: one centered distribution, vaguely normal looking. And the
center for a bunch of different codebases, including our toolchain, is
exactly at 5, which would mean 0.5 unique IDs per line. And the
distribution is pretty reliably bounded above by 10 or 1 unique ID per
line. Which almost seems to clean to be true? Slightly worried about
confirmation bias making me think this code is working because the
results look so pretty.

Here is the output for the toolchain:
```
  ## Unique IDs per 10 lines ## (median: 6)
  2 ids   [ 2]  █▎
  3 ids   [19]  ████████████▎
  4 ids   [32]  ████████████████████▋
  5 ids   [55]  ███████████████████████████████████▌
  6 ids   [62]  ████████████████████████████████████████
  7 ids   [44]  ████████████████████████████▍
  8 ids   [22]  ██████████████▎
  9 ids   [11]  ███████▏
  10 ids  [ 7]  ████▌
  11 ids  [ 2]  █▎
```

And here is the output for llvm-project/*/{lib,include} (to avoid
tests):
```
  # Unique IDs per 10 lines ## (median: 5)
  1 ids   [  29]  ▍
  2 ids   [ 282]  ███▊
  3 ids   [1492]  ███████████████████▉
  4 ids   [2674]  ███████████████████████████████████▌
  5 ids   [3011]  ████████████████████████████████████████
  6 ids   [2267]  ██████████████████████████████▏
  7 ids   [1549]  ████████████████████▋
  8 ids   [ 817]  ██████████▉
  9 ids   [ 301]  ████
  10 ids  [  98]  █▎
  11 ids  [  61]  ▊
  12 ids  [  50]  ▋
  13 ids  [  25]  ▍
  14 ids  [  33]  ▌
  15 ids  [  14]  ▏
  16 ids  [  15]  ▎
  17 ids  [   9]  ▏
  18 ids  [   8]  ▏
  19 ids  [  12]  ▏
  20 ids  [  15]  ▎
  21 ids  [   3]
  22 ids  [   8]  ▏
  23 ids  [   3]
  24 ids  [   3]
  25 ids  [   6]  ▏
  26 ids  [   0]
  27 ids  [   2]
  28 ids  [   0]
  29 ids  [   0]
  30 ids  [   3]
  31 ids  [   1]
  32 ids  [   1]
```
2024-07-01 19:34:31 +00:00
Jon Ross-Perkins 8218769e5e Fix quirks in debug printing (#4088)
So, I noticed that ImportIRInst didn't print properly while trying to
debug an issue, and that's where this started. Then I was sort of trying
to figure out why we have "type_blocks" but "typeBlock", so trying to
make that more consistent. "importIRInst0" felt more odd than
"import_ir_inst0" which is why I'm suggesting down this particular
route, but let me know if you'd prefer the reverse (but then do we also
do "typeBlocks", etc, removing the consistency with the member name?)

Also starting to print more detail on import_irs, and added
import_ir_insts (adjusting formatting for that too).
2024-07-01 18:03:47 +00:00
Chandler Carruth 6310293330 Fix some subtle UB found by MSan. (#4093)
Technically, any small size buffer's lifetime has ended by the time we
get to the base's destructor. This means its no longer valid to access
table contents if stored there from the base destructor. We need to
handle destruction in the table class instead.

This ends up being a trivial change because the logic is already
factored out, we just need to call it from a different point.
2024-06-29 07:44:34 +00:00
Jon Ross-Perkins 3f78e1d068 Change implicit import handling to be namespace-oriented. (#4089)
This refactors how the implicit import is handled in order to retain
more name scope information. As a consequence, private access control
works better between api files and implementation files. Note though
that this will also be essential for name poisoning between the API and
implementation, as discussed in #3763.

In implementing this, I ran into a couple issues with namespaces that I
think point to flaws in their handling. I've fixed some and added a TODO
for the biggest issue (in check.cpp line 281-288), which relates to the
handling of namespaces of direct imports which are first evaluated
indirectly.
2024-06-28 23:39:31 +00:00
Richard Smith 10a198a9e6 Use the correct type for Self in generic classes and generic interfaces (#4087)
In a `class C(T:! type)`, the type `Self` should be `C(T)`, not merely
`C`. Similarly, in an `interface I(T:! type)`, the type of self should
be `I(T)`, not merely `I`.
2024-06-28 20:20:40 +00:00
Richard SmithandJon Ross-Perkins 19c5596fd8 Build Generic objects for generic classes and interfaces. (#4086)
In `ClassType`s and `InterfaceType`s, track a `GenericInstanceId` for
the instance rather than just the argument list.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-06-27 20:22:10 +00:00
Richard Smith a0d767246f Add GenericInstance type to represent instances of generics. (#4085)
Also add a corresponding value store and YAML output.

We don't create any generic instances in this change; this is just
adding infrastructure for future changes.
2024-06-26 22:44:12 +00:00
Richard Smith e7b0529957 Create a Generic object to represent a generic. (#4081)
Build a `Generic` object for generic functions. This object tracks the
generic parameters that are in scope for the generic entity. Eventually
it will track other information about the generic too.

Add basic SemIR formatting support for generic functions.
2024-06-26 20:13:26 +00:00
Richard Smith e5efea89d7 Prefer function-style cast instead of static_cast to convert integers to Ids. (#4084)
As requested in review of #4082.
2024-06-26 19:46:34 +00:00
Jack McCluskeyandJon Ross-Perkins 319c3caf99 Convert Python type hinting to be PEP-585 Compliant (#4083)
Python [PEP-585](https://peps.python.org/pep-0585/) replaces a number of
`typing` module types with built-in equivalents and `collections.abc`
versions as of Python 3.9, with the aim of eventually removing the
`typing` module versions of these classes altogether. Since the minimum
required version of Python listed in the [Contribution Tools
document](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/contribution_tools.md#main-tools)
is 3.9, the type hints in the various python files in the repo can be
updated to this style of type hint without a need for backwards
compatibility.

Feel free to close if this isn't a desired change at this time!

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-06-26 19:32:37 +00:00
Geoff Romer 5a8dfda4f0 Diagnose missing definitions in impl files (#4079) 2024-06-26 18:57:37 +00:00
Richard Smith a699480dc9 Treat constants with symbolic type as being symbolic. (#4082)
When constant evaluation produces a known non-symbolic value, treat the
result as a symbolic constant anyway if the type of the value is
symbolic.

We don't yet have many ways to produce a constant that has a known value
but a symbolic type. The added test case is one such way: an array `[T;
0]` initialized from `()` is a symbolic constant only because its type
is symbolic -- we know its value is always `()`. More ways to form such
constants will be appearing soon as we start to support generics: for
example, a method of a generic class has a symbolic type but a known
constant value of `{}`.

When substituting into a symbolic constant, also substitute into its
type.
2024-06-26 18:46:48 +00:00
Jon Ross-Perkins 8bb80d8271 Add a basic Core.Print function for ints. (#4078)
We'd been discussing that explorer remains necessary for print, and I
was wondering if this kind of approach would be okay (we _probably_ want
this to work, based on #2110, albeit with more overloads -- but I don't
think there's a good way to support overloads at the moment).

```
╚╡../bazel-bin/examples/sieve
2
3
5
7
11
13
17
19
23
29
31
37
41
43
...
```
2024-06-25 21:32:07 +00:00
Chandler CarruthandJon Ross-Perkins 734b54e658 Switch to a carbon_binary rule with target config support. (#4076)
This switches from a macro that simply wraps genrules to a proper
Starlark rule that runs first compile and then link actions.

Most interestingly, this uses the rule structure to allow using the
Carbon toolchain built either in the target config or the exec config.
While the exec config is more principled and even necessary in a
cross-compile situaiton, it is dramatically less efficient when
developing Carbon as all the binaries and tests outside of our examples
will be built with the target config. This triggers a complete second
build of the toolchain in the exec config for examples before this PR.

It is tempting to try to keep the exec config but make it not cause
redundant actions, but the way Bazel sets up exec and target config
makes it essentially impossible to share their artifacts. There used to
be a hack in Bazel itself to force sharing but it was removed due to it
violating the principled design. Instead, these rules are explicit about
their intent to use the target config, much like a test would be.

I have rigged up a flag that is carefully threaded through a wrapper
macro with `select`s to allow easily switching to the exec configuration
in case it is desired or needed. But the the `.bazelrc` sets the default
to the target config. The `BUILD` file default is the principled `exec`
in case these rules are used by importing into some other Bazel
workspace where we might *only* need the exec config.

The net outcome of this is shaving over 2500 actions off of a clean
rebuild such as is triggered by a version bump to LLVM, including some
of the very slow and expensive compiles of LLVM and Clang themselves.
These would only be triggered if you built the examples so this may
mostly impact our CI latency.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-06-24 23:42:17 +00:00
Chandler Carruth f4b20fc186 Fix PR labeling and generate nightly build notes from them. (#4077)
This configures the nightly build to generate release notes and provides
a template for organizing them. The organization is done through
labeling of PRs and categorizing them based on those labels. I've tried
to provide a rough categorization that seems reasonable for folks.

While doing this I looked at our PR labeling and found a few bugs that
were preventing many labels form being attached. I've fixed those and
significantly expanded the coverage of file-based labeling. I've also
added code to do author-based labeling for automated PRs so those can be
separated out from human PRs.
2024-06-24 23:30:34 +00:00
Jon Ross-Perkins 1e78696f39 Update google_benchmark and remove the patch (#4063)
Updating to 1.8.4 breaks the patch file, so I'm looking at solutions
that don't require maintaining a patch.

Verifying this is working with `bazel build
//toolchain/lex:tokenized_buffer_benchmark && strings
bazel-bin/toolchain/lex/tokenized_buffer_benchmark |& grep pfm`
2024-06-24 16:35:39 +00:00
Chandler Carruth aff5b26181 Replace use of deprecated outputs rule parameter. (#4074)
Instead compute the output in the implementation and return it via the
`DefaultInfo` provider. This matches the latest docs on how to write
rules producing a file:
https://bazel.build/rules/rules-tutorial#creating_a_file
2024-06-22 03:11:18 +00:00
Chandler Carruth fa43bde82b Switch to using a Python rule for gen_tmpl.py. (#4073)
This ensures that the Python we have configured with Bazel is used and
not some other system install.
2024-06-22 03:07:04 +00:00
Chandler CarruthandRichard Smith 9d95c6836d Add a key-returning callback insert to Set. (#4072)
This turns out to be super useful now that we have the `key_context`
mechanism and can do much more meaningful heterogeneous lookups, where
the stored key can be *very* different from the lookup key.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-06-22 00:57:41 +00:00
Chandler CarruthandRichard Smith b70cfd0be9 Remove another hashtable iteraiton order dependency. (#4070)
Name scopes store the names in their scope in a `DenseMap`. Several
places reasonably avoid depending on the iteration order by sorting the
names -- they're in the formatting code path where that's a solid
approach.

Unfortunately, when we're importing one scope into another, we also need
to walk the entire scope and do something for each name. =[ This doesn't
seem like a great place to sort things to stabilize them.

I've switched to a fairly simplistic solution of having a vector of name
entries that can be iterated stably, and a separate map for lookups. I
didn't use the set-of-indices trick here because it's not clear that's
the right trade-off for a scope: likely a lot of small scopes here with
relatively hot name lookups. And the key here isn't a large or
dynamically sized thing that we're canonicalizing, it's a `NameId`. That
made me lean towards duplicating the name in the hashtable for lookup
and the vector for iteration.

I thought about a fancy approach of sorting the hashtable keys by their
values (the indices), but that would still require a bit of copying and
more code.

I also thought a bit about other optimizations, but decided to leave a
comment for now -- it's not obvious to me exactly how hot this is and
whether it's better served by faster lookups, being more memory dense,
etc. And that might involve more of an SOA layout change or some other
approach. Rather than do that here, and especially before switching
hashtables, I stuck with a simple approach to address the ordering.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-06-21 22:13:03 +00:00
Chandler CarruthandRichard Smith af6312a3aa Add assignment support to the hashtables. (#4066)
This lets copy and move assignment work. While it's a bit suboptimal to
do assignment with these tables, it still seems like an unreasonable
burden to not allow the basics to work. Even the toolchain ended up
doing this in a few places.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-06-21 21:49:56 +00:00
Danial Klimkin 7e4f2f2b49 Update FunctionContext::Inserter::InsertHelper for llvm changes (#4069)
The interface has changed upstream:


https://github.com/llvm/llvm-project/commit/80f881485accb020345ee7e1c4c3151ec55ce590
2024-06-21 20:49:13 +00:00
4132c6a65f Merge the suffix ops into a single box in the operator precedence mermaid diagram (#4067)
The current approach was done to work-around a limitation that we can
only have a single link per box, but is unscalable. Instead have a
single link to a new sections of the document that describes the box,
and has multiple links.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-06-20 21:17:25 +00:00
5415 changed files with 642520 additions and 347332 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.
+3
View File
@@ -7,3 +7,6 @@ bazel-carbon-lang
# See github_tools/MODULE.bazel.
github_tools
# Example Bazel project.
examples/bazel
-7
View File
@@ -1,7 +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
# Keep pinned to a recent release, listed at
# https://github.com/bazelbuild/bazel.
USE_BAZEL_VERSION=7.2.0
+176 -54
View File
@@ -2,104 +2,226 @@
# 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`.
build --workspace_status_command=./scripts/workspace_status.py
build --stamp
# 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 --nostamp
# Provide aliases for configuring the release and pre-release version being
# built. For documentation of these flags, see //bazel/version/BUILD.
build --flag_alias=release=//bazel/version:release
build --flag_alias=pre_release=//bazel/version:pre_release
build --flag_alias=rc_number=//bazel/version:rc_number
build --flag_alias=beta_number=//bazel/version:beta_number
build --flag_alias=alpha_number=//bazel/version:alpha_number
build --flag_alias=nightly_date=//bazel/version:nightly_date
common --flag_alias=release=//bazel/version:release
common --flag_alias=pre_release=//bazel/version:pre_release
common --flag_alias=rc_number=//bazel/version:rc_number
common --flag_alias=nightly_date=//bazel/version:nightly_date
# Support running clang-tidy with:
# bazel build --config=clang-tidy -k //...
# See: https://github.com/erenon/bazel_clang_tidy
build:clang-tidy --aspects @bazel_clang_tidy//clang_tidy:clang_tidy.bzl%clang_tidy_aspect
build:clang-tidy --output_groups=report
build:clang-tidy --@bazel_clang_tidy//:clang_tidy_config=//:clang_tidy_config
common:clang-tidy --aspects @bazel_clang_tidy//clang_tidy:clang_tidy.bzl%clang_tidy_aspect
common:clang-tidy --output_groups=report
common:clang-tidy --@bazel_clang_tidy//:clang_tidy_config=//:clang_tidy_config
common:clang-tidy --action_env=PATH --host_action_env=PATH
# This warning seems to incorrectly fire in this build configuration, despite
# not firing in our normal builds.
build:clang-tidy --copt=-Wno-unknown-pragmas
common:clang-tidy --copt=-Wno-unknown-pragmas
# --config=non-fatal-checks makes CHECK failures not terminate compilation.
common:non-fatal-checks --per_file_copt=common/check_internal.cpp@-DCARBON_NON_FATAL_CHECKS
# Provide an alias for controlling the `carbon_*` Bazel rules' configuration. We
# enable use of the target config here to make our build and tests more
# efficient, see the documentation in //bazel/carbon_rules/BUILD for details.
common --flag_alias=use_target_config_carbon_rules=//bazel/carbon_rules:use_target_config_carbon_rules
# Bazel doesn't track what commands the flag_alias is valid for, so we can't use
# common here.
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.
#
# Note that this cache will grow without bound currently. You should
# periodically run the `scripts/clean_disk_cache.sh` script or some equivalent.
# https://github.com/bazelbuild/bazel/issues/5139 tracks fixing this in Bazel.
build --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
# Enable some safety when using the build cache, likely to be defaulted in
# future Bazel releases.
build --experimental_guard_against_concurrent_changes
# Enable some safety when using the build cache. Defaults to `lite`.
common --guard_against_concurrent_changes=full
# Used by clang_configuration.bzl.
common --action_env=CC --host_action_env=CC
common --action_env=CMAKE_SYSROOT --host_action_env=CMAKE_SYSROOT
# Disable warnings for all external compilations. These involve code that isn't
# developed as part of Carbon and may be difficult or impossible to patch, so
# warnings aren't likely to be actionable.
build --per_file_copt=external/.*\.(c|cc|cpp|cxx)$@-w
build --host_per_file_copt=external/.*\.(c|cc|cpp|cxx)$@-w
# The `rules_treesitter` synthesized libraries don't allow us to inject flags,
# and compile generated code where we can't fix warnings.
build --per_file_copt=utils/treesitter/_treesitter.tree_sitter/.*\.c$@-w
build --host_per_file_copt=utils/treesitter/_treesitter.tree_sitter/.*\.c$@-w
# The `cc_proto_library` rule doesn't allow providing `copts`:
# https://github.com/bazelbuild/bazel/issues/22610
#
# We unfortunately need to work around issues with `-Wmissing-prototypes` in
# generated protobuf code, so pass the `copt` manually here. The warning issue
# is likely part of:
# https://github.com/llvm/llvm-project/issues/94138
build --per_file_copt=.*\.pb\.cc$@-Wno-missing-prototypes
build --host_per_file_copt=.*\.pb\.cc$@-Wno-missing-prototypes
common --per_file_copt=external/.*\.(c|cc|cpp|cxx)$@-w
common --host_per_file_copt=external/.*\.(c|cc|cpp|cxx)$@-w
# Default dynamic linking to off. While this can help build performance in some
# edge cases with very large linked executables and a slow linker, between using
# fast linkers on all platforms (LLD and the Apple linker), as well as having
# relatively few such executables, shared objects simply waste too much space in
# our builds.
build --dynamic_mode=off
common --dynamic_mode=off
# Always compile PIC code. There are few if any disadvantages on the platforms
# and architectures we care about and it avoids the need to compile files twice.
build --force_pic
common --force_pic
# Completely disable Bazel's automatic stripping of debug information. Removing
# that information causes unhelpful backtraces from unittest failures and other
# crashes. Optimized builds already avoid using debug information by default.
build --strip=never
common --strip=never
# Enable Abseil for GoogleTest.
build --define=absl=1
common --define=absl=1
# 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.
build:asan --features=asan
# Enable TCMalloc on Linux in optimized builds.
common --custom_malloc=//bazel/malloc:tcmalloc_if_linux_opt
# 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).
build:fuzzer --features=fuzzer
# Always allow tests to symbolize themselves with whatever `llvm-symbolize` is
# in the users environment.
build --test_env=ASAN_SYMBOLIZER_PATH
common:fuzzer --features=fuzzer
# Force actions to have a UTF-8 language encoding.
# TODO: Need to investigate what this should be on Windows, but at least for
# Linux and macOS this seems strictly better than the Bazel default of just
# `en_US`.
build --action_env=LANG=en_US.UTF-8
common --action_env=LANG=en_US.UTF-8
# Allow per-platform configuration.
common --enable_platform_specific_config
# Enable libpfm for google_benchmark on Linux only.
common:linux --define=pfm=1
# Enable split debug info on Linux, which is significantly more space efficient
# and should work well with modern debuggers. Note that this is Linux specific
# as macOS has its own approach that is always partially but not completely
# split.
#
# Note: if using GDB, see documentation to get that working:
# https://docs.carbon-lang.dev/docs/project/contribution_tools.html#debugging-with-gdb-instead-of-lldb
#
# TODO: Bazel has a bug where it doesn't manage dwo files in the cache correctly.
# common:linux --fission=yes
# 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
# Query error in `@bazel_tools`. This reproduces with
# `bazel query 'deps(//...)'`.
# TODO: Enable the flag once compatibility issues are fixed.
# common --incompatible_disable_non_executable_java_binary
# Incompatible with the clang-tidy build mode.
# TODO: Enable the flag once compatibility issues are fixed.
# common --incompatible_auto_exec_groups
# Incompatible with `rules_cc`.
# TODO: Enable the flag once compatibility issues are fixed.
# common --incompatible_no_rule_outputs_param
# common --incompatible_stop_exporting_language_modules
# Incompatible with `rules_pkg`.
# TODO: Enable the flag once compatibility issues are fixed.
# common --incompatible_disable_target_default_provider_fields
# Incompatible with `rules_shell`.
# TODO: Enable the flag once compatibility issues are fixed.
# common --incompatible_check_visibility_for_toolchains
# Enable as many incompatible flags as we can, per
# https://bazel.build/release/backward-compatibility. To get the latest list,
# using `bazelisk --migrate build //...` will help.
common --incompatible_allow_tags_propagation
common --incompatible_always_check_depset_elements
common --incompatible_always_include_files_in_data
common --incompatible_bazel_test_exec_run_under
common --incompatible_check_sharding_support
common --incompatible_check_testonly_for_output_files
common --incompatible_config_setting_private_default_visibility
common --incompatible_default_to_explicit_init_py
common --incompatible_depset_for_java_output_source_jars
common --incompatible_depset_for_libraries_to_link_getter
common --incompatible_disable_autoloads_in_main_repo
common --incompatible_disable_native_android_rules
common --incompatible_disable_native_repo_rules
common --incompatible_disable_objc_library_transition
common --incompatible_disable_starlark_host_transitions
common --incompatible_disable_target_provider_fields
common --incompatible_disallow_ctx_resolve_tools
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_dont_enable_host_nonhost_crosstool_features
common --incompatible_dont_use_javasourceinfoprovider
common --incompatible_enable_apple_toolchain_resolution
common --incompatible_enable_deprecated_label_apis
common --incompatible_enable_proto_toolchain_resolution
common --incompatible_enforce_config_setting_visibility
common --incompatible_enforce_starlark_utf8
common --incompatible_exclusive_test_sandboxed
common --incompatible_fail_on_unknown_attributes
common --incompatible_fix_package_group_reporoot_syntax
common --incompatible_java_common_parameters
common --incompatible_legacy_local_fallback
common --incompatible_locations_prefers_executable
common --incompatible_make_thinlto_command_lines_standalone
common --incompatible_merge_fixed_and_default_shell_env
common --incompatible_merge_genfiles_directory
common --incompatible_modify_execution_info_additive
common --incompatible_new_actions_api
common --incompatible_no_attr_license
common --incompatible_no_implicit_file_export
common --incompatible_no_implicit_watch_label
common --incompatible_objc_alwayslink_by_default
common --incompatible_package_group_has_public_syntax
common --incompatible_py2_outputs_are_suffixed
common --incompatible_py3_is_default
common --incompatible_python_disable_py2
common --incompatible_python_disallow_native_rules
common --incompatible_remote_use_new_exit_code_for_lost_inputs
common --incompatible_remove_legacy_whole_archive
common --incompatible_require_ctx_in_configure_features
common --incompatible_require_linker_input_cc_api
common --incompatible_run_shell_command_string
common --incompatible_sandbox_hermetic_tmp
common --incompatible_simplify_unconditional_selects_in_rule_attrs
common --incompatible_stop_exporting_build_file_path
common --incompatible_strict_action_env
common --incompatible_strip_executable_safely
common --incompatible_top_level_aspects_require_providers
common --incompatible_unambiguous_label_stringification
common --incompatible_use_cc_configure_from_rules_cc
common --incompatible_use_new_cgroup_implementation
common --incompatible_use_plus_in_repo_names
common --incompatible_use_python_toolchains
common --incompatible_validate_top_level_header_inclusions
common --incompatible_visibility_private_attributes_at_definition
+1
View File
@@ -0,0 +1 @@
8.6.0
+16 -1
View File
@@ -11,9 +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_RAW_ENUM_CLASS',
'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
+193 -67
View File
@@ -8,72 +8,198 @@ UseColor: true
# This is necessary for `--config=clang-tidy` to catch errors.
WarningsAsErrors: '*'
# - bugprone-exception-escape finds issues like out-of-memory in main(). We
# don't use exceptions, so it's unlikely to find real issues.
# - bugprone-macro-parentheses 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-switch-missing-default-case has false positives for `enum_base.h`.
# Clang's built-in switch warnings cover most of our risk of bugs here.
# - bugprone-unchecked-optional-access in clang-tidy 16 has false positives on
# code like:
# while (auto name_ref = insts().Get(inst_id).TryAs<SemIR::NameRef>()) {
# inst_id = name_ref->value_id;
# ^ unchecked access to optional value
# }
# - google-readability-function-size overlaps with readability-function-size.
# - modernize-use-designated-initializers is disabled because it fires on
# creation of SemIR typed insts, for which we do not currently want to use
# designated initialization.
# - modernize-use-nodiscard is disabled because it only fixes const methods,
# not non-const, which yields distracting results on accessors.
# - performance-unnecessary-value-param is disabled because it duplicate
# modernize-pass-by-value.
Checks:
-*, bugprone-*, -bugprone-branch-clone, -bugprone-easily-swappable-parameters,
-bugprone-exception-escape, -bugprone-macro-parentheses,
-bugprone-narrowing-conversions, -bugprone-switch-missing-default-case,
-bugprone-unchecked-optional-access, google-*,
-google-readability-function-size, -google-readability-todo,
misc-definitions-in-headers, misc-misplaced-const, misc-redundant-expression,
misc-static-assert, misc-unconventional-assign-operator,
misc-uniqueptr-reset-release, misc-unused-*, modernize-*,
-modernize-avoid-c-arrays, -modernize-return-braced-init-list,
-modernize-use-default-member-init, -modernize-use-designated-initializers,
-modernize-use-emplace, -modernize-use-nodiscard, performance-*,
-performance-unnecessary-value-param, readability-*,
-readability-convert-member-functions-to-static,
-readability-function-cognitive-complexity, -readability-else-after-return,
-readability-identifier-length, -readability-implicit-bool-conversion,
-readability-magic-numbers, -readability-make-member-function-const,
-readability-static-definition-in-anonymous-namespace,
-readability-suspicious-call-argument, -readability-use-anyofallof
# We turn on all of a few categories by default.
- '-*'
- 'bugprone-*'
- 'google-*'
- 'misc-*'
- 'modernize-*'
- 'performance-*'
- 'readability-*'
# Disabled due to the implied style choices.
- '-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'
- '-modernize-use-emplace'
- '-readability-avoid-nested-conditional-operator'
- '-readability-convert-member-functions-to-static'
- '-readability-else-after-return'
- '-readability-identifier-length'
- '-readability-implicit-bool-conversion'
- '-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'
# In clang-tidy 16, has false positives on code like:
# while (auto name_ref = insts().Get(inst_id).TryAs<SemIR::NameRef>()) {
# inst_id = name_ref->value_id;
# ^ unchecked access to optional value
# }
- '-bugprone-unchecked-optional-access'
# Overlaps with `readability-function-size`.
- '-google-readability-function-size'
# Suggests usernames on TODOs, which we don't want.
- '-google-readability-todo'
# 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
# status quo.
- '-modernize-avoid-c-arrays'
# Warns on creation of SemIR typed insts, for which we do not currently want
# to use designated initialization.
- '-modernize-use-designated-initializers'
# Only fixes const methods, not non-const, which yields distracting results on
# accessors.
- '-modernize-use-nodiscard'
# We aren't using the ranges library due to performance concerns.
- '-modernize-use-ranges'
# Low value compared to the engineering cost.
- '-performance-enum-size'
# Duplicates `modernize-pass-by-value`.
- '-performance-unnecessary-value-param'
# Warns on enums which use the `LastValue = Value` pattern if all the other
# discriminants aren't given an explicit value.
- '-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:
- { key: readability-identifier-naming.ClassCase, value: CamelCase }
- { key: readability-identifier-naming.ClassConstantCase, value: CamelCase }
- {
key: readability-identifier-naming.ConstexprVariableCase,
value: CamelCase,
}
- { key: readability-identifier-naming.NamespaceCase, value: CamelCase }
- { key: readability-identifier-naming.StructCase, value: CamelCase }
- {
key: readability-identifier-naming.TemplateParameterCase,
value: CamelCase,
}
- { key: readability-identifier-naming.TypeAliasCase, value: CamelCase }
- { key: readability-identifier-naming.TypedefCase, value: CamelCase }
- { key: readability-identifier-naming.UnionCase, value: CamelCase }
- { key: readability-identifier-naming.VariableCase, value: lower_case }
- { key: readability-identifier-naming.ParameterCase, value: lower_case }
- { key: readability-identifier-naming.ClassMemberCase, value: lower_case }
- {
key: readability-identifier-naming.MethodIgnoredRegexp,
value: '^classof$',
}
- {
# This erroneously fires in C++20 mode with LLVM 16 clang-tidy, due to:
# https://github.com/llvm/llvm-project/issues/46097
key: readability-identifier-naming.TemplateParameterIgnoredRegexp,
value: '^expr-type$',
}
# Don't warn on structs; done by ignoring when there are only public members.
- key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
value: true
# CamelCase names.
- key: readability-identifier-naming.ClassCase
value: CamelCase
- key: readability-identifier-naming.ClassConstantCase
value: CamelCase
- key: readability-identifier-naming.ConstexprVariableCase
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
value: CamelCase
- key: readability-identifier-naming.TypeAliasCase
value: CamelCase
- key: readability-identifier-naming.TypedefCase
value: CamelCase
- key: readability-identifier-naming.UnionCase
value: CamelCase
# lower_case names.
- key: readability-identifier-naming.ClassMemberCase
value: lower_case
- key: readability-identifier-naming.ParameterCase
value: lower_case
- key: readability-identifier-naming.VariableCase
value: lower_case
# TODO: This is for explorer's use of LLVM casting support, so we should be
# able to remove it once explorer is deleted.
- key: readability-identifier-naming.MethodIgnoredRegexp
value: '^classof$'
# This erroneously fires in C++20 mode with LLVM 16 clang-tidy, due to:
# https://github.com/llvm/llvm-project/issues/46097
- key: readability-identifier-naming.TemplateParameterIgnoredRegexp
value: '^expr-type$'
# 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
+32
View File
@@ -0,0 +1,32 @@
# 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
CompileFlags:
# Workaround for https://github.com/clangd/clangd/issues/1582
Remove: [-march=*]
Diagnostics:
# `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]
---
# Suppress common diagnostics for x-macro files.
If:
PathMatch: .*\.def
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
+9
View File
@@ -2,6 +2,9 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
AggregateT
AnyOther
ArchType
atleast
circularly
compiletime
@@ -12,7 +15,13 @@ crossreference
falsy
forin
groupt
indext
inout
isELF
iterm
parameteras
pullrequest
rightt
rouge
statics
switcht
-22
View File
@@ -1,22 +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": "carbon-lang",
"build": {
"dockerfile": "../docker/ubuntu2204/base/Dockerfile"
},
"customizations": {
"vscode": {
"extensions": [
"bazelbuild.vscode-bazel",
"bierner.github-markdown-preview",
"daohong-emilio.yash",
"esbenp.prettier-vscode",
"llvm-vs-code-extensions.vscode-clangd",
"ms-python.python"
]
}
}
}
+2 -1
View File
@@ -2,5 +2,6 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
source third_party/llvm-project/libcxx/utils/gdb/libcxx/printers.py
source external/+llvm_project+llvm-project/llvm/utils/gdb-scripts/prettyprinters.py
source external/+llvm_project+llvm-project/libcxx/utils/gdb/libcxx/printers.py
python register_libcxx_printer_loader()
+7
View File
@@ -0,0 +1,7 @@
# 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 tells Github to detect files having the extension `.def` as `C++` files, which
# ensures that these files get syntax highlighted properly.
*.def linguist-language=C++
@@ -1,44 +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: Carbon Explorer bug
description: >
Report a bug with the Carbon Explorer interpreter. This is what's provided at
[Compiler Explorer](https://carbon.compiler-explorer.com).
labels: [explorer]
body:
- type: markdown
attributes:
value: >
**Attention:** If this is a _question_, please use either [GitHub
Discussions](https://github.com/carbon-language/carbon-lang/discussions)
or [Discord](https://discord.gg/ZjVdShJDAs).
- type: textarea
id: desc
attributes:
label: >
Description of the bug:
- type: textarea
id: repro
attributes:
label: >
What did you do, or what's a simple way to reproduce the bug?
description: >
Please provide example code and errors; a shortlink to the execution on
[Compiler Explorer](https://carbon.compiler-explorer.com) can also help.
- type: textarea
id: expected
attributes:
label: >
What did you expect to happen?
- type: textarea
id: actual
attributes:
label: >
What actually happened?
- type: textarea
id: extras
attributes:
label: >
Any other information, logs, or outputs that you want to share?
+45 -10
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,15 +37,19 @@ 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
echo '*** clang++'
which clang++
clang++ --version
echo '*** clang-tidy'
which clang-tidy
clang-tidy --version
# Add our bazel configuration and print basic info to ease debugging.
- name: Configure Bazel and print info
@@ -57,9 +60,22 @@ runs:
shell: bash
run: |
cat >user.bazelrc <<EOF
# Disable the local disk cache as we use a remote cache and don't want
# two copies of every output taking up disk space. The only way to
# disable the disk cache is with an empty string:
# https://github.com/bazelbuild/bazel/issues/5308
build --disk_cache=
# Enable remote cache for our CI but minimize downloads.
build --remote_cache=https://storage.googleapis.com/carbon-builds-github-v${CACHE_VERSION}
build --remote_download_minimal
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
@@ -105,3 +121,22 @@ runs:
test --test_output=errors
EOF
./scripts/run_bazel.py info
- name: Run bazel to sync deps with retry
shell: bash
run: |
# GitHub sometimes has a high failure rate for Bazel's downloads (even
# from GitHub URLs). Bazel exits with `1` on HTTP errors, which is hard
# to distinguish from a normal, permanent error.
#
# This workaround runs fast commands that should always pass (although
# they may be broken by an invalid PR). All errors are retried. The hope
# is that this caches necessary downloads, allowing later commands to
# more reliably succeed without retrying "permanent" errors.
#
# Disable lockfile updates, because some actions want to see
# differences.
./scripts/run_bazel.py --attempts=5 --retry-all-errors \
mod --lockfile_mode=off deps
./scripts/run_bazel.py --attempts=5 --retry-all-errors \
cquery --lockfile_mode=off //... | wc -l
+25 -13
View File
@@ -9,15 +9,26 @@ inputs:
runs:
using: composite
steps:
# Install and cache LLVM 16 from Homebrew.
# TODO: We can potentially remove this and simplify things when the
# Homebrew version of LLVM updates to 16 here:
# https://github.com/actions/runner-images/blob/main/images/macos/macos-12-Readme.md
# Free up disk space as the macOS runners end up using most for Xcode
# versions we don't need and iOS simulators.
- name: Free up disk space
shell: bash
run: |
# The xcrun occasionally fails (maybe a race condition?), so retry a few
# times. Example failure:
# "data" couldn't be moved to "Deleting-<ID>"
echo '*** Delete iOS simulators'
xcrun simctl delete all || \
xcrun simctl delete all || \
xcrun simctl delete all
sudo rm -rf ~/Library/Developer/CoreSimulator/Caches/*
# 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@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2
env:
cache-name: cache-homebrew
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
@@ -34,7 +45,8 @@ runs:
'
}}
# Note the key needs to include all the packages we're adding.
key: Homebrew-Cache-${{ inputs.matrix_runner }}-${{ runner.arch }}
key:
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'
@@ -48,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@16
brew install --force-bottle --only-dependencies llvm@21
echo '*** Installing LLVM itself'
brew install --force-bottle --force --verbose llvm@16
echo '*** brew info llvm@16'
brew info llvm@16
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'
@@ -65,7 +77,7 @@ runs:
- name: Setup LLVM and Clang
shell: bash
run: |
LLVM_PATH="$(brew --prefix llvm@16)"
LLVM_PATH="$(brew --prefix llvm@21)"
echo "Using ${LLVM_PATH}"
echo "${LLVM_PATH}/bin" >> $GITHUB_PATH
echo '*** ls "${LLVM_PATH}"'
+34 -18
View File
@@ -6,8 +6,8 @@ name: Setup build environment (Ubuntu)
runs:
using: composite
steps:
# Ubuntu images start with 23GB available, and this adds 14GB more. For
# comparison, MacOS images have >100GB free.
# Ubuntu images start with ~23GB available; this takes a few seconds to add
# ~22GB more.
#
# Although we could delete more, if we run into a limit, not deleting
# everything provides a little flexibility to get space while trying
@@ -18,41 +18,57 @@ runs:
android: true
dotnet: true
haskell: true
# Enabling large-packages adds ~3 minutes to save ~4GB, so turn it off
# 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@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2
env:
cache-name: cache-llvm
uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
with:
path: ~/llvm
key: LLVM-16-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=clang+llvm-16.0.4-x86_64-linux-gnu-ubuntu-22.04
# `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-16.0.4/$LLVM_RELEASE.tar.xz"
echo "*** Extracting $LLVM_RELEASE"
tar -xJf "$LLVM_RELEASE.tar.xz"
echo "*** Moving to 'llvm'"
mv "$LLVM_RELEASE" llvm
wget --show-progress=off "https://github.com/llvm/llvm-project/releases/download/llvmorg-$LLVM_RELEASE/$LLVM_TARBALL_NAME.tar.xz"
echo "*** Extracting $LLVM_TARBALL_NAME.tar.xz"
mkdir $LLVM_PATH
tar -xJf $LLVM_TARBALL_NAME.tar.xz --strip-components=1 -C $LLVM_PATH
echo "*** Deleting $LLVM_TARBALL_NAME.tar.xz"
rm $LLVM_TARBALL_NAME.tar.xz
echo "*** Testing `clang++ --version`"
~/llvm/bin/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/lib/{*.a,*.so,*.so.*,*.bc}
rm llvm/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
du -hs $LLVM_PATH
- name: Setup LLVM and Clang paths
shell: bash
+172
View File
@@ -0,0 +1,172 @@
# 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: Test setup
inputs:
matrix_runner:
required: true
base_sha:
required: true
remote_cache_key:
required: true
targets_file:
required: true
use_direct_targets:
default: 'false'
outputs:
has_code:
value: ${{ steps.filter.outputs.has_code}}
has_cpp_files:
value: ${{ steps.filter.outputs.has_cpp_files}}
runs:
using: composite
steps:
# Tests should only run on applicable paths, but we still need to have an
# action run for the merge queue. We filter steps based on the paths here,
# and condition steps on the output.
- id: filter
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
with:
filters: |
has_code:
- '!{**/*.md,LICENSE,CODEOWNERS,.git*}'
has_cpp_files:
- '{**/*.cpp,**/*.h}'
# Disable uploads when the remote cache is read-only.
- name: Set up remote cache access (read-only)
if:
steps.filter.outputs.has_code == 'true' && github.event_name ==
'pull_request'
shell: bash
run: |
echo "remote_cache_upload=--remote_upload_local_results=false" \
>> $GITHUB_ENV
# Provide a cache key when the remote cache is read-write.
- name: Set up remote cache access (read-write)
if:
steps.filter.outputs.has_code == 'true' && github.event_name !=
'pull_request'
shell: bash
env:
REMOTE_CACHE_KEY: ${{ inputs.remote_cache_key }}
run: |
echo "$REMOTE_CACHE_KEY" | base64 -d > $HOME/remote_cache_key.json
echo "remote_cache_upload=--google_credentials=$HOME/remote_cache_key.json" \
>> $GITHUB_ENV
- uses: ./.github/actions/build-setup-common
if: steps.filter.outputs.has_code == 'true'
with:
matrix_runner: ${{ inputs.matrix_runner }}
remote_cache_upload: ${{ env.remote_cache_upload }}
# Just for visibility, print space before and after the build.
- name: Disk space before build
if: steps.filter.outputs.has_code == 'true'
shell: bash
run: df -h
- name: Verify MODULE.bazel.lock
if: steps.filter.outputs.has_code == 'true'
shell: bash
run: |
exit_code=0
./scripts/run_bazel.py \
--attempts=5 \
mod deps --lockfile_mode=error || exit_code=$?
if (( $exit_code != 0 )); then
./scripts/run_bazel.py \
--attempts=5 \
mod deps --lockfile_mode=update
echo "MODULE.bazel.lock is out of date! Use below file for update."
echo "Platforms may require merging output, for example by applying"
echo "an update, re-running triggers, and applying the next update."
echo "============================================================"
cat MODULE.bazel.lock
echo "============================================================"
exit 1
fi
# Build and run all targets on branch pushes to ensure we always have a
# clean tree. We don't expect this to be an interactive path and so don't
# optimize the latency of this step.
- name: Using all targets for push
if: steps.filter.outputs.has_code == 'true' && github.event_name == 'push'
shell: bash
env:
TARGETS_FILE: ${{ inputs.targets_file }}
run: |
echo "//..." >$TARGETS_FILE
# Compute the set of possible rules impacted by this change using
# Bazel-based diffing. This lets PRs and the merge queue have a much more
# efficient test CI action by avoiding even enumerating (and downloading)
# all of the unaffected Bazel targets.
- name: Compute indirect pull request targets
if:
steps.filter.outputs.has_code == 'true' && github.event_name != 'push'
&& inputs.use_direct_targets != 'true'
shell: bash
env:
# Compute the base SHA from the different event structures.
GIT_BASE_SHA: ${{ inputs.base_sha }}
TARGETS_FILE: ${{ inputs.targets_file }}
run: |
# First fetch the relevant base into the git repository.
git fetch --depth=1 origin $GIT_BASE_SHA
# Do a retried query to try to download things for target-determinator.
./scripts/run_bazel.py --attempts=5 cquery //... > /dev/null
# Then use `target-determinator` as wrapped by our script.
./scripts/target_determinator.py $GIT_BASE_SHA >$TARGETS_FILE
# Bazel requires a test target to run the test command. There may be
# no targets or there may only be non-test targets that we want to
# build, so simply inject an explicit no-op test target.
echo "//scripts:no_op_test" >> $TARGETS_FILE
# Run the query to generate the targets file.
- name: Compute direct pull request targets
if:
steps.filter.outputs.has_code == 'true' && github.event_name != 'push'
&& inputs.use_direct_targets == 'true'
shell: bash
env:
GIT_BASE_SHA: ${{ inputs.base_sha }}
QUERY_FILE: ${{ inputs.targets_file }}.query
TARGETS_FILE: ${{ inputs.targets_file }}
run: |
# First fetch the relevant base into the git repository.
git fetch --depth=1 origin $GIT_BASE_SHA
# Generate the query file. `same_pkg_direct_rdeps` is used to try to
# only get targets that contain modified files as srcs or hdrs (or
# similar artifacts).
echo 'same_pkg_direct_rdeps(' > $QUERY_FILE
# Start with an uninteresting file so that we can `union` below.
echo ' scripts/no_op_test.py' >> $QUERY_FILE
# Use `union` to join the list of files. Add quotes to defend against
# spaces. Note we can filter to the intersection of Carbon extensions
# and the supported list at:
# https://github.com/erenon/bazel_clang_tidy/blob/master/clang_tidy/clang_tidy.bzl#L65
for f in $(git diff --name-only --diff-filter=d \
$GIT_BASE_SHA -- '**/*.h' '**/*.cpp'); do
echo " union '$f'" >> $QUERY_FILE
done
echo ')' >> $QUERY_FILE
# Use query because cquery doesn't support `same_pkg_direct_rdeps`.
./scripts/run_bazel.py \
--attempts=5 \
query --query_file=$QUERY_FILE \
> $TARGETS_FILE
+43
View File
@@ -0,0 +1,43 @@
# 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
#
# Provide the configuration and categorization for generated release notes.
changelog:
exclude:
labels:
- ignore-for-release
categories:
- title: 'Proposals accepted and merged :scroll:'
labels:
- proposal
exclude.labels:
- bot
- title: 'Toolchain and implementation changes :hammer_and_wrench:'
labels:
- toolchain
exclude.labels:
- bot
- title: 'Documentation changes :memo:'
labels:
- documentation
exclude.labels:
- bot
- title: 'Utilities :triangular_ruler:'
labels:
- utilities
exclude.labels:
- bot
- title: 'Infrastructure changes :building_construction:'
labels:
- infrastructure
exclude.labels:
- bot
- title: 'Automated robot PRs :robot:'
labels:
- bot
- title: 'Other changes'
labels:
- '*'
+25 -1
View File
@@ -1,4 +1,4 @@
# Testing workflows
# Workflows
<!--
Part of the Carbon Language project, under the Apache License v2.0 with LLVM
@@ -6,6 +6,30 @@ Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
## Hardening
Workflows are hardened using
[Step Security tool](https://app.stepsecurity.io/secureworkflow). Findings for
the "Harden Runner" steps are
[available online](https://app.stepsecurity.io/github/carbon-language/carbon-lang/actions/runs).
### Allowed endpoints
Most jobs only have a few endpoints, but due to tools which do downloads, a few
have significantly more. These are:
- clangd_tidy.yaml (Bazel)
- prek.yaml (Bazel, prek)
- nightly_release.yaml (Bazel)
- tests.yaml (Bazel)
When updating one of these, consider updating all of them.
We try to keep `allowed-endpoints` with one per line. Prettier wants to wrap
them, which we fix this with `prettier-ignore`.
## Testing
We keep around an `action-test` branch in carbon-lang, which can be used to test
triggers with `push:` configurations. For example:
-68
View File
@@ -1,68 +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'
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@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
with:
egress-policy: audit
- 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'
explorer:
- 'explorer/**'
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-explorer
if: steps.filter.outputs.explorer == 'true'
uses: hkusu/review-assign-action@5bee595fdb9765d4a0bd35724b6302fa15569158 # v1.4.0
with:
reviewers: geoffromer, jonmeow, 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, geoffromer, jonmeow, josh11b, zygoloid
max-num-of-reviewers: 1
- id: assign-fallback
if: |
steps.filter.outputs.leads != 'true' &&
steps.filter.outputs.explorer != 'true' &&
steps.filter.outputs.toolchain != 'true'
uses: hkusu/review-assign-action@5bee595fdb9765d4a0bd35724b6302fa15569158 # v1.4.0
with:
reviewers: chandlerc, jonmeow, josh11b, zygoloid
max-num-of-reviewers: 1
+122
View File
@@ -0,0 +1,122 @@
# 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 label PRs'
on:
pull_request_target:
types: [opened, ready_for_review]
permissions:
pull-requests: write # For gh to edit labels.
# TODO: `--repo carbon-language/carbon-lang` is a temporary workaround for:
# https://github.com/cli/cli/issues/11055
# Once a later version is released on runners, maybe August 2025, we should be
# able to remove the extra flag.
jobs:
set_labels:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
# prettier-ignore
allowed-endpoints: >
api.github.com:443
- id: filter
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
with:
filters: |
documentation:
- '*.md'
- 'docs/**'
- 'examples/**'
- 'third_party/examples/**'
infrastructure:
- '*.bzl'
- '*.cfg'
- '*.toml'
- '.*'
- '.*/**'
- 'BUILD'
- 'MODULE.*'
- 'WORKSPACE'
- 'bazel/**'
- 'github_tools/**'
- 'proposal/scripts/**'
- 'scripts/**'
# Here we only want the `proposal` label when a *new* file is added
# directly in this directory. We use `added` and a single level glob
# to achieve that.
proposal:
- added: 'proposals/*'
# We include common, shared code into the toolchain label for
# convenience. Essentially, this is everything we intend to ship as
# part of the reference implementation of the language.
toolchain:
- 'common/**'
- 'core/**'
- 'testing/**'
- 'toolchain/**'
utilities:
- 'utils/**'
- id: documentation
if: steps.filter.outputs.documentation == 'true'
run: |
gh pr edit "${PR}" --add-label "documentation" --repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
- id: infrastructure
if: steps.filter.outputs.infrastructure == 'true'
run: |
gh pr edit "${PR}" --add-label "infrastructure" --repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
- id: proposal
if: steps.filter.outputs.proposal == 'true'
run: |
gh pr edit "${PR}" --add-label "proposal" --repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
- id: toolchain
if: steps.filter.outputs.toolchain == 'true'
run: |
gh pr edit "${PR}" --add-label "toolchain" --repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
- id: utilities
if: steps.filter.outputs.utilities == 'true'
run: |
gh pr edit "${PR}" --add-label "utilities" --repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
# Note that this is not a path-based label, but an *author* based label,
# and it applies orthogonally to the others.
- id: automated
if:
contains(fromJSON('["CarbonInfraBot", "dependabot"]'),
github.event.pull_request.user.login)
run: |
gh pr edit "${PR}" --add-label "automated" --repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
+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 }}
+89
View File
@@ -0,0 +1,89 @@
# 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 (clangd)'
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:
clangd-tidy:
runs-on: ubuntu-22.04
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.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
uploads.github.com:443
www.googleapis.com:443
- 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
if: steps.filter.outputs.has_cpp == 'true'
with:
matrix_runner: 'ubuntu-22.04'
remote_cache_upload: '--remote_upload_local_results=false'
- name: Create compile commands
if: steps.filter.outputs.has_cpp == 'true'
run: ./scripts/create_compdb.py
- name: Run clangd-tidy
if: steps.filter.outputs.has_cpp == 'true'
env:
FILTER_FILES: ${{ steps.filter.outputs.has_cpp_files }}
run: |
uvx --with clangd-tidy==1.1.0.post2 clangd-tidy -p . -j 10 $FILTER_FILES
+6 -6
View File
@@ -2,23 +2,23 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: Wiki Changed Discord Notification
name: Discord Wiki Change Notifications
on: gollum
permissions: none
# Minimum permissions.
permissions:
contents: read
jobs:
notify:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
- uses:
'oznu/gh-wiki-edit-discord-notification@1f5b688c27310fba606368b20469c81f5ffd9a2f
# v1.0.0'
- uses: oznu/gh-wiki-edit-discord-notification@1f5b688c27310fba606368b20469c81f5ffd9a2f # v1.0.0
with:
discord-webhook-url: ${{ secrets.DISCORD_WEBHOOK_WIKI_EDIT }}
+50
View File
@@ -0,0 +1,50 @@
# 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: GitHub Pages CI
on:
pull_request:
# 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
permissions:
contents: read
jobs:
# Build job
build:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
- name: Checkout
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@6ca151fd1bfcfd6fe0c4eb6837eb0584d0134a0c # v1.290.0
with:
# Runs 'bundle install' and caches installed gems automatically.
bundler-cache: true
# Increment this number if you need to re-download cached gems.
cache-version: 0
- name: Build with Jekyll
run: bundle exec jekyll build
+88
View File
@@ -0,0 +1,88 @@
# 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: GitHub Pages deploy
on:
# Runs on pushes targeting the default branch.
push:
branches: ['trunk']
# Allows you to run this workflow manually from the Actions tab.
workflow_dispatch:
# 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
permissions: {}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
- name: Checkout
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@6ca151fd1bfcfd6fe0c4eb6837eb0584d0134a0c # v1.290.0
with:
# Runs 'bundle install' and caches installed gems automatically.
bundler-cache: true
# Increment this number if you need to re-download cached gems.
cache-version: 0
- 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}"
- name: Upload artifact
# Automatically uploads an artifact from the './_site' directory by
# default.
uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4.0.0
deploy:
environment:
name: github-pages
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@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4.0.5
-71
View File
@@ -1,71 +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 label PRs'
on:
pull_request_target:
types: [opened, ready_for_review]
permissions:
pull-requests: write # For gh to edit labels.
jobs:
assign_reviewer:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
with:
egress-policy: audit
- id: filter
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
with:
filters: |
documentation:
- '*.md'
- 'docs/**'
explorer:
- 'explorer/**'
infrastructure:
- 'BUILD'
- 'WORKSPACE'
- '.*'
- '.*/**'
- 'bazel/**'
- 'scripts/**'
toolchain:
- 'toolchain/**'
- id: documentation
if: steps.filter.outputs.docs == 'true'
run: |
gh pr edit "${PR}" --add-label "documentation"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
- id: explorer
if: steps.filter.outputs.explorer == 'true'
run: |
gh pr edit "${PR}" --add-label "explorer"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
- id: infrastructure
if: steps.filter.outputs.docs == 'true'
run: |
gh pr edit "${PR}" --add-label "infrastructure"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
- id: toolchain
if: steps.filter.outputs.toolchain == 'true'
run: |
gh pr edit "${PR}" --add-label "toolchain"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
-94
View File
@@ -1,94 +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
#
# This workflow creates a GitHub "release" of a nightly build of the project.
#
# Note: This is just an initial rough attempt, there is a lot of future work
# needed here. A brief summary of TODOs:
#
# - Configure a nice release notes template and switch to generating the title
# and notes instead of hard coding them.
#
# - Do some amount of testing prior to building and uploading the release.
# - Tempting to try to examine existing testing workflow, but maybe better to
# allow re-using any complex parts and do our own testing. That would, for
# example, allow us to narrow or expand the set of tests uses for
# pre-release testing to potentially be different from continuous testing.
# - Some questions around what to do in the event of a failure... error? Where
# does the error go? Create a draft, unpublished release instead?
#
# - Build artifacts for all the different OSes we have GitHub runners for rather
# than just x86 Linux.
name: Nightly Release
on:
schedule:
- cron: '0 2 * * *'
# Enable manual runs for testing or manually (re-)creating a nightly release.
workflow_dispatch:
permissions:
contents: write # For creating and uploading to releases.
jobs:
release:
runs-on: ubuntu-22.04
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
with:
egress-policy: audit
- name: Checkout branch
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Set up remote cache access
env:
REMOTE_CACHE_KEY: ${{ secrets.CARBON_BUILDS_GITHUB }}
run: |
echo "$REMOTE_CACHE_KEY" | base64 -d > $HOME/remote_cache_key.json
echo "remote_cache_upload=--google_credentials=$HOME/remote_cache_key.json" \
>> $GITHUB_ENV
- uses: ./.github/actions/build-setup-common
with:
matrix_runner: ubuntu-22.04
remote_cache_upload: ${{ env.remote_cache_upload }}
- name: Get nightly date
run: |
echo "nightly_date=$(date '+%Y.%m.%d')" >> $GITHUB_ENV
- name: Build release
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 }} \
//toolchain/install:prefix_root/bin/carbon \
//toolchain/install:carbon_toolchain_tar_gz_rule \
//toolchain/install:carbon_toolchain_tar_gz_test
- name: Extract the release version
run: |
# Make sure we can run the toolchain to get the version.
./bazel-bin/toolchain/install/prefix_root/bin/carbon version
# Now stash it in a variable and export it.
VERSION=$( \
./bazel-bin/toolchain/install/prefix_root/bin/carbon version \
| cut -d' ' -f5 | cut -d'+' -f1)
echo "release_version=$VERSION" >> $GITHUB_ENV
- name: Create the release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create \
--title "Nightly build ${{ env.nightly_date }}" \
--notes 'A nightly development build of Carbon.' \
--prerelease \
v${{ env.release_version }} \
"bazel-bin/toolchain/install/carbon_toolchain-${{ env.release_version }}.tar.gz"
+122
View File
@@ -0,0 +1,122 @@
# 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 workflow creates a GitHub "release" of a nightly build of the project.
#
# Note: This is just an initial rough attempt, there is a lot of future work
# needed here. A brief summary of TODOs:
#
# - Configure a nice release notes template and switch to generating the title
# and notes instead of hard coding them.
#
# - Do some amount of testing prior to building and uploading the release.
# - Tempting to try to examine existing testing workflow, but maybe better to
# allow reusing any complex parts and do our own testing. That would, for
# example, allow us to narrow or expand the set of tests uses for
# pre-release testing to potentially be different from continuous testing.
# - Some questions around what to do in the event of a failure... error? Where
# does the error go? Create a draft, unpublished release instead?
#
# - Build artifacts for all the different OSes we have GitHub runners for rather
# than just x86 Linux.
name: Nightly Release
on:
schedule:
- cron: '0 2 * * *'
# Enable manual runs for testing or manually (re-)creating a nightly release.
workflow_dispatch:
permissions:
contents: write # For creating and uploading to releases.
jobs:
release:
runs-on: ubuntu-22.04
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.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
storage.googleapis.com:443
uploads.github.com:443
www.googleapis.com:443
- name: Checkout branch
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Set up remote cache access
env:
REMOTE_CACHE_KEY: ${{ secrets.CARBON_BUILDS_GITHUB }}
run: |
echo "$REMOTE_CACHE_KEY" | base64 -d > $HOME/remote_cache_key.json
echo "remote_cache_upload=--google_credentials=$HOME/remote_cache_key.json" \
>> $GITHUB_ENV
- uses: ./.github/actions/build-setup-common
with:
matrix_runner: ubuntu-22.04
remote_cache_upload: ${{ env.remote_cache_upload }}
- name: Get nightly date
run: |
echo "nightly_date=$(date '+%Y.%m.%d')" >> $GITHUB_ENV
- name: Build release
run: |
./scripts/run_bazel.py \
--attempts=5 --jobs-on-last-attempt=4 \
test -c opt --stamp --remote_download_toplevel \
--pre_release=nightly --nightly_date=${nightly_date} \
//toolchain \
//toolchain/install:carbon_toolchain_tar_gz \
//toolchain/install:carbon_toolchain_tar_gz_test
- name: Extract the release version
run: |
# Make sure we can run the toolchain to get the version.
./bazel-bin/toolchain/carbon version
# Now stash it in a variable and export it.
VERSION=$( \
./bazel-bin/toolchain/carbon version \
| cut -d' ' -f5 | cut -d'+' -f1)
echo "release_version=$VERSION" >> $GITHUB_ENV
- name: Create the release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create \
--title "Nightly build ${nightly_date}" \
--generate-notes \
--prerelease \
v${release_version} \
"bazel-bin/toolchain/install/carbon_toolchain-${release_version}.tar.gz"
-45
View File
@@ -1,45 +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: pre-commit
on:
pull_request:
merge_group:
push:
branches: [trunk]
permissions:
contents: read # For actions/checkout.
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
with:
egress-policy: audit
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
# We want to automatically create github suggestions for pre-commit 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,
# we upload the diffs and event configuration to an artifact for use by
# that action.
- name: Collect pre-commit 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
if: failure()
with:
name: pre-commit output
path: pre-commit-output/*
@@ -1,62 +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
# Create PR suggestions based on problems found by pre-commit action.
name: 'Add pre-commit 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
# `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.
#
# This action is only run from the workflow file on the trunk branch. Changes to
# this file will not take effect until they are merged to trunk.
on:
workflow_run:
workflows: [pre-commit]
types:
- completed
# Note reviewdog/reviewdog has its own token.
permissions:
contents: read # For actions/checkout.
jobs:
pull-request-suggestions:
# Only generate suggestions if pre-commit for a PR failed.
if: |
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.event == 'pull_request' &&
github.actor != 'jonmeow'
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
with:
egress-policy: audit
- uses: reviewdog/action-setup@3f401fe1d58fe77e10d665ab713057375e39b887 # v1.3.0
with:
reviewdog_version: latest
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Download pre-commit output
uses: actions/download-artifact@c850b930e6ba138125429b7e5c93fc707a7f8427 # v4.1.4
with:
name: pre-commit 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.
- name: Create suggestions
env:
REVIEWDOG_GITHUB_API_TOKEN:
${{ secrets.CARBON_INFRA_BOT_FOR_REVIEWDOG }}
run: |
cat ./diff | \
GITHUB_EVENT_PATH=./event \
reviewdog -f=diff -f.diff.strip=1 -reporter=github-pr-review
+80
View File
@@ -0,0 +1,80 @@
# 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: prek
on:
pull_request:
merge_group:
push:
branches: [trunk]
permissions:
contents: read # For actions/checkout.
jobs:
prek:
runs-on: ubuntu-22.04
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.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
uploads.github.com:443
www.googleapis.com:443
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
# Ensure LLVM is set up consistently.
- uses: ./.github/actions/build-setup-common
with:
matrix_runner: ubuntu-22.04
remote_cache_upload: '--remote_upload_local_results=false'
- uses: j178/prek-action@01345c78b7de7d79edf368729212760396ba9345 # v2
# 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 prek_suggestions.yaml. Here,
# we upload the diffs and event configuration to an artifact for use by
# that action.
- name: Collect prek output
if: failure()
run: |
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: prek output
path: prek-output/*
+70
View File
@@ -0,0 +1,70 @@
# 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
# Create PR suggestions based on problems found by prek action.
name: 'Add prek suggestions'
# 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.
#
# This action is only run from the workflow file on the trunk branch. Changes to
# this file will not take effect until they are merged to trunk.
on:
workflow_run:
workflows: [prek]
types:
- completed
# Note reviewdog/reviewdog has its own token.
permissions:
contents: read # For actions/checkout.
jobs:
pull-request-suggestions:
# Only generate suggestions if prek for a PR failed.
if: |
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
# prettier-ignore
allowed-endpoints: >
api.github.com:443
github.com:443
objects.githubusercontent.com:443
raw.githubusercontent.com:443
- uses: reviewdog/action-setup@3f401fe1d58fe77e10d665ab713057375e39b887 # v1.3.0
with:
reviewdog_version: latest
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
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 prek created.
- name: Create suggestions
env:
REVIEWDOG_GITHUB_API_TOKEN:
${{ secrets.CARBON_INFRA_BOT_FOR_REVIEWDOG }}
run: |
cat ./diff | \
GITHUB_EVENT_PATH=./event \
reviewdog -f=diff -f.diff.strip=1 -reporter=github-pr-review
+20 -7
View File
@@ -22,14 +22,22 @@ on:
permissions:
pull-requests: write # For gh to edit labels.
# TODO: `--repo carbon-language/carbon-lang` is a temporary workaround for:
# https://github.com/cli/cli/issues/11055
# Once a later version is released on runners, maybe August 2025, we should be
# able to remove the extra flag.
jobs:
proposal_labeled:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
disable-sudo: true
egress-policy: block
# prettier-ignore
allowed-endpoints: >
api.github.com:443
- name: draft
if: |
@@ -40,7 +48,8 @@ jobs:
--remove-label "proposal accepted" \
--remove-label "proposal declined" \
--remove-label "proposal deferred" \
--add-label "proposal"
--add-label "proposal" \
--repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
@@ -54,7 +63,8 @@ jobs:
--remove-label "proposal accepted" \
--remove-label "proposal declined" \
--remove-label "proposal deferred" \
--add-label "proposal"
--add-label "proposal" \
--repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
@@ -68,7 +78,8 @@ jobs:
--remove-label "proposal rfc" \
--remove-label "proposal declined" \
--remove-label "proposal deferred" \
--add-label "proposal"
--add-label "proposal" \
--repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
@@ -82,7 +93,8 @@ jobs:
--remove-label "proposal rfc" \
--remove-label "proposal accepted" \
--remove-label "proposal deferred" \
--add-label "proposal"
--add-label "proposal" \
--repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
@@ -96,7 +108,8 @@ jobs:
--remove-label "proposal rfc" \
--remove-label "proposal accepted" \
--remove-label "proposal declined" \
--add-label "proposal"
--add-label "proposal" \
--repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
+12 -3
View File
@@ -13,15 +13,23 @@ on:
permissions:
pull-requests: write # For gh to edit labels.
# TODO: `--repo carbon-language/carbon-lang` is a temporary workaround for:
# https://github.com/cli/cli/issues/11055
# Once a later version is released on runners, maybe August 2025, we should be
# able to remove the extra flag.
jobs:
proposal_ready:
if: contains(github.event.pull_request.labels.*.name, 'proposal')
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
disable-sudo: true
egress-policy: block
# prettier-ignore
allowed-endpoints: >
api.github.com:443
- name: rfc
run: |
@@ -30,7 +38,8 @@ jobs:
--remove-label "proposal accepted" \
--remove-label "proposal declined" \
--remove-label "proposal deferred" \
--add-label "proposal rfc"
--add-label "proposal rfc" \
--repo carbon-language/carbon-lang
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR: ${{ github.event.pull_request.html_url }}
-59
View File
@@ -1,59 +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: 'Triage inactive issues and PRs'
on:
schedule:
- cron: '30 1 * * *'
permissions:
issues: write # For actions/stale to close stale issues.
pull-requests: write # For actions/stale to close stale PRs.
jobs:
stale:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
with:
egress-policy: audit
- uses: actions/stale@28ca1036281a5e5922ead5184a1bbf96e5fc984e # v9.0.0
with:
stale-issue-message: >
We triage inactive PRs and issues in order to make it easier to find
active work. If this issue should remain active or becomes active
again, please comment or remove the `inactive` label. The `long
term` label can also be added for issues which are expected to take
time.
This issue is labeled `inactive` because the last activity was over
90 days ago.
stale-pr-message: >
We triage inactive PRs and issues in order to make it easier to find
active work. If this PR should remain active, please comment or
remove the `inactive` label.
This PR is labeled `inactive` because the last activity was over 90
days ago. This PR will be closed and archived after 14 additional
days without activity.
close-pr-message: >
We triage inactive PRs and issues in order to make it easier to find
active work. If this PR should remain active or becomes active
again, please reopen it.
This PR was closed and archived because there has been no new
activity in the 14 days since the `inactive` label was added.
stale-issue-label: 'inactive'
stale-pr-label: 'inactive'
exempt-issue-labels:
'long term,design idea,design update,good first issue,leads question'
days-before-stale: 90
days-before-close: 14
days-before-issue-close: -1
operations-per-run: 100
+5 -3
View File
@@ -2,7 +2,7 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: sync-repos
name: Sync repos
on:
push:
@@ -25,13 +25,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
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
+67 -141
View File
@@ -2,7 +2,7 @@
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
name: test
name: Tests
on:
push:
@@ -22,142 +22,83 @@ concurrency:
jobs:
test:
name:
Testing ${{ matrix.config.name != 'Default' && format('({0})',
matrix.config.name) || '' }} (${{ matrix.runner }})
strategy:
matrix:
# On PRs and in the merge queue test a recent version of each supported
# OS. On push (post-submit), also run on `macos-12` to get Intel macOS
# coverage.
runner:
${{ fromJSON(github.event_name != 'push' && '["ubuntu-22.04",
"macos-14"]' || '["ubuntu-22.04", "macos-14", "macos-12"]') }}
build_mode: [fastbuild, opt]
include:
# The clang-tidy config doesn't work on macos (missing `truncate`).
- runner: ubuntu-22.04
build_mode: clang-tidy
# 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@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
egress-policy: audit
egress-policy: block
# When adding endpoints, see README.md.
# prettier-ignore
allowed-endpoints: >
*.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
uploads.github.com:443
www.googleapis.com:443
# Checkout the pull request head or the branch.
- name: Checkout pull request
if: github.event_name == 'pull_request'
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: Checkout branch
if: github.event_name != 'pull_request'
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
# Tests should only run on applicable paths, but we still need to have an
# action run for the merge queue. We filter steps based on the paths here,
# and condition steps on the output.
- id: filter
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
with:
filters: |
has_code:
- '!{**/*.md,LICENSE,CODEOWNERS,.git*}'
# Disable uploads when the remote cache is read-only.
- name: Set up remote cache access (read-only)
if:
steps.filter.outputs.has_code == 'true' && github.event_name ==
'pull_request'
run: |
echo "remote_cache_upload=--remote_upload_local_results=false" \
>> $GITHUB_ENV
# Provide a cache key when the remote cache is read-write.
- name: Set up remote cache access (read-write)
if:
steps.filter.outputs.has_code == 'true' && github.event_name !=
'pull_request'
env:
REMOTE_CACHE_KEY: ${{ secrets.CARBON_BUILDS_GITHUB }}
run: |
echo "$REMOTE_CACHE_KEY" | base64 -d > $HOME/remote_cache_key.json
echo "remote_cache_upload=--google_credentials=$HOME/remote_cache_key.json" \
>> $GITHUB_ENV
- uses: ./.github/actions/build-setup-common
if: steps.filter.outputs.has_code == 'true'
- id: test-setup
uses: ./.github/actions/test-setup
with:
matrix_runner: ${{ matrix.runner }}
remote_cache_upload: ${{ env.remote_cache_upload }}
# Just for visibility, print space before and after the build.
- name: Disk space before build
if: steps.filter.outputs.has_code == 'true'
run: df -h
- name: Verify MODULE.bazel.lock
if: steps.filter.outputs.has_code == 'true'
run: |
exit_code=0
./scripts/run_bazel.py \
--attempts=5 \
mod deps --lockfile_mode=error || exit_code=$?
if (( $exit_code != 0 )); then
./scripts/run_bazel.py \
--attempts=5 \
mod deps --lockfile_mode=update
echo "MODULE.bazel.lock is out of date! Use below file for update."
echo "Platforms may require merging output, for example by applying"
echo "an update, re-running triggers, and applying the next update."
echo "============================================================"
cat MODULE.bazel.lock
echo "============================================================"
exit 1
fi
# Build and run all targets on branch pushes to ensure we always have a
# clean tree. We don't expect this to be an interactive path and so don't
# optimize the latency of this step.
- name: Compute impacted pull request targets (for push)
if:
steps.filter.outputs.has_code == 'true' && github.event_name == 'push'
env:
TARGETS_FILE: ${{ runner.temp }}/targets
run: |
echo "//..." >$TARGETS_FILE
# Compute the set of possible rules impacted by this change using
# Bazel-based diffing. This lets PRs and the merge queue have a much more
# efficient test CI action by avoiding even enumerating (and downloading)
# all of the unaffected Bazel targets.
- name: Compute impacted pull request targets
if:
steps.filter.outputs.has_code == 'true' && github.event_name != 'push'
env:
# Compute the base SHA from the different event structures.
GIT_BASE_SHA:
base_sha:
${{ github.event_name == 'pull_request' &&
github.event.pull_request.base.sha ||
github.event.merge_group.base_sha }}
TARGETS_FILE: ${{ runner.temp }}/targets
run: |
# First fetch the relevant base into the git repository.
git fetch --depth=1 origin $GIT_BASE_SHA
# Then use `target-determinator` as wrapped by our script.
./scripts/target_determinator.py $GIT_BASE_SHA >$TARGETS_FILE
# Bazel requires a test target to run the test command. There may be
# no targets or there may only be non-test targets that we want to
# build, so simply inject an explicit no-op test target.
echo "//scripts:no_op_test" >> $TARGETS_FILE
remote_cache_key: ${{ secrets.CARBON_BUILDS_GITHUB }}
targets_file: ${{ runner.temp }}/targets
# Build and run just the tests impacted by the PR or merge group.
- name: Test (${{ matrix.build_mode }})
if:
steps.filter.outputs.has_code == 'true' && matrix.build_mode !=
'clang-tidy'
- name: Test (${{ matrix.config.name }})
if: steps.test-setup.outputs.has_code == 'true'
shell: bash
env:
# 'libtool_check_unique failed to generate' workaround.
# https://github.com/bazelbuild/bazel/issues/14113#issuecomment-999794586
@@ -166,29 +107,14 @@ 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
# 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.filter.outputs.has_code == 'true' && matrix.build_mode ==
'clang-tidy'
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".
# See "Disk space before build" in `test-setup`.
- name: Disk space after build
if: steps.filter.outputs.has_code == 'true'
if: steps.test-setup.outputs.has_code == 'true'
run: df -h
+64
View File
@@ -0,0 +1,64 @@
# 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: 'Triage inactive issues and PRs'
on:
schedule:
- cron: '30 1 * * *'
permissions:
issues: write # For actions/stale to close stale issues.
pull-requests: write # For actions/stale to close stale PRs.
jobs:
stale:
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@58077d3c7e43986b6b15fba718e8ea69e387dfcc # v2.15.1
with:
disable-sudo: true
egress-policy: block
# prettier-ignore
allowed-endpoints: >
api.github.com:443
- uses: actions/stale@28ca1036281a5e5922ead5184a1bbf96e5fc984e # v9.0.0
with:
stale-issue-message: >
We triage inactive PRs and issues in order to make it easier to find
active work. If this issue should remain active or becomes active
again, please comment or remove the `inactive` label. The `long term
issue` label can also be added for issues which are expected to take
time.
This issue is labeled `inactive` because the last activity was over
90 days ago.
stale-pr-message: >
We triage inactive PRs and issues in order to make it easier to find
active work. If this PR should remain active, please comment or
remove the `inactive` label.
This PR is labeled `inactive` because the last activity was over 90
days ago. This PR will be closed and archived after 14 additional
days without activity.
close-pr-message: >
We triage inactive PRs and issues in order to make it easier to find
active work. If this PR should remain active or becomes active
again, please reopen it.
This PR was closed and archived because there has been no new
activity in the 14 days since the `inactive` label was added.
stale-issue-label: 'inactive'
stale-pr-label: 'inactive'
exempt-issue-labels:
'long term issue,design idea,design update,good first issue,leads
question'
days-before-stale: 90
days-before-close: 14
days-before-issue-close: -1
operations-per-run: 100
+20 -3
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.
@@ -33,10 +39,21 @@
\#*\#
# vim temporary files
.*.swp
.*.sw[a-p]
.swp
# generated by utils/treesitter/helix.sh
# generated by utils/tree_sitter/helix.sh
/.helix/
# Ignore .DS_Store files
.DS_Store
# 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
+8
View File
@@ -0,0 +1,8 @@
# 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
command script import external/+llvm_project+llvm-project/llvm/utils/lldbDataFormatters.py
command script import scripts/lldbinit.py
settings set escape-non-printables false
settings set target.max-string-summary-length 10000
+105 -47
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: 2c9f875913ee60ca25ce70243dc24d5b6415598c # frozen: v4.6.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,21 +66,46 @@ 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: 3702ba224ecffbcec30af640c149f231d90aebdb # frozen: 24.4.2
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 0c7b6c989466a93942def1f84baf36ddfcd60c83 # frozen: v0.15.14
hooks:
- id: black
- repo: https://github.com/pre-commit/mirrors-prettier
rev: ffb6a759a979008c0e6dff86e39f4745a2d9eac4 # frozen: v3.1.0
- 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
name: prettier
language: node
# 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, yaml]
entry: npx prettier@3.3.3 --write --log-level=warn
- repo: local
hooks:
- id: buildifier
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)^(
@@ -81,17 +128,10 @@ repos:
- id: clang-format
name: clang-format
entry: clang-format
types_or: [c++, proto, def]
types_or: [c++, def]
language: python
args: ['-i']
additional_dependencies: ['clang-format==17.0.1']
- id: explorer-format-grammar
name: Format the explorer grammar file
entry: explorer/syntax/format_grammar.py
language: python
files: ^explorer/syntax/(lexer.lpp|parser.ypp)$
pass_filenames: false
additional_dependencies: ['clang-format==17.0.1']
additional_dependencies: ['clang-format==21.1.8']
- repo: local
hooks:
@@ -108,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
@@ -130,34 +187,8 @@ repos:
language: python
files: ^.*/BUILD$
pass_filenames: false
- repo: https://github.com/PyCQA/flake8
rev: 7d37d9032d0d161634be4554273c30efd4dea0b3 # frozen: 7.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'e5ea6670624c24f8321f6328ef3176dbba76db46' # frozen: v1.10.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
# 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: 6e41aba91fb32e9feb741a6258eefeb9c6e4a482 # frozen: v2.2.6
rev: 2ccb47ff45ad361a21071a7eedda4c37e6ae8c5a # frozen: v2.4.2
hooks:
- id: codespell
args: ['-I', '.codespell_ignore', '--uri-ignore-words-list', '*']
@@ -180,17 +211,22 @@ repos:
Exceptions. See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
- --custom_format
- '\.(carbon|c|json|proto|ypp)(\.tmpl)?$'
- '\.(carbon|c|json|scss|ypp)(\.tmpl)?$'
- ''
- '// '
- ''
- --custom_format
- '\.(js|ts|mjs)$'
- '/*'
- ' * '
- ' */'
- --custom_format
- '\.(l|lpp|y)$'
- '/*'
- ''
- '*/'
- --custom_format
- '\.(plist)$'
- '\.(plist|tmLanguage)$'
- '<!--'
- ''
- '\-->'
@@ -207,26 +243,48 @@ repos:
- --custom_format
- '\.lua$'
- ''
- '-- '
- '\-- '
- ''
exclude: |
(?x)^(
.bazelversion|
.github/pull_request_template.md|
.python-version|
LICENSE.*|
compile_flags.txt|
github_tools/requirements.txt|
third_party/.*|
utils/vscode/esbuild.js|
website/.ruby-version|
website/Gemfile.lock|
.*\.def|
.*\.png|
.*\.svg|
.*/fuzzer_corpus/.*|
.*/testdata/.*\.golden
)$
- id: check-links
- repo: local
hooks:
- id: check-build-graph
name: Check build graph
entry: scripts/check_build_graph.py
language: python
pass_filenames: false
files: |
(?x)^(
.*BUILD.*|
.*MODULE.bazel.*|
.*WORKSPACE.*|
.*\.bzl
)$
# 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
@@ -9,6 +9,6 @@ tabWidth: 2
trailingComma: 'es5'
useTabs: false
overrides:
- files: '*.md'
- files: '**/*.md'
options:
tabWidth: 4
+1
View File
@@ -0,0 +1 @@
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"
+4 -2
View File
@@ -2,9 +2,11 @@
"recommendations": [
"bazelbuild.vscode-bazel",
"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"
]
}
-1
View File
@@ -1 +0,0 @@
../../utils/vscode/
+25
View File
@@ -0,0 +1,25 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "by-gdb",
"request": "launch",
"name": "file_test (gdb)",
"program": "bazel-bin/toolchain/testing/file_test",
"programArgs": "--file_tests=${relativeFile}",
"cwd": "${workspaceFolder}",
"env": {
"TEST_TARGET": "//toolchain/testing:file_test",
"TEST_TMPDIR": "/tmp"
}
},
{
"type": "by-gdb",
"request": "launch",
"name": "carbon compile (gdb)",
"program": "bazel-bin/toolchain/carbon",
"programArgs": "compile --phase=lower --dump-sem-ir --stream-errors ${relativeFile}",
"cwd": "${workspaceFolder}"
}
]
}
+63
View File
@@ -0,0 +1,63 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb-dap",
"request": "launch",
"name": "file_test (lldb)",
"program": "bazel-bin/toolchain/testing/file_test",
"args": ["--file_tests=${relativeFile}"],
"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",
"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": "carbon compile (lldb)",
"program": "bazel-bin/toolchain/carbon",
"args": [
"compile",
"--phase=lower",
"--dump-sem-ir",
"--stream-errors",
"${relativeFile}"
],
"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"
]
}
]
}
+38
View File
@@ -0,0 +1,38 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "saveAll",
"command": "${command:workbench.action.files.saveAll}"
},
{
"label": "autoupdate: toolchain tests",
"type": "process",
"command": "toolchain/autoupdate_testdata.py",
"group": "build",
"dependsOn": ["saveAll"],
"dependsOrder": "sequence",
"presentation": {
"echo": false,
"panel": "dedicated",
"showReuseMessage": false,
"clear": true
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceFolder}"],
"source": "autoupdate",
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
+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
+2 -9
View File
@@ -145,16 +145,9 @@ any member of the conduct team directly.
## Conduct team
The conduct team can be emailed at conduct@carbon-lang.dev, and currently has
the following members:
The conduct team can be emailed at conduct@carbon-lang.dev.
- Allison Poppe (@acpoppe on Discord and GitHub)
- Céline Dedaj (@celineausberlin on Discord and GitHub)
- Christopher Di Bella (@cjdb.work on Discord, @cjdb on GitHub)
- Lexi Bromfield (@lexinadia on Discord and @lexi-nadia on GitHub)
- flysand (@flysand on Discord and @flysand7 on GitHub)
More details about the team and its management are on the
More details about the team, its current members and its management are on the
[conduct team page](/docs/project/teams/conduct_team.md).
### Reporting conduct
+68 -14
View File
@@ -25,6 +25,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
- [Collaboration systems](#collaboration-systems)
- [Getting access](#getting-access)
- [Contribution tools](#contribution-tools)
- [Using AI-based contribution tools](#using-ai-based-contribution-tools)
- [Contribution guidelines and standards](#contribution-guidelines-and-standards)
- [Guidelines and philosophy for contributions](#guidelines-and-philosophy-for-contributions)
- [How to say things](#how-to-say-things)
@@ -32,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)
@@ -97,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
@@ -177,14 +179,13 @@ the Code of Conduct.
- [Google Calendar](https://calendar.google.com/calendar/embed?src=c_07td7k4qjq0ssb4gdl6bmbnkik%40group.calendar.google.com)
is used for meeting invites and project reminders. Contributors may add
calendar entries for meetings added to discuss details. Standard entries
are:
- The
[weekly sync](https://docs.google.com/document/d/1dwS2sJ8tsN3LwxqmZSv9OvqutYhP71dK9Dmr1IXQFTs/edit?resourcekey=0-NxBWgL9h05yD2GOR3wUisg),
where contributors are welcome.
- [Open discussions](https://docs.google.com/document/d/1tEt4iM6vfcY0O0DG0uOEMIbaXcZXlNREc2ChNiEtn_w/edit),
which are unstructured meeting slots used for discussing proposals,
tooling, and other Carbon topics based on who attends.
have
[minutes](https://drive.google.com/drive/folders/1VssO6kn9-HeKfzPDqBDR0Sy5CUE0OnSs)
and include:
- The weekly sync, where contributors are welcome.
- Open discussions, which are unstructured meeting slots used for
discussing proposals, tooling, and other Carbon topics based on who
attends.
#### Getting access
@@ -226,9 +227,55 @@ 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),
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 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:
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
All documents and pull requests must be consistent with the guidelines and
@@ -262,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.
@@ -359,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:
@@ -381,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.
+90 -96
View File
@@ -4,78 +4,55 @@
"""Bazel modules.
If `MODULE.bazel.lock` changes locally, it means the host platform hasn't yet
been added to the lock file. 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.
`MODULE.bazel.lock` may change locally when `bazel` is executed. This means one
of:
Platforms tested with GitHub actions are kept up-to-date. Other platforms may
fall out of sync on dependency changes, and should be updated with a PR the same
way a platform is added.
1. An input is changing, typically `MODULE.bazel` or `.bazelversion`.
- Running `bazel mod deps` provides a canonical update to
`MODULE.bazel.lock`; include the changes.
- GitHub test actions may also identify platform-specific lockfile
updates.
2. The host platform hasn't yet been added to the lock file.
- Platforms tested with GitHub actions are kept up-to-date. Other
platforms may fall out of sync due to `bazel` or dependency changes,
and should be updated with a PR the same way a platform is added.
- 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 = "bazel_skylib", version = "1.7.1")
bazel_dep(name = "rules_pkg", version = "0.10.1")
bazel_dep(name = "abseil-cpp", version = "20240116.2")
bazel_dep(name = "re2", version = "2024-06-01")
bazel_dep(name = "googletest", version = "1.14.0.bcr.1")
google_benchmark_version = "1.8.3"
bazel_dep(name = "google_benchmark", version = google_benchmark_version)
archive_override(
module_name = "google_benchmark",
integrity = "sha256-a8GApX0j1NlRVRn5KwyD1hsFtbqxiJYfNqx7BrDZ6c4=",
patch_strip = 1,
patches = ["@//bazel/google_benchmark:0001-Use-libpfm-by-default-on-supported-platforms.patch"],
strip_prefix = "benchmark-{0}".format(google_benchmark_version),
urls = ["https://github.com/google/benchmark/archive/refs/tags/v{0}.tar.gz".format(google_benchmark_version)],
)
# 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"
archive_override(
module_name = "libpfm",
integrity = "sha256-0YuXdkx1VSjBBR03bjNUXQ62DG6/hWgENoE/pbBMw9E=",
patch_strip = 1,
patches = ["@//bazel/libpfm:0001-Introduce-a-simple-native-Bazel-build.patch"],
strip_prefix = "libpfm-{0}".format(libpfm_version),
urls = ["https://sourceforge.net/projects/perfmon2/files/libpfm4/libpfm-{0}.tar.gz".format(libpfm_version)],
)
bazel_dep(name = "rules_bison", version = "0.2.2")
bazel_dep(name = "rules_flex", version = "0.2.1")
bazel_dep(name = "rules_m4", version = "0.2.3")
bazel_dep(name = "rules_cc", version = "0.0.9")
bazel_dep(name = "rules_proto", version = "6.0.2")
bazel_dep(name = "protobuf", version = "27.1")
libprotobuf_mutator_version = "1.3"
http_archive(
name = "com_google_libprotobuf_mutator",
build_file = "@//:third_party/libprotobuf_mutator/BUILD.txt",
sha256 = "1ee3473a6b0274494fce599539605bb19305c0efadc62b58d645812132c31baa",
strip_prefix = "libprotobuf-mutator-{0}".format(libprotobuf_mutator_version),
urls = ["https://github.com/google/libprotobuf-mutator/archive/v{0}.tar.gz".format(libprotobuf_mutator_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 2024-03-12.
commit = "bff5c59c843221b05ef0e37cef089ecc9d24e7da",
# HEAD as of 2026-01-28.
commit = "c4d35e0d0b838309358e57a2efed831780f85cd0",
remote = "https://github.com/erenon/bazel_clang_tidy.git",
)
@@ -87,50 +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 2024-03-12.
commit = "204aa593e002cbd177d30f11f54cff3559110bb9",
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 = "0.0.10")
bazel_dep(name = "zlib", version = "1.3.1.bcr.1", repo_name = "llvm_zlib")
bazel_dep(name = "zstd", version = "1.5.6", repo_name = "llvm_zstd")
bazel_dep(name = "platforms", version = "1.0.0")
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 2024-05-17.
llvm_project_version = "a68d20e986053ec571223a9f3ead3e146a27dc82"
# Load a repository for the raw llvm-project, pre-overlay.
http_archive(
name = "llvm-raw",
bazel_dep(name = "llvm-raw")
git_override(
module_name = "llvm-raw",
build_file_content = "# empty",
patch_args = ["-p1"],
# We pin to specific upstream commits and try to track top-of-tree
# reasonably closely rather than pinning to a specific release.
# HEAD as of 2026-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",
"//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",
],
sha256 = "4c53512522cfd625a75aa7f201e6932f18ebf3fbe8ee89e05883c3d30ca935ac",
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.
@@ -144,10 +109,39 @@ use_repo(llvm_project, "llvm-project")
# Python
###############################################################################
bazel_dep(name = "rules_python", version = "0.33.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",
)
+816 -3901
View File
File diff suppressed because it is too large Load Diff
+145 -73
View File
@@ -29,10 +29,9 @@ https://drive.google.com/drive/folders/1QrBXiy_X74YsOueeC0IYlgyolWIhvusB
<!--
Don't let the text wrap too narrowly to the left of the above image.
The `div` reduces the vertical height.
GitHub will autolink `img`, but won't produce a link when `href="#"`.
The `div` reduces the vertical height. The `picture` prevents autolinking.
-->
<div><a href="#"><img src="docs/images/bumper.png"></a></div>
<div><picture><img src="docs/images/bumper.png" alt=""></picture></div>
**Fast and works with C++**
@@ -124,9 +123,9 @@ and provides a deeper view into our goals for the Carbon project and language.
## Project status
Carbon Language is currently an experimental project. There is no working
compiler or toolchain. You can see the demo interpreter for Carbon on
[compiler-explorer.com](http://carbon.compiler-explorer.com/).
Carbon Language is currently an experimental project. We are hard at work on a
toolchain implementation with compiler and linker. You can try out the current
state at [compiler-explorer.com](http://carbon.compiler-explorer.com/).
We want to better understand whether we can build a language that meets our
successor language criteria, and whether the resulting language can gather a
@@ -146,15 +145,17 @@ and the language:
- Operator overloading
- Lexical and syntactic structure
- Code organization and modular structure
- A prototype interpreter demo that can both run isolated examples and gives a
detailed analysis of the specific semantic model and abstract machine of
Carbon. We call this the [Carbon Explorer](/explorer/).
- An under-development [compiler and toolchain](/toolchain/) that will compile
Carbon (and eventually C++ code as well) into standard executable code. This
is where most of our current implementation efforts are directed.
- Historically, there was also a prototype
[explorer](https://github.com/carbon-language/explorer) interpreter that
implemented an older version of the Carbon language design, but is no
longer under development and has been archived.
If you're interested in contributing, we're currently focused on
[developing the Carbon toolchain until it can support Carbon ↔ C++ interop](/docs/project/roadmap.md#objective-for-2024-a-working-toolchain-that-supports-c-interop).
If you're interested in contributing, we're currently focused on developing the
Carbon toolchain until it can
[support Carbon ↔ C++ interop](/docs/project/roadmap.md#access-most-non-template-c-apis-in-carbon).
Beyond that, we plan to continue developing the design and toolchain until we
can ship the
[0.1 language](/docs/project/milestones.md#milestone-01-a-minimum-viable-product-mvp-for-evaluation)
@@ -168,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">
@@ -243,44 +247,84 @@ and with a smooth evolutionary path.
Safety, and especially
[memory safety](https://en.wikipedia.org/wiki/Memory_safety), remains a key
challenge for C++ and something a successor language needs to address. Our
initial priority and focus is on immediately addressing important, low-hanging
fruit in the safety space:
challenge for C++ and something a successor language needs to address.
We plan to support a two step migration process:
1. Highly automated, minimal supervision migration from C++ to a dialect of
Carbon designed for C++ interop and migration.
2. Incremental refactoring of the Carbon code to adopt memory-safe designs,
patterns, and APIs.
We also want to address important, low-hanging fruit in the safety space
immediately when migrating into Carbon:
- Tracking uninitialized states better, increased enforcement of
initialization, and systematically providing hardening against
initialization bugs when desired.
- Designing fundamental APIs and idioms to support dynamic bounds checks in
debug and hardened builds.
- Having a default debug build mode that is both cheaper and more
comprehensive than existing C++ build modes even when combined with
initialization, and hardening against initialization bugs when needed.
- Designing fundamental APIs and idioms to support dynamic bounds checking.
- Switching from undefined behavior to erroneous behavior wherever possible,
and marking the remaining undefined behavior with visible `unsafe` syntax.
- Having a default debug build mode that has less runtime overhead while being
more comprehensive than existing C++ debug build modes combined with
[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer).
Once we can migrate code into Carbon, we will have a simplified language with
room in the design space to add any necessary annotations or features, and
infrastructure like [generics](#generics) to support safer design patterns.
Longer term, we will build on this to introduce **a safe Carbon subset**. This
will be a large and complex undertaking, and won't be in the 0.1 design.
Meanwhile, we are closely watching and learning from efforts to add memory safe
semantics onto C++ such as Rust-inspired
[lifetime annotations](https://discourse.llvm.org/t/rfc-lifetime-annotations-for-c/61377).
For more details, see our [safety design](/docs/design/safety).
## Getting started
To try out Carbon, you can use the Carbon explorer to interpret Carbon code and
print its output. You can try it out immediately at
[compiler-explorer.com](http://carbon.compiler-explorer.com/).
To try out Carbon immediately in your browser, you can use the toolchain at:
[carbon.compiler-explorer.com](http://carbon.compiler-explorer.com/).
Because Carbon is an early, experimental project we don't yet have releases you
can download and try out locally, you'll instead need to build any tools
yourself from source. We expect to have packaged releases you can try out when
we reach our
We are developing a traditional toolchain for Carbon that can compile and link
programs. However, Carbon is still an early, experimental project, and so we
only have very experimental nightly releases of the Carbon toolchain available
to download, and only on limited platforms. If you are using a recent Ubuntu
Linux or similar (Debian, WSL, etc.), you can try these out by going to our
[releases](https://github.com/carbon-language/carbon-lang/releases) page and
download the latest nightly toolchain tar file:
`carbon_toolchain-0.0.0-0.nightly.YYYY.MM.DD.tar.gz`. Then you can try it out:
```shell
# A variable with the nightly version from yesterday:
VERSION="$(date -d yesterday +0.0.0-0.nightly.%Y.%m.%d)"
# Get the release
wget https://github.com/carbon-language/carbon-lang/releases/download/v${VERSION}/carbon_toolchain-${VERSION}.tar.gz
# Unpack the toolchain:
tar -xvf carbon_toolchain-${VERSION}.tar.gz
# Create a simple Carbon source file:
echo "import Core library \"io\"; fn Run() { Core.Print(42); }" > forty_two.carbon
# Compile to an object file:
./carbon_toolchain-${VERSION}/bin/carbon compile \
--output=forty_two.o forty_two.carbon
# Install minimal system libraries used for linking. Note that installing `gcc`
# or `g++` for compiling C/C++ code with GCC will also be sufficient, these are
# just the specific system libraries Carbon linking still uses.
sudo apt install libgcc-11-dev
# Link to an executable:
./carbon_toolchain-${VERSION}/bin/carbon link \
--output=forty_two forty_two.o
# Run it:
./forty_two
```
As a reminder, the toolchain is still very early and many things don't yet work.
Please hold off on filing lots of bugs: we know many parts of this don't work
yet or may not work on all systems. We expect to have releases that are much
more robust and reliable that you can try out when we reach our
[0.1 milestone](/docs/project/milestones.md#milestone-01-a-minimum-viable-product-mvp-for-evaluation).
If you do want to try out Carbon locally, you'll need to install our
[build dependencies](/docs/project/contribution_tools.md#setup-commands) (Bazel,
Clang, LLD, libc++) and check out the Carbon repository, for example on Debian
or Ubuntu:
If you want to build Carbon's toolchain yourself or are thinking about
contributing fixes or improvements to Carbon, you'll need to install our
[build dependencies](/docs/project/contribution_tools.md#setup-commands) (Clang,
LLD, libc++) and check out the Carbon repository. For example, on Debian or
Ubuntu:
```shell
# Update apt.
@@ -288,7 +332,6 @@ sudo apt update
# Install tools.
sudo apt install \
bazel \
clang \
libc++-dev \
libc++abi-dev \
@@ -299,19 +342,12 @@ $ git clone https://github.com/carbon-language/carbon-lang
$ cd carbon-lang
```
Then you can build and run the explorer:
```shell
# Build and run the explorer.
$ bazel run //explorer -- ./explorer/testdata/print/format_only.carbon
```
And you can try out our toolchain which has a very early-stage compiler for
Then you can try out our toolchain which has a very early-stage compiler for
Carbon:
```shell
# Build and run the toolchain's help to get documentation on the command line.
$ bazel run //toolchain/driver:carbon -- help
$ ./scripts/run_bazelisk.py run //toolchain -- help
```
For complete instructions, including installing dependencies on various
@@ -322,45 +358,81 @@ Learn more about the Carbon project:
- [Project goals](/docs/project/goals.md)
- [Language design overview](/docs/design)
- [Carbon Explorer](/explorer)
- [Carbon Toolchain](/toolchain)
- [FAQ](/docs/project/faq.md)
## Conference talks
Past Carbon focused talks from the community:
Carbon focused talks from the community:
### 2022
### 2026
- [Carbon Language: An experimental successor to C++](https://www.youtube.com/watch?v=omrY53kbVoA),
CppNorth
- [Carbon Language: Syntax and trade-offs](https://www.youtube.com/watch?v=9Y2ivB8VaIs),
Core C++
- 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/))
### 2023
### 2025
- [Carbons Successor Strategy: From C++ interop to memory safety](https://www.youtube.com/watch?v=1ZTJ9omXOQ0),
C++Now
- Definition-Checked Generics
([Part 1](https://www.youtube.com/watch?v=FKC8WACSMP0),
[Part 2](https://www.youtube.com/watch?v=VxQ3PwxiSzk)), C++Now
- [Modernizing Compiler Design for Carbons Toolchain](https://www.youtube.com/watch?v=ZI198eFghJk),
C++Now
- 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
- [Carbon: An experiment in different tradeoffs](https://llvm.swoogo.com/2024eurollvm/session/2086974/carbon-an-experiment-in-different-tradeoffs),
panel session at EuroLLVM 2024
- Generic implementation strategies in Carbon and Clang, LLVM Developers'
Meeting ([video](https://youtu.be/j0BL52NdjAU),
[slides](https://chandlerc.blog/slides/2024-llvm-generic-implementation/#/))
- The Carbon Language: Road to 0.1, NDC {TechTown}
([video](https://youtu.be/bBvLmDJrzvI),
[slides](https://chandlerc.blog/slides/2024-ndc-techtown-carbon-road-to-0-dot-1))
- How designing Carbon with C++ interop taught me about C++ variadics and
overloads, CppNorth ([video](https://youtu.be/8SGMy9ENGz8),
[slides](https://chandlerc.blog/slides/2024-cppnorth-design-stories))
- Generic Arity: Definition-Checked Variadics in Carbon, C++Now
([video](https://youtu.be/Y_px536l_80),
[slides](https://docs.google.com/presentation/d/10aM1mFMN6Cd5ZkE4OfeiZtSnkVNbo33N-V0et21umww/edit))
- Carbon: An experiment in different tradeoffs, panel session, EuroLLVM
([video](https://youtu.be/Za_KWj5RMR8),
[slides](https://llvm.org/devmtg/2024-04/slides/LightningTalks/Smith-Carbons-high-level-semanticIR.pdf))
- [Alex Bradbury's notes](https://muxup.com/2024q2/notes-from-the-carbon-panel-session-at-eurollvm)
- [Generic Arity: Definition-Checked Variadics in Carbon](https://schedule.cppnow.org/session/generic-arity-definition-checked-variadics-in-carbon/),
C++Now
- Carbon's high-level semantic IR lightning talk, EuroLLVM
([video](https://youtu.be/vIWT4RhUcyw))
### Upcoming
### 2023
- [How designing Carbon with C++ interop taught me about C++ variadics and overloads](https://cppnorth.ca/speaker-chandler-carruth.html),
CppNorth, July 21-24
- [The Carbon Language: Road to 0.1](https://ndctechtown.com/agenda/the-carbon-language-road-to-01-0sqv/0526yb03a59),
NDC {TechTown}, Sept. 11
- Carbons Successor Strategy: From C++ interop to memory safety, C++Now
([video](https://youtu.be/1ZTJ9omXOQ0),
[slides](https://chandlerc.blog/slides/2023-cppnow-carbon-strategy/index.html#/))
- Definition-Checked Generics, C++Now
- Part 1 ([video](https://youtu.be/FKC8WACSMP0),
[slides](https://chandlerc.blog/slides/2023-cppnow-generics-1/#/))
- Part 2 ([video](https://youtu.be/VxQ3PwxiSzk),
[slides](https://chandlerc.blog/slides/2023-cppnow-generics-2/#/))
- Modernizing Compiler Design for Carbons Toolchain, C++Now
([video](https://youtu.be/ZI198eFghJk),
[slides](https://chandlerc.blog/slides/2023-cppnow-compiler/index.html#/))
### 2022
- Carbon Language: Syntax and trade-offs, Core C++
([video](https://youtu.be/9Y2ivB8VaIs),
[slides](https://docs.google.com/presentation/d/1znvL12xCuEfcsP6tpPdrQPnh-UoPFOLnC_RVXZteYaM/edit))
- Carbon Language: An experimental successor to C++, CppNorth
([video](https://youtu.be/omrY53kbVoA),
[slides](https://chandlerc.blog/slides/2022-07-19-cppnorth-keynote/#/))
### Other videos
We additionally have [toolchain videos](/toolchain/docs/README.md#videos).
## Join us
+3 -4
View File
@@ -1,11 +1,11 @@
# Security policy
<!--
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
-->
# Security policy
It's important to us that the Carbon Language provides a secure implementation.
Thank you for taking the time to report vulnerabilities.
@@ -13,7 +13,7 @@ The Carbon Language is still an
[experimental project](/README.md#project-status), so please be careful if using
it in security-sensitive environments.
# Reporting a vulnerability
## Reporting a vulnerability
Please use
<https://github.com/carbon-language/carbon-lang/security/advisories/new> to
@@ -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))
-57
View File
@@ -1,57 +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
workspace(name = "carbon")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
###############################################################################
# Example conversion repositories
###############################################################################
local_repository(
name = "brotli",
path = "third_party/examples/brotli/original",
)
new_local_repository(
name = "woff2",
build_file = "third_party/examples/woff2/BUILD.original",
path = "third_party/examples/woff2/original",
workspace_file = "third_party/examples/woff2/WORKSPACE.original",
)
local_repository(
name = "woff2_carbon",
path = "third_party/examples/woff2/carbon",
)
###############################################################################
# Treesitter rules
###############################################################################
http_archive(
name = "rules_nodejs",
sha256 = "d124665ea12f89153086746821cf6c9ef93ab88360a50c1aeefa1fe522421704",
strip_prefix = "rules_nodejs-6.0.0-beta1",
url = "https://github.com/bazelbuild/rules_nodejs/releases/download/v6.0.0-beta1/rules_nodejs-v6.0.0-beta1.tar.gz",
)
load("@rules_nodejs//nodejs:repositories.bzl", "DEFAULT_NODE_VERSION", "nodejs_register_toolchains")
nodejs_register_toolchains(
name = "nodejs",
node_version = DEFAULT_NODE_VERSION,
)
http_archive(
name = "rules_tree_sitter",
sha256 = "a09f177a2b8acb2f8a84def6ca0c41a5bd26b25634aa7313f22ade6c54e57ca1",
strip_prefix = "rules_tree_sitter-bc3a2131053207de7dfd9b24046b811ce770e35d",
urls = ["https://github.com/Maan2003/rules_tree_sitter/archive/bc3a2131053207de7dfd9b24046b811ce770e35d.tar.gz"],
)
load("@rules_tree_sitter//tree_sitter:tree_sitter.bzl", "tree_sitter_register_toolchains")
tree_sitter_register_toolchains()
-1
View File
@@ -1 +0,0 @@
bazel-out/../../_main
+23
View File
@@ -1,3 +1,26 @@
# 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("@bazel_skylib//rules:common_settings.bzl", "bool_flag")
package(default_visibility = ["//visibility:public"])
# Flag controlling whether the target config is used for the `carbon_*` Bazel
# rules. The default is to use the exec config as that is more correct in cases
# where the target config is not compatible with the exec (cross compiling), and
# for library users of Carbon likely the most efficient as it will provide an
# optimized toolchain.
#
# However, for building the Carbon project itself, this will roughly double the
# build cost by forcing a build in both target and exec config. As a consequence
# we disable the flag in the `.bazelrc` of the project for its builds.
bool_flag(
name = "use_target_config_carbon_rules",
build_setting_default = False,
)
config_setting(
name = "use_target_config_carbon_rules_config",
flag_values = {":use_target_config_carbon_rules": "True"},
)
+381 -40
View File
@@ -4,51 +4,392 @@
"""Provides rules for building Carbon files using the toolchain."""
def carbon_binary(name, srcs):
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.
srcs_and_flags = [(ctx.files.srcs, 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_files + [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"] +
[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 = depset(direct = objs + dep_link_inputs),
executable = toolchain_driver,
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 = {
"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",
),
"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"),
"_default_deps": attr.label_list(default = [Label("//core:io")]),
},
executable = True,
fragments = ["cpp"],
)
_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.
"""
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_root` based rule similar to linking when
# the prelude moves there.
out = src + ".o"
srcs_reordered = [s for s in srcs if s != src] + [src]
native.genrule(
name = src + ".compile",
tools = [
"//toolchain/install:prefix_root/bin/carbon",
"//toolchain/install:install_data",
],
cmd = "$(execpath //toolchain/install:prefix_root/bin/carbon) compile --output=$@ $(SRCS)",
srcs = srcs_reordered,
outs = [out],
)
_carbon_binary_internal(
name = name,
srcs = srcs,
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,
)
# For now, we assume that the prelude doesn't produce any necessary object
# code, and don't include the .o files for //core/prelude... in the final
# linked binary.
#
# TODO: This will need to be revisited eventually.
objs = [s + ".o" for s in srcs]
native.genrule(
name = name + ".link",
tools = [
"//toolchain/install:prefix_root/bin/carbon",
"//toolchain/install:install_data",
],
cmd = "$(execpath //toolchain/install:prefix_root/bin/carbon) link --output=$@ $(SRCS)",
srcs = objs,
outs = [name],
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,
)
+5
View File
@@ -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
# Empty; only defs.bzl is needed.
+33
View File
@@ -0,0 +1,33 @@
# Part of the Carbon Language project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Wraps standard cc rules with the `cc_env` addition.
These should generally be used in place of `@rules_cc`.
"""
load(
"@rules_cc//cc:defs.bzl",
actual_cc_binary = "cc_binary",
actual_cc_library = "cc_library",
actual_cc_test = "cc_test",
)
load("//bazel/cc_toolchains:defs.bzl", "cc_env")
# Expose cc_library directly, for consistency.
cc_library = actual_cc_library
def cc_binary(env = {}, **kwargs):
"""Wraps `cc_binary`, adding `cc_env`."""
actual_cc_binary(
env = cc_env() | env,
**kwargs
)
def cc_test(env = {}, **kwargs):
"""Wraps `cc_binary`, adding `cc_env`."""
actual_cc_test(
env = cc_env() | env,
**kwargs
)
+55 -6
View File
@@ -3,8 +3,14 @@
# 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")
# For use by rules.bzl.
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(
name = "macos_asan",
@@ -14,14 +20,14 @@ selects.config_setting_group(
],
)
# For use by rules.bzl.
# For use by defs.bzl.
# Matches macOS platforms.
config_setting(
name = "is_macos",
constraint_values = ["@platforms//os:osx"],
constraint_values = ["@platforms//os:macos"],
)
# For use by rules.bzl.
# For use by defs.bzl.
# Matches build modes where asan is enabled.
selects.config_setting_group(
name = "macos_asan_build_modes",
@@ -31,16 +37,59 @@ selects.config_setting_group(
],
)
# For use by rules.bzl.
# For use by defs.bzl.
# Matches dbg.
config_setting(
name = "dbg",
values = {"compilation_mode": "dbg"},
)
# For use by rules.bzl.
# For use by defs.bzl.
# Matches fastbuild.
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()

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