Commit Graph
39 Commits
Author SHA1 Message Date
Jon Ross-Perkins a905cdea30 Improve parsing of invalid expressions. (#2726)
This addresses crashes for infix operator expressions, but the approach should more generally yield balanced parsed trees.
2023-03-31 20:51:59 -07:00
Jon Ross-Perkins e89fb83e7e Rename self/Self enums to SelfValueIdentifier/SelfTypeIdentifier (#2701)
Using `Identifier` because `self` and `Self` will resolve to different things. While `i32` uses `Literal`, it'd always resolve to the same type.
2023-03-22 10:07:09 -07:00
Jon Ross-Perkins d0105e119f Parse self in expressions. (#2697)
`self` wasn't being handled in expression logic, only parameter logic. This is needed for `self.x`.

Also renames SelfDeducedParameter to SelfIdentifier because it's parsed fairly consistently with Identifier; this better represents the situations where `self` will need to be handled, it's where `Identifier` is allowed (although `Identifier` could also refer to a type... but I still think `SelfDeducedParameter` is a more difficult to understand name).
2023-03-20 14:13:29 -07:00
Jon Ross-Perkins cf26249429 Replace BraceExpressionKind switches with parameters for better consistency. (#2686)
I've been heading this route with other parts of the parser because the overhead of adding enums and then switching on them felt tedious, and odd from a performance perspective to make calls when the caller knew the value to use. My leaning is towards this approach that makes it clearer what's actually different between the modes, and allows removing BraceExpressionKindToParserState. It's a mild code size decrease.
2023-03-16 10:51:00 -07:00
Jon Ross-PerkinsandRichard Smith d7ab71ba7d Parsing for generic and template parameters. (#2685)
Also cleans up some comments about related parse nodes. Currently basic and not heavily validated.

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-03-16 10:50:35 -07:00
Jon Ross-Perkins 7d553107dd Extend deduced and regular parameter handling to types. (#2684)
This makes it possible to specify both deduced and regular parameters on types. It reorganizes the handling of parameter lists in order to allow more reuse of code in this approach. Both functions and types use the new DeclarationNameAndParams handling. Overall the goal here is to take advantage of commonality in structure.

Regarding destructors, the likely approach would be to use ParameterListAsDeduced directly because `destructor` is a keyword with no declaration name and no regular parameters.
2023-03-16 09:06:45 -07:00
Jon Ross-PerkinsandChandler Carruth 51f887c348 Add a macro to simplify XAsY variant state generation (#2679)
This is just a mild simplification to address repeat macro use. I'm hoping it makes it clearer and easier in parser_state.def to write down the multiple variants.

I'm writing these macros in a simple form that I think is easy to read, versus some complex macro recursion which I think is _possible_ but would be harder to reason. And, we don't really need arbitrary arg counts -- this is probably going to stay fairly limited long-term, although I could easily see something like a half dozen in some cases so maybe I'll be wrong and it'll go higher. But, I feel like these macros still make it easier to focus on the _intent_ of cases, rather than visually comparing each line for differences.

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-03-14 10:19:40 -07:00
Jon Ross-Perkins e613ad5323 Reorganize interface parsing so that it's shared with class and constraint (#2666)
We could similarly add others -- this is intended to make it easy to add more that parse essentially the same.

The functionality expected is that types will use GetDeclarationContext in order to error on certain functionality in the declaration scope loop. e.g., with how constraints and interfaces currently don't allow definitions.

I've only moved out `package` because it's only valid on the top line. It might still be good to parse it later, but with slightly different logic because it would always be an error, and the declaration context isn't quite the right framing for that.

Also unifies some errors with `fn`.
2023-03-13 17:24:01 -07:00
Jon Ross-Perkins b35e803a7f Fold deduced pattern parsing into the general pattern parsing. (#2649)
Depends on #2646 

Right now, deduced parameter handling is very narrow to `self` support. This folds it into pattern handling, which should eventually be a superset of deduced parameter support, so this will avoid more duplication of logic.

Note, this subtly adds handling of multiple deduced parameters, but not generic parameters (`:!`) so it's still not quite right.
2023-03-07 09:27:55 -08:00
Jon Ross-Perkins 4083d7f5b9 Reorganize interface parsing to be more consistent with other declarations. (#2646)
The comments in parse_node_kind.def capture the change being made here.

Before:

```
//   _external_: DeclaredName
//     InterfaceBodyStart
//     _external_: statements
//   InterfaceBodyEnd
// InterfaceDefinition
```

After:

```
//     InterfaceIntroducer
//     DeclaredName
//   InterfaceDefinitionStart
//   _external_: declarations
// InterfaceDefinition
```

Really I just want to treat introduced things consistently. `var` defines my philosophy here: it doesn't always have a `DeclaredName`, so the `VarIntroducer` _must_ be the bounding node. By being consistent with that, I believe that overall the structure becomes easier to understand (that is, there are fewer inconsistencies to understand).

This also adds InterfaceDeclaration, since I think it can be predicted we'll have that, and it's helpful for making recover consistent with HandleDeclarationError.

Similarly, I'm also trying to standardize the loop processing a little with HandleDeclarationLoop. In the current approach, InterfaceDefinitionFinish isn't a necessary state, so I'm removing it.
2023-03-06 16:31:01 -08:00
Jon Ross-Perkins 28327a00a9 Replace ParseContext with an examination of state_stack_. (#2645)
Per [discussion](https://discord.com/channels/655572317891461132/655578254970716160/1078427629427904563), there's a preference for having the support this enables in the parser. For example, that the parser should detect and error on a non-default interface function's definition.

However, we do need to handle nesting of declarations. We could do that by making this a stack. I think though that it'll be more efficient to keep using state_stack_, since it'll be called in places which are a limited number of steps from the actual state. That may already be in cache since we frequently look at state_stack_, so I'm uncertain that maintaining an additional stack would be a net benefit.
2023-03-06 15:09:48 -08:00
Jon Ross-Perkins 22d7cd19ed Polish out support for reals and strings. (#2593)
Reals were mostly handled, but this PR adds storage of them. It also switches a little towards the FloatingPointType semantic from TokenizedBuffer.

While real literals like `1.0` were handled, the type literals were not. This just adds `f64`, similar to how I also only support `i32`.

The String type literal wasn't used, so I've added support in lexer and parser. Per discussion with @zygoloid String might be renamed based on the newer type literal plan, but it's still String in explorer and the design, so this is just consistent.

The builtin_types.carbon tests the three basic types that are there right now. The test is added to both parser and semantics so that it's clear what the state is in both stages.
2023-02-13 08:04:49 -08:00
Jon Ross-Perkins 82f7d06855 Fix function parameter parsing past 2 params. (#2542)
The comment on FunctionParameterFinish is actually correct (`1. FunctionParameter`), just a typo in the implementation. It specifically failed parsing at the comma after the 2nd param, regardless of whether there were more params.
2023-01-23 13:28:34 -08:00
Jon Ross-Perkins 94872ef6da Change TokenKind's Print overload to a format_provider. (#2534)
Fundamentally this `.Print()` is wrong for debug output at present because `.fixed_spelling()` can be empty. It's also inconsistent with other enums to use it. We frequently print tokens for debugging, and it's easy to forget to specify `.name()` there.

Diagnostics use formatv, so we can provide a format_provider and address it in one spot that way. It also makes it harder to just forget to do the right thing.
2023-01-18 12:20:56 -08:00
Jon Ross-PerkinsandChandler Carruth 78ac6cb7d1 Switch TokenKind to EnumBase (#2509)
This shouldn't have any behavior change, it's just using #2504

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-01-05 14:11:30 -08:00
Jon Ross-Perkins 97634a5e91 Switch ParseNodeKind to EnumBase (#2510)
This shouldn't have any behavior change, it's just using #2504
2023-01-05 13:33:32 -08:00
Richard Smith 4daaa4866f Rename Type -> type, per #2360. (#2507)
Also make minor updates to the skeletal design in
docs/design/name_lookup.md following #2113, as there are no longer any prelude names that are made available to unqualified name lookup by default.

Add `type` to the keyword list in
docs/design/lexical_conventions/words.md, following #2360.
2023-01-04 14:22:30 -08:00
Chandler CarruthandJon Ross-Perkins a1ad39fa29 Introduce helpers to build enum-wrapping classes. (#2504)
The goal here is to (significantly) reduce the boilerplate needed when defining classes that wrap enums, especially those managed with the `.def`-file style X-macros that are common in the toolchain.

This should also provide both better and more consistent functionality to those classes once ported over to it.

Initially, only `ParserState`, `SemanticsNodeKind`, and `SemanticsBuiltinKind` are ported as these were also the three that JonMeow ported in his original pull/2453 "option 5". This is heavily based on that version of the code.

Goals I was considering that influenced the design:

- Keep the individual enum-wrapping classes as simple and easy to read as possible. Especially important is keeping the `.def` files that are often filled with really important documentation clean and easy to maintain over time.

- Don't rely on computed `#include`s as that is an especially dark corner of the preprocessor and breaks some build systems.

- Have a really good API of the enum-wrapping class, including nice constant names for the values, easy printing, and even easy debugger-callable methods to get the name (as opposed to the integer value).

- Keep the API that users interact with in the base class as clean and easy to read as possible.

- Reduce the boiler plate for each instance of these as much as possible.

- Avoid excessive inline generated code or constants that would result in steady growth in object file sizes and linker effort doing deduplication.

These goals aren't always compatible, so we end up needing to pick a compromise between them when in tension. I think this version is a pretty good compromise.

The original version I started with already pull most of the API into a CRTP-style base class. This version pulls *all* of the common API. This is the main tool for getting consistency and avoiding duplication. However, connecting this base class to the individual enum wrappers is still difficult. Some specific changes here that try to do as much as possible there:

- Use a slightly fancier macro pattern to reduce the boilerplate of defining the raw `enum class` prior to the wrapper class.

- Use a macro to simplify naming the base class.

- Move the name table to a `.cpp` file to avoid every inclusion generating a complete copy of the strings (that the linker has to deduplicate). This is done with some care to sharply reduce the boilerplate needed in that `.cpp` file.

- Sink the name _API_ fully into the CRTP base class. This requires some significant complexity in the implementation, but all of that is hidden behind a single implementation detail macro, and the API itself is simple and readable. This also makes it much more reasonable to test the entire system a single time next to the base class.

This version also moves from constant factory functions to normal constants. This requires two batches -- first a declaration, and then a definition -- but the API result is significantly better and similar to the original option, the macro structure reduces the cost of these. Unfortunately that makes the adoption a bit noisy, but I think its worth the churn.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-01-04 12:33:06 -08:00
Jon Ross-Perkins 11deb14dc6 Handle var init-with-self situations. (#2488)
The problem I'm trying to solve is: `var x: i32 = x;`. This change makes it so that name lookup fails, by removing `x` from name lookup between the `=` and `;`.

`var x: i32` still adds to name lookup to handle future situations like `var (x: i32, x: i32);` which is still a redefinition of `x`; if we don't add `x` to name lookup, it gets harder to catch that example.

The VariableDeclaration/VariableInitializer refactor in ParseTree supports this by given a bracketing-like structure for semantics to cue that it's entering an initialization expression. With this, VariableInitializer can remove the name lookup and queue it to be restored. VariableDeclaration doesn't need to change too much since it's still bracketed by VariableIntroducer, and so we just traverse slightly differently.

Note this also incidentally changes a little about NameReference, that it's returning the storage consistently instead of the name. You can see this e.g. in global_lookup.carbon, `Assign(node8, node4): node2;` using node4 (VarStorage) instead of Node5 (BindName). Really either _could_ work, since from a BindName we can get to the VarStorage, and that may be reason to switch later if we find it preferable to have the BindName for whatever reason.

But the *actual* value in NameLookup is a BindName so that errors can associate with the _name_ instead of the "storage" parse node, which is currently the `:`. This is mainly for fail_duplicate_decl.carbon, which has a "Previous definition" note that points at the storage's parse node.
2022-12-28 12:55:40 -08:00
Jon Ross-Perkins 733965704a Start building some checking of diagnostic use. (#2487)
In theory we're doing a central registry so that we can ensure there's at least one test for each. This isn't doing that, but I'm trying to validate that the central registry isn't leading to duplicates or abandoned checks (and catching a couple of each).
2022-12-27 08:43:58 -08:00
Jon Ross-Perkins 5d123189c3 Small cleanups in toolchain code (#2474)
Doing some sorting of functions / enums (generally speaking, I've been trying to keep these loosely lexically sorted for lack of a better ordering).

Also removes some code that seems to be dead, and a minor TODO comment fix.
2022-12-16 15:46:53 -08:00
Kareem Ergawy c74e39dbb3 [parser] More support for interfaces: methods and self deduced param. (#2427)
Summary:

Extends the current support for parsing `interface`s. In particular, adds support for parsing functions and `me` params.
2022-12-16 11:23:02 -08:00
Jon Ross-Perkins d42d864e82 Make TokenKind's API closer to toolchain's typical API setup. (#2456)
This is somewhat based on the name vs Name difference, but I figured I'd split it out and just sweep up the API on the whole while looking at a different approach to #2453
2022-12-08 15:31:04 -08:00
Jon Ross-Perkins 60eb06ce94 Move trace banners to driver and trace intermediate state. (#2443)
Printing intermediate state should be helpful to be able to examine the input when debugging later steps.

Intermediate state is hard to trace from the individual libraries since they don't know whether `dump` is going to print the state, so this moves some trace logic into the driver which is better equipped to make the decision.
2022-12-07 09:17:54 -08:00
Chandler CarruthandJon Ross-Perkins 94cf343b05 Update LLVM and switch to std::optional. (#2424)
LLVM's bazel build has changed a bit, so this updates the tree for that.

LLVM is also moving `llvm::Optional` to match the standard API, but it seemed simpler to just switch to `std::optional`.

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2022-12-01 09:22:43 -08:00
Jon Ross-Perkins 16bbdbbdb8 Add vlog output to the parser. (#2435)
Might eventually want to change this further, but I'm just adding the quick framework for it.
2022-11-30 17:28:49 -08:00
Jon Ross-Perkins 6bfd202f4e Finish bracketing of parse nodes. (#2430)
- Finishes remaining "todo" parse nodes.
- Improving error recovery for invalid designators and structs, so that the parse tree still looks similar to a valid parse tree.
- Call expressions now have the thing being called as a child (of the start) instead of a sibling.
- Use of Start is replacing use of End in several parse nodes, like structs and call expressions.
- Adjusting documentation of parse node structures in an attempt to make it more consistent and understandable.
- The current state for interfaces and if/else is mostly being documented, not altered.
2022-11-30 09:14:07 -08:00
Jon Ross-PerkinsandChandler Carruth 84deb62aef Work on ParseTree structure to use more bracketed structures. (#2416)
This works on multiple statements to make them better for the bracketing model. Stub nodes are added in more cases of invalid syntax, simply so that the semantics has reliably structured input. Comments in parse_node_kind.def now try to show the expected parse tree structure in postorder form.

This labels If, While, and For a little differently in parse nodes so that at the start of the postorder traversal, it'll already be available to semantics which structure is being processed. I need to do a little more with If in particular, but this felt like a reasonable stopping point.

While this makes significant parser changes, the changes to parser_state.def are minimal, mostly naming-related. The actual flow isn't substantively changed, just a couple minor names and the new As(If|While) state which allows distinguishing IfCondition and WhileCondition.

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2022-11-28 15:02:59 -08:00
Kareem Ergawyandergawy a508390423 [parser] Start re-implementing interfaces using the stack parser. (#2412)
First change towards re-implementing interfaces using the new parser. I kept it small to make sure we are on the same page regarding stack states and how the parse tree should look like.

Co-authored-by: ergawy <kareem.ergawy@guardsquare.com>
2022-11-28 12:58:41 -08:00
Jon Ross-Perkins d9ce1827c8 Adjust how invalid declarations pass errors. (#2413)
When there's no semicolon for an invalid EmptyDeclaration, rather than producing nothing, produce an EmptyDeclaration with the original location that led to the error.

Note this removes a direct edit (the only one) of the parse tree's error state. Elsewhere it's an indirection from adding an error node.
2022-11-18 08:02:07 -08:00
Jon Ross-Perkins adac572430 Replace some reference members with pointer members. (#2408)
I'd noted this while rewriting the parser and, while I kept it there during conversion, I think switching is consistent with the higher-level desire and the use of references therein was just an oversight.

Discussed at:
https://discord.com/channels/655572317891461132/655578254970716160/1042551242813083840
2022-11-17 08:58:43 -08:00
Jon Ross-Perkins fbed1398fe Change ParameterList to use a Start that brackets params (#2403)
The code change is small here. I'm breaking this out because it has a lot of test churn, and semantics doesn't have significant logic around it yet.
2022-11-17 08:57:22 -08:00
Jon Ross-Perkins 5da32bd560 Rename to StructLiteralOrStructTypeLiteralStart (#2404)
As requested
2022-11-17 08:56:48 -08:00
Jon Ross-Perkins dc23f6305d Use Consume() more where possible. (#2397)
Just trying to standardize the use in a few spots; no behavioral change.
2022-11-15 22:45:47 -08:00
Jon Ross-Perkins c165ab6c2b Change StructLiteral and StructTypeLiteral parsing to use an ambiguous start. (#2396)
This is necessary in order to use a bracketing approach; parsing doesn't know the contained format until it parses the first element, which we don't want to do look-ahead for. I think the bracketing is higher value than knowing the format before adding the node.
2022-11-15 22:44:57 -08:00
Jon Ross-Perkins b914f46ec5 Change keyword statements to bracket arguments. (#2394)
This changes `return`, `break`, and `continue` to treat the keyword as the "start" and semicolon as the "parent", essentially bracketing the keyword.

Pragmatically this is focusing on making `return` work with only one ParseNodeKind: because `return` and `;` now bracket the expression, we can tightly determine whether the `return` has arguments without looking at subtree size. However, it's possible that `break` and `continue` may in the future take some kind of label as an argument, so the consistency seems beneficial there too.

Note this eliminates the StatementEnd ParseNodeKind, as it's obsolete with this change.
2022-11-15 22:42:54 -08:00
Jon Ross-Perkins 310cf0d2f9 Refactor Pattern and FunctionParameter handling for Parser consistency (#2385)
While the Parser has similar divergent states, lists of Expressions tend to be handled more like this. I'm keeping the divergent start state in order to continue support of a distinct error, but I think this organization of FunctionParameter/FunctionParameterFinish will be less surprising.
2022-11-15 22:36:52 -08:00
Jon Ross-Perkins b163aaaf74 Add a ForIn node for a , move the error (#2387)
This is to keep the tree consistent with the error-free state. It also more precisely locates the error.
2022-11-14 13:17:58 -08:00
Jon Ross-Perkins 6433a1bab6 Rename Parser2 to Parser, and delete the original (#2383) 2022-11-11 13:35:45 -08:00