Commit Graph
195 Commits
Author SHA1 Message Date
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
Manmeet Singh 68e15c37a3 feat: implement namespace alias (#2720)
Fixes 

https://github.com/carbon-language/carbon-lang/blob/46503c0a9d20d8e38dde1ff4266f4e2b98699669/explorer/interpreter/resolve_names.cpp#L281

This was super fun to implement as first contribution. Learnt a lot about how the interpreter works while digging through the code and trying different ways to fix it.
2023-04-17 15:56:31 -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 1f49c3e36d Add some validation of as intrinsics. (#2767) 2023-04-13 12:53:49 -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
Amr Hesham 0fd0855da0 Detect duplicate struct member names (#2764)
Detect struct literal or struct type literal member duplicate name

Closes #2762
2023-04-12 16:24:29 -07:00
Jon Ross-Perkins 9245e17d4c Validate that the argument to __mix is a mixin. (#2757) 2023-04-12 09:25:43 -07:00
Jon Ross-Perkins 819c1745c7 Fix handling of struct conversions in deduction (#2758)
This case previously crashed. Trying to handle allow_implicit_conversion better per discussion; I've split out the for loop for each path because I think it's now clearer this way.
2023-04-11 15:50:03 -07:00
Manmeet Singh 7979c886e0 fix: incorrect loop in builtins_indexes (#2751)
Replaces the incorrect `<=` with `<`. Earlier this also included `Builtin::Invalid` which is meant to be used as count of Builtins.

Closes #2729
2023-04-10 13:37:57 -07:00
Manmeet Singh d9e37da4fb fix: set StaticScope::NameStatus correctly for Associated Constants (#2752)
The StaticScope::NameStatus pattern is not being correctly follow for associated constant deceleration.

Closes #2728
Closes #2730
2023-04-10 13:21:32 -07:00
Manmeet Singh 72d8f86e79 fix: incorrect index in TypeEqual for ConstraintType (#2754)
Just a typo.

Closes #2727
2023-04-10 13:17:33 -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
Amr Hesham 0dc80bac01 Explorer: Report compiletime error when global variable type is abstract (#2748)
Add concrete type check for Variable Declaration to report a compile time error when the variable type is abstract

Closes #2747
2023-04-07 17:37:08 -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 8cb3f00f1b Explorer: fix assignment error typo (#2746)
Fix typo in error message from expression categories renaming
2023-04-06 16:48:51 -07:00
Adrien Leravat 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
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 SmithandJon Ross-Perkins 28946d4b87 Order impl matching by type structure (#2691)
As described in [the generics design](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/generics/details.md#type-structure-of-an-impl-declaration), `impl` declarations are prioritized by type structure. Given two `impl` declarations that match a `type as interface` query, the one that describes the longest prefix of the query without using placeholders is preferred.

We implement this by putting all impls in a total order, first by type structure equivalence classes and then by lexical order. When matching an impl, we walk this total order, and stop once we find a match and reach the end of its equivalence class.

Equivalence classes are determined by finding the locations of the "holes" (the positions where deduced parameters appear) within the type structure, viewed as a tree. Two impls are in the same equivalence class if their holes are in the same place, and equivalence classes are ordered based on a reverse lexicographical ordering of their holes.

Explorer doesn't keep the `Bindings` list for a parameterized type in any particular order, but the type structure rule requires that we consider them in lexical order. In order to support this, we now track an index on the declared parameters of each generic. This is a simple numbering of enclosing generic parameters, both on that generic and on all lexically enclosing generics.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-03-17 16:50:06 -07:00
Richard SmithandJon Ross-Perkins 5b6873d147 Fix handling of choice types with a mixture of alternatives with parameters and alternatives without parameters in pattern analysis. (#2626)
This case previously caused a crash.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-03-07 17:09:40 -08:00
Richard Smith c8141b59d9 Remove ExpectType and some calls to IsImplicitlyConvertible. (#2647)
These functions are dangerous, as they check whether conversions are possible without actually performing the conversions. In each case where they were used, explorer would crash in some cases if a user-defined conversion is required.

This change moves us more towards implicit conversions being handled by a regular function call on an interface and away from them being magical builtins. Unfortunately, this exposes a pre-existing bug that a call of the form `x.(ImplicitAs(T).Convert)()` compiles even if `x` only has an explicit conversion to `T`. That's worked around here for now, but will need a proper fix later.
2023-03-02 14:04:44 -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
Jon Ross-PerkinsandRichard Smith 9df70fb115 Disable most tracing in the prelude. (#2616)
This is intended to address currently flaky timeouts that are likely caused by the size of the prelude. I'm addressing a performance bottleneck in AnalyzeProgram with trace output. Trying to omit prelude traces reduces most trace output significantly,  and I think it'll scale better as the prelude size increases.

The basic mechanics here are:

- In order to consistently track whether tracing is on, I've added a TraceStream class, explorer/interpreter/trace_stream.h.
- The AST now has a num_prelude_declarations field, so that it's provided where the boundary is.
- In order to mark where we try to skip prelude output, I've added calls to set_in_prelude in type_checker.
- In exec_program, I just use num_prelude_declarations directly to skip over.
- Everywhere checks TraceStream::is_enabled before printing, similar to the std::optional check that was previously used.

This does add some timing output in order to better diagnose where slowness is coming from, when tracing. It also adds "verbose" targets to make it easier to get the trace output.

So for example, here's a timing for zero.carbon:

```
Timings:
- Parse: 13ms
- AddPrelude: 25ms
- AnalyzeProgram: 116ms
- ExecProgram: 12ms
```

If I make a small change to just not set skipping_prelude (essentially getting back to current output):

```
- Parse: 13ms
- AddPrelude: 25ms
- AnalyzeProgram: 2359ms
- ExecProgram: 57ms
```

Thus in this trivial example, I'm eliminating about 95% of the execution time.

Note this approach could still be refined in a few ways:

- We could add a flag to allow overriding in_prelude. It should be a small amount of work after this change. But it's a little consistent with how parser_debug works, that it won't print prelude output by default (unless there's an error).
- Execution could skip messages involving initialization of globals declared in the prelude. This is a little noisy right now, but I don't think it's significant for performance because ExecProgram is tiny.
- Once files are more separated, we should be able to change the num_prelude_declarations/set_in_prelude approach.

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-02-22 13:41:12 -08:00
Richard Smith 4b2254a61f Fix some comments after #2612. (#2614) 2023-02-21 09:58:31 -08:00
Jon Ross-PerkinsandRichard Smith 73869e9438 Modify lit_autoupdate so that it can handle errors in prelude.carbon (#2612)
The intent here is that changes to prelude.carbon shouldn't break every test that expects some error from prelude.carbon; that would be too fragile. As a consequence, this effectively ignores the line number in prelude.carbon.

This is a little complex because we don't know which line in the original source file is actually causing the error, just that there is an error. Also, the previous look-behind approach required a fixed-with prefix, whereas we want a little more than that in order to capture the filename for comparison.

This would be hard to do with extra_check_replacement because the path to bazel.runfiles is complex to calculate. As a consequence, this is basically all new code.

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-02-17 09:31:48 -08:00
Richard Smith 81532c8918 Fix mishandling of struct and tuple types in impl matching termination check. (#2609)
Both cases need a label for each level of struct and tuple type appearing in the impl query, because we can have an unbounded number of such levels with the types otherwise being the same.

Prior to this, both added testcases exhibit unbounded recursion.
2023-02-15 15:10:01 -08:00
Richard Smith 0e41c569b1 Implement the termination algorithm for impl selection described in #2458 (#2602)
Detect when evaluating an impl recursively tries to evaluate the same impl for the same or a more complex set of parameters.

In order to perform the check after we have tested that the type structure matches and before we check that constraints are recursively satisfied, argument deduction is extended to check structural matching properties earlier.

This requires us to separate match failures into two kinds: hard failures that produce errors that should never be swallowed, and soft failures such as a missing impl that lead us to merely discard an impl as a candidate. A flag has been added to `ImplScope` and `ArgumentDeduction` to specify whether soft failures should produce an error message or not.
2023-02-14 17:44:16 -08:00
Richard Smith 59ff7743c0 Expect parentheses after an alternative only if they were present in its declaration (#2605)
The design of choice types expects the declaration of an alternative to match the usage: if an alternative is declared as `None`, then it should be used as `None` not `None()`, and if it is declared as `None()` then it should be used as `None()` not `None`. Update explorer to match.

Also clean up the handling of choice types and alternative values a little in general, by moving away from identifying choice types and alternatives as strings and towards identifying them symbolically.

Closes #2422
2023-02-14 13:28:52 -08:00
Amr Hesham 98041d70c2 Explorer: error on bit-shift overflow (#2600)
Return Integer overflow Runtime error for bit shift if The second operand is less than zero or bigger than or equal bit width of the first operand in this case (32 bit for int)

Issue #2595
2023-02-13 08:01:24 -08:00
Adrien Leravat 266fa401e6 Explorer: assert Optional not empty on Get() (#2587)
Prevent from unwrapping an empty Optional
2023-02-09 22:39:43 -08:00
Richard Smith 4fa71e32f5 Add support for most kinds of declarations to be declared and used as namespace members (#2575)
Support for global variables is still missing; they're a bit more tricky because they use a pattern to introduce their name.

Prior to this change, explorer heavily relied on name comparisons to determine whether two declarations declare the same entity. Some of those instances are fixed in this PR, but more remain to be fixed, and some TODOs are added for some harder-to-fix instances.
2023-02-08 13:21:15 -08:00
Adrien Leravat 65078ea943 Explorer: make use of != in Carbon lit (#2586)
Swap `not (a == b)` for `a != b` in test now that we have it.
2023-02-07 10:10:45 -08:00
Richard Smith 1a8a41a5a6 Improve diagnostic for unknown name in name qualifier. (#2579)
As requested in #2572.
2023-02-03 16:05:08 -08:00
Richard Smith 6d4920148b Initial support for name lookup into namespaces. (#2572)
Name lookup into namespaces needs to be resolved early, as part of name resolution, so that we can properly diagnose references to entities before they are fully declared.  Make name resolution set a target `value_node` on simple member accesses that name namespace members, and in type-checking rewrite those member accesses into `IdentifierExpression`s that directly reference the namespace member.
2023-02-03 12:58:38 -08:00
Richard SmithandJon Ross-Perkins c172487395 Support for declaring functions within a namespace (#2569)
First step towards permitting declarations within namespaces. Supports only functions within namespaces for now, with no way to call those functions except from within other such functions. Unqualified lookups within a function in a namespace look in that namespace first.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-02-02 14:11:03 -08:00
Richard Smith 60af531f5b Support parsing namespace declarations (#2563)
Initial support for parsing namespace declarations and referring to namespace names. No support for declaring members of namespaces yet.
2023-01-30 17:25:44 -08:00
Adrien Leravat b4e3a3e6cc Explorer: fix class destructor not called with heap.Delete (#2546)
This change ensures that DestroyAction is executed for the value being deallocated when calling heap.Delete.

Relates to #2521
2023-01-24 11:34:47 -05:00