Commit Graph
40 Commits
Author SHA1 Message Date
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
Geoff Romer 493eb75e7f Rename PointerType::type to pointee_type. (#2468)
This avoids the confusion that can arise from the natural assumption that `foo->type()` returns the type of the value `foo`.
2022-12-13 13:08:08 -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
josh11b 9c8fd6864e Implement rename me -> self (#2444)
Implements change proposed in #1382

Replaces #1624
2022-12-06 20:17:00 -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 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
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
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 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
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 b6721a1a93 Move member types of ConstraintType out to namespace Carbon. (#2327)
We had already moved two of these out because they're more generally
applicable. Move the other two out for consistency and remove the member
names.
2022-10-21 08:00:13 -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
Jon Ross-Perkins 8e5dcc2588 Enable readability-qualified-auto (#2314)
As suggested on #2310
2022-10-18 19:21:49 -07:00
Jon Ross-Perkins 4d522c8e90 Finish making clang-tidy (mostly) work (again) and run -fix (#2312)
This does some more work to the run_clang_tidy.py wrapper script, and runs an example pass.

"again" because it's really the proto fuzzer changes that broke it, it had been working before.

"mostly" because there's still an issue within the proto fuzzer that it can't find "port/protobuf.h", i.e. https://github.com/google/libprotobuf-mutator/tree/master/port, but I'm still hesitant to add an include path there.
2022-10-18 15:48:17 -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
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
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
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 2340cb6703 Build value representations for all kinds of witness (#2250)
Instead of forming a `SymbolicWitness` that contains an `Expression` when we can't directly resolve a witness to an `impl`, form different kinds of `Witness` values for the various situations:

- A `BindingWitness` witnesses that a type implements a constraint by reference to an `ImplBinding`.
- A `ConstraintWitness` witnesses that a type implements a constraint by reference to witnesses for each of the impl constraints within the constraint.
- A `ConstraintImplWitness` witnesses that a type implements a constraint by reference to a larger constraint which contains that constraint as an impl constraint.

Remove `SymbolicWitness` values and `InstantiateImpl` expressions, which are now unused. In order to remove the final usage of `SymbolicWitness`, I fixed a TODO to give `Self` the proper type within an interface declaration. I don't think this is an observable change.

No functional change intended.
2022-10-04 12:14:52 -07:00
pmqtt cfa295c0af Feature destructor (#2116) 2022-09-26 10:11:05 -07:00
Darshal Shettyandjosh11b 037c99e2fb Explorer: Mixin phase 1 (#2069)
* Replay changes from pre-force-push mixin branch

* Base MixinPseudoType off of the new InterfaceType

* Add more test cases.

Also removed an unnecessary check that would have already been
handled by the parser.

* WIP detect member clashes during mixing mixins

* Implement fuzzer changes

* Implement member name clash check when mixing mixins

* Modify parser and lexer for experimental mixin feature

* Add comments

* Update explorer/testdata/mixin/simple-mix-in-mixin.carbon

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

* Update explorer/testdata/mixin/use-mixin-method-in-class-method.carbon

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

* Make code review changes

Co-authored-by: josh11b <josh11b@users.noreply.github.com>
2022-09-06 17:08:05 -04:00
pmqtt f957d4d87d Feature generic choice (#2042)
Implementation of generic choices!

I hope it is useful!
2022-08-24 11:30:04 -07:00
Richard Smith e26bc32343 Change remaining uses of Bool to bool, following #750. (#1901)
The most significant change here is that explorer now uses the chosen spelling
rather than the old `Bool` spelling. Also update a few documentation examples
and some skeletal design docs to use the chosen spelling.
2022-08-03 17:55:34 -07:00
Zenong ZhangandJon Ross-Perkins 52ee050019 Initial implementation of unformed state for local variables. (#1387)
Allows unformed state for local variables. Reports a run-time error when an unformed local variable is used.
- Added declaration without initialization for local variables in the parser.
- Made the init expression of VariableDefinition optional.
- Expanded (alive, dead) to (uninitialized, alive, dead) in the Heap.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2022-07-20 16:03:52 -04:00
Richard SmithandJon Ross-Perkins 663ed32b1b Initial support for associated constants (#1376)
Basic support for declaring, specifying the values of, and using associated constants.

This is incomplete in various ways. For example, when checking whether a type satisfies a constraint, there is no check that its associated constants match those in the constraint, and name lookup into a value whose type is an associated constant is not supported yet.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2022-07-14 18:18:27 -07:00
Richard Smith a1be2a8a38 Track the arguments and witnesses on values indirectly. (#1335)
This avoids the need to make copies of potentially large maps when
the same bindings are used in multiple values, such as when forming
a bound method value.
2022-06-21 08:48:48 -07:00
Richard Smith 17ee3ed9b7 Track a resolved Member on each member access expression. (#1333)
Type checking now stores information on a member access identifying the member that was accessed, not only its name. This parallels what we do for other similar constructs whose meaning is resolved by name lookup or type-checking, and will allow us to avoid redoing lookups in some cases during interpretation.
2022-06-16 17:22:31 -07:00
Jeremy G. Siek b759401328 Heap allocation basics (#1323)
* initial implementation of new and delete

* remove requirement for empty heap from trace.carbon

* more tests

* fixed substitution for generic function types
2022-06-11 18:47:07 -04:00
Richard Smith b74d3f80f1 Add a new kind of Witness value that carries an expression (#1324)
This renames `Witness` to `ImplWitness` and adds a new form, `SymbolicWitness`, that holds an expression by which a witness can be computed. A common base class `Witness` is provided.

We form the new kind of witness when evaluation of a witness expression fails because the witness is not in scope, as happens when evaluating a subexpression such as a type expression in isolation, and retry evaluation in the larger context when the interpreter performs type instantiation when running the code.

This allows us to properly handle compile-time evaluation of constructs involving witness table lookups when the witness can be statically determined. The intent is that we will eventually also form symbolic witness table references when impl selection finds a non-final witness, in order to support specialization.

Simplify `NominalClassValue`: it can now always store a witness map rather than either a witness map or a witness-or-witness-expression map.
2022-06-10 14:16:54 -07:00
Richard Smith 1bb370420b Initial support for constraints formed by combining interfaces (#1307)
Add scaffolding for constraints in general, and support specifically constraints formed by applying a `&` operator.

No support for constraints formed with `where` nor for named constraints at this point.
2022-06-07 13:59:23 -07:00
Darshal Shetty e4a2d0f047 Addr Keyword Implementation (#1255)
* Implement addr keyword

* Add files that were deleted during merge

Some files got deleted during merging trunk because of the executable
semantics rename.

* Implement changes from code review.

Major changes:
- Rename AddrBindingPattern to AddrPattern
- Fix AddrPattern related changes in fuzzing

* Update documentation for GetField

* Fix AddPattern according to @zygoloid's suggestions

* Apply @zygoloid's changes to method comment

* Add a multi-component field example

* Incorporate AST changes to fuzzer corpus

* Refactor the deduced_param_list grammar rule

Suggested by @zygoloid
2022-06-01 13:51:37 -04:00
Richard Smith 4cf7ed4f12 Rename some classes to match the design better (#1287)
* `FieldAccessExpression` -> `SimpleMemberAccessExpression`
    * Member `aggregate` -> `object`
    * Member `field` -> `member`
* `CompoundFieldAccessExpression` -> `CompoundMemberAccessExpression`
* `GetField` -> `GetMember`

As discussed in #1233.
2022-05-24 17:51:54 -07:00
Richard Smith c48d024eea Produce a class value when converting {} to class type. (#1265)
Previously we missed this special case because {} results in a
StructType value not a StructValue value.
2022-05-16 16:18:32 -07:00
235cb88a8e Compound member access syntax. (#1233)
Implement initial support for `A.(B)` syntax, per #989. Specifically, this supports:

* `object.(Type.member)` for instance members,
* `object.(Interface.member)` for instance and non-instance members,
* `object.(Type.(Interface.member))` for instance members,
* `Type.(Interface.member)` for non-instance members.

Three new AST nodes are introduced:

* `CompoundFieldAccessExpression` represents the `A.(B)` syntax.
* `MemberName` is a `Value` that represents the result of evaluating an expression such as `Type.member` or `Interface.member` or `Type.(Interface.member)`.
* `TypeOfMemberName` is the type of a `MemberName` value.

In order to handle members of classes and interfaces which have corresponding declarations and may need substitution into their types, and members of structs which don't have declarations but also don't need substitution, a class `Member` is introduced that can refer to either of these kinds of member.

Co-authored-by: Geoff Romer <gromer@google.com>
Co-authored-by: Jon Meow <jperkins@google.com>
2022-05-13 16:52:41 -07:00
Richard Smith 27c8d1fc12 Support explicit generic parameters in function parameter lists (#1259) 2022-05-12 12:39:51 -07:00
Jon Meow af694b97cb Prefix most macro names with CARBON_ (#1232)
I'm doing this to avoid macro name conflicts, following https://google.github.io/styleguide/cppguide.html#Preprocessor_Macros: "If you do export a macro from a header, it must have a globally unique name. To achieve this, it must be named with a prefix consisting of your project's namespace name (but upper case)."

Commands run:

```
sed -i 's/\(DCHECK\|CHECK\|FATAL\|MAKE_UNIQUE_NAME\|MAKE_UNIQUE_NAME_IMPL\|RAW_EXITING_STREAM\|RETURN_IF_ERROR\|RETURN_IF_ERROR_IMPL\|ASSIGN_OR_RETURN\|ASSIGN_OR_RETURN_IMPL\|DIAGNOSTIC_KIND\|RETURN_IF_STACK_LIMITED\)(/CARBON_\1(/g' $(git ls-files *.cpp *.h *.lpp *.ypp *.def ':!third_party')
sed -i 's/#undef DIAGNOSTIC_KIND/#undef CARBON_DIAGNOSTIC_KIND/' toolchain/diagnostics/diagnostic_registry.def
```

Note this isn't *quite* everything, but it's intended to be a large pass at everything:

```
╚╡git grep '#define ' *.cpp *.h *.lpp *.ypp *.def ':!third_party' | grep -v '#define CARBON' | grep -v _H_
explorer/syntax/lexer.lpp:  #define YY_USER_ACTION                                             \
explorer/syntax/lexer.lpp:  #define SIMPLE_TOKEN(name) \
explorer/syntax/lexer.lpp:  #define ARG_TOKEN(name, arg) \
explorer/syntax/parse_and_lex_context.h:#define YY_DECL                                                         \
migrate_cpp/cpp_refactoring/var_decl.cpp:#define ABSTRACT_TYPE(Class, Base)
migrate_cpp/cpp_refactoring/var_decl.cpp:#define TYPE(Class, Base)     \
```

We may in particular want to do a pass to clean up #ifdef guards and make them be CARBON_ rooted.
2022-05-06 15:30:25 -07:00
Richard Smith a2176e1e28 Use a separate type for a parameterized entity name that is waiting for its arguments to arrive. (#1223)
Previously we modeled these as being class types or interface types, with special case checks to treat them as not actually being class or interface types.
2022-05-05 14:30:18 -07:00
Jon Meow 309ec35f95 Rename executable_semantics to explorer (#1188)
Change generated with:

```
#!/usr/bin/bash -eux

# Helper script for renaming pending work.
# Run from the repo root.

# Rename executable_semantics in code.
sed -i 's/executable_semantics/explorer/g' \
  $(git grep -l 'executable_semantics' . | grep -v proposals)
sed -i 's/executable semantics/explorer/g' \
  $(git grep -l 'executable semantics' . | grep -v proposals)
sed -i 's/Executable semantics/Explorer/g' \
  $(git grep -l 'Executable semantics' . |  grep -v proposals)
sed -i 's/Executable Semantics/Explorer/g' \
  $(git grep -l 'Executable Semantics' . |  grep -v proposals)
sed -i 's/EXECUTABLE_SEMANTICS/EXPLORER/g' \
  $(git grep -l 'EXECUTABLE_SEMANTICS' . | grep -v proposals)
sed -i 's/ExecutableSemantics/Explorer/g' \
  $(git grep -l 'ExecutableSemantics' . | grep -v proposals)
sed -i 's/executable-semantics/explorer/g' \
  $(git grep -l 'executable-semantics' . | grep -v proposals)

# This is only needed for the initial move.
mv executable_semantics explorer
mv explorer/fuzzing/executable_semantics_fuzzer.cpp explorer/fuzzing/explorer_fuzzer.cpp
```

Verified with `bazel test ...`
2022-04-29 13:20:25 -07:00