Commit Graph
234 Commits
Author SHA1 Message Date
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
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
Prabhat Sachdeva 90d2d075f2 Explorer: add blank lines between trace of different sections (#3096) 2023-08-15 21:10:12 +00:00
Prabhat Sachdeva da35a9806a Explorer: make pattern match trace consistent (#3093)
Makes the trace output for pattern match more consistent with the rest
of the trace by using `Match()` and `Indent()` prefix methods and
wrapping the code in the trace with backticks.
2023-08-12 00:02:41 +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
Prabhat Sachdeva 2f70c7d8bb Explorer: Reduce prelude path when printing source location (#3080)
The Prelude path can be very long, which can make the `SourceLocation`'s
`Print(...)` method output unnecessarily verbose. This PR modifies the
`SourceLocation`'s `Print()` method to just print the **filename** and
**line number** for prelude.
2023-08-09 17:57:07 +00:00
Richard Smith 212188a922 Prefer to put STDOUT CHECK at the end of the file. (#3073)
Allow interleaving of STDOUT and STDERR check lines. Put STDOUT lines
after the line they're attached to, and STDERR lines before. If no
STDOUT check line is attached to any line, then put them all at the end
of the file instead.

This is intended to better handle the case where stdout contains
unreplaced mentions of line numbers, and also reflects that stdout is
typically a consequence of the test rather than commentary on it, so
placing it after the test seems likely to read better.
2023-08-08 19:51:52 +00:00
Prabhat SachdevaandRichard Smith a359da37c4 Explorer: improve type checking trace output (#3039)
Updates the trace output for type checking to be more consistent like
the rest of trace output.
This PR also includes few changes in the lit tests related to trace
output.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-08-08 17:58:12 +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 96517a1ee3 Migrate explorer tests to file_test and remove lit support. (#3050)
This migrates explorer tests to file_test, using the new --autoupdate
functionality. Per discussion, the trace tests that were using "not"
output are mostly migrated to checking full output. The main exception
is tests that were including trace output from the prelude: the prelude
output is pretty long (multiple MB already) and I think it wasn't the
intent to include, only trace output from the small program.

This is the remaining use of lit support, so the supporting libraries
are also removed here.
2023-08-02 21:44:16 +00:00
josh11b 1006956ed5 Fix class_value_ptr invariant bug found by fuzzer (#3025)
Invariant is `*class_value_ptr == this` when the static type matches the
dynamic type.
2023-07-27 20:39:54 +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
josh11bandGeoff Romer cf2ddc6072 Temporary restriction that extend base is first in a class to avoid #2994 (#2995)
Closes #2994

---------

Co-authored-by: Geoff Romer <gromer@google.com>
2023-07-24 18:11:40 +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
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
Jon Ross-Perkins f71a3b71b4 Disallow namespaces as class members (#2996)
Breaking apart namespaces from the main declaration list is, I think,
the most scalable approach to this. If we have more divergence in
supported declarations it gives a fairly straightforward way for
splitting, and roughly mirrors how class_body splits.

Fixes #2980
2023-07-19 01:02:47 +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 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
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
Richard Smith a5c8cbdbf8 Require a complete type when enumerating the fields of a class. (#2956)
Fixes a crash on invalid found by fuzzing.
2023-06-28 14:56:27 -07:00
josh11bandRichard Smith 318eb793eb Explorer: Include self pattern in method type (#2935)
This fixes a bug where Explorer would not detect when:

- an implementation used a method to implement a class function in an interface
- an implementation used a class function to implement a method in an interface
- an implementation method used `addr self` when the interface method did not
- an interface method used `addr self` when the implementation method did not

at type checking time. This would then cause a crash at runtime.

Closes #2857

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-06-28 09:07:01 -07:00
Geoff Romer adcb5fb0b5 Set class static type before base class lookup (#2931)
This avoids a crash when a class inherits from itself.

Closes #2929
2023-06-26 17:02:31 -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
Chandler Carruth abecb25185 Fix a fuzzer-found crash. (#2930)
The crash occurred because of an alias target of a mixin. While
eventually, we should probably have some ability to alias mixins, this
isn't yet setup in the explorer and doesn't seem like a current
priority.

We got here because the mixin type checking made it far enough to not
reject this within the type checker, but the next step wasn't prepared
for this to come out of the type checker. The simplest fix seems to be
to reflect that it *can* escape the type checker, but still isn't (yet)
a valid alias target.

Test case added.
2023-06-20 12:32:58 -07:00
josh11b 401880a14b Fix merge conflict between #2906 and #2881 (#2910) 2023-06-15 09:42:41 -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 SmithandGeoff Romer 4e1adcf4c7 Bring constraints into scope when a generic calls a template. (#2878)
When a template has an argument that involves a generic parameter, we're supposed to delay instantiation until we know the concrete value, but explorer is not set up to do that yet, so for now we instead instantiate the template with the symbolic argument. When that happens, bring the constraints on the generic parameter into scope so they can be used inside the template instantiation.

This requires adding a new search over a value for the generic parameters that appear within it; a `VisitNestedValues` visitor is added to visit all the `Value`s nested with a value, and also convert an existing place where we were doing the same thing in a way that was incorrect (but harmlessly incorrect for now) to use it.

This is needed by #2881, which needs implementations of `ImplicitAs` for nested types when instantiating a builtin impl of `ImplicitAs` for an aggregate type.

Co-authored-by: Geoff Romer <gromer@google.com>
2023-06-09 10:09:52 -07:00
Richard Smith e066e96464 Fix false positive in potential cycle detection. (#2879)
Fix misidentification of a potential cycle in the case where the inner match is missing labels from the outer match, and the inner match is strictly more complex when considering only its labels. We previously ignored labels in the outer match that are absent in the inner match, but the existence of any such label should cause us to treat the inner match as not being strictly more complex.
2023-06-07 14:39:05 -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 6b7a522b3f Provide local paths for file tests. (#2830)
The intent of this change is that instead of paths looking like `explorer/testdata/foo/bar.carbon` (repo-relative), they're now just `bar.carbon` (local). The consequence is that paths should be a bit more durable in various environments, and just paths should be shorter and easier to read.

The explorer's prelude is an exception to this since it comes from data, rather than being the test target. Due to the change in approaches, it needs the regex again.

Uses #2829
2023-05-18 10:20:51 -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
Jon Ross-PerkinsandChandler Carruth 941e60ade6 Add framework for replacing lit with cc_test (#2814)
This is really part of #2811, but is extracted out to allow a little review in parallelism because #2811 expects #2813. Getting this in will allow migration of toolchain tests, whereas #2811 is focused on explorer tests. For explorer test timing information, see #2811.

The syntax being used for matching deliberately mirrors the `FileCheck` setup, partly for compatibility if something changes, partly so there's nothing new to learn, partly so that we don't need to build more test updating.

Individual tests look like:

```
[ RUN      ] ParseAndExecuteTestFile.explorer/parse_and_execute/testdata/assert/convert.carbon

To test this file alone, run:
  bazel test //explorer/parse_and_execute:file_test.subset --test_arg=explorer/parse_and_execute/testdata/assert/convert.carbon

[       OK ] ParseAndExecuteTestFile.explorer/parse_and_execute/testdata/assert/convert.carbon (202 ms)
```

The printed command line is intended to assist developers in debugging a single test, particularly when sharding the main test. The use of a single `.subset` target means the total number of targets is constant even as the number of test files increases, which may be important for some `bazel` execution environments. I plan to make similar changes to the `glob_sh_run` implementation so that we have consistent setups, i.e. that we no longer create target-per-file scaling risks.

This uses `native_test` to share the test binary, avoiding re-linking if files are individually run.

Investigation did reveal a mistake where STDOUT/STDERR wasn't prefixed on empty output lines; this PR fixes that mistake, so that output is fully covered.

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-05-12 10:05:08 -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 ad52f1e547 Fix lit_autoupdate for explorer (#2801)
#2793 added a README.md, #2796 added the non-auto-updated test.
2023-04-26 13:52:16 -07:00
Jon Ross-Perkins 8715cded29 Prevent generic bindings in binding types (#2789)
Adds TODO #2788 for the bigger refactoring.

Fixes #2783
2023-04-24 14:06:35 -07:00
Manmeet Singh 90577f18a0 fix alias resolved_declaration error (#2796)
Closes #2794
2023-04-24 10:02:04 -07:00
Lucile Rose Nihlen c180e6367b [explorer] fix assert when aliasing interface as member (#2792)
Note that this code still results in a compilation error pending the merge of #2628, this just prevents the assertion from happening.

Closes #2583.
2023-04-24 08:05:31 -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
Manmeet Singh f310316ef4 fix printing for single element tuple values (#2786)
adds trailing comma to single element tuple

example:
```carbon
package ExplorerTest api;

fn Main() -> i32
{
  var a: (i32,) = (1, 2);
  return 0;
}

```

change in error message:
```diff
-type error in initializer of variable: '(i32, i32)' is not implicitly convertible to '(i32)'
+type error in initializer of variable: '(i32, i32)' is not implicitly convertible to '(i32,)'
```
2023-04-21 09:34:22 -07:00
Jon Ross-Perkins c9f0ef9e2c Require names where we expect binding patterns (#2782)
This also clusters the various `var` tests. This tests similar patterns for a few syntaxes, but `fn f(x: i32, i32) {}` and local variables `var (x: i32, i32);` and `var i32;` were the crashers I found.

In `fn`, the `x: i32,` is helpful to convince the parser that this is valid syntax.

Fixes #2778
2023-04-20 10:58:03 -07:00
masbuz ac10b36595 Fix BindingPattern type check handling (#2777) (#2787)
Recursive call of TypeCheckPattern ignored 'expected' parameter.

Closes #2777
2023-04-20 09:48:36 -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 60059ff726 Type check the mix argument before interpreting it (#2781)
This is a crash bug.

Fixes #2779
2023-04-19 11:56:39 -07:00