Refactor the Optimizer class no visit the AST

Just takes care of Variables for now.

Increases performance.
This commit is contained in:
Marc-André Cournoyer
2020-10-07 16:06:50 -04:00
parent 4196a94aa3
commit 9cc410478e
3 changed files with 12 additions and 46 deletions

View File

@@ -5,7 +5,7 @@ module Liquid
def self.parse(tokens, parse_context)
doc = new(parse_context)
doc.parse(tokens, parse_context)
Optimizer.new.optimize(doc)
doc
end
attr_reader :parse_context, :body

View File

@@ -2,54 +2,18 @@
module Liquid
class Optimizer
def optimize(node)
case node
when Liquid::Template then optimize(node.root.body)
when Liquid::Document then optimize(node.body)
when Liquid::BlockBody then optimize_block(node)
when Liquid::Variable then optimize_variable(node)
when Liquid::Assign then optimize_assign(node)
when Liquid::For then optimize_for(node)
when Liquid::If then optimize_if(node)
end
node
end
class << self
attr_accessor :enabled
def optimize_block(block)
block.nodelist.each { |node| optimize(node) }
end
def optimize_variable(node)
return unless enabled
def optimize_variable(node)
# Turn chained `| append: "..."| append: "..."`, into a single `append_all: [...]`
if node.filters.size > 1 && node.filters.all? { |f, _| f == "append" }
node.filters = [["append_all", node.filters.map { |f, (arg)| arg }]]
end
end
def optimize_assign(node)
optimize(node.from)
end
def optimize_for(node)
optimize(node.collection_name)
optimize_block(node)
end
def optimize_if(node)
node.blocks.each do |block|
optimize_condition(block)
optimize(block.attachment)
end
end
def optimize_condition(node)
case node
when Liquid::ElseCondition
# noop
when Liquid::Condition
optimize(node.left)
optimize(node.right) if node.right
# Turn chained `| append: "..."| append: "..."`, into a single `append_all: [...]`
if node.filters.size > 1 && node.filters.all? { |f, _| f == "append" }
node.filters = [["append_all", node.filters.map { |f, (arg)| arg }]]
end
end
end
self.enabled = true
end
end

View File

@@ -31,6 +31,8 @@ module Liquid
@line_number = parse_context.line_number
parse_with_selected_parser(markup)
Optimizer.optimize_variable(self)
end
def raw