]> git.lizzy.rs Git - rust.git/blobdiff - docs/dev/syntax.md
internal: use idiomatic form of assertions
[rust.git] / docs / dev / syntax.md
index e138c656a72c5266060445f363b66ab25258c7cc..4f45aa321b3ba4a1a05e02aad0087320b7ee7571 100644 (file)
@@ -6,18 +6,18 @@ This guide describes the current state of syntax trees and parsing in rust-analy
 
 ## Source Code
 
-The things described are implemented in two places
+The things described are implemented in three places
 
 * [rowan](https://github.com/rust-analyzer/rowan/tree/v0.9.0) -- a generic library for rowan syntax trees.
 * [ra_syntax](https://github.com/rust-analyzer/rust-analyzer/tree/cf5bdf464cad7ceb9a67e07985a3f4d3799ec0b6/crates/ra_syntax) crate inside rust-analyzer which wraps `rowan` into rust-analyzer specific API.
   Nothing in rust-analyzer except this crate knows about `rowan`.
-* [ra_parser](https://github.com/rust-analyzer/rust-analyzer/tree/cf5bdf464cad7ceb9a67e07985a3f4d3799ec0b6/crates/ra_parser) crate parses input tokens into an `ra_syntax` tree
+* [parser](https://github.com/rust-analyzer/rust-analyzer/tree/cf5bdf464cad7ceb9a67e07985a3f4d3799ec0b6/crates/parser) crate parses input tokens into an `ra_syntax` tree
 
 ## Design Goals
 
-* Syntax trees are lossless, or full fidelity. All comments and whitespace are preserved.
+* Syntax trees are lossless, or full fidelity. All comments and whitespace get preserved.
 * Syntax trees are semantic-less. They describe *strictly* the structure of a sequence of characters, they don't have hygiene, name resolution or type information attached.
-* Syntax trees are simple value type. It is possible to create trees for a syntax without any external context.
+* Syntax trees are simple value types. It is possible to create trees for a syntax without any external context.
 * Syntax trees have intuitive traversal API (parent, children, siblings, etc).
 * Parsing is lossless (even if the input is invalid, the tree produced by the parser represents it exactly).
 * Parsing is resilient (even if the input is invalid, parser tries to see as much syntax tree fragments in the input as it can).
@@ -35,7 +35,7 @@ The syntax tree consists of three layers:
 * AST
 
 Of these, only GreenNodes store the actual data, the other two layers are (non-trivial) views into green tree.
-Red-green terminology comes from Roslyn ([link](https://docs.microsoft.com/en-ie/archive/blogs/ericlippert/persistence-facades-and-roslyns-red-green-trees)) and gives the name to the `rowan` library. Green and syntax nodes are defined in rowan, ast is defined in rust-analyzer.
+Red-green terminology comes from Roslyn ([link](https://ericlippert.com/2012/06/08/red-green-trees/)) and gives the name to the `rowan` library. Green and syntax nodes are defined in rowan, ast is defined in rust-analyzer.
 
 Syntax trees are a semi-transient data structure.
 In general, frontend does not keep syntax trees for all files in memory.
@@ -64,7 +64,7 @@ struct Token {
 }
 ```
 
-All the difference bettwen the above sketch and the real implementation are strictly due to optimizations.
+All the difference between the above sketch and the real implementation are strictly due to optimizations.
 
 Points of note:
 * The tree is untyped. Each node has a "type tag", `SyntaxKind`.
@@ -72,9 +72,9 @@ Points of note:
 * Trivia and non-trivia tokens are not distinguished on the type level.
 * Each token carries its full text.
 * The original text can be recovered by concatenating the texts of all tokens in order.
-* Accessing a child of particular type (for example, parameter list of a function) generarly involves linerary traversing the children, looking for a specific `kind`.
+* Accessing a child of particular type (for example, parameter list of a function) generally involves linearly traversing the children, looking for a specific `kind`.
 * Modifying the tree is roughly `O(depth)`.
-  We don't make special efforts to guarantree that the depth is not liner, but, in practice, syntax trees are branchy and shallow.
+  We don't make special efforts to guarantee that the depth is not linear, but, in practice, syntax trees are branchy and shallow.
 * If mandatory (grammar wise) node is missing from the input, it's just missing from the tree.
 * If an extra erroneous input is present, it is wrapped into a node with `ERROR` kind, and treated just like any other node.
 * Parser errors are not a part of syntax tree.
@@ -82,36 +82,35 @@ Points of note:
 An input like `fn f() { 90 + 2 }` might be parsed as
 
 ```
-FN_DEF@[0; 17)
-  FN_KW@[0; 2) "fn"
-  WHITESPACE@[2; 3) " "
-  NAME@[3; 4)
-    IDENT@[3; 4) "f"
-  PARAM_LIST@[4; 6)
-    L_PAREN@[4; 5) "("
-    R_PAREN@[5; 6) ")"
-  WHITESPACE@[6; 7) " "
-  BLOCK_EXPR@[7; 17)
-    BLOCK@[7; 17)
-      L_CURLY@[7; 8) "{"
-      WHITESPACE@[8; 9) " "
-      BIN_EXPR@[9; 15)
-        LITERAL@[9; 11)
-          INT_NUMBER@[9; 11) "90"
-        WHITESPACE@[11; 12) " "
-        PLUS@[12; 13) "+"
-        WHITESPACE@[13; 14) " "
-        LITERAL@[14; 15)
-          INT_NUMBER@[14; 15) "2"
-      WHITESPACE@[15; 16) " "
-      R_CURLY@[16; 17) "}"
+FN@0..17
+  FN_KW@0..2 "fn"
+  WHITESPACE@2..3 " "
+  NAME@3..4
+    IDENT@3..4 "f"
+  PARAM_LIST@4..6
+    L_PAREN@4..5 "("
+    R_PAREN@5..6 ")"
+  WHITESPACE@6..7 " "
+  BLOCK_EXPR@7..17
+    L_CURLY@7..8 "{"
+    WHITESPACE@8..9 " "
+    BIN_EXPR@9..15
+      LITERAL@9..11
+        INT_NUMBER@9..11 "90"
+      WHITESPACE@11..12 " "
+      PLUS@12..13 "+"
+      WHITESPACE@13..14 " "
+      LITERAL@14..15
+        INT_NUMBER@14..15 "2"
+    WHITESPACE@15..16 " "
+    R_CURLY@16..17 "}"
 ```
 
 #### Optimizations
 
 (significant amount of implementation work here was done by [CAD97](https://github.com/cad97)).
 
-To reduce the amount of allocations, the GreenNode is a DST, which uses a single allocation for header and children. Thus, it is only usable behind a pointer
+To reduce the amount of allocations, the GreenNode is a [DST](https://doc.rust-lang.org/reference/dynamically-sized-types.html), which uses a single allocation for header and children. Thus, it is only usable behind a pointer.
 
 ```
 *-----------+------+----------+------------+--------+--------+-----+--------*
@@ -123,7 +122,7 @@ To more compactly store the children, we box *both* interior nodes and tokens, a
 `Either<Arc<Node>, Arc<Token>>` as a single pointer with a tag in the last bit.
 
 To avoid allocating EVERY SINGLE TOKEN on the heap, syntax trees use interning.
-Because the tree is fully imutable, it's valid to structuraly share subtrees.
+Because the tree is fully immutable, it's valid to structurally share subtrees.
 For example, in `1 + 1`, there will be a *single* token for `1` with ref count 2; the same goes for the ` ` whitespace token.
 Interior nodes are shared as well (for example in `(1 + 1) * (1 + 1)`).
 
@@ -134,8 +133,8 @@ Currently, the interner is created per-file, but it will be easy to use a per-th
 
 We use a `TextSize`, a newtyped `u32`, to store the length of the text.
 
-We currently use `SmolStr`, an small object optimized string to store text.
-This was mostly relevant *before* we implmented tree interning, to avoid allocating common keywords and identifiers. We should switch to storing text data alongside the interned tokens.
+We currently use `SmolStr`, a small object optimized string to store text.
+This was mostly relevant *before* we implemented tree interning, to avoid allocating common keywords and identifiers. We should switch to storing text data alongside the interned tokens.
 
 #### Alternative designs
 
@@ -146,7 +145,7 @@ Another alternative (used by swift and roslyn) is to explicitly divide the set o
 
 ```rust
 struct Token {
-    kind: NonTriviaTokenKind
+    kind: NonTriviaTokenKind,
     text: String,
     leading_trivia: Vec<TriviaToken>,
     trailing_trivia: Vec<TriviaToken>,
@@ -162,12 +161,12 @@ Explicit trivia nodes, like in `rowan`, are used by IntelliJ.
 
 ##### Accessing Children
 
-As noted before, accesing a specific child in the node requires a linear traversal of the children (though we can skip tokens, beacuse the tag is encoded in the pointer itself).
+As noted before, accessing a specific child in the node requires a linear traversal of the children (though we can skip tokens, because the tag is encoded in the pointer itself).
 It is possible to recover O(1) access with another representation.
 We explicitly store optional and missing (required by the grammar, but not present) nodes.
 That is, we use `Option<Node>` for children.
 We also remove trivia tokens from the tree.
-This way, each child kind genrerally occupies a fixed position in a parent, and we can use index access to fetch it.
+This way, each child kind generally occupies a fixed position in a parent, and we can use index access to fetch it.
 The cost is that we now need to allocate space for all not-present optional nodes.
 So, `fn foo() {}` will have slots for visibility, unsafeness, attributes, abi and return type.
 
@@ -193,9 +192,9 @@ Modeling this with immutable trees is possible, but annoying.
 ### Syntax Nodes
 
 A function green tree is not super-convenient to use.
-The biggest problem is acessing parents (there are no parent pointers!).
+The biggest problem is accessing parents (there are no parent pointers!).
 But there are also "identify" issues.
-Let's say you want to write a code which builds a list of expressions in a file: `fn collect_exrepssions(file: GreenNode) -> HashSet<GreenNode>`.
+Let's say you want to write a code which builds a list of expressions in a file: `fn collect_expressions(file: GreenNode) -> HashSet<GreenNode>`.
 For the input like
 
 ```rust
@@ -207,7 +206,7 @@ fn main() {
 }
 ```
 
-both copies of the `x + 2` expression are representing by equal (and, with interning in mind, actualy the same) green nodes.
+both copies of the `x + 2` expression are representing by equal (and, with interning in mind, actually the same) green nodes.
 Green trees just can't differentiate between the two.
 
 `SyntaxNode` adds parent pointers and identify semantics to green nodes.
@@ -236,12 +235,12 @@ impl SyntaxNode {
         self.parent.clone()
     }
     fn children(&self) -> impl Iterator<Item = SyntaxNode> {
-        let mut offset = self.offset
+        let mut offset = self.offset;
         self.green.children().map(|green_child| {
             let child_offset = offset;
             offset += green_child.text_len;
             Arc::new(SyntaxData {
-                offset: child_offset;
+                offset: child_offset,
                 parent: Some(Arc::clone(self)),
                 green: Arc::clone(green_child),
             })
@@ -250,7 +249,7 @@ impl SyntaxNode {
 }
 
 impl PartialEq for SyntaxNode {
-    fn eq(&self, other: &SyntaxNode) {
+    fn eq(&self, other: &SyntaxNode) -> bool {
         self.offset == other.offset
             && Arc::ptr_eq(&self.green, &other.green)
     }
@@ -274,7 +273,7 @@ This is OK because trees traversals mostly (always, in case of rust-analyzer) ru
 The other thread can restore the `SyntaxNode` by traversing from the root green node and looking for a node with specified range.
 You can also use the similar trick to store a `SyntaxNode`.
 That is, a data structure that holds a `(GreenNode, Range<usize>)` will be `Sync`.
-However rust-analyzer goes even further.
+However, rust-analyzer goes even further.
 It treats trees as semi-transient and instead of storing a `GreenNode`, it generally stores just the id of the file from which the tree originated: `(FileId, Range<usize>)`.
 The `SyntaxNode` is the restored by reparsing the file and traversing it from root.
 With this trick, rust-analyzer holds only a small amount of trees in memory at the same time, which reduces memory usage.
@@ -285,9 +284,9 @@ They also point to the parent (and, consequently, to the root) with an owning `R
 In other words, one needs *one* arc bump when initiating a traversal.
 
 To get rid of allocations, `rowan` takes advantage of `SyntaxNode: !Sync` and uses a thread-local free list of `SyntaxNode`s.
-In a typical traversal, you only directly hold a few `SyntaxNode`s at a time (and their ancesstors indirectly), so a free list proportional to the depth of the tree removes all allocations in a typical case.
+In a typical traversal, you only directly hold a few `SyntaxNode`s at a time (and their ancestors indirectly), so a free list proportional to the depth of the tree removes all allocations in a typical case.
 
-So, while traversal is not exactly incrementing a pointer, it's still prety cheep: tls + rc bump!
+So, while traversal is not exactly incrementing a pointer, it's still pretty cheap: TLS + rc bump!
 
 Traversal also yields (cheap) owned nodes, which improves ergonomics quite a bit.
 
@@ -308,15 +307,15 @@ struct SyntaxData {
 }
 ```
 
-This allows using true pointer equality for comparision of identities of `SyntaxNodes`.
-rust-analyzer used to have this design as well, but since we've switch to cursors.
-The main problem with memoizing the red nodes is that it more than doubles the memory requirenments for fully realized syntax trees.
+This allows using true pointer equality for comparison of identities of `SyntaxNodes`.
+rust-analyzer used to have this design as well, but we've since switched to cursors.
+The main problem with memoizing the red nodes is that it more than doubles the memory requirements for fully realized syntax trees.
 In contrast, cursors generally retain only a path to the root.
 C# combats increased memory usage by using weak references.
 
 ### AST
 
-`GreenTree`s are untyped and homogeneous, because it makes accomodating error nodes, arbitrary whitespace and comments natural, and because it makes possible to write generic tree traversals.
+`GreenTree`s are untyped and homogeneous, because it makes accommodating error nodes, arbitrary whitespace and comments natural, and because it makes possible to write generic tree traversals.
 However, when working with a specific node, like a function definition, one would want a strongly typed API.
 
 This is what is provided by the AST layer. AST nodes are transparent wrappers over untyped syntax nodes:
@@ -342,7 +341,7 @@ pub struct FnDef {
 impl AstNode for FnDef {
     fn cast(syntax: SyntaxNode) -> Option<Self> {
         match kind {
-            FN_DEF => Some(FnDef { syntax }),
+            FN => Some(FnDef { syntax }),
             _ => None,
         }
     }
@@ -387,7 +386,7 @@ trait HasVisibility: AstNode {
     fn visibility(&self) -> Option<Visibility>;
 }
 
-impl HasVisbility for FnDef {
+impl HasVisibility for FnDef {
     fn visibility(&self) -> Option<Visibility> {
         self.syntax.children().find_map(Visibility::cast)
     }
@@ -397,7 +396,7 @@ impl HasVisbility for FnDef {
 Points of note:
 
 * Like `SyntaxNode`s, AST nodes are cheap to clone pointer-sized owned values.
-* All "fields" are optional, to accomodate incomplete and/or erroneous source code.
+* All "fields" are optional, to accommodate incomplete and/or erroneous source code.
 * It's always possible to go from an ast node to an untyped `SyntaxNode`.
 * It's possible to go in the opposite direction with a checked cast.
 * `enum`s allow modeling of arbitrary intersecting subsets of AST types.
@@ -437,13 +436,13 @@ impl GreenNodeBuilder {
 }
 ```
 
-The parser, ultimatelly, needs to invoke the `GreenNodeBuilder`.
+The parser, ultimately, needs to invoke the `GreenNodeBuilder`.
 There are two principal sources of inputs for the parser:
   * source text, which contains trivia tokens (whitespace and comments)
   * token trees from macros, which lack trivia
 
-Additionaly, input tokens do not correspond 1-to-1 with output tokens.
-For example, two consequtive `>` tokens might be glued, by the parser, into a single `>>`.
+Additionally, input tokens do not correspond 1-to-1 with output tokens.
+For example, two consecutive `>` tokens might be glued, by the parser, into a single `>>`.
 
 For these reasons, the parser crate defines a callback interfaces for both input tokens and output trees.
 The explicit glue layer then bridges various gaps.
@@ -491,7 +490,7 @@ Syntax errors are not stored directly in the tree.
 The primary motivation for this is that syntax tree is not necessary produced by the parser, it may also be assembled manually from pieces (which happens all the time in refactorings).
 Instead, parser reports errors to an error sink, which stores them in a `Vec`.
 If possible, errors are not reported during parsing and are postponed for a separate validation step.
-For example, parser accepts visibility modifiers on trait methods, but then a separate tree traversal flags all such visibilites as erroneous.
+For example, parser accepts visibility modifiers on trait methods, but then a separate tree traversal flags all such visibilities as erroneous.
 
 ### Macros
 
@@ -501,7 +500,7 @@ Specifically, `TreeSink` constructs the tree in lockstep with draining the origi
 In the process, it records which tokens of the tree correspond to which tokens of the input, by using text ranges to identify syntax tokens.
 The end result is that parsing an expanded code yields a syntax tree and a mapping of text-ranges of the tree to original tokens.
 
-To deal with precedence in cases like `$expr * 1`, we use special invisible parenthesis, which are explicitelly handled by the parser
+To deal with precedence in cases like `$expr * 1`, we use special invisible parenthesis, which are explicitly handled by the parser
 
 ### Whitespace & Comments
 
@@ -527,7 +526,7 @@ In practice, incremental reparsing doesn't actually matter much for IDE use-case
 
 ### Parsing Algorithm
 
-We use a boring hand-crafted recursive descent + pratt combination, with a special effort of continuting the parsing if an error is detected.
+We use a boring hand-crafted recursive descent + pratt combination, with a special effort of continuing the parsing if an error is detected.
 
 ### Parser Recap