Repository navigation
Conversation
|
At @Myriad-Dreamin's request I have copied everything I wrote from the discord thread below: Re, this comment: #3786 (comment)
I think the current Concretely, the parser tries to abstract trivia (spaces/newlines/comments) from Math/Code mode by keeping track of 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 An example issue with the trivia invariant is the My main desired outcome is to make it impossible to represent the state where the parser is in math/code and I'm thinking of achieving this with the following changes:
As for function naming, I think the ambiguity of My main note on these is that 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! |
|
As an aside, I was also looking into the following patch to improve the 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
left a comment
There was a problem hiding this comment.
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 Not sure if there would be any big downsides, although this might end up adding a constant |
|
Just commited a change to put |
|
The I took the approach of not changing the internal lexer stuff too much for now. That is, |
|
Sorry for the slowness here, but I'd prefer to wait for #4459 to be merged before proceeding here. |
|
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 |
3020889 to
e38713e
Compare
b59735b to
3342deb
Compare
|
Just rebased onto main and amended a change for #4869 in the lexer mode -> closures commit. |
|
Ok, I put together a simple pair of scripts to measure parser timing. My test file is the concatenated sources of 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' > $OUTFILEThis gives about 5000 lines of code and markup, which feels about right On main, my laptop takes around 4400 us (4.4ms) to parse this. With the current I got these from the following scripts by using the existing
run-timings.sh script. |
|
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:
But for now, I think this is ready for another round of review! |
| /// 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I do think the change for math field accesses is a win. Curious what your thougts are there.
ca4bb41 to
0ddd977
Compare
I don't feel like it makes sense to go fully into SyntaxNode as that would greedily create the node's EcoString, but I haven't measured it so maybe it's fine.
Also break out the newline counting to make it more explicit where newlines are actually counted.
Long live the Token struct All hail the Token struct
f15c24d to
bea8405
Compare
bea8405 to
e866992
Compare
|
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. |
|
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? |
|
Whichever you prefer is fine with me. |
|
Alright, I'm going to close this one and reopen a new PR so we can start fresh. |
Draft refactor for discussing how the parser should handle trivia.
See detailed explanation in this thread: https://discord.com/channels/1054443721975922748/1088371867913572452/1249492570380435496