Commit Graph
2860 Commits
Author SHA1 Message Date
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
Geoff RomerandDavid Blaikie 2e155567bd Disallow :? within var (#6812)
Co-authored-by: David Blaikie <dblaikie@gmail.com>
2026-03-06 21:08:22 +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
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
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
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
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-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
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