Commit Graph
136 Commits
Author SHA1 Message Date
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
Jon Ross-Perkins 60b45e3d30 The typed_linked_list test trace output is too slow, so stop testing it. (#2494)
Another case of flakiness from trace output performance:
https://github.com/carbon-language/carbon-lang/actions/runs/3760820974/jobs/6391950894
2022-12-23 06:44:42 -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
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
Richard Smith 0ef7fa3a1d Support p->member, rewriting it to (*p).member in the parser. (#2455)
* Support `p->member`, rewriting it to `(*p).member` in the parser.

This behavior is as described in
https://github.com/carbon-language/carbon-lang/tree/trunk/docs/design#pointer-types:

> `p->m` is syntactic sugar for `(*p).m`.
2022-12-08 13:42:36 -08:00
josh11b 9c8fd6864e Implement rename me -> self (#2444)
Implements change proposed in #1382

Replaces #1624
2022-12-06 20:17:00 -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 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
Jon Ross-Perkins f6c5298c15 Make lit tests small (#2391)
Makes explorer/testdata/assoc_const/rewrite_large_type.carbon NOAUTOUPDATE and no-trace because otherwise it takes ~130s to run. With this it's sub-second, explorer is just dumping a lot of trace output (maybe still something to fix).
2022-11-14 11:35:14 -08:00
Jon Ross-Perkins fd455ed36b Add convenience .run targets for test files. (#2384)
e.g., for `//explorer/testdata:tuple/no_ending_comma.carbon.test`, `bazel run //explorer/testdata:tuple/no_ending_comma.carbon.run`
2022-11-14 08:39:56 -08:00
Liz 25d1b62df0 explorer: Typed double linked list test (#2366)
This adds a second double linked list test carbon program, which has
the major difference, that it is not bound to a type but rather uses the
generics system to allow the type to be be specified at creation.
Of course this is heavily inspired by the first linked_list example program,
but this does show of/test a different feature set solving the same problem.
2022-11-11 14:00:19 -08:00
Richard Smith e557d4af3b Make addr me: Self* work for interface methods. (#2374)
Fixes #2223.
2022-11-07 08:11:19 -08:00
Richard Smith 9e8cacae00 Implement support for named constraints (#2359)
Basic support for named constraints as described in [the generics design](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/generics/details.md#named-constraints). Support is provided for `extends` and `impl` declarations in `constraint`, but not yet for member aliases.

The missing prelude named constraints `Add`, `Mul`, `Ordered`, etc. are also added.
2022-11-04 16:23:02 -07:00
cef93fba5e Feature call destructor for tuples and bug fixes for the destructor process (#2255)
This PR includes the following changes:
*  Added destruction process for tuples
*  Fix: In the current version only the last member of a object can be destroyed
*  Fix: In the current version, the destructor of the object is called after each method call 

I hope it is useful

Co-authored-by: m new <michael.burzan@outlook.de>
Co-authored-by: Geoff Romer <gromer@google.com>
2022-11-04 12:13:24 -07:00
Richard Smith 0219218b01 Make type contexts expect a value of type Type. (#2357)
In particular, this means that a type can implement `ImplicitAs(Type)` and have values of that type behave like types.

This implies that `()` and `{}` are no longer types. They are now values whose type is the result of converting `()` or `{}` to type `Type`, as has been discussed recently and seems to be the supported direction. This fixes various cases where these types were previously mishandled.
2022-10-28 08:20:49 -07:00
Richard Smith f46eaf49a2 Compute a fixed point of rewrite constraints. (#2350)
When resolving a constraint type, compute the fixed point of the specified rewrite constraints, as requested by @josh11b in review of #2173 and tentatively agreed as our direction. If no such fixed point exists, detect that situation and diagnose the problem.

The algorithm used here is to iteratively apply all rewrites to each rewrite constraint until either one of them refers to itself, which indicates there's a cycle in the rewrite graph, or the set of rewrites converges.

This algorithm has some pathological inputs in which the runtime can grow exponentially in the size of the input (indeed, the fully-rewritten set of rewrites can grow exponentially in the size of the input, so this is unavoidable), so an iteration limit is also provided.
2022-10-26 14:49:17 -07:00
Richard Smith 5c3f48b0fb Distinguish between the symbolic .Self value for an associated constant and the value found when referencing one. (#2348)
Within the type of an associated constant, references to `.Self` should resolve symbolically to that associated constant as a `GenericBinding` so that it can be substituted for the actual value when using its type. However, when the associated constant is referenced from elsewhere in the same interface, the value we want is a symbolic value naming the constant as a member of `Self`.
2022-10-25 12:29:51 -07:00
Richard Smith bc7bf325d6 Set the value of .Self in a where to that of the outer .Self. (#2344)
Prior to this change, declarations like `let N:! X(.Self) where .(X(.Self).Y) == 5;` have the surprising behavior of the two `.Self` expressions resolving to two different symbolic values. Fix this by forcing the inner one to have the same symbolic value as the outer one, albeit with a different type.
2022-10-25 11:59:42 -07:00
c68cced1fb Fix explorer crash - Assign different struct types (#2345)
* fix issue-1392

* run pre-commit

* run pre-commit

* Update explorer/interpreter/type_checker.cpp

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>

* change test file

* change test file

* remove size check

* Update explorer/interpreter/type_checker.cpp

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>

Co-authored-by: m new <michael.burzan@outlook.de>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2022-10-25 20:35:48 +02:00
Richard Smith adc78fbdb0 Defer resolving rewrites until we apply a constraint to a binding (#2333)
Instead of checking and resolving rewrites eagerly, defer doing so until a constraint is applied to a binding. Actual resolution of rewrites is not yet implemented, so this is mostly just refactoring, but the eventual goal is to support things like `(Constraint where .T = .U) & (Constraint where .U = V)` (however they are reached) by applying one rewrite to the other, as agreed with @josh11b in discussion of #2173.

One nice consequence is that substitution into a constraint type no longer has a failure path, so substitution is once again not able to fail.
2022-10-24 15:50:31 -07: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
Richard Smith 374bf9f853 Require convertibility to the type of the associated constant when checking a rewrite constraint. (#2321)
Per recent discussion, in `... where .A = B`, require that `B` is implicitly convertible to the type of `A` immediately, rather than treating that as part of the criteria that a type must satisfy to satisfy the resulting constraint. Extend the implementation of implicit conversion so that conversion of a type to a constraint checks that the type satisfies the constraint.

As part of implementing this, stop duplicating rewrite constraints as equality constraints. Instead, when checking that a constraint is satisfied, check both its equality constraints and its rewrite constraints. This fixes an infinite recursion that would otherwise be caused by this change, and is also a necessary prerequisite for applying rewrite constraints to equality constraints, where we would otherwise collapse the implied equality constraints to a tautological `V == V` constraint.

In passing, make ErrorBuilder support building the error message more incrementally and use that to improve diagnostics for mismatched values with equality constraints.
2022-10-20 16:18:26 -07:00
Richard Smith 561e45033e Remove TypeOf*Type for types whose type-of-type can just be Type (#2302)
We don't seem to have any need for `TypeOf*Type` types, and having them introduces the temptation to use them during type-checking, which would lead to types having different behavior when their type-of-type is `Type` versus when it's a more precise type. Remove these types for now.

If we later decide that we want each type literal to have a unique type, as we do for value literals, we can introduce a single value kind for that rather than one for each kind of type.

No changes to `TypeOfMemberName`, `TypeOfParameterizedEntityName`, and `TypeOfMixinPseudoType`, which are placeholders, not real types.
2022-10-18 14:08:40 -07:00
Jon Ross-Perkins 3578f2b214 Fix AUTOUPDATE lines in new tests (#2306) 2022-10-18 11:26:30 -07:00
Richard Smith b4418e29ec Properly check that a constraint appears after is. (#2304)
In particular, if we find the name of an interface after `is`, it should
be exapnded to a constraint, including any implied constraints such as
extended interfaces, rather than forming a constraint requiring only
that interface in isolation.
2022-10-18 09:07:58 -07:00
Richard Smith fa18cc0f9f Fix test failures caused by interaction between #2294 and #2292. (#2303) 2022-10-18 08:53:12 -07:00
Richard Smith 4b679510e7 Check equality constraints when checking whether a constraint is satisfied (#2294)
Add checking that a type only satisfies a constraint if it satisfies all of that constraint's equality and rewrite constraints.

Enforce the rule that `=` must be used in impls when specifying associated constant values rather than `==`.

Turn off the pre-#2173 single-step equality behavior. This is getting somewhat ahead of the approved design, but it's a one-line change to restore the old behavior.

Fix `CARBON_CHECK` to handle top-level `,`s in its argument, such as may happen in template argument lists, as this change introduces such a check.
2022-10-17 22:07:19 -07:00
Jon Ross-Perkins eac7c2bda4 Automate the addition of RUN and simplify RUN lines (#2292)
This was an offshoot of the discussion about how much boilerplate we could remove. lit requires RUN lines be there, everything else is optional.
2022-10-17 13:52:37 -07:00
a3329cf004 Diagnose uses of declarations that are too early. (#2288)
There are lots of ways a declaration can be used before we have the information necessary to handle that use. Issue diagnostics for these.

Interleave declaration and type-checking of global declarations so that declaring a later declaration can depend on the results of type-checking an earlier one.

Incorporates tests added in #2266.

Fixes #1394, fixes #1395, fixes #1396.

Co-authored-by: pmqtt <51272730+pmqtt@users.noreply.github.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2022-10-13 15:30:29 -07:00
Jon Ross-Perkins e111418b32 Merge and label stdout/stderr for FileCheck (#2283)
Adds a simple script to merge stdout/stderr and put on labels. This is hidden to the RUN line using lit.cfg.py.

This is my solution to addressing how errors printed by the toolchain break sorting of stdout output; just put stdout first. We could also have toggles for interleaving output or such, which might help test whether we do it properly.

This also moves some previous-distributed replacement logic into lit_autoupdate_base.py: I think having that adjacent to lit.cfg.py is probably the better choice, and it reduces duplication in toolchain scripts. It happens here because I need to change the resulting commands to include the merge.
2022-10-13 14:46:30 -07:00
Richard Smith b1c50bd6a7 Revert "Fix: Issue #1394 (#2266)" (#2285)
This change left a test broken and removed a fair amount of test coverage for unrelated features, and after further discussion it's not clear that this is the direction we want to go in.

This reverts commit 6cf2272bbe.
2022-10-13 12:15:56 -07:00
6cf2272bbe Fix: Issue #1394 (#2266)
* start correct

* Fix #1394

* remove llvm::outs()

* Fix #1394

* ---

* fix issue-1394

* fix issue-1394

* Update explorer/interpreter/interpreter.cpp

Co-authored-by: Geoff Romer <gromer@google.com>

* fix issue-1394

* remove and rename test files

* add changes from j.m

Co-authored-by: m new <michael.burzan@outlook.de>
Co-authored-by: Geoff Romer <gromer@google.com>
2022-10-13 19:44:53 +02:00
Richard Smith e74c73240c Factor out duplicated code converting type-of-types to ConstraintType. (#2282) 2022-10-13 09:11:22 -07:00
Richard Smith 7f7b9a4086 Implement support for extends and impl as declarations in interfaces (#2279) 2022-10-12 17:13:25 -07:00
Jon Ross-Perkins 55e124a667 Refactor update_checks into a more generic lit_autoupdate (#2277)
I've refactored the script in order to make it work in more contexts, which is why the delta is lost. I've actually refactored a significant amount with the intent of making the logic easier to understand, because I was also adjusting bits of it.

Some key notes:

- Removes the multi-pass update that was dealing with unfixed line numbers in explorer (I think the current script should work in one pass)
  - Fixed explorer to handle multiple line numbers on the same line (turns out we can rely on local format for line numbers).
- Using execv instead of imports because making Python imports work in a setup like this feels like it's not worth it; only a nuisance.
- Adding __init__.py to satisfy mypy, which otherwise considers the lit_autoupdate.py scripts to be issues.
- Using py because I was thinking sh would be more platform-dependent. py should port better to Windows.
- Getting rid of [[ID#]] capture groups in the semantics-ir tests because with the autoupdate it's kind of moot (also, hard to autogenerate the pairs without relying on the %### value).

Note this does mean tests switch to more of a "make a change, see which tests change" setup. I don't know that that's a _bad_ thing though -- it's pretty much how tests are being written right now, which is why I went down this rabbit hole. It's a nuisance to make a change then _manually_ have to update a bunch of code.

My intent is to use this for to convert parse-tree tests to lit, but I wanted to do this with _existing_ tests first as a proof of concept and to make sure there's agreement.
2022-10-12 15:01:38 -07:00
Richard Smith 61552a788b Bring constraints for an associated constant into scope within the interface (#2278)
This allows us to write code within an interface that assumes its associated types satisfy their constriants.
2022-10-12 13:21:00 -07:00
Richard Smith 9f534ae004 Implement support for rewrite constraints (#2276)
Implements basic support for rewrite constraints as proposed in #2173.

Support for associated constants and complex constraints in general is also made more robust: argument deduction now properly computes and substitutes witnesses, and interface declarations track a more correct description of the constraint that they introduce than the one we previously built.
2022-10-12 12:55:55 -07:00
Richard Smith 9feff92f22 Track witnesses wherever possible (#2263)
Change explorer's handling of witnesses to track them wherever possible. Associated constant support needs witnesses to be available much more pervasively.

The main changes here are:

-   `Substitute` now takes a set of bindings covering both `Value`s for `GenericBinding`s and `Witness`es for `ImplBinding`s, and substitutes both.
-   Witnesses are now tracked within `ConstraintType`s. The `.Self` type has an `ImplBinding` that self-references from parts of the constraint to other parts of the constraint can use to access the witness for the constraint.
-   The constraint type for an `impl` and for a `GenericBinding` are now stored in pre-substituted form, with references to the actual constrained type rather than symbolic references to `.Self`. This results in minor changes in diagnostic text.

Argument deduction still performs substitutions without remapping witnesses.
2022-10-11 15:20:23 -07:00
Jon Ross-Perkins b9d3d9a3df Unify lit.cfg.py approach (#2249)
On #2224 @zygoloid pointed out we needed --implicit-check-not to ensure we were correctly matching output. This is the standard way we're writing explorer tests, so I was looking at unifying our lit approaches.

This is one take on it, making more use of substitutions to bring various testing into alignment, as well as symlinks to avoid config skew (maybe I'll eventually figure out a better solution than symlinks).

Makes a couple small fixes in explorer to remove end-of-line whitespace on output.
2022-10-06 12:25:23 -07:00
Richard Smith 8f0f69b65f Remove RuntimeError / CompilationError. (#2258)
Instead, work out the prefix for an error based on whether it was produced during parsing, semantic analysis, or when running the program.
2022-10-04 15:39:04 -07:00
Richard Smith e172c0a581 Add test for member access into symbolic witness. (#2256)
Add missing test requested by @jonmeow in review of #2250.
2022-10-04 12:51:02 -07:00
pmqtt cfa295c0af Feature destructor (#2116) 2022-09-26 10:11:05 -07:00
micttyl c63ae9b05d Prefix Fail to Failing Test (#2212) 2022-09-24 11:40:08 -07:00
Junhee Cho 69d4363ea5 Adds division to multiplicative expression. (#2091)
* Multiplication and division have the same priority.
* A new builtin interface DivWith is added.
* In some tests expecting a compilation error (syntax error), the error
  message now says it is expecting SLASH or binary *.
2022-09-19 15:02:29 -07:00
Jon Ross-PerkinsandRichard Smith 005ab78766 Remove indirection for builtin operator tests (#2109)
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2022-09-15 14:36:20 -07:00
Richard Smith bfcab23795 Implement == and != for bool. (#2182) 2022-09-14 21:55:39 -07:00
Richard SmithandJon Ross-Perkins 0191e2e41e implement checking for pattern match exhaustiveness and for unreachable cases (#2164)
When checking for control flow falling off a function after a `match`, determine whether it's possible for no case to have matched. Using the same implementation, also detect whether `case`s in a `match` are unreachable.

For now, the implementation never considers a match against specific values for any type other than tuples, alternatives, and `bool` to be exhaustive. In particular, matching against the sole value `{}` of type `{}` is not considered exhaustive. This is probably best left until explorer supports matching on struct and maybe class types more generally.

This implementation closely follows the algorithm described in the paper [Warnings for pattern matching](http://moscova.inria.fr/~maranget/papers/warn/warn.pdf) by Luc Maranget. Various optimizations are possible, such as reducing the amount of copying done, but for the purposes of explorer, comprehensibility is being favored over efficiency.

The problem is, perhaps surprisingly, co-NP-hard (by reduction to the tautology problem for disjunctive normal form, which is in turn dual to the satisfaction problem for conjunctive normal form, which is well-known to be NP-hard). The algorithm is therefore exponential-time in the worst case, but seems to be well-studied and performs well enough on non-pathological examples. Nonetheless, a depth limit has been imposed to prevent pathological examples such as those generated by a fuzzer from causing long runtimes.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2022-09-13 13:40:25 -07:00
Jon Ross-Perkins 2db09a1fd5 Rename dashes in a few test files to underscores (#2170)
This is somewhat https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#file-names, but in general, underscores are more consistent.
2022-09-13 09:39:47 -07:00