2015-11-23 00:14:53 -05:00
|
|
|
require 'hamlit/ruby_expression'
|
2015-11-13 11:17:30 -05:00
|
|
|
|
|
|
|
module Hamlit
|
2015-12-23 09:33:42 -05:00
|
|
|
class StaticAnalyzer < Temple::Filter
|
2015-11-13 11:17:30 -05:00
|
|
|
STATIC_TOKENS = %i[
|
|
|
|
on_tstring_beg on_tstring_end on_tstring_content
|
|
|
|
on_embexpr_beg on_embexpr_end
|
|
|
|
on_lbracket on_rbracket
|
2015-11-28 03:48:06 -05:00
|
|
|
on_qwords_beg on_words_sep on_qwords_sep
|
2015-11-13 11:17:30 -05:00
|
|
|
on_lparen on_rparen
|
2015-11-16 01:14:49 -05:00
|
|
|
on_lbrace on_rbrace on_label
|
2015-11-13 11:17:30 -05:00
|
|
|
on_int on_float on_imaginary
|
|
|
|
on_comma on_sp
|
|
|
|
].freeze
|
|
|
|
|
|
|
|
DYNAMIC_TOKENS = %i[
|
2015-11-16 01:14:49 -05:00
|
|
|
on_ident on_period
|
2015-11-13 11:17:30 -05:00
|
|
|
].freeze
|
|
|
|
|
|
|
|
STATIC_KEYWORDS = %w[
|
|
|
|
true false nil
|
|
|
|
].freeze
|
|
|
|
|
2015-11-16 01:14:49 -05:00
|
|
|
STATIC_OPERATORS = %w[
|
|
|
|
=>
|
|
|
|
].freeze
|
|
|
|
|
2015-12-23 09:33:42 -05:00
|
|
|
def self.static?(code)
|
|
|
|
return false if code.nil? || code.strip.empty?
|
|
|
|
return false if RubyExpression.syntax_error?(code)
|
2015-11-13 11:17:30 -05:00
|
|
|
|
2015-12-23 09:33:42 -05:00
|
|
|
Ripper.lex(code).each do |(_, col), token, str|
|
2015-11-13 11:17:30 -05:00
|
|
|
case token
|
|
|
|
when *STATIC_TOKENS
|
|
|
|
# noop
|
|
|
|
when :on_kw
|
2015-11-16 01:14:49 -05:00
|
|
|
return false unless STATIC_KEYWORDS.include?(str)
|
|
|
|
when :on_op
|
|
|
|
return false unless STATIC_OPERATORS.include?(str)
|
2015-11-13 11:17:30 -05:00
|
|
|
when *DYNAMIC_TOKENS
|
|
|
|
return false
|
|
|
|
else
|
|
|
|
return false
|
|
|
|
end
|
|
|
|
end
|
|
|
|
true
|
|
|
|
end
|
2015-12-23 09:33:42 -05:00
|
|
|
|
|
|
|
def on_dynamic(code)
|
|
|
|
if StaticAnalyzer.static?(code)
|
|
|
|
[:static, eval(code).to_s]
|
|
|
|
else
|
|
|
|
[:dynamic, code]
|
|
|
|
end
|
|
|
|
end
|
2015-11-13 11:17:30 -05:00
|
|
|
end
|
|
|
|
end
|