Skip to content

Parser trivia refactor - #4364

Closed
wrzian wants to merge 24 commits into
typst:mainfrom
wrzian:parser_trivia_refactor
Closed

wrzian wants to merge 24 commits into
typst:mainfrom
wrzian:parser_trivia_refactor

Conversation

@wrzian

@wrzian wrzian commented Jun 10, 2024

Copy link
Copy Markdown
Contributor

Draft refactor for discussing how the parser should handle trivia.

See detailed explanation in this thread: https://discord.com/channels/1054443721975922748/1088371867913572452/1249492570380435496

@wrzian

wrzian commented Jun 10, 2024

Copy link
Copy Markdown
Contributor Author

At @Myriad-Dreamin's request I have copied everything I wrote from the discord thread below:

Re, this comment: #3786 (comment)

Also, and this is out of scope, I would be interested in simplifying the parser interface somewhat (and adding comments/documentation) in a future PR if that would be desired.

In principle yes, but let's best first discuss it a bit, so that we're on the same page about what changes would be desirable. If you're on the Discord, doing it there in <#1088371867913572452> would be simplest.

I think the current Parser impl (bottom of parser.rs) has one particular issue that echoes out into the rest of the parser and has both performance and cleanliness implications: it doesn't abstract trivia properly for math and code mode. This core issue is exacerbated by small function naming ambiguities that make the parser harder to reason about than it should be in math/code. I don't have all the answers, but I have some partially-implemented ideas for changes to simplify the parser and would like to discuss them!

Concretely, the parser tries to abstract trivia (spaces/newlines/comments) from Math/Code mode by keeping track of prev_end and current_start indices into the overall text string which represent the end of the last non-trivia token (so the start of any trivia token) and the start of the current non-trivia token. (Note that Markup mode handles trivia manually during parsing, so isn't really relevant here)

The invariant that Math and Code shouldn't need to think about trivia when parsing is only enforced ad-hoc by the parser and has been the cause of a number of bugs (one of which I fixed!). I think we could improve this by representing the presence of leading trivia over the current node in the type-system via an Option type, and also representing the current token's text and kind together in an actual Token struct as the current element.

An example issue with the trivia invariant is the wrap() function. To get the end marker for wrapping, wrap() calls before_trivia() which does a full reverse iteration over nodes in order to find the last non-trivia node's index before calling wrap_within() and then nodes.drain() on the indices. If we instead just keep that index inside of a trivia Option type, then we can avoid this loop. Similar issues exist in the unskip() function, which is only called in three locations, that could each be simplified.


My main desired outcome is to make it impossible to represent the state where the parser is in math/code and Parser:current is a trivia node.

I'm thinking of achieving this with the following changes:

  1. Remove the skip(), unskip(), lex() functions, and fold their behavior into a new lex_past_trivia() function which updates the nodes and skips trivia correctly, paired with a re_lex() function, that just truncates nodes to before the trivia, then calls lex_past_trivia() again from that point.

  2. Replace prev_end, current_start, and current with two new elements
    a. prev_end tracked the existence of leading trivia, we instead start to track trivia in math/code with a value trivia_start: Option<Triv{node: Marker, text_offset: usize}>, now representing whether there was leading trivia at all, the starting index of the leading trivia node, and the starting position of the trivia in text for jumping the lexer.
    b. current_start and current (in combination with the implicit lexer.cursor()) tracked the string slice for the current token and its kind. I think it would be better to give the parser a new struct: current: Token{kind, text} that greedily gets lexer.cursor() and is always valid. I think these Token structs would be well placed in the Lexer, but aren't necessary there.

    (Note that these are effectively identical to leaf nodes in nodes.rs when they're first constructed, lacking only a default constructed Span, and with their text still referencing the parser's text, instead of as a new EcoString)


As for function naming, I think the ambiguity of Parser::current(), Parser::eat(), and Parser::wrap() adds a lot to this annoyance, especially with Parser::eat() not having any comments and its body literally just being { save(); lex(); skip(); }.

My main note on these is that current() really acts like a peek() function, since its token is not yet part of the nodes vector. Then save(), just saves the current node as a leaf node, and eat() combines save() with moving the lexer forward, but also skipping trivia. In my changes, lex() and skip() would no longer be separate, and I think every place that would normally call save() could then be replaced entirely by just eat().

I don't know that the functions need to be changed, doc-comments about their behavior will likely suffice 😁, but slight naming changes could be helpful!

@wrzian
wrzian marked this pull request as ready for review June 17, 2024 15:30
@wrzian

wrzian commented Jun 17, 2024

Copy link
Copy Markdown
Contributor Author

As an aside, I was also looking into the following patch to improve the Parser::finish() function, but wasn't able to make it work cleanly due to failing some tests in how I believe code-mode gets re-parsed. I think it might be fixed if the parser is instantiated with text as the exact range that it needs to re-parse, but I haven't looked into how that's used elsewhere in-detail yet.

Here's the patch, apply with `git apply`.
diff --git a/crates/typst-syntax/src/parser.rs b/crates/typst-syntax/src/parser.rs
index 4a2fd5c6..d0470548 100644
--- a/crates/typst-syntax/src/parser.rs
+++ b/crates/typst-syntax/src/parser.rs
@@ -15 +15 @@ pub fn parse(text: &str) -> SyntaxNode {
-    p.finish().into_iter().next().unwrap()
+    p.finish_as_root()
@@ -21,4 +21,3 @@ pub fn parse_code(text: &str) -> SyntaxNode {
-    let m = p.before_trivia();
-    code_exprs(&mut p, |_| false);
-    p.wrap_within(m, p.marker(), SyntaxKind::Code);
-    p.finish().into_iter().next().unwrap()
+    code(&mut p, |_| false);
+    // Note that trailing trivia right here is an annoying edge case.
+    p.finish_as_root()
@@ -31 +30 @@ pub fn parse_math(text: &str) -> SyntaxNode {
-    p.finish().into_iter().next().unwrap()
+    p.finish_as_root()
@@ -828,2 +827 @@ pub(super) fn reparse_block(text: &str, range: Range<usize>) -> Option<SyntaxNod
-    (p.balanced && p.prev_end() == range.end)
-        .then(|| p.finish().into_iter().next().unwrap())
+    (p.balanced && p.prev_end() == range.end).then(|| p.finish_as_root())
@@ -1618,0 +1617,7 @@ impl<'s> Parser<'s> {
+    /// Consume the parser, yielding the root SyntaxNode of the parsed syntax tree.
+    fn finish_as_root(self) -> SyntaxNode {
+        assert!(self.current.kind == SyntaxKind::End);
+        assert!(self.nodes.len() == 1);
+        self.nodes.into_iter().next().unwrap()
+    }
+
@@ -1764 +1769,5 @@ impl<'s> Parser<'s> {
-        self.wrap_within(from, self.before_trivia(), kind);
+        if self.at(SyntaxKind::End) {
+            self.wrap_within(from, self.before_trivia(), kind);
+        } else {
+            self.wrap_within(from, self.marker(), kind);
+        }

@laurmaedje laurmaedje left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing I've talked about with @PgBiel recently is allowing the lexer to return not just tokens but full subtrees for specific cases where it's simpler to handle at the lexer stage. This currently concerns only raw blocks, but might expand to other stuff in the future.

Do you think this makes sense and, if yes, how would it integrate with these changes, in particular with the Token struct?

Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
@wrzian

wrzian commented Jun 26, 2024

Copy link
Copy Markdown
Contributor Author

One thing I've talked about with @PgBiel recently is allowing the lexer to return not just tokens but full subtrees for specific cases where it's simpler to handle at the lexer stage. This currently concerns only raw blocks, but might expand to other stuff in the future.

Do you think this makes sense and, if yes, how would it integrate with these changes, in particular with the Token struct?

I would be a fan of that change. It would also be really convenient for math parsing as it could simpify both field access and primes.

I think an interesting direction could be to make lexer::next() just return a full SyntaxNode, which the parser would place as its current node, then we don't need a token struct and don't have to convert the node in the Parser. I think this would be reasonably clean and could probably remove the error: Option<SyntaxError> field from the Lexer.

Not sure if there would be any big downsides, although this might end up adding a constant Span::detatched() that would be needlessly copied, so I could see this either improving or hurting performance. Would need to measure.

@wrzian

wrzian commented Jun 26, 2024 •

Copy link
Copy Markdown
Contributor Author

Just commited a change to put NewlineMode inside LexMode::Code. I think this is a lot cleaner than before and really centralizes the relevant code. However there are still a few code sections I'm not sure about. Let me know what you think.

@PgBiel PgBiel mentioned this pull request Jun 26, 2024
5 of 8 tasks
@PgBiel

PgBiel commented Jun 26, 2024

Copy link
Copy Markdown
Contributor

The next() -> SyntaxNode change has been implemented for #4459 , @wrzian feel free to share any possible suggestions :)

I took the approach of not changing the internal lexer stuff too much for now. That is, take_error is still there, as most functions were not changed (still return SyntaxKind). But take_error is now a private function in the lexer, since it eventually (at next()) converts the syntax kinds to nodes without any intervention from the parser.

@laurmaedje laurmaedje added the waiting-on-review This PR is waiting to be reviewed. label Jul 7, 2024
@laurmaedje

Copy link
Copy Markdown
Member

Sorry for the slowness here, but I'd prefer to wait for #4459 to be merged before proceeding here.

@laurmaedje laurmaedje added blocked This PR is blocked by something. and removed waiting-on-review This PR is waiting to be reviewed. labels Jul 15, 2024
@laurmaedje laurmaedje removed the blocked This PR is blocked by something. label Aug 7, 2024
@wrzian

wrzian commented Aug 7, 2024

Copy link
Copy Markdown
Contributor Author

Ok, I think this is in a good spot to review now. I didn't fully make the lexer return SyntaxNodes, but I did make the motion of the error case more explicit, although I couldn't find a better method to organize them, and I feel like the cost of making current into a full syntaxnode (thus requiring checking the type on every access) outweighs the benefits.

@wrzian
wrzian force-pushed the parser_trivia_refactor branch from 3020889 to e38713e Compare August 7, 2024 23:48
Comment thread crates/typst-syntax/src/lexer.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
@laurmaedje laurmaedje added the waiting-on-author Pull request waits on author label Aug 15, 2024
@wrzian
wrzian force-pushed the parser_trivia_refactor branch from b59735b to 3342deb Compare September 3, 2024 04:14
@wrzian

wrzian commented Sep 3, 2024

Copy link
Copy Markdown
Contributor Author

Just rebased onto main and amended a change for #4869 in the lexer mode -> closures commit.

@wrzian

wrzian commented Sep 3, 2024 •

Copy link
Copy Markdown
Contributor Author

Ok, I put together a simple pair of scripts to measure parser timing.

My test file is the concatenated sources of
typst-examples-book.
You can make your own version by cloning the repo and using ripgrep:

git clone [email protected]:sitandr/typst-examples-book.git examples-book
cd examples-book/src
OUTFILE="typst-examples-all.typ"
rg --sort=path --pcre2 -I -U '^(`+)\s*typ(((?!\1)(?s:.))+)\1' -r '$2' > $OUTFILE

This gives about 5000 lines of code and markup, which feels about right
for a parser testbench. Note that the file doesn't actually compile, but
it does parse without error, which is all we need here.

On main, my laptop takes around 4400 us (4.4ms) to parse this. With the current
changes in this PR there's no notable difference.

I got these from the following scripts by using the existing --timings
flag and pulling out the delta for the "parsing file" item.

Initial run-timings.sh script.

Note: Requires installing jq for JSON parsing.

#!/usr/bin/sh
# Run timing compilation
USAGE="$0 <BIG_FILE> <BUILD_DIR>"

for f in "$1" "$2"; do
    if test ! -e "$f" ; then
        echo "'$f' doesn't exist."
        echo $USAGE
        exit 1
    fi
done

echo "Using the release build in '$2'"
EXE="$2/target/release/typst"

if test ! -e "$EXE" ; then
    echo "'$EXE' doesn't exist."
    echo "Rebuild with: cargo build --release"
    exit 1
fi

TIMING_JSON="time-$(basename "$2").json"

CMD="$EXE compile --ignore-system-fonts $1 --timings $TIMING_JSON"
echo Running: "$CMD"
$CMD
echo Output is in: "$TIMING_JSON"

NAME_SEARCH='parsing file'
echo "Getting timing for item: '$NAME_SEARCH'"
MICROSEC=$(jq "map(select(.name == \"$NAME_SEARCH\") | .ts) | (.[1] - .[0]) | round" $TIMING_JSON)
echo "Ran in $MICROSEC us"

avg-timings.sh to run 100 times and get the average.

#!/usr/bin/sh
# Average over many timing runs
USAGE="$0 <BIG_FILE> <BUILD_DIR>"

for f in "$1" "$2"; do
    echo $f
    if test ! -e "$f" ; then
        echo "'$f' doesn't exist."
        echo $USAGE
        exit 1
    fi
done

N=100
echo "Running $N times..."

OUTFILE="times-$N-$(basename "$2").json"
echo > "$OUTFILE"
for i in $(seq 1 $N); do
    MICROSEC=$(./run-timings.sh "$1" "$2" 2> /dev/null | sed -E -n 's/Ran in (.+) us/\1/p');
    echo $MICROSEC >> "$OUTFILE"
done

# Why is this the best way to get an average from the shell? Ugh.
AVG=$(awk '{sum += $1; count += 1} END {printf "%i\n", sum/count}' "$OUTFILE")
echo "Average: $AVG us"
rm "$OUTFILE"

@wrzian

wrzian commented Sep 8, 2024

Copy link
Copy Markdown
Contributor Author

Completed the change to make the Lexer return full SyntaxNodes and implemented this for Raw nodes. With the timing check I've found that returning SyntaxNode adds about a 6% performance hit to the parser, but this is likely acceptable given that eval and layout are usually the dominating performance issue.

I'll also copy another note I made on Discord:

One problem I ran into was an annoying lifetime issue with SyntaxNode:

The Parser::current_text() function currently returns a &str borrow from the original source text (the 's lifetime that the parser contains), but since SyntaxNodes own their string, changing current_text to use SyntaxNode::text() now has a lifetime matching the parser itself, which differs and causes issues.

My temporary solution is to convert to an EcoString and clone it in a number of places where the current_text() method is used (it still returns a &str when possible). This mostly affects the hashmaps used for function arg named-parameters. It might be possible to reduce this with a lot of extra lifetime annotations in the right spots, but it would be a bit of work.

But for now, I think this is ready for another round of review!

@wrzian
wrzian requested a review from laurmaedje September 8, 2024 04:46
@laurmaedje laurmaedje removed the waiting-on-author Pull request waits on author label Sep 8, 2024
Comment thread crates/typst-syntax/src/lexer.rs Resolved
Comment thread crates/typst-syntax/src/lexer.rs Outdated
Comment on lines +19 to +25
/// The state held by raw line lexing. This is emptied into an inner SyntaxNode before
/// returning from [`lex_past_trivia`].
raw: Vec<SyntaxNode>,
/// An error for the last token.
///
/// This is present to increase convenience when returning an error by avoiding the
/// need to manually return an error from most lexer functions.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like mentioned in another comment, it feels somewhat unfortunate that we still keep raw and error even though they are not really necessary with the new design.

@wrzian wrzian Sep 11, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could see that as an option, but if we did make that change, then we would likely make most of the other lexer functions return a Result type or other wrapping enum. I could be convinced of this, but I'm not sure how helpful it is.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would have thought just a SyntaxNode. Not sure how it affects performance, but overall I think it would reap the rewards of the whole refactor.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's going to help that much at this stage. I tried converting Lexer::error() into creating a syntax node and it just adds a ton of noise everywhere.
I also did a draft of moving the raw Vec into the raw function and having it return a SyntaxNode, but it has annoyances due to how Lexer::code is currently called when checking for the newline mode.

@wrzian wrzian Sep 13, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do think the change for math field accesses is a win. Curious what your thougts are there.

Comment thread crates/typst-syntax/src/lexer.rs Resolved
Comment thread crates/typst-syntax/src/lexer.rs Resolved
Comment thread crates/typst-syntax/src/lexer.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
Comment thread crates/typst-syntax/src/parser.rs Resolved
@wrzian
wrzian force-pushed the parser_trivia_refactor branch 4 times, most recently from ca4bb41 to 0ddd977 Compare September 13, 2024 04:35
@wrzian
wrzian requested a review from laurmaedje September 13, 2024 04:36
@wrzian
wrzian force-pushed the parser_trivia_refactor branch from f15c24d to bea8405 Compare September 23, 2024 09:10
@wrzian
wrzian force-pushed the parser_trivia_refactor branch from bea8405 to e866992 Compare September 23, 2024 09:14
@laurmaedje laurmaedje added the waiting-on-review This PR is waiting to be reviewed. label Sep 26, 2024
@laurmaedje

Copy link
Copy Markdown
Member

Sounds good, I'll take a closer look and hopefully we'll get this merged after 0.12. I wouldn't want to make such a big change so close to the release.

@wrzian

wrzian commented Oct 22, 2024

Copy link
Copy Markdown
Contributor Author

FYI I've been working on reorganizing these commits and am effectively rewriting everything. Would you prefer if I did a force-push on this branch or create a new pull request for this?

@laurmaedje

Copy link
Copy Markdown
Member

Whichever you prefer is fine with me.

@wrzian

wrzian commented Oct 27, 2024

Copy link
Copy Markdown
Contributor Author

Alright, I'm going to close this one and reopen a new PR so we can start fresh.

@wrzian wrzian closed this Oct 27, 2024
@wrzian wrzian mentioned this pull request Oct 28, 2024
@wrzian
wrzian deleted the parser_trivia_refactor branch October 31, 2024 17:58
@laurmaedje laurmaedje removed the waiting-on-review This PR is waiting to be reviewed. label Dec 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants