Commit Graph
142 Commits
Author SHA1 Message Date
Jon Ross-Perkins 53af8f04b2 Provide a Printable CRTP parent to replace HasPrintable templates. (#3166)
With the toolchain splitting namespaces, ostream.h's `operator<<`
templates aren't reliably found with name lookup, likely due to the loss
of associated namespaces (zygoloid commented on this at
https://github.com/carbon-language/carbon-lang/pull/3161#discussion_r1307941999).
This is especially a barrier to moving the lex files into `Carbon::Lex`;
versus other parts of the toolchain, they contain more printable types
which are used cross-namespace, including `Carbon::Testing`. As a
consequence, I'm looking at migrating ostream.h to a more reliable
approach that doesn't rely as much on everything being in the `Carbon`
namespace.
2023-08-30 21:32:19 +00:00
Lucile Rose Nihlen af0710ea16 Add addr self binding support in destructors (#3117)
Refactors `CallDestructor` and `CallFunction` to both call a new method
`BindSelfIfPresent`, which includes support for binding `addr self` if
specified. Fixes the associated unit test.

Closes #2802.
2023-08-29 20:46:39 +00:00
Jon Ross-Perkins f63834c71d Move PrintAsID into explorer. (#3163)
#2569 added PrintAsID to //common/ostream.h, but given it's
explorer-specific behavior, I don't think it's the right home for it.

Noticed this while pondering better ostream interfaces.
2023-08-28 23:39:56 +00:00
Prabhat SachdevaandJon Ross-Perkins 289d05813e Explorer: Remove PrintDepth and implement PrintIndent. (#3113)
This PR removes `PrintDepth` from statement and declaration.
Implements `PrintIndent` for better indented formatting along with
various changes to make printing of statements and declarations better.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-08-25 17:17:39 +00:00
Jon Ross-Perkins c3da338ce4 Make more use of llvm::zip and enumerate in explorer (#3135)
I was initially looking at llvm::seq, but then looking through uses it
seemed like enumerate/zip would be best for these, allowing less direct
indexing and more range-based looping.
2023-08-22 21:19:46 +00:00
Jon Ross-Perkins 357baaeef8 Rename //explorer/common to base (#3103)
Renaming per #3100
2023-08-15 19:23:23 +00:00
Prabhat Sachdeva c5667c0e10 Explorer: add trace for InstantiateType (#3041)
Adds trace output for `Interpreter::InstantiateType` method.
2023-08-11 18:05:30 +00:00
Prabhat Sachdeva 2a74c807d8 Explorer: Add heading and sub-heading methods to trace (#3088)
Instead of manually putting symbols before and after heading, this
introduces two methods `Heading` and `SubHeading` inside `TraceStream`.

Both methods take `llvm::StringRef` as parameter, formats the given text
as follows and adds it into the output stream.

**Heading**
```
* * * * * * * * * *  heading  * * * * * * * * * *
-------------------------------------------------
```
**Sub heading**
```
- - - - -  sub heading  - - - - -
---------------------------------
```

Note: both methods assert that tracing should be enabled.
2023-08-10 22:40:21 +00:00
Prabhat Sachdeva 3cca175a57 Explorer: Add source snippets to trace output (#3082)
Adds **Source Snippets** for interpreter and type checker's trace
output.
Note: Source snippets are trace for only declarations and statements.
2023-08-10 18:29:52 +00:00
Prabhat Sachdeva 0bcba9d05e Explorer: Add methods to trace for line prefixes (#3076)
Defines methods into `TraceStream` for adding line prefixes. Instead of
directly using string literals.

Example usage,
```
trace_stream_->Start() << "declaring ... " << ... ;
```
will result in,
```
->> declaring ... 
```
2023-08-09 19:05:19 +00:00
kshokhin d34b3e02c2 Add type_utils file (#2926)
Prerequisite for #2909. Moves some type-related functions to the
separate file.
2023-08-07 16:22:19 +00:00
c93a0e5e42 Implement canonicalization of Value and Element (#3024)
See arena.h for discussion of what canonicalization means in this
context. This is primarily intended to support implementing a memo table
of template instantiations to resolve #2951, but could be useful for
other purposes as well.

Additional changes:
- Pass `VTable` constructor parameters by pointer, to avoid the need to
define `operator==` and `hash_value` for it.
- Clean up the recurring pattern of allocating identical `NamedElement`s
on the stack and heap. Instead we always allocate it on the heap and
pass it by pointer.
- Add `Print()` and `Dump()` to `Bindings` as a debugging convenience.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-08-03 16:05:59 +00:00
Prabhat Sachdeva 2c4fff25a8 Explorer: add more information to stack trace (#3040)
Adds **action kind** and **source location** for stack trace.
Example:
```
(+) stack-push: <action> (<source location>)
(+) stack-pop:  <action> (<source location>)
```
This PR also updates the `Action::Print(...)` method, following is the
generalized view of `Action::Print(...)`.
```
ActionKind pos: <pos_count> `<related_code>` results: [<collected_results>]  scope: [<scope>]
```
2023-08-03 16:05:37 +00:00
Jon Ross-Perkins bbf896e165 Convert returned associated constants. (#3029)
Associated constants were getting returned directly, crashing because
the value InterpProgram received was an AssociatedConstant instead of an
IntValue. We have a similar Convert call in ReturnVar, so I _think_ this
is the right approach.
2023-07-26 21:30:28 +00:00
Jon Ross-Perkins a3d52b089d Fix missing assignment to me_value found by msan. (#3019)
Looks like a small oversight in #2946. Probably missed because type
access shouldn't really access the me_value.
2023-07-24 22:31:39 +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
Prabhat Sachdeva 126d45a1f1 Trace stack and memory only when there is change in state (#2982)
Add state (stack and heap information) to the trace stream only when
there is a change in state, this would prevent consecutive repetition of
state information in the trace output.

Checks it based on change in size of the stack and heap, added
`std::pair<int, int> stack_heap_sizes` in `Interpreter` to store size of
stack and heap for comparison.
2023-07-21 05:02:00 +00:00
Richard SmithandJon Ross-Perkins ea60e4f491 Track the file kind on SourceLocation rather than computing it from the file name. (#2999)
This will be more correct if a user file is named prelude.carbon, and
reduces the explorer runtime by about 10% by removing a string
comparison from the check for whether trace output is enabled.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-07-19 23:07:53 +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
Prabhat SachdevaandRichard Smith c0d18a62eb Trace output filtering based on file context (#2916)
To filter based on file contexts, you can use `-trace_file_context=...`
flag along with `--trace_file=...` flag. These are the following options
you can pass to the `-trace_file_context=...` flag (you can also pass
them as list by separating them with comma).
1. `main`: Include trace output for file containing the main function.
2. `prelude`: Include trace output for prelude.
3. `import`: Include trace output for imports.
4. `include`: Include trace output for all.

If the flag isn't used or non of the options are passed, by default only
main file context is traced.

File contexts are distinguished based upon the source location by
passing the source location to `TraceStream::is_enabled(..)` as
arguments. If no arguments are passed, file context is
`FileContext::Unknown` and for now it will add the trace from unknown
file context.

Note: `import` option currently doesn't work as imports aren't supported
yet.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-07-07 22:17:34 +00:00
josh11b 798233fe23 Error evaluating symbolic tuple (#2957)
Reports an error (`value of generic binding T is not known`) instead of
performing an invalid cast when attempting to index into a tuple. Can
occur when trying to cast a generic constant in the interface position
of an implementation to `type`.

Closes #2938
2023-06-29 00:37:13 +00:00
Jon Ross-Perkins 7bcfe7df59 LLVM should be included using quotes. (#2952)
This also results in correct dependency discovery (the missing LLVM dep on expression_category).
2023-06-28 15:50:08 -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
josh11b 1505a634a4 Implement syntax changes from #2760 in Explorer (#2906)
Implement syntax changes from #2760 in Explorer
2023-06-15 08:42:14 -07:00
Geoff Romer b03d0d542b Disallow calling Print() at compile time (#2903)
Closes #2865
2023-06-15 08:32:29 -07:00
Richard Smith 474b1eb24c Support builtin conversions that internally rely on user-defined conversions (#2881)
There are a few implicit conversions that are implemented by an `impl` of `ImplicitAs` that delegates to code in explorer:

- Converting between tuple types
- Converting from tuples of types to `type`
- Converting from tuples of values to an array type
- Converting between struct types
- Converting from a struct type to a class type

These conversions can all rely on performing more conversions for elements or subobjects, but previously those inner conversions could only be performed if they were built into explorer. This change instead uses the full implicit conversion machinery in explorer to perform these conversions, including searching for a user-defined `impl` of `ImplicitAs` when necessary.

For example, this permits a conversion from `{.a: T}` to `{.a: U}`, or from `(T, T)` to `(U, U)`, or from `(T, T)` to `[U; 2]` when there is a user-defined conversion from `T` to `U`.

Depends on #2878
2023-06-14 16:14:21 -07:00
Richard Smith 81e53886a8 Fix crash on use of uninitialized array element, and improve unformed checking (#2862)
Per #257, we should be treating unformedness as all-or-nothing, rather than being a per-field or per-array-element property. Previously we initialized an array with no explicit initializer as containing a sequence of uninitialized values, but that led to crashes when attempting to access those values, as the checks for reading an uninitialized value only expected values to be uninitialized at the top level.

Also, we had existing tests that attempt to store to an element of an uninitialized array. We now detect that and treat it as UB during evaluation, rather than crashing due to trying to perform field access into an uninitialized value.

Finally, many of these problems can be detected statically, but the resolve_unformed pass wasn't catching them because it missed a few expression and declaration forms. Support for those cases has been added too. This causes the pass to recurse more often, and in particular our existing recursion test started hitting a stack overflow after this, so resolve_unformed now uses `RunWithExtraStack`. In passing, remove the need to explicitly tell `RunWithExtraStack` the return type, and infer it as the return type of the callable instead.
2023-05-31 16:35:21 -07:00
kshokhin 40b3518d37 Add array size deduction from tuple(fix#1590) (#2825)
Allow array size deduction from tuples and arrays on array declaration

Closes #1590
2023-05-22 11:36:29 -07:00
Jon Ross-Perkins 82f33ff384 Use new test framework in explorer to reduce per-test overhead (#2811)
Isolating test execution time (no build time included):

- Linux, `lit` test-per-file: Elapsed time: 28.214s, Critical Path: 13.97s
- Linux, `cc_test`-per-file: Elapsed time: 11.534s, Critical Path: 6.05s
- Linux, merged `cc_test` with 50 shards: Elapsed time: 11.677s, Critical Path: 11.17s
- Mac, `lit` test-per-file: Elapsed time: 295.686s, Critical Path: 20.00s
- Mac, `cc_test`-per-file: Elapsed time: 55.788s, Critical Path: 3.81s
- Mac, merged `cc_test` with 50 shards: Elapsed time: 16.269s, Critical Path: 7.54s

In GH actions:

- [Before](https://github.com/carbon-language/carbon-lang/actions/runs/4866602695/jobs/8678306144?pr=2799):
  - test / test (ubuntu-22.04, fastbuild) (pull_request_target) Successful in 20m
  - test / test (ubuntu-22.04, opt) (pull_request_target) Successful in 15m
  - test / test (macos-12, fastbuild) (pull_request_target) Successful in 36m
  - test / test (macos-12, opt) (pull_request_target) Successful in 21m
- [After](https://github.com/carbon-language/carbon-lang/actions/runs/4875154751/jobs/8697004066?pr=2811):
  - test / test (ubuntu-22.04, fastbuild) (pull_request_target) Successful in 10m
  - test / test (ubuntu-22.04, opt) (pull_request_target) Successful in 9m
  - test / test (macos-12, fastbuild) (pull_request_target) Successful in 12m
  - test / test (macos-12, opt) (pull_request_target) Successful in 9m

I'm still leaving a handful of `lit` tests to test end-to-end binary execution. This is why testdata directories are split (`lit` tests next to the `explorer` binary, the `cc_test`s next to `ParseAndExecute`).
2023-05-15 16:23:59 -07:00
Amr Hesham 681dcfdcef Fix local and global uninitialized array access (#2816)
* Fix uninitialized array access/initialization

* Handle printing uninitialized value

* Fix error message directory name
2023-05-05 11:20:20 -07:00
Jon Ross-Perkins b9bd7e1eff Turn addr self in destructors into an error. (#2803)
Previously crashed. See #2802
2023-05-01 11:30:19 -07:00
Jon Ross-Perkins b828093c87 Start checking for a few possible resource exhaustion scenarios for explorer (#2793)
I couldn't figure out a way to actually hit a reasonable out-of-memory case once I add the maximum interpreter step count. However, the step count limit seems more important.

I've moved the todo stack limit out of function calls because there are plenty of ways to build up the todo stack without any function calls.

Fixes #2791
2023-04-21 15:14:14 -07:00
Jon Ross-Perkins 62ee4a5c7a Suppress Print intrinsic output in the fuzzer. (#2784)
Related to #2780, but mostly an issue when running over the committed corpus since we use Print a lot.
2023-04-19 16:56:02 -07:00
Jon Ross-Perkins 39155d34ae Remove experimental continuation support (#2776)
Removes `__continuation`, `__await`, and `__run`.

In part here, the discussion was that while the feature had been useful for validating the early explorer design, it's no longer needed for that role as the explorer is now quite robust. Continuations have been experimental and, at this point, don't have an owner pushing to a proposal.

The triggering factor is that, as we push to address fuzzer issues, I ran into a crash bug in this code; basically, `fn Main() -> i32 { __await; return 0; }`. When I mentioned this, the reaction seemed to trend towards removal of the feature.
2023-04-19 14:22:43 -07:00
Jon Ross-Perkins 710eb0480c Add validation of Print format strings (#2765)
Also adds some validation of various direct print intrinsic calls.

Fixes #2734
2023-04-17 11:45:21 -07:00
Jon Ross-Perkins d7978deb3a Start doing more validation of intrinsics: assert, new, delete, rand (#2766)
This is adding more validation of intrinsics. It addresses a bug in rand where CHECK-fails would occur for bad range inputs, instead of a runtime error. I'm also addressing what I think was an int32 range issue in the handling by running the generator with int64.
2023-04-13 12:53:34 -07:00
Jon Ross-Perkins 694dd7bf55 Fix poor dyn_cast usage (#2763)
Note the dest_class case didn't actually check dyn_cast success until after using the pointer. That's the case I noticed first, but also cleaning up a couple other small related things.
2023-04-12 15:56:27 -07:00
Amr Hesham 08f8c9bb27 Explorer: Move Concrete type check for Variable Definition to the type checker (#2750)
Move concrete type check for Variable Definition (Local variable) from interpreter to type checker using the `ExpectConcreteType` function created in #2748
2023-04-10 12:15:49 -07:00
Poorna Gunathilaka 0177764a03 Explorer: Fuzzer issue around integer overflow (#2737)
Closes #2732
2023-04-06 16:54:58 -07:00
Amr Hesham 87df7f7c43 Explorer: Fuzzer issue around infinite recursion (#2741)
I limited the stack size to 1K we can change it or make it dynamic from CLI later

Closes #2733
2023-04-06 16:50:02 -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
Prabhat Sachdeva 3f1515af55 Change InstantiateType to be an Action (#2660)
Added an alternative way of Instantiating types (it was previously done using `InstantiateType` method).
Created an `Action` called `TypeInstantiationAction` and changed most of the code that directly invokes `InstantiateType` to instead spawn a new `TypeInstantiationAction`.

Relates to [#2594 ](https://github.com/carbon-language/carbon-lang/issues/2594)
2023-04-03 17:15:24 -07:00
Amr Hesham 29cdeb0d6b Explorer: Fuzzer issue around divide-by-zero (#2735)
fail with a runtime error, preventing the divide-by-zero from actually running.

Issue #2731
2023-03-31 20:53:26 -07:00
josh11bandGeoff Romer 46503c0a9d Explorer and toolchain changes to implement #2483 (#2707)
This PR is making two main changes to the Explorer and Toolchain:
- Replace the `is` keyword in `where SomeType is SomeInterface` with `impls`, so it is `where SomeType impls SomeInterface`
- Rewrite uses of the "impls" to something else to avoid, frequently "`impl` declarations" or "implementations", to avoid confusion with the `impls` keyword.

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2023-03-28 12:28:52 -07:00
Richard Smith e0c90767be Support for templated impl declarations (#2700)
The strategy that we use for now to support template instantiation is to check the impl declaration as if it were a generic, but to defer all checking of the impl definition until we see a use in which all template parameters have arguments. At that point, we clone the impl definition and type-check the whole thing, with constant values set on the template parameters corresponding to the given arguments.

No caching of template instantiations is performed yet; each time we form a reference to a template instantiation, we instantiate it afresh. We also don't implement the name lookup rule from #949 yet; lookups during template instantiation look only in the actual type and not in the constraint.

Depends on #2699
2023-03-22 14:19:02 -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
Richard Smith bfe5c36bfc Move Value, Address, and ElementPath to ast/. (#2659)
These are used by the AST in lots of ways, and this resolves various layering issues.

This means that `AllocationId` also lives in ast/, but is managed by interpreter/. A better layering here would be desirable, but this seems good enough for the time being.
2023-03-06 16:28:03 -08:00
Richard Smith 2717dc1097 Decouple Value from interpreter-specific representation of continuations. (#2658)
`ContinuationValue` is the only dependency that `Value`s have on implementation details of the interpreter, and removing this allows `Value` to be moved from interpreter/ to ast/, as [discussed on #explorer](https://discord.com/channels/655572317891461132/763516049710120960/1081326038858092624).
2023-03-06 15:25:53 -08:00
Richard Smith 752692e08d Factor out a common base class from function and bound method values. (#2622)
This allows simplification of the interpreter in places where these two
kinds of value can be handled with common code.
2023-02-22 15:04:00 -08:00
Richard Smith 7fe06a5d2f Unify handling of calls to functions and to methods. (#2620)
This fixes some bugs in each, where the fixes had only been made on one
side of the switch or the other. Also don't forget to instantiate
deduced generic arguments in a call when we read them out of the AST.
2023-02-22 13:51:25 -08:00