Commit Graph
100 Commits
Author SHA1 Message Date
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
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
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
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
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
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
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
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
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
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
Richard Smith 0ea8fb2e74 Add documentation for our constrained overload set idiom. (#7681)
As used in #7679.
2026-08-27 18:51:30 +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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Richard Smith ee81a4e48e Bump vscode extension version to 0.0.9 for release. (#7522) 2026-07-16 18:49:59 +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
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
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
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
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
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
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
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
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
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
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
Richard Smith de6c8b0990 Delete some dead variables. (#7410) 2026-06-24 04:24:40 +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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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