Dana Jansens 9fb428d713 Ensure specific in ImplWitness has resolved definition before accessing witness table (#8040)
When impl lookup results in an `ImplWitness`, either directly or later
through `LookupImplWitness` evaluating to an `ImplWitness` inside some
specific, it represents a dependency on the eval blocks of the
`ImplDecl` that the `ImplWitness` comes from. The `ImplWitness` contains
a `SpecificId` of the `ImplDecl`, and the constants in the witness table
must be viewed through that `SpecificId`. The constants may depend on
the declaration or the definition block of the `ImplDecl`'s specific, so
any use of the witness table from `ImplWitness` requires the specific
from the `ImplWitness` to be fully resolved: both the decl and
definition blocks.

The specific declaration block is always resolved immediately when
forming a specific id, so there's nothing to do there. And things are
simple when the `ImplWitness` returned from impl lookup is concrete. We
would simply resolve the specific definition directly in the evaluation
of `LookupImplWitness`.

But when the `ImplWitness` is symbolic, meaning there's a dependency on
generic parameters in its referenced specific, then we have a dependency
on resolving the specific definition in the `ImplWitness` for every
specific that gets applied to the `ImplWitness`, eventually resulting in
a concrete specific.

Previously we attempted to do this by representing a dependency edge
from the eval block containing the `ImplWitness` instruction to the
definition block of the specific inside the `ImplWitness`. We
represented this dependency edge with the `RequireSpecificDefinition`
instruction.

The challenge with the `RequireSpecificDefinition` instruction was
ensuring it always landed in the _same eval block_ as the one holding
the symbolic `ImplWitness`. Ultimately, we've found a way to do this
without the `RequireSpecificDefinition`. The witness table is accessed
through `ImplWitnessAccess`, so we resolve the specific definition
before each access to the witness table. If the definition is already
resolved, this just costs a lookup of the Specific from the value store.

We document the other things we tried, which don't work or were too
complex, below.

In PR #6236, we added the `RequireSpecificDefinition` instruction in the
eval of `LookupImplWitness`, but this is too late. If impl lookup
resolved to a symbolic `LookupImplWitness`, the `LookupImplWitness` is
added some eval block. Later, we form specifics and re-evaluate that
eval block, and the `LookupImplWitness` can evaluate to an
`ImplWitness`. Adding the `RequireSpecificDefinition` instruction at
this point inserts the instruction into whatever generic's eval block
happens to be on the top of the generic stack, not the eval block of the
generic we are building a specific for. And indeed we can't add
instructions to a generic's eval block later like this, as it would be
missing from specifics that were already resolved for the generic. This
incorrect insertion shows up as a crash in eval at the CHECK introduced
but commented out in [eval.cpp in
#7981](https://github.com/carbon-language/carbon-lang/blob/56d9bbc40add1e9263f2f9b2555c3a27292d1725/toolchain/check/eval.cpp#L3507-L3512).
This is covered by the
`require_specific_impl_definition_through_specific_instantiation.carbon`
test.

We tried moving the insertion of `RequireSpecificDefinition` to be
earlier - at the point where the `LookupImplWitness` is constructed, in
the `LookupImplWitness()` function, instead of inside evaluation. This
seemed like a straightforwardly correct answer, as the eval block that
contains the `LookupImplWitness` will then also contain the
`RequireSpecificDefinition`. However, this can cause us to lose the
`RequireSpecificDefinition` entirely. Because it's a separate
instruction, not an operand of `LookupImplWitness`, it does not get
treated as a dependency of the witness. When we do an impl lookup inside
an `alias`, we build a generic for the alias and then discard it. This
discards the eval block containing the `LookupImplWitness`. Then, in an
enclosing generic, we refer to the constructed `AliasDecl` instruction,
which pulls all its dependent operands into the enclosing eval block.
This pulls in the `LookupImplWitness` into the enclosing eval block, but
it does not preserve the `RequireSpecificDefinition`. This is covered by
the
`require_specific_impl_definition_from_lookup_impl_witness_in_class_definition.carbon`
test.

We tried having `ImplWitness` evaluation resolve the specific definition
of the specific `ImplDecl` it refers to. This seems like the simplest
approach by far as we should always be working with the correct eval
block and nothing can get lost. However it does not work because of the
recursive nature of `ImplWitness`. The `ImplWitness` instruction appears
in the declaration of an `ImplDecl`, and the `ImplWitness` holds a
`SpecificId` for that same `ImplDecl`. When building a specific
`ImplDecl`, we evaluate the `ImplWitness` in the `ImplDecl`'s
declaration block which then immediately resolves the specific
definition before the declaration is finished. This leads to missing
instructions in the specific definition. In short, this puts the
dependency edge to the `ImplDecl`'s specific inside the `ImplDecl`
itself, which is problematic.

We tried wrapping `ImplWitness` in another instruction,
`ImplWitnessUse`. Inside the `ImplDecl` declaration there is still
`ImplWitness`, but then in the definition there is `ImplWitnessUse` and
that is what is returned from the evaluation of `LookupImplWitness`. The
`ImplWitnessUse` is an `ImplWitness` plus it ensures the specific
referred to by the witness has its definition resolved. However this
breaks constant comparisons, as we get different witnesses inside an
impl versus outside.

The first iteration of this PR's solution had us insert the
`RequireSpecificDefinition` into the eval block when we sniffed a
`LookupImplWitness` instruction, however that missed cases where impl
lookup immediately resolved to a symbolic `ImplWitness`, which is why we
now sniff for the `ImplWitness` in the eval block. This is covered by
the
`require_specific_impl_definition_from_symbolic_impl_in_class_definition.carbon`
test.

We also originally made a mistake of not inserting
`RequireSpecificDefinition` when inside the impl definition that the
`ImplWitness` refers to. But we can form specifics ImplWitness values
through function signatures, and these must add the dependency edge on
that specific ImplDecl definition. This is covered by the
`require_specific_impl_definition_from_inside_impl_definition.carbon`
test.

Finally, we did have a working solution. It was to sniff instructions
added to the eval block of a generic, and when an `ImplWitness` is added
to the eval block (it is implied that it is symbolic), also add a
`RequireSpecificDefinition` to that eval block immediately. We also
resolved the definition of a specific referred to by `ImplWitness` when
`LookupImplWitness` evaluates to `ImplWitness` to cover the concrete
witness case. This complicated the construction of the eval block
immensely, however. It caused a situation where adding one inst to the
eval block actually adds two, which we needed to avoid when importing.
And it required inst-kind specific behaviour in the very general
construction of an eval block, completely outside of eval itself.
2026-11-03 14:15:14 +00:00
2026-09-29 03:32:33 +00:00
2025-01-06 23:50:12 +00:00
2020-06-16 17:58:17 -07:00

Carbon Language:
An experimental successor to C++

Why? | Goals | Status | Getting started | Join us

See our announcement video from CppNorth. Note that Carbon is not ready for use.

Quicksort code in Carbon. Follow the link to read more.

Fast and works with C++

  • Performance matching C++ using LLVM, with low-level access to bits and addresses
  • Interoperate with your existing C++ code, from inheritance to templates
  • Fast and scalable builds that work with your existing C++ build systems

Modern and evolving

  • Solid language foundations that are easy to learn, especially if you have used C++
  • Easy, tool-based upgrades between Carbon versions
  • Safer fundamentals, and an incremental path towards a memory-safe subset

Welcoming open-source community

  • Clear goals and priorities with robust governance
  • Community that works to be welcoming, inclusive, and friendly
  • Batteries-included approach: compiler, libraries, docs, tools, package manager, and more

Why build Carbon?

C++ remains the dominant programming language for performance-critical software, with massive and growing codebases and investments. However, it is struggling to improve and meet developers' needs, as outlined above, in no small part due to accumulating decades of technical debt. Incrementally improving C++ is extremely difficult, both due to the technical debt itself and challenges with its evolution process. The best way to address these problems is to avoid inheriting the legacy of C or C++ directly, and instead start with solid language foundations like modern generics system, modular code organization, and consistent, simple syntax.

Existing modern languages already provide an excellent developer experience: Go, Swift, Kotlin, Rust, and many more. Developers that can use one of these existing languages should. Unfortunately, the designs of these languages present significant barriers to adoption and migration from C++. These barriers range from changes in the idiomatic design of software to performance overhead.

Carbon is fundamentally a successor language approach, rather than an attempt to incrementally evolve C++. It is designed around interoperability with C++ as well as large-scale adoption and migration for existing C++ codebases and developers. A successor language for C++ requires:

  • Performance matching C++, an essential property for our developers.
  • Seamless, bidirectional interoperability with C++, such that a library anywhere in an existing C++ stack can adopt Carbon without porting the rest.
  • A gentle learning curve with reasonable familiarity for C++ developers.
  • Comparable expressivity and support for existing software's design and architecture.
  • Scalable migration, with some level of source-to-source translation for idiomatic C++ code.

With this approach, we can build on top of C++'s existing ecosystem, and bring along existing investments, codebases, and developer populations. There are a few languages that have followed this model for other ecosystems, and Carbon aims to fill an analogous role for C++:

  • JavaScript → TypeScript
  • Java → Kotlin
  • C++ → Carbon

Language Goals

We are designing Carbon to support:

  • Performance-critical software
  • Software and language evolution
  • Code that is easy to read, understand, and write
  • Practical safety and testing mechanisms
  • Fast and scalable development
  • Modern OS platforms, hardware architectures, and environments
  • Interoperability with and migration from existing C++ code

While many languages share subsets of these goals, what distinguishes Carbon is their combination.

We also have explicit non-goals for Carbon, notably including:

Our detailed goals document fleshes out these ideas and provides a deeper view into our goals for the Carbon project and language.

Project status

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.

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 critical mass of interest within the larger C++ industry and community.

Currently, we have fleshed out several core aspects of both Carbon the project and the language:

  • The strategy of the Carbon Language and project.
  • An open-source project structure, governance model, and evolution process.
  • Critical and foundational aspects of the language design informed by our experience with C++ and the most difficult challenges we anticipate. This includes designs for:
    • Generics
    • Class types
    • Inheritance
    • Operator overloading
    • Lexical and syntactic structure
    • Code organization and modular structure
  • An under-development compiler and 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 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. Beyond that, we plan to continue developing the design and toolchain until we can ship the 0.1 language and support evaluating Carbon in more detail.

You can see our full roadmap for more details.

Carbon and C++

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 snippet of C++ code. Follow the link to read it.

corresponds to this Carbon code:

A snippet of converted Carbon code. Follow the link to read it.

You can call Carbon from C++ without overhead and the other way around. This means you migrate a single C++ library to Carbon within an application, or write new Carbon on top of your existing C++ investment. For example:

A snippet of mixed Carbon and C++ code. Follow the link to read it.

Read more about C++ interop in Carbon.

Beyond interoperability between Carbon and C++, we're also planning to support migration tools that will mechanically translate idiomatic C++ code into Carbon code to help you switch an existing C++ codebase to Carbon.

Generics

Carbon provides a modern generics system with checked definitions, while still supporting opt-in templates for seamless C++ interop. Checked generics provide several advantages compared to C++ templates:

  • Generic definitions are fully type-checked, removing the need to instantiate to check for errors and giving greater confidence in code.
    • Avoids the compile-time cost of re-checking the definition for every instantiation.
    • When using a definition-checked generic, usage error messages are clearer, directly showing which requirements are not met.
  • Enables automatic, opt-in type erasure and dynamic dispatch without a separate implementation. This can reduce the binary size and enables constructs like heterogeneous containers.
  • Strong, checked interfaces mean fewer accidental dependencies on implementation details and a clearer contract for consumers.

Without sacrificing these advantages, Carbon generics support specialization, ensuring it can fully address performance-critical use cases of C++ templates. For more details about Carbon's generics, see their design.

In addition to easy and powerful interop with C++, Carbon templates can be constrained and incrementally migrated to checked generics at a fine granularity and with a smooth evolutionary path.

Memory safety

Safety, and especially memory safety, remains a key 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 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.

For more details, see our safety design.

Getting started

To try out Carbon immediately in your browser, you can use the toolchain at: carbon.compiler-explorer.com.

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 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:

# 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.

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 (Clang, LLD, libc++) and check out the Carbon repository. For example, on Debian or Ubuntu:

# Update apt.
sudo apt update

# Install tools.
sudo apt install \
  clang \
  libc++-dev \
  libc++abi-dev \
  lld

# Download Carbon's code.
$ git clone https://github.com/carbon-language/carbon-lang
$ cd carbon-lang

Then you can try out our toolchain which has a very early-stage compiler for Carbon:

# Build and run the toolchain's help to get documentation on the command line.
$ ./scripts/run_bazelisk.py run //toolchain -- help

For complete instructions, including installing dependencies on various different platforms, see our contribution tools documentation.

Learn more about the Carbon project:

Conference talks

Carbon focused talks from the community:

2026

  • Carbon memory safety: a first deep dive (July 10, video, transcript, slides)
  • Benchmarking and optimizing the Carbon compiler, NDC {Toronto} (May 5-8) (video, slides)
  • Carbon: graduating from the experiment, NDC {Toronto} (May 5-8) (video, slides)

2025

  • Carbon: from C++ to Memory Safety, REBASE - ICFP/SPLASH (slides)
  • Memory safety everywhere with both Carbon and Rust, RustConf (video, slides)

2024

  • Generic implementation strategies in Carbon and Clang, LLVM Developers' Meeting (video, slides)
  • The Carbon Language: Road to 0.1, NDC {TechTown} (video, slides)
  • How designing Carbon with C++ interop taught me about C++ variadics and overloads, CppNorth (video, slides)
  • Generic Arity: Definition-Checked Variadics in Carbon, C++Now (video, slides)
  • Carbon: An experiment in different tradeoffs, panel session, EuroLLVM (video, slides)
  • Carbon's high-level semantic IR lightning talk, EuroLLVM (video)

2023

  • Carbon’s Successor Strategy: From C++ interop to memory safety, C++Now (video, slides)
  • Definition-Checked Generics, C++Now
  • Modernizing Compiler Design for Carbon’s Toolchain, C++Now (video, slides)

2022

  • Carbon Language: Syntax and trade-offs, Core C++ (video, slides)
  • Carbon Language: An experimental successor to C++, CppNorth (video, slides)

Other videos

We additionally have toolchain videos.

Join us

We'd love to have folks join us and contribute to the project. Carbon is committed to a welcoming and inclusive environment where everyone can contribute.

Contributing

You can also directly:

You can check out some "good first issues", or join the #contributing-help channel on Discord. See our full CONTRIBUTING documentation for more details.

S
Description
Carbon Language's main repository: documents, design, implementation, and related tools. (NOTE: Carbon Language is experimental; see README)
Readme Apache-2.0
2.8 GiB
0 Stars 1 Watchers 0 Forks
Languages
C++ 89.9%
Starlark 4.2%
Python 3.4%
Carbon 1.5%
JavaScript 0.4%
Other 0.3%