Skip to content

Add a Real Parser. Closes #229 and closes #225. - #235

Merged
trishume merged 57 commits into
masterfrom
recursive-parsing
Aug 30, 2013
Merged

trishume merged 57 commits into
masterfrom
recursive-parsing

Conversation

@trishume

Copy link
Copy Markdown
Contributor

@fw42 @RichardBlair @boourns @tobi
This massive pull request contains a brand new parser and lexer for variable tags and if statements that can be easily extended to work with all other tags. It uses proper parsing so it is both easier to understand and less fraught with quirks and bugs. It gives real syntax errors that tell the user what they did wrong.

The parser and lexer are made as utilities that can easily be used in other tags.

This fixes many problems with the liquid parser including closing #229 and #225. It makes the variable tag sane and
tells users what they did wrong instead of silently doing whatever the heck it wants.

Backwards Compatibility

I also added a system for determining the parsing mode. By default it is set to a compatibility mode where if a syntax error occurs it will add an error message and then fall back on the old parser instead of crashing. It can also be set to use either only the old parser or only the new parser.

Shopify could be configured to use the warning mode so that existing templates would continue working but it would show syntax warnings in the theme editor. In Liquid 2.6 the warning mode should be the default but in Liquid 3.0 the strict mode could be the default.

Tests

I added many tests for both the lexer and parser classes as well as fixing tests to expect syntax errors. I kept the tests for the lax parser and added a helper that sets the parsing mode to lax. Interestingly, there were even tests
that asserted that certain bugs like #225 existed.

Internals

Two new classes were added Liquid::Parser and Liquid::Lexer. The lexer is a hand-written one using StringScanner and the parser is a hand-written LL(k) recursive descent parser.

Tags can use the parser class as a utility to do their own parsing. Here is an example of using the parser class:

p = Parser.new(markup)
# Could be just filters with no input
@name = p.look(:pipe) ? '' : p.expression
while p.consume?(:pipe)
  filtername = p.consume(:id)
  filterargs = p.consume?(:colon) ? parse_filterargs(p) : []
  @filters << [filtername, filterargs]
end
p.consume(:end_of_string)

Examples

Here are some examples of what it fixes:

{{ variable.: }}
old => ""
new => Liquid::SyntaxError: Expected id but found <colon: ':'>

{% assign foo = 1 + 2 %}{{ foo }}
old => "1"
new => Liquid::SyntaxError: Unexpected character +

{% if true && false %} wrong {% endif %}
old => "wrong"
new => Liquid::SyntaxError: Unexpected character &

{{---E(R[\'\"\'\"\'(+=EH%*^(@#^%$)?||?\eE,PUZE:::~~~~``}}
old => ""
new => Liquid::SyntaxError: Unexpected character (.

Benchmarks

I added a new benchmarking command rake benchmark:lax which runs the benchmarks with the old parser.

Old parser (rake benchmark:lax):

Rehearsal ------------------------------------------------
parse:         3.840000   0.050000   3.890000 (  4.026889)
parse & run:   8.110000   0.050000   8.160000 (  8.154465)
-------------------------------------- total: 12.050000sec

                   user     system      total        real
parse:         3.410000   0.020000   3.430000 (  3.436315)
parse & run:   7.950000   0.040000   7.990000 (  8.140029)

New parser (rake benchmark:run):

Rehearsal ------------------------------------------------
parse:         5.560000   0.040000   5.600000 (  5.745558)
parse & run:  10.800000   0.040000  10.840000 ( 10.930402)
-------------------------------------- total: 16.440000sec

                   user     system      total        real
parse:         5.450000   0.020000   5.470000 (  5.575437)
parse & run:  10.630000   0.040000  10.670000 ( 10.783157)

The new parser is a bit slower. According to basic profiling the performance issues are mostly in the lexer, which I could try writing in Ragel but I think the added complexity of Ragel outweighs the performance benefits.

@trishume

Copy link
Copy Markdown
Contributor Author

The CI seems to break but the tests pass fine on my computer. I will look into why they fail later. I think I just have to require "stringscanner" in the lexer.

@fw42

fw42 commented Jul 26, 2013

Copy link
Copy Markdown
Contributor

Haven't looked at the code yet, but it sounds awesome from the description. Although "fast" might be more important than "awesome" :-(

@fw42

fw42 commented Jul 26, 2013

Copy link
Copy Markdown
Contributor

cc @hornairs for performance discussion

@airhorns

Copy link
Copy Markdown
Contributor

Herm. I don't think we can accept a perf hit for cleaner code either. That sucks tho cause this is glorious.

I tried removing the Token class and inlining some Parser methods and shaved a bit of time off, see recursive-parsing...array_tokens :

oration ~/C/liquid  (array_tokens*) ➜  rake benchmark:run
/opt/boxen/rbenv/versions/1.9.3-p448/bin/ruby ./performance/benchmark.rb
Rehearsal ------------------------------------------------
parse:         4.300000   0.020000   4.320000 (  4.329285)
parse & run:   9.470000   0.030000   9.500000 (  9.499332)
-------------------------------------- total: 13.820000sec

                   user     system      total        real
parse:         4.260000   0.010000   4.270000 (  4.263429)
parse & run:   9.380000   0.030000   9.410000 (  9.409803)
oration ~/C/liquid  (array_tokens) ➜  git co recursive-parsing
oration ~/C/liquid  (recursive-parsing) ➜  rake benchmark:run
/opt/boxen/rbenv/versions/1.9.3-p448/bin/ruby ./performance/benchmark.rb
Rehearsal ------------------------------------------------
parse:         5.240000   0.020000   5.260000 (  5.259000)
parse & run:  10.710000   0.040000  10.750000 ( 10.755690)
-------------------------------------- total: 16.010000sec

                   user     system      total        real
parse:         5.170000   0.010000   5.180000 (  5.183431)
parse & run:  10.310000   0.020000  10.330000 ( 10.325539)

but as you said @trishume it looks like a lot of the time is spent doing Regexp#===. Is the order in which the regexps are scanned for determined by token precedence? Could we mess with that order to get more "hits" earlier on in the case statement? Also, I think it might be worth exploring Ragel cause I believe there are already a few grammars hanging out on the internet and you did the awesome work to let two versions co-exist, which I think was most of the battle.

Awesome job @trishume

EDIT: added stuff about method inlining

@trishume

Copy link
Copy Markdown
Contributor Author

@hornairs I don't think the Regexps can be rearanged that much. I used to have them in optimal order and it was a little bit faster but then I kept finding problems like floating point numbers being lexed as an integer and then a dot and another integer. Right now they are in the right order for dependencies.

I also tried putting all the smaller regexes into a bigger one and then disambiguating with capture groups but that wasn't any faster.

Also keep in mind that this is not only about cleaner code. It also has the significant benefit of telling theme editors where they made a mistake rather than silently doing the wrong thing.

I'll see what I can do about optimizing it some more.

@nickpearson

Copy link
Copy Markdown
Contributor

I've never written a complex parser before so I'm not sure this is practical, but I thought it'd be worth throwing out there. Is it possible with the new parser to look at a Liquid segment/tag before parsing it? If so, it may save on performance to parse a segment/tag with the existing regex parser if it can be known beforehand that the segment/tag uses proper syntax.

I realize this adds an extra regex check for every segment/tag, but if the cost of this check pays off in a high enough percentage of cases (where the Liquid code is very simple) by using the faster parser, it may be worth exploring.

For example, to check for simple, valid segments:

r = /\{\{ *\w+(?: *\| *\w+)* *\}\}/

# matches
"{{some_var}}"                       =~ r #=> 0
"{{some_var|upcase}}"                =~ r #=> 0
"{{ some_var | upcase }}"            =~ r #=> 0
"{{ some_var | upcase | downcase }}" =~ r #=> 0

# non-matches
"{{'val'}}"           =~ r #=> nil
"{{ array[0] }}"      =~ r #=> nil
"{{ var | test: 1 }}" =~ r #=> nil
"{{ var | test 1 }}"  =~ r #=> nil
"{{ var | test: }}"   =~ r #=> nil

This regex will match the simplest segments: a variable reference with zero or more filters with no filter parameters. My guess is that a large chunk of the invalid Liquid syntax is in filter parameters (the other large chunk being in tag attributes). Something similar might be practical for simple tags, though it would be need to be a bit more complex to also match a high percentage of tags.

If this is worth looking into, it may also be worth knowing what percentage of Liquid segments in Shopify templates are without any filter parameters. I just used this to check all the templates in my app:

simple = 0
total = 0
Template.all.each do |template|
  segments = template.text.to_s.scan(/\{\{.*?\}\}/)
  total += segments.size
  simple += segments.select do |segment|
    segment =~ /\{\{ *\w+(?: *\| *\w+)* *\}\}/
  end.size
end
puts "#{simple}/#{total} = #{simple/total.to_f}"

And by the way, awesome work on this @trishume. I'm hoping the performance hit can be worked out or at least be shown to be worth it.

Comment thread lib/liquid/lexer.rb Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe I don't get it, but this whole case block looks like it's scanning the same string 6 times in the worst case. Shouldn't that be possible with only one iteration?

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.

Tobi, Harry and I talked about that, I'm going to try something out.

@fw42

fw42 commented Aug 27, 2013

Copy link
Copy Markdown
Contributor

Can someone else besides me (one of @arthurnn, @sirupsen, @hornairs, @csfrancis, ... maybe) please review this too please? (preferably today)

👍 from me, but this is pretty big, so I want a second opinion. For reference, see also https://github.com/Shopify/shopify/pull/7885.

Comment thread lib/liquid/lexer.rb

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Are the most common cases in usual Liquid code first here?

Also I'm not sure if I'm a fan of using then, I'd prefer newlines.

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.

They are in the right order such that they will parse correctly. For example, comparison can be contains which is also a valid identifier so it has to parse comparisons first.

As for the thens, there are just so many cases and the body of the cases is so small that splitting it up might make it harder to read.

@sirupsen

Copy link
Copy Markdown
Contributor

Overall it looks like excellent work @trishume! It seems clean, the Liquid parsing errors are going to be amazing. 👍 Huge props.

@trishume

Copy link
Copy Markdown
Contributor Author

Ready to merge? CI is passing, it is ready to be used in Shopify, any last comments? :shipit:

@sirupsen

Copy link
Copy Markdown
Contributor

🐳 🐳 🐳

@fw42

fw42 commented Aug 30, 2013

Copy link
Copy Markdown
Contributor

trishume added a commit that referenced this pull request Aug 30, 2013
Add a Real Parser. Closes #229 and closes #225.
@trishume
trishume merged commit 0e41c2c into master Aug 30, 2013
@trishume
trishume deleted the recursive-parsing branch August 30, 2013 14:12
@trishume

Copy link
Copy Markdown
Contributor Author

Yay! 🎊 ✨

@trishume trishume removed their assignment May 15, 2014
eq19 pushed a commit to VirtualNetworks/liquid that referenced this pull request May 2, 2025
eq19 pushed a commit to VirtualNetworks/liquid that referenced this pull request May 2, 2025
eq19 pushed a commit to VirtualNetworks/liquid that referenced this pull request May 2, 2025
eq19 pushed a commit to VirtualNetworks/liquid that referenced this pull request May 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants