Skip to content

Replace StringScanner with plain Ruby scanning - #2150

Draft
girachawda wants to merge 3 commits into
Shopify:mainfrom
girachawda:sf/b777ab2f-1217-490f-b093-17e68ac85b30
Draft

girachawda wants to merge 3 commits into
Shopify:mainfrom
girachawda:sf/b777ab2f-1217-490f-b093-17e68ac85b30

Conversation

@girachawda

Copy link
Copy Markdown

Why

Liquid depends on the strscan gem only for its tokenizer, its lexer and Expression.parse_number. strscan is a native extension. Applications that bundle Liquid must lock, build and install it, although these three scanners need only a few byte operations. This change does the same work with plain Ruby String methods (getbyte, byteindex, byteslice), so Liquid no longer needs strscan. Under YJIT the plain Ruby code is also faster.

What changes

  • Tokenizer finds {{, {% and %} with String#byteindex and reads single bytes with String#getbyte. For sources in UTF-8, US-ASCII or binary, an ASCII byte is always an ASCII character, so a byte search finds the same delimiters as the old regular expression search. For other encodings the tokenizer still uses the old regular expressions, through String#byteindex.
  • Lexer.tokenize scans whitespace, identifiers, numbers and strings byte by byte with lookup tables, as the old jump tables already did for the first byte.
  • Expression.parse_number reads markup.getbyte instead of a reset scanner.
  • ParseContext and Context no longer create a shared StringScanner.
  • liquid.gemspec drops strscan and requires Ruby 3.2, the first version with String#byteindex. CI already tests 3.3 and later.

Compatibility

The behavior stays the same, including the errors and their messages:

  • a source with an invalid byte sequence raises Liquid::SyntaxError from Tokenizer.new, as main does since fix(tokenizer): raise Liquid::SyntaxError for invalid UTF-8 whatever the first token is #2148, and the lexer raises Liquid::SyntaxError for one, as before;
  • an ASCII-incompatible source (such as UTF-16LE) raises Encoding::CompatibilityError, as before;
  • unterminated variables and tags, {% inside {{, and multibyte characters next to delimiters give the same tokens as before.

The public signatures stay compatible. Tokenizer.new(string_scanner:), and the scanner arguments of Expression.parse, Expression.safe_parse and VariableLookup.parse, are optional and not used. RangeLookup.parse keeps its scanner argument and passes it on unused. Lexer.tokenize, Lexer.raise_syntax_error and Parser.new take a String or a StringScanner, and a scanner ends at the same position as before.

Three changes are visible to callers, and History.md lists them:

  • Liquid::HAS_STRING_SCANNER_SCAN_BYTE is removed, because Liquid no longer loads StringScanner. Code that uses StringScanner must require "strscan" itself.
  • Lexer.tokenize raises TypeError for input that is not a String or a scanner. It raised NoMethodError before; Parser.new already raised TypeError.
  • The minimum Ruby version is 3.2.

This branch is merged with main after #2148, which makes the tokenizer raise Liquid::SyntaxError for every source with invalid bytes. The merge keeps #2148's valid_encoding? check in Tokenizer#initialize and drops this branch's own invalid-source handling in the tokenizer (a rescue and two regular expression calls), which could no longer run. It keeps #2148's tests and drops the two tests of this branch that pinned the old behavior.

Validation

  • A differential fuzzer ran the old and new Tokenizer, Lexer (with a String and with a StringScanner) and Expression.parse_number on 1,100,000 random inputs: UTF-8, binary, US-ASCII, Shift_JIS (including characters whose second byte is { or }), EUC-JP, UTF-16LE and invalid UTF-8. It compared tokens, token encodings, line numbers, error classes, error messages and their encodings, and the final scanner position. There were no differences.
  • An end-to-end check parsed and rendered the 34 benchmark templates and 20,000 generated templates in the lax, warn, strict, strict2 and rigid modes with main and with this branch, and compared the output, warnings and errors of all 100,170 cases. There were no differences.
  • The fuzzer and end-to-end comparisons above ran before the merge with fix(tokenizer): raise Liquid::SyntaxError for invalid UTF-8 whatever the first token is #2148, against main without it.
  • After the merge, the test suite passes in lax, strict and strict2 modes on Ruby 4.0.9, and RuboCop reports no offenses. Before the merge it also passed on Ruby 3.4.12. New unit tests pin the tokenizer and lexer edge cases above, and a test checks that parsing and rendering do not load strscan.

Benchmarks

Ruby 4.0.9, the median time of alternating runs of main and this branch, in separate processes, on the performance/tests templates. A negative change is faster. The host was shared and loaded (load average about 50 on 4 CPUs), so a change within about ±10% in one case is noise: render corpus runs no changed code except 14 Expression.parse calls, and a 5-round YJIT run measured it +12.8% and an 8-round run −4.5%.

Case YJIT Interpreter (6 rounds) Allocations, main → branch
tokenize the templates −42.3% −17.0% 1,900 → 1,901
tokenize the templates × 20 −46.4% −14.9% 35,324 → 35,324
lex 18 expressions −26.2% −14.0% 99 → 99
parse, lax −4.3% −1.3% 50,757 → 50,702
parse, strict +3.4% −0.1% 51,843 → 51,788
parse, strict2 −6.6% −3.9% 51,856 → 51,801
parse the templates × 20, lax −12.2% −0.7% 348,094 → 348,173
render −4.5% (8 rounds) +0.5% 10,036 → 9,976
parse and render −9.6% −2.8% 62,268 → 62,153
parse 7 malformed templates, lax −6.5% −7.3% 43,265 → 43,255
parse 7 malformed templates, strict −16.4% −9.1% 19,624 → 19,617

YJIT figures are from 5 rounds unless noted. The malformed templates are unterminated variables, tags and strings, 5,000 {, an invalid byte, 300 unclosed if tags and a bad filter. Each benchmark sampled 5 timings a round, and the allocations are per iteration.

Liquid needs the strscan gem only to scan template sources in the
Tokenizer, the Lexer and Expression.parse_number. strscan is a native
extension, so every application that bundles Liquid must lock, build
and install it for a few byte operations.

The Tokenizer now finds "{{", "{%" and "%}" with String#byteindex and
reads single bytes with String#getbyte. In UTF-8, US-ASCII and binary
sources an ASCII byte is always an ASCII character, so a byte search
finds the same delimiters as the old regular expressions. Other
encodings keep the regular expression search. The Lexer scans
whitespace, identifiers, numbers and strings with byte tables, and
Expression.parse_number reads bytes from the markup.

The tokens, the errors and their messages do not change. The
string_scanner arguments stay optional and unused, and Lexer.tokenize,
Lexer.raise_syntax_error and Parser.new still take a StringScanner and
move it as before. Liquid::HAS_STRING_SCANNER_SCAN_BYTE is removed, and
the gem requires Ruby 3.2 for String#byteindex.

Co-authored-by: Gira Chawda <gira.chawda@shopify.com>
main moved CI to ruby/setup-ruby v1.338.0 and .ruby-version to 4.0.9.
Neither touches the files this branch changes.

Co-authored-by: Gira Chawda <gira.chawda@shopify.com>
Resolve the conflict with Shopify#2148: keep its valid_encoding? check in Tokenizer#initialize and drop this branch's invalid-source handling in the tokenizer, which can no longer run. Keep both sets of tokenizer tests, minus the two that pinned the old ArgumentError and invalid-variable behaviour.

Co-authored-by: Gira Chawda <gira.chawda@shopify.com>

This branch has not been deployed

No deployments
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.

1 participant