Move deallocation logic to `StepCleanUp` to have all necessary cleanup actions in the same place. Currently this means `DestroyAction` and `heap_.Deallocate`.
The comment on FunctionParameterFinish is actually correct (`1. FunctionParameter`), just a typo in the implementation. It specifically failed parsing at the comma after the 2nd param, regardless of whether there were more params.
Fix variables not being properly cleaned up if declared before an unformed variable.
### Details
Currently the following example / test
```
package ExplorerTest api;
class A {
var i: i32;
destructor[self: Self] {
Print("Destructor A {0}", self.i);
}
}
fn Main() -> i32 {
var a0: A;
var a1: A = {.i = 1};
var a2: A;
var a3: A = {.i = 3};
return 0;
}
```
prints
```
Destructor A 3
```
instead of
```
Destructor A 3
Destructor A 1
```
This PR fixes the issue in the `CleanUp` logic.
Add support for user-defined assignment, as well as compound assignment and increment, following the design direction in pending proposal #2511.
Some of this isn't fully testable yet: because explorer doesn't properly support `impl` specialization, the blanket `impl`s in the prelude prevent types from customizing assignment.
Naming this ToString within the Carbon namespace encourages incidental overloading of the function, and that doesn't seem to be intentional; this feels questionable [under overloading style](https://google.github.io/styleguide/cppguide.html#Function_Overloading). OperatorToString seems helpful in that it makes it easy to see at a glance where it's being used.
Allow explicit conversion from a tuple of `T1`, `T2`, ... to a tuple of `U1`, `U2`, ... if each element has an explicit conversion.
Also add a comment to existing `ImplicitAs` impl for tuples explaining its purpose.
Add a check to prevent creating a class from a struct with a missing parent.
This is already type-checked for carbon / user code, but not when using `Convert` manually.
Although the implementation is similar in size, I think the consistency benefits are helpful. registry.def -> kind.def is also consistent with other implementations.
Also switching int32_t -> uint16_t because I think we it might be enough space (?). We use uint8_t elsewhere, but that's certainly going to be too small. Sticking with int32_t felt inconsistent.
The parser and lexer already produce YAML, so this is fundamentally a consistency issue. I've been thinking about this, and was looking again because I'm working on adding callables, and figured I'd just fix it now.
Add a blanket `ImplicitAs` implementation to perform the conversions that explorer can perform as built-in conversions. This allows those conversions to be detected by constraints and to be used as part of other user-defined conversions. For now, a single monolithic conversion is exposed. I intend to split this up into multiple smaller conversion kinds for each kind of conversion in a follow-up change.
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Fundamentally this `.Print()` is wrong for debug output at present because `.fixed_spelling()` can be empty. It's also inconsistent with other enums to use it. We frequently print tokens for debugging, and it's easy to forget to specify `.name()` there.
Diagnostics use formatv, so we can provide a format_provider and address it in one spot that way. It also makes it harder to just forget to do the right thing.
Add basic support for `match_first` declarations to explorer, as described in https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/generics/details.md#prioritization-rule. The concrete syntax here is not yet approved, so `match_first` is renamed to `__match_first` for now, but the semantics are necessary to implement other approved features in explorer so we're intentionally getting a little ahead of the design here.
Improves the error produced when 'Main' is declared with parameters. Resolves a TODO in the typechecker. Explorer only.
PR also adds a test for this error message.
Currently, only the action class uses the noun case (`Cleanup`), while the kind enum and functions are spelled `CleanUpAction`. Other actions use consistent casing between class and enum names. This change makes the name consistent, and unsurprising for developers. Mirrors `DestroyAction` (verb).
Currently, there's a mix of accessing node_stack_ both directly and indirectly, and there are already several Push/Pop methods to help wrap the behavior. However, there's also direct access because of shifting over time, as well as variations in _how_ the stack is used.
This migrates to a separate class in order to make a more specific contract for the API. It cleans up existing uses and adds APIs where needed.
This somewhat abuses control-flow macro handling in `clang-format` to get the behavior we want. Fortunately, I don't think we're ever likely to want this for its intended purpose so it seems harmless to co-opt it like this. If we really wanted, we can narrow it to `if`-macros, but I picked the simpler option to start.
FWIW, I tried all the other macro formatting special cases to see if one would work but it didn't. Might be worth filing a feature request to get a `TypeDefinitionMacros` setting to compliment `TypenameMacros` and format like this does, but it seems (very) low priority.
Also make minor updates to the skeletal design in
docs/design/name_lookup.md following #2113, as there are no longer any prelude names that are made available to unqualified name lookup by default.
Add `type` to the keyword list in
docs/design/lexical_conventions/words.md, following #2360.
The goal here is to (significantly) reduce the boilerplate needed when defining classes that wrap enums, especially those managed with the `.def`-file style X-macros that are common in the toolchain.
This should also provide both better and more consistent functionality to those classes once ported over to it.
Initially, only `ParserState`, `SemanticsNodeKind`, and `SemanticsBuiltinKind` are ported as these were also the three that JonMeow ported in his original pull/2453 "option 5". This is heavily based on that version of the code.
Goals I was considering that influenced the design:
- Keep the individual enum-wrapping classes as simple and easy to read as possible. Especially important is keeping the `.def` files that are often filled with really important documentation clean and easy to maintain over time.
- Don't rely on computed `#include`s as that is an especially dark corner of the preprocessor and breaks some build systems.
- Have a really good API of the enum-wrapping class, including nice constant names for the values, easy printing, and even easy debugger-callable methods to get the name (as opposed to the integer value).
- Keep the API that users interact with in the base class as clean and easy to read as possible.
- Reduce the boiler plate for each instance of these as much as possible.
- Avoid excessive inline generated code or constants that would result in steady growth in object file sizes and linker effort doing deduplication.
These goals aren't always compatible, so we end up needing to pick a compromise between them when in tension. I think this version is a pretty good compromise.
The original version I started with already pull most of the API into a CRTP-style base class. This version pulls *all* of the common API. This is the main tool for getting consistency and avoiding duplication. However, connecting this base class to the individual enum wrappers is still difficult. Some specific changes here that try to do as much as possible there:
- Use a slightly fancier macro pattern to reduce the boilerplate of defining the raw `enum class` prior to the wrapper class.
- Use a macro to simplify naming the base class.
- Move the name table to a `.cpp` file to avoid every inclusion generating a complete copy of the strings (that the linker has to deduplicate). This is done with some care to sharply reduce the boilerplate needed in that `.cpp` file.
- Sink the name _API_ fully into the CRTP base class. This requires some significant complexity in the implementation, but all of that is hidden behind a single implementation detail macro, and the API itself is simple and readable. This also makes it much more reasonable to test the entire system a single time next to the base class.
This version also moves from constant factory functions to normal constants. This requires two batches -- first a declaration, and then a definition -- but the API result is significantly better and similar to the original option, the macro structure reduces the cost of these. Unfortunately that makes the adoption a bit noisy, but I think its worth the churn.
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Without this, some compile setups can get a missing symbol for llvm::raw_ostream; this is relying on ostream.h through other code paths at present, so should be explicit about it.
Features:
* Add basic support for `impl` virtual methods (override virtual method)
* Error on invalid declaration for `impl` and `virtual`, covering simple use cases
* Add `abstract` fn parser-only support
Changes:
* Modify parser to handle new function specifiers, resolve conflicts
* Group `virtual_override` and `FN`, and group `impl_kind` and `IMPL` to avoid ambiguities with around `impl` token parsing
* Add new `VirtualOverride` enum for function declarations, and matching `virt_override() -> VirtualOverride` getter
* Update function declaration logic
Depends on #2462
Features:
* Add `virtual` virtual override keyword for functions
* Support `virtual` class methods using dynamic dispatch
Changes:
* Add `vtable` in `NominalClassType`,
* Add `NominalClassValue**` in class values pointing to descendant-most class
* Resolve virtual methods during member lookup
Limitations:
* Does not include yet `impl`, `abstract` virtual override keywords, or the complete logic for virtual function declaration
Depends on #2460
Relates to #1881
Relates to #2493
Protobufs code hits a warning with the latest system headers on macOS.
I figured this may have been fixed so I updated protobufs and Bazel to
the latest releases. This generally cleaned things up.
However, it actually added *more* warnings. This clearly isn't a really
well tested path. In fact, we already have a disabled warning that we'd
like for Carbon code because LLVM isn't clean for that warning.
So I've switched our warning strategy to a more durable approach of
suppressing all warnings for external repository headers and source
files. This lets us re-enable the missing warning and should fix the
protobuf warning that started me down this twisty path.
Sadly, we *have* to update to Bazel 6 in order to have the necessary
flag to use this approach to suppressing warnings, so I couldn't do this
as two PRs cleanly. =/ That's why I've bundled both the Bazel (and
protobuf) updates with the warning strategy change.
Last but not least, I've fixed several unused parameters in Carbon's
code that our warnings now catch.
Followup for #2490
The switch of DiagnosticMessage to have DiagnosticMessage means we don't need to use unique_ptr. This means that copy constructors are implicit again and don't need to be avoided, but per discussion still keeping with moves. Comments on HandleDiagnostic try to capture the use of moves there.
I'm keeping DiagnosticLevel at the top-level, and adding some checking that notes are actually Notes.
Also, adding MakeMessage to unify some of the logic (this has particularly been bugging me around format_fn, and I ran into it here because of the Diagnostic -> DiagnosticMessage change). The addition of NoTypeDeduction is intended to avoid some duplicative comments that'd been piling up.
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
The problem I'm trying to solve is: `var x: i32 = x;`. This change makes it so that name lookup fails, by removing `x` from name lookup between the `=` and `;`.
`var x: i32` still adds to name lookup to handle future situations like `var (x: i32, x: i32);` which is still a redefinition of `x`; if we don't add `x` to name lookup, it gets harder to catch that example.
The VariableDeclaration/VariableInitializer refactor in ParseTree supports this by given a bracketing-like structure for semantics to cue that it's entering an initialization expression. With this, VariableInitializer can remove the name lookup and queue it to be restored. VariableDeclaration doesn't need to change too much since it's still bracketed by VariableIntroducer, and so we just traverse slightly differently.
Note this also incidentally changes a little about NameReference, that it's returning the storage consistently instead of the name. You can see this e.g. in global_lookup.carbon, `Assign(node8, node4): node2;` using node4 (VarStorage) instead of Node5 (BindName). Really either _could_ work, since from a BindName we can get to the VarStorage, and that may be reason to switch later if we find it preferable to have the BindName for whatever reason.
But the *actual* value in NameLookup is a BindName so that errors can associate with the _name_ instead of the "storage" parse node, which is currently the `:`. This is mainly for fail_duplicate_decl.carbon, which has a "Previous definition" note that points at the storage's parse node.
This is currently used once for PreviousDefinition in semantics.
This PR doesn't just add a builder, it also adds support to the emitter itself to collect notes attached to a diagnostic, and to the consumers and emitters to print all of them.
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
In theory we're doing a central registry so that we can ensure there's at least one test for each. This isn't doing that, but I'm trying to validate that the central registry isn't leading to duplicates or abandoned checks (and catching a couple of each).
While we have a generic 'long term' label, it seems redundant for some
issues that are already labeled with something that clearly is
open-ended and not something we should expect to have a bounded
timeline. For example, we want to actively curate a backlog of design
ideas and good first issues for folks to browse and pick up, so we
shouldn't be marking them as inactive after any fixed time frame.
Define a "type" to be a value of type `type`. Contexts expecting a type perform an implicit conversion to `type`. Values like `()` and `(i32, i32)` and `{}` are no longer types, but instead implicitly convert to `type`. Values of interface or constraint type (now called "facets") are similarly not formally types but implicitly convert to `type`.
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
Co-authored-by: josh11b <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Addresses comments from this discussion: https://github.com/carbon-language/carbon-lang/pull/2460#discussion_r1046444433
Features:
* Move subtyping logic from Interpreter to TypeChecker, exposing subtyping as a series of access to `.base`.
* Excludes function parameter conversion, which is still done in ::Convert due to parameters conversion being handled differently.
Changes:
* Add new `class BaseAccessExpression : public MemberAccessExpression`, allowing rewrites
* Handle `BaseAccessExpression` expression type in Interpreter
* Move subtyping logic to `TypeChecker::ImplicitlyConvert`
The doc is more up-to-date than the readme right now, and I'm not ready to migrate it back for the moment, but this should at least make it clear what the status is.
This switches to single list storage of SemanticsNode. The driving motivation behind this is to simplify cross-references within a given IR. Types of nodes will frequently refer to other blocks. This causes a significant increase in the number of cross-references, which can become difficult to manage (and reason about). By reducing to a single list of nodes, cross-references are only needed when crossing IR boundaries.
Because cross-references now only have 2 things to track (IR and index), they can be a regular SemanticsNode and don't need further indirection. This wasn't motivating, but feels like it reinforces the simplification.
Note this isn't being used to deduplicate nodes, at least right now. That could lead to difficult-to-update situations, but also most nodes are associated with the underlying ParseTree::Node in order to track sources for diagnostics; as a consequence, nodes representing equal text in different source locations wouldn't be the same node. There may be future opportunities here, discussed with @zygoloid, but no action is taken at present.
We may eventually want to switch the storage of NodeBlocks to have `[start, end)` ranges instead of individual numbers, but I'm leaving that alone for now.
As an aside, I noticed I was accidentally overloading the copy constructor on SemanticsIR. I've added some disambiguation on that, but am not deleting the copy constructor per style advice (even though the type should never be copied due to storage size).
codespell tries to change `CrossReference -> cross-reference` so disabling it there.