Commit Graph
3720 Commits
Author SHA1 Message Date
bc439ad092 Forward impl declarations of incomplete facet types (#5219)
Implements some of the changes from proposal #5168.

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

---------

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

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

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

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

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

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

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

---------

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

Symbolic `constant_id`:

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

`generic_id`:

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

`specific_id`:

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

---------

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

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

A couple things I considered and discarded were:

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

I'm not sure if there's a better way to set up the table generators, I
might keep tinkering with those for ideas.
2025-03-28 23:24:36 +00:00
dependabot[bot] 2973cafd60 Bump tar-fs from 2.1.1 to 2.1.2 in /utils/vscode in the npm_and_yarn group across 1 directory (#5214)
Bumps the npm_and_yarn group with 1 update in the /utils/vscode
directory: [tar-fs](https://github.com/mafintosh/tar-fs).

Updates `tar-fs` from 2.1.1 to 2.1.2
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/mafintosh/tar-fs/commit/d97731b0e1b8a244ab859784b514cfcf5585ad3d"><code>d97731b</code></a>
2.1.2</li>
<li><a
href="https://github.com/mafintosh/tar-fs/commit/fd1634e869e7c5f85948e95eabdaa8451a085de5"><code>fd1634e</code></a>
symlink tweak from main</li>
<li>See full diff in <a
href="https://github.com/mafintosh/tar-fs/compare/v2.1.1...v2.1.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=tar-fs&package-manager=npm_and_yarn&previous-version=2.1.1&new-version=2.1.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's major version (unless you unignore this specific
dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this
group update PR and stop Dependabot creating any more for the specific
dependency's minor version (unless you unignore this specific
dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR
and stop Dependabot creating any more for the specific dependency
(unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore
conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will
remove the ignore condition of the specified dependency and ignore
conditions
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/carbon-language/carbon-lang/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-28 22:39:55 +00:00
Boaz Brickner ac3bf0d3fa Change TypeStructureBuilder.context_ from reference to pointer (#5211)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:23 +00:00
Boaz Brickner 3acca8402f Change NodeIdTraversal.context_ from reference to pointer (#5210)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:17 +00:00
Boaz Brickner 9d3664baa9 Change PendingBlock.context_ from reference to pointer (#5209)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:11 +00:00
Boaz Brickner bd24d74975 Change SubstConstantCallbacks.context_ from reference to pointer (#5208)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-03-28 16:24:03 +00:00
Dana Jansens 496eddfaf4 Handle FacetAccessType as the self type in symbolic impl lookups (#5200)
It is possible to construct a symbolic impl lookup query that, when
evaluated against a specific, will have a self type that is:
- A facet value instruction with a symbolic constant value
- That constant value is rewritten to a FacetValue pointing through a
FacetAccessType to a symbolic facet value.

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

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

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

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

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

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

What this does not do:

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

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

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

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

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

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

---------

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

---------

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

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

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

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

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

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

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

Fixes #5094

---------

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

--- Impl lookup changes ---

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

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

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

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

--- The long tail ---

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

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

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

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

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

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

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

IdKind is extended to include SpecificInterfaceId.

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

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

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

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

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

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

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

---------

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

Fix this by performing substitution into `bind_symbolic_name` rather
than copying it directly, and instead, detect cases where substitution
determined that the instruction was unchanged despite having a symbolic
constant value, and force it to be rebuilt in that case.

I've not found any way that the previous behavior actually caused
problems, or affected the observable behavior of the toolchain. The type
of these instructions in the eval block doesn't make much difference to
anything because they get immediately replaced by their corresponding
argument values when we run the eval block. But this came up and caused
some test output churn when I was making a different change, and it
seems like a fix to our representation even if it's not changing
behavior, so I'm splitting it out so it can be handled separately.
v0.0.0-0.nightly.2025.03.26
2025-03-25 22:53:25 +00:00
Jon Ross-Perkins 75bbfb3f90 Refactor StringifyTypeExpr to use overloads (#5180)
StringifyTypeExpr has gotten a little long. I know there's some
preference for the effects of explicitly handling cases, but maybe it's
okay to adopt an overload pattern similar to what we do elsewhere? Note
I'm trying to force types to provide overloads, as a case which are
clearly intended to be handled.

Also, perhaps subtly, the list of "singleton" instructions previously
included Vtable, which is not a singleton. With this change, which
instead directly handles singleton instructions by
`requires(IsSingletonInstKind(InstT::Kind))`, Vtable will switch default
handling. But it's not directly printed for types, so there is no net
impact on IR.

At present I have this split from `StepStack` because with these changes
it'd no longer be a simple stack. It felt like maybe the type separation
would help readers.
2025-03-25 20:31:08 +00:00
josh11bandJosh L a7d9ac576c Narrowing facet type conversion tests (#5172)
Merges in the "subtyping" tests from the `impl/lookup` directory along
with some new tests into
`convert_facet_value_to_narrowed_facet_type.carbon` in the `facet`
directory.

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
v0.0.0-0.nightly.2025.03.25
2025-03-25 00:11:00 +00:00
Boaz Brickner 44bcceba86 When import C++ names, add the note on the ClangLookup() as well (#5142)
Currently has no effect because we can't do lookup in classes, yet.

Part of #4666.
2025-03-24 17:27:20 +00:00
Alexander Kornienko b3c7a7e988 Fix a compilation error with a recent Clang (#5170)
This fixes a `copy constructor must pass its first argument by
reference` compilation error when compiled with a recent enough Clang
(after
https://github.com/llvm/llvm-project/commit/fe0d3e3764961b62f43f1b129f30aaec5f30bc16,
targeted for LLVM 21 release).

```
carbon/lang/common/set.h:81:59: error: copy constructor must pass its first argument by reference
   81 |   SetView(SetView<std::remove_const_t<KeyT>, KeyContextT> other_view)
      |                                                           ^
```
2025-03-24 15:45:45 +00:00
Ivana Ivanovska ce2ff0a35d Add support for int return type in Carbon/C++ interop (#5114)
Adding support for importing C++ functions with `int` return type in
Carbon.

Part of #5063

Here is a demo of the functionality:

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

auto foo_int() -> int;
```

```c++
// hello_int.cpp

#include "hello_int.h"

auto foo_int() -> int {
    return 1;
}
```

```carbon
// main.carbon

library "Main";

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

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

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

```
$ clang -c hello_int.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$  bazel-bin/toolchain/carbon link hello_int.o main.o --output=demo
$ ./demo
1
```
2025-03-24 15:18:20 +00:00
Jon Ross-PerkinsandRichard Smith c0ee446cec Refactor InstBlockStore's API, AddDefaultValue -> AddPlaceholder (#5166)
`AddDefaultValue` doesn't quite capture the intended semantics; it
should typically be replaced with an actual value when dealing with
control flows. Trying to indicate the "assign later" with
`AddPlaceholder`, mirroring `AddPlaceholderInst`.

Shifting the `protected` functionality on `BlockValueStore` so that it's
not providing functions just for `InstBlockStore` to use. Also hoping
that seeing the comments next to the function name makes them easier to
understand, whereas `using` buries that a little.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
v0.0.0-0.nightly.2025.03.24 v0.0.0-0.nightly.2025.03.23 v0.0.0-0.nightly.2025.03.22
2025-03-21 23:09:37 +00:00
Dana Jansens 6dbcc78e6c Rewrite symbolic constants in generic redeclarations (#5154)
When a generic function declaration was encountered for the second or
more time, we would FinishGenericRedecl() for the function decl, but
this just popped the generic region stack and moved on.

The issue with that is when the stack entry is gone, we lose the
symbolic constants from that declaration, and are unable to rewrite them
to point to the actual generic. This left us with a function declaration
with abstract symbolic values that were not useful, and in a function
call we use the declaration attached to the definition, which would be a
declaration with broken symbolic values. Then the function would be
uncallable since deduce would be unable to determine argument types
without the generic bindings.

This resolves the issue for functions, as well as ensuring the correct
generic id from a previous declaration is used for other generic entity
types that have redeclarations.

When a function declaration is qualified, such as defining a class
method outside the class body, we need only the function declaration to
contribute to its generic region stack. The code was collecting constant
values from all qualifier segments together incorrectly.

So when we PushNameQualifierScope(), we also drop the current generic
region stack and rewrite its constant values by calling
FinishGenericRedecl(), and open a new stack entry for the next part of
the qualified declaration.

If a generic declaration somehow has more dependent instruction than a
previous declaration, it would add new instructions to its eval block
with indices beyond the elements in the actual declaration eval block,
since we only store the block from the first declaration found. To avoid
this we plumb through that we are in a redeclaration, and terminate with
an ICE instead of adding new instructions to crash on later.

Fixes #5136.
2025-03-21 22:26:08 +00:00