43 Commits
Author SHA1 Message Date
1d4e9ee1ea ranged-based for for user-defined types (#1885)
The goal of this proposal is to provide a way for user-defined types to
support range-based iteration with `for`.
The current proposed solution exposes 3 interfaces that can be
implemented by user types to enable support for
ranged-for loops.

Co-authored-by: josh11b <josh11b@users.noreply.github.com>

---------

Co-authored-by: josh11b <josh11b@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-08-25 23:25:19 +00:00
Adrien LeravatandJon Ross-Perkins 9edfa9cad3 Explorer: Avoid unecessary copies when a value binding is created from a value expression (#3000)
#### Functional changes

* Avoid unnecessary copies when a value binding is created from a value
expression in call parameters
* Ensure the result of the value expression bound is destroyed
* Provide storage to initializing expressions used in call parameters

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-07-24 14:39:13 +00:00
Adrien Leravat d02366f881 Explorer: Prevent copies when initializing a let binding from reference expression (#2946)
Prevent copies when initializing value expression from reference
expression. This is based on
https://github.com/carbon-language/carbon-lang/pull/2006, which
introduces expression categories, and how it is possible to convert
to/from those different categories. Continuation of
https://github.com/carbon-language/carbon-lang/pull/2907

## Functional changes

* Initializing a value expression from a reference expression takes its
value without a copy
* Reading from the value expression causes an error if the value changed
from the time it was initialized
* In this situation, prevents a copy both for variable definitions, and
call parameter bindings

## Main implementation changes

* Add new `ExpressionCategoryAction`, which evaluates an expression and
returns an `ExpressionValue` containing its category and address (if
any), in addition to the resulting `Value*`
* `ExpressionAction`s now invokes `ExpressionCategoryAction` and unwraps
the returned `ExpressionValue`
* `RuntimeScope::BindAndPin` method, and corresponding when attempting
to read a `value_node`.

## Next work

* Avoid unnecessary copies from value expression to value expression,
after ensuring that even value expression temporaries are registered for
destruction (https://github.com/Pixep/carbon-lang/pull/9)
2023-07-17 23:26:01 +00:00
Adrien Leravatandjonmeow a914932b1c doc: update PR workflow for GH merge queues (#2965)
Co-authored-by: jonmeow <jperkins@google.com>
2023-07-06 18:33:58 +00:00
Adrien LeravatandChandler Carruth cb14ce56a8 GitHub merge queue test commit (#2959)
Test change for the merge queue.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-06-29 00:38:59 +00:00
Adrien Leravat f091a45c19 Infra: run pre-commit on merge groups (#2960) 2023-06-28 17:21:54 -07:00
Adrien Leravat 92d73985df CI: tentative enabling of tests workflow for merge group (#2933) 2023-06-24 12:08:50 -07:00
Adrien Leravat 19c74ead49 Explorer: Add initial initializing expression support for variable declaration (#2907)
Add partial support for initializing expressions for variable declaration. This is based on https://github.com/carbon-language/carbon-lang/pull/2006, which introduces expression categories, and how it is possible to convert to/from those different categories.

## Functional changes

* Initializing expressions initialize directly the provided storage when used to initialize a variable.
   * Allows initializing expressions to avoid a copy when using `[var|let] name: type = call_expression(...)` by initializing `name` in-place.
   * Support `returned var: ...` and `return <expr>`
   * Support nested initializing expressions

## Main implementation changes

* Updated PatternMatch logic to handle expression categories
* Updated `VariableDefinition` interpreter statement to allocate and pass a location to initializing expressions
    * Update statement actions to allow passing an allocation, used by return expr or returned var
* Modified the RuntimeScope API to be one step closer to the memory model we want to have
    * Remove `GetAllocationId` and older `Bind` which don't apply
* New set of tests to highlight those different situations
    * Added a new intrinsic to print the allocation stack (and make sure we behave correctly, beyond visible side effects)

## Next work

* Dedicated `Action` to retrieve expression category information in the interpreter (https://github.com/carbon-language/carbon-lang/pull/2927)
* Avoid copies when initializing value expression from reference expression and prevent mutations for the duration of the "pinning" (https://github.com/carbon-language/carbon-lang/pull/2927)
* Avoid unnecessary copies from value expression to value expression, after ensuring that even value expression temporaries are registered for destruction.
* Avoid unnecessary copies when binding function arguments
2023-06-23 21:42:00 -07:00
Adrien Leravat 1b50bd156c README.md: Add links to C++Now 2023 talks slides (#2925) 2023-06-20 10:33:51 -07:00
Adrien Leravat da647f579a Explorer: readme: clarify fuzzer debugging (#2905)
Slightly clarify the debugging process in case of fuzzer crash with Explorer.
2023-06-15 09:18:16 -07:00
Adrien Leravat b843096bcd explorer/README.md: update test documentation (#2872)
Update explorer test documentation to match the new tools used.
2023-06-07 13:55:07 -07:00
Adrien Leravat 8cb3f00f1b Explorer: fix assignment error typo (#2746)
Fix typo in error message from expression categories renaming
2023-04-06 16:48:51 -07:00
Adrien Leravat 65578bd8db Documentation: fix typo (#2742) 2023-04-05 16:17:03 -07:00
Adrien Leravat d0645c6a85 Explorer: rename value categories to expression categories (#2744)
Rename value categories to expression categories based on [Discord discussion](https://discord.com/channels/655572317891461132/753021843459538996/1092924035517665332) regarding naming and behavior.

>* let expression -> value expression
>* var expression -> reference expression
>* located expression -> initializing expression
>So:
>- "value expressions" produce values (with no associated location). "reference expressions" produce a location of an existing value. "initializing expressions" take a location and initialize it.
>- A let binding is initialized by a value expression, because lets represent values (with category conversions performed as needed, but if a conversion is performed from a different category of expression, the value of the object is pinned for the lifetime of the let).
>- A var binding is initialized by an initializing expression, without performing a copy (with category conversions performed as needed, calling a copy constructor if the initializer is a different expression category).
>- The & operator requires a reference expression, and it's an error to give it other kinds.
>- The left-hand side of . requires a value expression when calling a function with a non-addr receiver, and requires a reference expression when calling a function with an addr receiver (it's an error to give it a value expression, and for an initializing expression, a temporary is materialized).

Changes
* Rename "value category" to "expression category"
* Rename Var and Let value categories to Value, Reference, and Initializing expression
* Rename `lvalue` to `location` (most of the time)
2023-04-05 16:16:10 -07:00
Adrien Leravat 2c59dbc5fe doc: replace references to #821 by #2006 (#2724)
Replaces references to PR #821 (closed) by #2006 (draft) which tracks the same feature definition.
2023-03-30 09:43:46 -07:00
Adrien Leravat df289efac4 Explorer: Add virtual destructor support (#2695)
### Features

* Add virtual `destructor`s support (Closes #2521)
* Check virtual override for virtual destructors
* Error if attempting to `Delete` a class that does not have virtual destructors from a base class pointer 

### Implementation

* Update parser to support virtual override introducers for destructors
* Check virtual override for class destructor and add to class vtable if necessary
* Add corresponding tests

### Notes

Contrary to initial implementation, this implementation leverages the `Address` structure and implements a new `Address::DowncastedAddress()` method to get address from child most class from a base class address. This avoids the need to use `GetAllocationId` and its issues when it comes to having multiple values for an `AllocationId`.

### Next work

Following this PR, we need to:

* Check when using `Delete` that the class was allocated with `New` (WIP)
* Drop the old `GetAllocationId(Value*)` in favor of a better system (WIP)
2023-03-22 09:58:30 -07:00
Adrien LeravatandChandler Carruth 49726cd89e doc: add / refresh information regarding contributions (#2611)
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-02-27 17:38:52 -08:00
Adrien Leravat 09891d4141 Explorer: drop outdated TODO comment. (#2639)
Drop TODO as discussed in https://discord.com/channels/655572317891461132/763516049710120960/1079844131737714718
2023-02-27 13:30:04 -08:00
Adrien Leravat 266fa401e6 Explorer: assert Optional not empty on Get() (#2587)
Prevent from unwrapping an empty Optional
2023-02-09 22:39:43 -08:00
Adrien Leravat 245e4d1ea6 Explorer: drop unused PrintScopes method (#2588) 2023-02-08 09:31:13 -08:00
Adrien Leravat 65078ea943 Explorer: make use of != in Carbon lit (#2586)
Swap `not (a == b)` for `a != b` in test now that we have it.
2023-02-07 10:10:45 -08:00
Adrien Leravat 7222f349d6 Explorer: move deallocation to StepCleanUp (#2547)
Move deallocation logic to `StepCleanUp` to have all necessary cleanup actions in the same place. Currently this means `DestroyAction` and `heap_.Deallocate`.
2023-01-24 12:24:05 -08:00
Adrien Leravat b4e3a3e6cc Explorer: fix class destructor not called with heap.Delete (#2546)
This change ensures that DestroyAction is executed for the value being deallocated when calling heap.Delete.

Relates to #2521
2023-01-24 11:34:47 -05:00
Adrien Leravat ec683d1ab2 Explorer: fix variables not cleaned up if declared before unformed (#2544)
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.
2023-01-23 08:59:14 -08:00
Adrien Leravat 35989c5283 Explorer: prevent creating invalid class with missing parent (#2536)
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.
2023-01-19 08:56:57 -08:00
Adrien Leravat 7936bfa019 Explorer: fix case for CleanUpAction enum kind (#2520)
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).
2023-01-10 19:22:50 -08:00
Adrien Leravat d7b5e537d6 Explorer: drop unused NominalClassType constructor (#2513)
This constructor was previously used for instantiated vs non-instantiated generics, but is not necessary anymore.
2023-01-05 09:18:19 -08:00
Adrien Leravat 798a40c886 Basic support for impl virtual override keyword (#2493)
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
2023-01-04 11:09:23 -08:00
Adrien Leravat 8301258ef8 Explorer: support virtual class methods (#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
2023-01-02 12:37:49 -08:00
Adrien Leravat 026c4b9dc3 Explorer: move subtyping logic to TypeChecker (#2484)
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`
2022-12-21 19:01:02 -08:00
Adrien Leravat 34ec3ce74b Explorer: add missing Nonnull<> (#2486)
Trivial change adding a missing `Nonnull<>` to `RewritableMixin`.
2022-12-21 12:48:27 -08:00
9299e51511 Explorer: Support class subtyping (#2460)
Features:
* Adds support for [subtyping](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/classes.md#subtyping) for local variables, and function parameters

Changes:
* Update function parameter `Deduce` to handle subtyping
* Update `InstantiateType` to support `PointerType`
* Update `Convert` to support convertion from child class to a base class

Relates to #1881 

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2022-12-19 11:32:32 -08:00
Adrien Leravat e37a69a6d5 Destroy class hierarchy when destroying class with a base (#2378)
Depends on #2361, #2421

Add support for destructors of base classes.
Features:
- Call destructors from derived to base class
- Support addressing `TupleValue` using a new `Member` variant

Changes:
- Update `StepDestroy()` to recursively call destructors from derived to base class
- Add new `Member` variant and `IndexedValue` struct to be usable with `TupleValue`
2022-12-12 09:59:03 -08:00
Adrien Leravat 563768c6d3 Explorer: split Member into dedicated classes (#2421)
Features:
* Split `Member` class into 3 dedicated classes covering named, positional, and a new "base class" element

Changes:
* Rename `Member` to `Element` to better reflect the variants covered
* Add `NamedElement`, `PositionalElement`, and `BaseElement` child classes for `Element`
* Split `GetMember` into 3 function variants based on available attributes (index, name, nothing).
* Add some unit tests to provide coverage of core features

Motivation:
This changeset splits Member into (currently 2) classes, as we see the need for more Member variants (base class access needed for #2378, possibly unnamed mixins, ...), which in addition to the current ones, also have significantly different attributes. This will allow supporting more Member types in the future cleanly.

Alternatives considered:
The alternative solution, "one class for positional, named & base class access", would expose unused or unavailable attributes depending on the Member actual type (`index()` only for positional, `name()` only for named, and neither for base class access).
2022-12-09 16:09:50 -08:00
Adrien Leravat 0cb2c92c6c Explorer: support index-based fields for FieldPath and Members (#2417)
Features
* Support addressing positional members (i.e. tuple fields) using an index.
* Addresses a couple of `TODO`s relative to positional members

Changes:
* Add a new `IndexedValue` mirroring `NamedValue`
* Adds `FieldPath::index() -> int`
* Adds a `Member` variant for `IndexedValue`
2022-12-06 13:31:18 -08:00
Adrien Leravat 1d0bb85d0c Explorer: basic abstract class support (#2441)
Relates to #1881 

Features:
* Add basic support for `abstract` class
    * Allow extending an abstract class
    * Prevent direct instantiation of an abstract class
Changes:
* Check that class extensibility for `VariableDefinition` is not `Abstract`
* Add corresponding set of lit tests
2022-12-06 09:35:55 -08:00
Adrien Leravat 054537270b README.md: add a section with past talks (#2434)
Suggesting to add a section with past conference talks, to include content that has been created around carbon. This feel to me like an accessible type of content to have in the main README for those wanting to dig a bit deeper without going into /docs.

This does not show the speaker name to keep it "Carbon/community" oriented, vs naming, but there's an argument both ways I think.
2022-12-02 17:41:20 -08:00
Adrien LeravatandRichard Smith 46f4887cf7 Explorer: support .base to initialize parent class from struct (#2361)
Relates to https://github.com/carbon-language/carbon-lang/issues/1881

- Add support for `.base` field in structs for [parent class initialization](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/classes.md#constructors)
    - Disabling base class initialization without `.base`
- Support class constructors (`Create() -> Self`) for base classes
- Direct access to base class(es) attributes with `object.var` remains unaffected

Changes:
- Add `TypeChecker::FieldTypesWithBase` to help assessing if a struct with `base` fields can be converted to a class
- Add a new `base_type()` attribute+getter to `NominalClassDeclaration` to as a first step to allow resolving parametrized classes
- Add a new `base` attribute+getter to `NominalClassValue` that contains the base class `NominalClassValue`. It is currently used mainly to get and set members of a class object.
- Add `Interpreter::ConvertClassWithBase` to build `NominalClassValue` from a init struct, that contains `.base` fields with either `NominalClassValue` or `StructValue`
- Add `FindClassField` to find a field in a class or its base classes
- Remove superfluous `ClassDeclaration::base()` in favor of `ClassDeclaration::base_type()`

Limitations;
- Though some work is done in that direction, parametrized base class where time is not know at the declaration site are not supported. Namely the example below does not compile
```
base class A(T:! Type) {}
class B(T:! Type) extends A(T) {}
```
But this one is functional already
```
base class A(T:! Type) {}
class B extends A(i32) {}
```

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2022-11-29 13:14:30 -08:00
Adrien Leravat 7c19ef5be3 Explorer: Support class extension (#1946)
Support class extension with `extends`
Relates to #1881 

Add support for:
* Class extension with `extends`
* Using base class methods and members
2022-10-21 08:08:07 -07:00
Adrien Leravat 8e8e8ced60 docs: fix code sample typo (#2254)
Fix small typo in classes documentation
Added to a decicated PR to keep things orderly
2022-10-04 08:57:10 -07:00
Adrien Leravat b7ee1dfa22 docs: fix typo in generics overview.md (#2025)
PR for tiny fix to generics overview doc, as suggest here: https://github.com/carbon-language/carbon-lang/pull/1885/files#r943743464
2022-08-15 11:22:51 -07:00
Adrien Leravat 094311133d Add parsing (only) support for class prefix and 'extends' (#1880)
Provides a first implementation iteration towards class prefix and extension, along with user-friendly error regarding missing implementation for #1881 

**Explorer behavior**
For class prefix `base` and `abstract`: 
```
Class prefixes `base` and `abstract` are not supported yet
```
For extension with `extends`: 
```
Class extension with `extends` is not supported yet
```

**Motivation**
* Provides user-friendly error for these unsupported features
* First implementation increment in supporting class prefix and extension.
2022-08-03 15:24:28 -07:00
Adrien Leravat cbd4b8d82d Add explorer support for short-circuit evaluation for 'and' and 'or' (#1789)
Implements short-circuit evaluation for `and` and `or` binary
operators.

Fixes #1651
2022-07-29 13:10:40 -07:00