Skip to content

Commit

Permalink
Support newlines in StaticAnalyzer
Browse files Browse the repository at this point in the history
  • Loading branch information
k0kubun committed Feb 10, 2017
1 parent dd5ab95 commit f357a41
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 6 deletions.
3 changes: 2 additions & 1 deletion CHANGES
@@ -1,14 +1,15 @@
0.8.0

* Add Temple::StaticAnalyzer to analyze Ruby expressions
* Support newlines in Temple::Filters::StaticAnalyzer

0.7.8

* Fix an warning in StaticAnalyzer

0.7.7

* Add StaticAnalyzer, StringSplitter filters
* Add Temple::Filters::StaticAnalyzer, Temple::Filters::StringSplitter
* Freeze string literals

0.7.6
Expand Down
13 changes: 10 additions & 3 deletions lib/temple/filters/static_analyzer.rb
Expand Up @@ -2,18 +2,25 @@ module Temple
module Filters
# Convert [:dynamic, code] to [:static, text] if code is static Ruby expression.
class StaticAnalyzer < Filter
def call(ast)
def call(exp)
# Optimize only when Ripper is available.
if ::Temple::StaticAnalyzer.available?
super
else
ast
exp
end
end

def on_dynamic(code)
if ::Temple::StaticAnalyzer.static?(code)
[:static, eval(code).to_s]
exp = [:static, eval(code).to_s]

newlines = code.count("\n")
if newlines == 0
exp
else
[:multi, exp, *newlines.times.map { [:newline] }]
end
else
[:dynamic, code]
end
Expand Down
2 changes: 1 addition & 1 deletion lib/temple/static_analyzer.rb
Expand Up @@ -13,7 +13,7 @@ module StaticAnalyzer
:on_lparen, :on_rparen,
:on_lbrace, :on_rbrace, :on_label,
:on_int, :on_float, :on_imaginary,
:on_comma, :on_sp,
:on_comma, :on_sp, :on_ignored_nl,
].freeze

DYNAMIC_TOKENS = [
Expand Down
9 changes: 9 additions & 0 deletions test/filters/test_static_analyzer.rb
Expand Up @@ -3,6 +3,7 @@
describe Temple::Filters::StaticAnalyzer do
before do
@filter = Temple::Filters::StaticAnalyzer.new
@generator = Temple::Generator.new
end

if Temple::StaticAnalyzer.available?
Expand All @@ -15,6 +16,14 @@
exp = [:dynamic, '"#{hello}#{100}"']
@filter.call(exp).should.equal(exp)
end

it 'should not change number of newlines in generated code' do
exp = [:dynamic, "[100,\n200,\n]"]
@filter.call(exp).should.equal([:multi, [:static, '[100, 200]'], [:newline], [:newline]])

@generator.call(@filter.call(exp)).count("\n").
should.equal(@generator.call(exp).count("\n"))
end
else
it 'should do nothing' do
[
Expand Down
2 changes: 1 addition & 1 deletion test/test_static_analyzer.rb
Expand Up @@ -10,7 +10,7 @@
if Temple::StaticAnalyzer.available?
describe '.static?' do
it 'should return true if given Ruby expression is static' do
['true', 'false', '"hello world"', "[1, { 2 => 3 }]"].each do |exp|
['true', 'false', '"hello world"', "[1, { 2 => 3 }]", "[\n1,\n]"].each do |exp|
Temple::StaticAnalyzer.static?(exp).should.equal(true)
end
end
Expand Down

0 comments on commit f357a41

Please sign in to comment.