Commit Graph
52 Commits
Author SHA1 Message Date
Richard Smith b138c90c9e Use constant evaluation to determine the identity of types. (#3617)
Remove the type canonicalization mechanism and instead rely on constant
canonicalization to deduplicate types.

Rename the `Canonicalize*Type` functions to reflect that they're no
longer performing canonicalization. Switch code that creates types due
to semantic checking, rather than due to source syntax, to directly
create type constants through evaluation rather than creating an
instruction and evaluating it to produce a separate constant
representation.

The mapping from `const (const T)` that was previously performed by type
canonicalization is now implemented in expression evaluation instead.

The value `<error>` is now treated as a constant value, with a special
property that an instruction involving `<error>` that could possibly be
constant evaluates to `<error>`. This helps avoid producing follow-on
errors when an error occurs as a subexpression of an expression, such as
a type, that is intended to be constant.
2024-01-19 00:47:37 +00:00
Jon Ross-Perkins d0fb4b5815 Change DiagnoseDuplicateName to expect an inst ID for the duplicate. (#3616)
This makes duplicate and previous definition handling match. While we
may want to make both point more fine-grained at the name, the necessary
logic seems likely to be equivalent.

Note, I'm looking at this mainly due to duplicate names in imports,
where it's especially helpful to take an instruction instead of a parse
node. We'll eventually want to handle parse nodes from other imports
better, and I think this is the way it would most likely work.
2024-01-18 23:23:31 +00:00
Richard Smith 906346cf35 Ensure we evaluate instructions created in uncommon ways. (#3598)
Instructions created by splices during conversion are now evaluated, as
are instructions created in cases where we first create a placeholder
instruction and later replace it by a different instruction.

This also removes the ability to set a parse node and instruction
independently after creating an `InstId`, which could lead to them
accidentally not matching.
2024-01-16 21:28:14 +00:00
Richard Smith d712bf12a6 Remove parse nodes from constants. (#3599)
These instructions are intended to be shared across all uses and so
don't have a meaningful location. So far, only type constants are
shared.
2024-01-13 04:52:25 +00:00
Jon Ross-Perkins f5e9158fa7 Support passing an InstId for check diagnostics. (#3597) 2024-01-12 22:09:32 +00:00
Jon Ross-PerkinsandRichard Smith f197219c10 Split parse nodes out from instructions because they're rarely used. (#3590)
The parse nodes are still tracked as part of the same value store
interface in order to ensure parity, but they're split out from Inst
itself in order to reduce the size of Inst -- the expectation is that
they don't need to be passed around quite as much.

This change doesn't actually reduce the passing very much, although
there are hints of it: AddInstAndPush doesn't typically need a separate
parse node from the one on the Inst itself, for example. In a couple
spots I changed code to rely a little more on the InstId until the
ParseNode is needed, but it's very low hanging fruit where done. I think
convert could do more to not eagerly fetch the parse node before its
use, but more cleanup felt it would be easier to handle separately. I'm
currently viewing this as making such cleanup _possible_ rather than
executing on it up-front.

But also, I want to make sure there's a consensus to head in this
direction before pulling the trigger. We speculated that this would
result in the parse node being passed around less, and I do think that's
the case, although it's a bit fuzzy in the change.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-01-12 19:01:51 +00:00
Jon Ross-PerkinsandRichard Smith cad4605dad Add imports of enclosing scopes. (#3575)
Namespaces are copied, which means also adding their name to the
underlying instruction. It happened not to be done previously; the name
was only in name lookup.

Since the only import supported right now is the default import,
functionality is limited; in the future I'll need to deal with namespace
vs package conflicts.

Tests of namespace imports are under "namespace" -- I figured this would
be best for scaling as more instructions get support.

This also improves some debugging-related output that I was trying to
use while trying to build the support.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-01-10 17:36:50 +00:00
josh11b 0b9e73ab07 Put check stage handle functions in execution order (#3573)
No changes other than moving code and adding section comments.
2024-01-09 02:46:10 +00:00
Richard Smith a6508fcf05 Basic support for generic bindings. (#3555)
This change adds a `BindSymbolicName` instruction for generic bindings,
paralleling the existing `BindName`. A mechanism is also added to allow
both kinds of binding to be accessed uniformly, for convenience in the
case where the two different kinds of binding are treated the same.

Generic bindings of type `type` are allowed to be used as types,
although no operations are provided for such types. For now lowering
treats these types as empty structs, which seems like a reasonable
lowering for non-monomorphized unconstrained types.
2024-01-05 03:39:45 +00:00
Jon Ross-Perkins 0205645e7d Refactor BindName to support tracking the enclosing scope. (#3566)
This is a step towards adding enclosing scopes for imports. It creates
an indirection for all bind names.

We discussed specializing for bindings that are in function scope (i.e.,
not a useful enclosing scope for imports or diagnostics). However, the
thought is to go ahead with this singular approach for now, and only
change structure if it's a performance issues so that we have
incrementally fewer instructions to handle.
2024-01-05 02:56:03 +00:00
josh11b 770876bbcb Define Any...DeclId aliases for brevity (#3562) 2024-01-04 00:03:44 +00:00
josh11bandRichard Smith b0da52a3d7 Use typed parse node ids in SemIR instruction types (#3560)
This involves a number of supporting changes:
* The `parse_node;` member of instruction types may now have any type
derived from `Parse::NodeId` and is no longer required to have that
exact type.
* `Parse::Node::Invalid` is now a singleton object of a separate type
that is convertible to `Parse::NodeId` and its descendants. This
replaces the `Invalid` member of its descendants, and avoids having to
write long `NodeIdOneOf<...>` types when initializing variables to
invalid.
* `IndexBase` now allows `==` and `!=` comparisons between its derived
classes and types that are convertible to those types.
* A number of functions in the check stage have been changed to preserve
more type information instead of using `Parse::NodeId`.
* `NodeIdForKind<K>` (also known as `KId`) now has a `Kind` member so it
may be used to declare `NodeIdOneOf<T, U>` types without #including
`parse/typed_nodes.h`.
* `NodeIdForKind<K>` (also known as `KId`) may be implicitly converted
to `NodeIdOneOf<T, U>` if `T::Kind == K` or `U::Kind == K` (executing a
TODO).

Many of the `parse_node` members were not converted since they would
have required more extensive changes. They have been marked with "TODO"
comments.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-01-03 23:13:30 +00:00
josh11bandChandler Carruth 48c986f52d Start using typed parse node ids in the check stage (#3547)
Goal is to increase type safety, though more work needs to be done (see
added TODOs).

Note that, after this change, check handlers corresponding to deleted
parse node kinds will no longer compile.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-12-29 01:28:09 +00:00
Richard Smith fe24ebc021 Create a BindName for function parameters. (#3535)
The goal here is to make the representation more uniform so that we can
start adding different kinds of binding -- checked generic bindings and
template bindings -- across both function parameters and local `let`
declarations.

With this change, the entry in the parameter list for the function is
the name binding, not the Param itself, which has some ripple effects on
consumers of that list that want to access the parameter rather than the
binding. This is expected to change again when we start adding more of
the pattern matching SemIR, but this seems good enough for now.
2023-12-22 00:12:16 +00:00
Richard Smith 0a1abe9f64 Clean up some uses of the node stack. (#3512)
Also minor cleanups for the stack itself.
2023-12-14 20:57:03 +00:00
Richard Smith fbb4ecf319 Remove SelfParam, add an AddrPattern instead. (#3506)
This is intended to make the representation of a `self` pattern be more
similar to other patterns.
2023-12-14 20:53:51 +00:00
josh11b 23c7d7dd99 Underline the complete declaration in diagnostics (#3508)
Builds upon @domisterwoozy 's excellent #3442 . Removes the need to
store the first node of a declaration in the declaration state stack.
2023-12-14 19:18:17 +00:00
Jacob Schneider 6419568142 Fully underline parse nodes in diagnostics. (#3442)
Another incremental change to diagnostic formatting. I simply recurse
over all the tokens in the subtree of a parse node and construct a
`DiagnosticLocation` that covers all of the tokens.

I believe it's nicer for the user to be directed at the entire chunk of
source where the error is occurring rather then just pointing at the
bracketing/terminator tokens, but let me know if you all agree.
2023-12-13 18:43:19 +00:00
Geoff RomerandRichard Smith 6e65a30b5d Rename ParamList to TuplePattern (#3479)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-12-08 23:35:47 +00:00
josh11b 407079c33a Pop decl state stack earlier (#3483)
Since we switched to using the scope stack instead of the decl state
stack to hold information about the containing definition in #3460 , we
can now pop the decl state at the end of the declaration instead of the
end of the body of the definition.
2023-12-08 23:01:34 +00:00
josh11b 3b0923c81d Add interface support to check (#3474)
Largely copied from the `class` code
2023-12-08 17:13:49 +00:00
Richard Smith 18d7ba9542 Factor out common pattern of trying to complete a type then falling back to an error type if that fails. (#3454)
As requested in [review of
#3450](https://github.com/carbon-language/carbon-lang/pull/3450#discussion_r1414220143).
2023-12-07 01:53:30 +00:00
josh11b e9fc07feee Abbreviate "representation" -> "repr" (#3464)
Specifically using these abbreviations:
* InitRepr: "initializing representation"
* ObjectRepr: "object representation"
* ValueRepr: "value representation"

As discussed in [#toolchain
discord](https://discord.com/channels/655572317891461132/655578254970716160/1182086098470572143)
and now documented in the [list of
abbreviations](https://docs.google.com/document/d/1RRYMm42osyqhI2LyjrjockYCutQ5dOf8Abu50kTrkX0/edit?resourcekey=0-kHyqOESbOHmzZphUbtLrTw#heading=h.pph7i5m5un7q).
2023-12-06 23:11:47 +00:00
josh11b f4677eea8d Use the scope stack instead of the decl state stack for context (#3460) 2023-12-06 17:59:22 +00:00
josh11bandJon Ross-Perkins fada410559 Support declaration modifier keywords (#3412)
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-12-05 22:45:57 +00:00
Richard Smith 22dff46ed2 Remove support for disambiguating a stringified type as being a type. (#3456)
Most of the calls to `StringifyType` already passed `true` for
`in_type_context`. Checking the rest, I found that every one of them was
already sufficiently clear that they were printing a type, or could be
made so with a very small change to the diagnostic text.
2023-12-05 17:34:04 +00:00
Richard Smith 332a368cee Rename Parse::Node -> Parse::NodeId. (#3432)
As discussed [on
discord](https://discord.com/channels/655572317891461132/655578254970716160/1178878128714678282)
and today's toolchain discussion.
2023-11-29 18:53:12 +00:00
Jon Ross-PerkinsandChandler Carruth 0c0998d7cd Error when passing StringRef to CARBON_DIAGNOSTIC. (#3431)
This gets to a lifetime subtlety, particularly with things like the
sorting diagnostic consumer that delay output. In order to reduce the
chance of accidental references, disallow StringRef in the diagnostics.

For example:

```
./toolchain/diagnostics/diagnostic_emitter.h:162:5: error: static_assert failed due to requirement '!std::is_same_v<llvm::StringRef, llvm::StringRef>' "Use std::string or llvm::StringLiteral for diagnostic lifetimes."
    static_assert(
    ^
toolchain/check/convert.cpp:477:11: note: in instantiation of member function 'Carbon::Internal::DiagnosticBase<std::string, std::string, llvm::StringRef>::DiagnosticBase' requested here
          CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
          ^
./toolchain/diagnostics/diagnostic_emitter.h:47:7: note: expanded from macro 'CARBON_DIAGNOSTIC'
      ::Carbon::Internal::DiagnosticBase<__VA_ARGS__>(        \
      ^
```

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-11-29 17:04:11 +00:00
josh11bandJon Ross-Perkins c53b248800 Abbreviate "parameter" -> "param" (#3392)
Part of switching to the [abbreviations we've decided to
use](https://docs.google.com/document/d/1RRYMm42osyqhI2LyjrjockYCutQ5dOf8Abu50kTrkX0/edit?resourcekey=0-kHyqOESbOHmzZphUbtLrTw#heading=h.pph7i5m5un7q).

I will rename files in a follow-up PR.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-11-13 19:06:54 +00:00
josh11b 522dcc44c5 Finish "declaration" -> "decl" (#3391)
Some new uses of "declaration" introduced in #3374 were missed in #3382
since #3374 was still in flight.
2023-11-13 16:01:40 +00:00
Richard Smith afd6d85610 Support for returned var and return var. (#3374)
Implement toolchain support for `returned var` and `return var`.

- Modeled `returned` in the parse tree as a `ReturnedSpecifier`
appearing after the `VariableIntroducer`.
- Modeled `return var` in the parse tree as a `ReturnVarSpecifier`
appearing after the `ReturnStatementStart`.
- Factored out the implementation of `return` statement and `returned
var` handling in check into a new `return.{h,cpp}`. The parse nodes
themselves are still handled in `handle_*.cpp`. This allows easy code
reuse between `return` and `returned var`.
2023-11-10 19:52:30 +00:00
josh11b 5020fdb3be Use abbreviation "decl" instead of "declaration" (#3382)
Part of switching to the [abbreviations we've decided to
use](https://docs.google.com/document/d/1RRYMm42osyqhI2LyjrjockYCutQ5dOf8Abu50kTrkX0/edit?resourcekey=0-kHyqOESbOHmzZphUbtLrTw#heading=h.pph7i5m5un7q).

I will rename files in a follow-up PR.
2023-11-10 10:43:25 +00:00
josh11b 11ca083855 Use abbreviation "expr" instead of "expression" (#3375)
Part of switching to the [abbreviations we've decided to
use](https://docs.google.com/document/d/1RRYMm42osyqhI2LyjrjockYCutQ5dOf8Abu50kTrkX0/edit?resourcekey=0-kHyqOESbOHmzZphUbtLrTw#heading=h.pph7i5m5un7q).

I will rename files in a follow-up PR.
2023-11-10 01:32:32 +00:00
Richard Smith 71aa4a45be Distinguish between name IDs and string IDs in the type system. (#3341)
Add a `NameId` that is effectively just a wrapper around a `StringId`,
with
some additional predefined values for names that don't correspond to
strings, such as the name of `self` or the function's return slot.
2023-11-09 16:51:36 +00:00
Richard Smith 3bee8932a9 Rework name lookup to handle non-lexical scoping. (#3354)
When declaring a name such as `fn Ns.Class.F() { ... }`, enter the
scopes of `Ns` and `Ns.Class` as we form the name, and remain in those
non-lexical scopes until the end of the declaration.

When performing an unqualified lookup, look in any enclosing non-lexical
scopes in addition to looking into the lexical name table.

We now track a scope index with each lookup result in the lexical name
lookup table. This is used to determine whether a lexical or non-lexcial
result is the innermost result and whether a declared name is in the
same scope as some previous introduction of that name or in a nested
scope. For now, this could just be the index into the scope_stack, but
the intent is to also use this to detect names being declared after they
are first looked up, which requires the indexes to outlive their scopes,
so we use a persistent numbering of all scopes instead. The persistent
numbering also permits more invariant checking.
2023-11-06 19:48:41 +00:00
Jon Ross-Perkins 3401eed8d8 Split IdentifierId and StringLiteralId from StringId (#3352)
Following up on discussion yesterday regarding this split.

Note, I'm expecting #3341 to do IdentifierId -> NameId in SemIR. It
might be worth adding NameId creation directly to StringStore if you're
content with this setup though.
2023-11-02 18:44:32 +00:00
josh11bandChandler Carruth 7edfd8e02a Rename SemIR::Node to SemIR::Inst (#3355)
And generally replace "node" by "inst" in the code and "instruction" in
comments.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-11-02 17:58:30 +00:00
Richard Smith 04ae5a0531 Support for functions with a self parameter. (#3338)
So far, such functions can only be defined; calls are not supported yet.
2023-10-26 21:01:46 +00:00
Richard Smith 7f2f4bec4f Add a Field node for fields in a class. (#3332)
This replaces the use of `VarStorage` in this case.

Add an `UnboundFieldType` type as the type of a field, in cases where
it's referenced without an accompanying object.

Add a `BindName` node to describe the name binding performed for both
variables and fields so that we can handle them more uniformly.
2023-10-25 18:49:36 +00:00
Jon Ross-Perkins e6634d240f Make SemIR::File access more terse. (#3331)
1. In general, `semantics_ir` -> `sem_ir`, to match the directory name.
2. For the list of `ValueStore`-related accessors on `SemIR::File`, add
them to `check`'s `Context` object, shortening access.
2023-10-24 21:05:46 +00:00
Jon Ross-Perkins 1d6298290f Add more value store types to File. (#3317)
Finishing what #3316 started, add more bespoke ValueStore-like
structures to File. With this, the things which previously had somewhat
boilerplate Add/Get functions are now all on side classes, giving a
uniform style of API for calling.

Note, I was on the fence about making things public on ValueStore. If
it's preferred that I make some things there protected I certainly can,
there's just a trade-off that may mean more distinct child/wrapper
types.
2023-10-24 18:23:40 +00:00
Jon Ross-Perkins 7e9d644e1f Switch File functions, classes, and types to ValueStores (#3316)
Building on #3313, start using ValueStore on File. Functions and classes
are straightforward. Types here I present as a borderline case where
maybe we want a more bespoke API, but maybe this is okay? Most other
things probably need a slightly different API, which although I might do
that for a consistent interface, felt more out-of-scope for this change.
2023-10-20 22:40:18 +00:00
Richard Smith a46e7dd967 Remove most of the metaprogramming in node.h in favor of listing all the members in the typed node structs. (#3310)
Split `node.h` into separate files for ID types (`id.h`) and for typed
nodes (`typed_nodes.h`). The per-node-kind data is now specified as part
of declaring the typed nodes, and is removed from the node kinds
x-macros, which now simply enumerate the node kinds.
2023-10-20 20:26:10 +00:00
Jon Ross-Perkins 1b55ad86dd Extend SharedValueStores to SemIR (#3313)
Building on #3311, change SemIR to use the SharedValueStore. Since this
removes hermeticity, raw output no longer prints ints, reals, and
strings. TokenizedBuffer accessors are modified to return IDs because
values are often passed through in semantics without needing to read
them.

I would've put SharedValueStores on Context, except for the
GetArrayBoundValue convenience method. I felt awkward removing that, so
it's on File, at least for now. That's then used by the formatter and
Lower too. The flipside of this is that TokenizedBuffer has a
SharedValueStores only for printing, so maybe that's similar enough to
what File is doing.

This doesn't start shifting other SemIR members to ValueStore, but that
seems like a next step.
2023-10-20 17:53:00 +00:00
Jon Ross-PerkinsandRichard Smith d13f76e001 Add value store to be shared across compile stages. (#3311)
This updates lexing to use the data. I'll do checking separately, just
to split changes.

Note the ValueStore structure is also set up such that SemIR::File can
use it for other fields.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-10-20 15:00:53 +00:00
Richard SmithandJon Ross-Perkins b01dfb3f93 Support for class definitions with static member functions. (#3305)
This includes being able to define a class that was previously
forward-declared, and being able to define a member function out-of-line
that was previously declared inside a class.

No support for fields or methods yet, and a class definition doesn't yet
cause the class to be treated as a complete type.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-10-18 19:49:45 +00:00
Richard Smith 69353ed271 Basic support for incomplete types. (#3302)
Incomplete types may be nested within other types; for example, a tuple
type might have an incomplete type as an element. Handle such cases by
walking through nested incomplete types when completing a type. This is
done non-recursively in case a very complex type is formed.

Types are generally no longer completed at the point where they're
formed. Instead, we attempt to complete a type when it is used in a
context that requires a complete type, and diagnose if the type cannot
be completed at that point. This will be necessary for classes, which
can become complete after their first use, and helps tease out bugs
where a type completeness check is missing.
2023-10-17 19:30:51 +00:00
josh11bandRichard Smith 8d0831f431 Made function and namespace nodes typed to remove a crash (#3285)
Bug found by fuzzing. Problem was untyped SemIR nodes had an invalid
type id, which was retrieved by `HandlePrefixOperator` and then passed
to `context.GetUnqualifiedType`, ultimately performing an invalid access
in `semantics_ir_->GetNode`.

We prefer to make a placeholder type for functions and namespaces to
remove the need for checking for the untyped case everywhere. Eventually
functions will have their own types, but this approach will be needed
for namespaces (and perhaps other non-first-class entities like unbound
methods and interface members) long term.

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-10-12 21:14:16 +00:00
Richard Smith c7a9e29a89 Add typed nodes to SemIR. (#3280)
Replace `SemIR::Node::GetAsFoo` and `SemIR::Node::Foo::Make` with
`SemIR::Foo` class that represents a particular kind of node, with named
fields.

Rename `SemIR::IntegerLiteral` and `SemIR::RealLiteral` to
`IntegerValue` / `RealValue` to better reflect their purpose and avoid a
name collision with the corresponding `SemIR` node kinds.

Remove `NodeKind::Invalid` and the `SemIR::Node` default constructor
entirely, as they were not used for anything.
2023-10-11 05:39:59 +00:00
Richard Smith bfa5463e5b Add signature enforcement for Main.Run and give it the symbol name main. (#3266)
For #2550.
2023-10-05 18:24:17 +00:00