1
0
Fork 0
mirror of https://github.com/haml/haml.git synced 2022-11-09 12:33:31 -05:00

Delegate static analysis to StaticAnalyzer

by changing StaticAnalyzer to a Temple filter
This commit is contained in:
Takashi Kokubun 2015-12-23 23:33:42 +09:00
parent e8b612ebb6
commit 7dd8ab7dd9
4 changed files with 27 additions and 7 deletions

View file

@ -111,8 +111,6 @@ module Hamlit
type, exp = values.last
case
when type == :dynamic && StaticAnalyzer.static?(exp)
temple << [:html, :attr, key, [:escape, @escape_attrs, [:static, eval(exp).to_s]]]
when type == :dynamic && RubyExpression.string_literal?(exp)
value_temple = [:multi]
StringInterpolation.compile(exp).each do |type, v|

View file

@ -3,6 +3,7 @@ require 'hamlit/parser'
require 'hamlit/compiler'
require 'hamlit/escapable'
require 'hamlit/html'
require 'hamlit/static_analyzer'
module Hamlit
class Engine < Temple::Engine
@ -21,6 +22,7 @@ module Hamlit
use Parser
use Compiler
use HTML
use StaticAnalyzer
use Escapable
filter :ControlFlow
filter :MultiFlattener

View file

@ -1,7 +1,7 @@
require 'hamlit/ruby_expression'
module Hamlit
class StaticAnalyzer
class StaticAnalyzer < Temple::Filter
STATIC_TOKENS = %i[
on_tstring_beg on_tstring_end on_tstring_content
on_embexpr_beg on_embexpr_end
@ -25,11 +25,11 @@ module Hamlit
=>
].freeze
def self.static?(exp)
return false if exp.nil? || exp.strip.empty?
return false if RubyExpression.syntax_error?(exp)
def self.static?(code)
return false if code.nil? || code.strip.empty?
return false if RubyExpression.syntax_error?(code)
Ripper.lex(exp).each do |(_, col), token, str|
Ripper.lex(code).each do |(_, col), token, str|
case token
when *STATIC_TOKENS
# noop
@ -45,5 +45,13 @@ module Hamlit
end
true
end
def on_dynamic(code)
if StaticAnalyzer.static?(code)
[:static, eval(code).to_s]
else
[:dynamic, code]
end
end
end
end

View file

@ -0,0 +1,12 @@
describe 'optimization' do
def compiled_code(haml)
Hamlit::Engine.new.call(haml)
end
describe 'static analysis' do
it 'renders static value for href statically' do
haml = %|%a{ href: 1 }|
assert_equal true, compiled_code(haml).include?(%|href='1'|)
end
end
end