Sha256: 7f7cce5687841129850acf5fea03b595671f6262154719015278d71750d75ea3

Contents?: true

Size: 1.26 KB

Versions: 13

Compression:

Stored size: 1.26 KB

Contents

require 'hamlit/ruby_expression'

module Hamlit
  class StaticAnalyzer < Temple::Filter
    STATIC_TOKENS = %i[
      on_tstring_beg on_tstring_end on_tstring_content
      on_embexpr_beg on_embexpr_end
      on_lbracket on_rbracket
      on_qwords_beg on_words_sep on_qwords_sep
      on_lparen on_rparen
      on_lbrace on_rbrace on_label
      on_int on_float on_imaginary
      on_comma on_sp
    ].freeze

    DYNAMIC_TOKENS = %i[
      on_ident on_period
    ].freeze

    STATIC_KEYWORDS = %w[
      true false nil
    ].freeze

    STATIC_OPERATORS = %w[
      =>
    ].freeze

    def self.static?(code)
      return false if code.nil? || code.strip.empty?
      return false if RubyExpression.syntax_error?(code)

      Ripper.lex(code).each do |(_, col), token, str|
        case token
        when *STATIC_TOKENS
          # noop
        when :on_kw
          return false unless STATIC_KEYWORDS.include?(str)
        when :on_op
          return false unless STATIC_OPERATORS.include?(str)
        when *DYNAMIC_TOKENS
          return false
        else
          return false
        end
      end
      true
    end

    def on_dynamic(code)
      if StaticAnalyzer.static?(code)
        [:static, eval(code).to_s]
      else
        [:dynamic, code]
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
hamlit-2.2.4 lib/hamlit/static_analyzer.rb
hamlit-2.6.1 lib/hamlit/static_analyzer.rb
hamlit-2.6.0 lib/hamlit/static_analyzer.rb
hamlit-2.5.0 lib/hamlit/static_analyzer.rb
hamlit-2.4.2 lib/hamlit/static_analyzer.rb
hamlit-2.4.1 lib/hamlit/static_analyzer.rb
hamlit-2.4.0 lib/hamlit/static_analyzer.rb
hamlit-2.3.1 lib/hamlit/static_analyzer.rb
hamlit-2.3.0 lib/hamlit/static_analyzer.rb
hamlit-2.2.3 lib/hamlit/static_analyzer.rb
hamlit-2.2.2 lib/hamlit/static_analyzer.rb
hamlit-2.2.1 lib/hamlit/static_analyzer.rb
hamlit-2.2.0 lib/hamlit/static_analyzer.rb