Sha256: 807ea244766f3341b528e425e976d4902fa95d9d48bbc27e4fb6404639bb4674

Contents?: true

Size: 1.92 KB

Versions: 10

Compression:

Stored size: 1.92 KB

Contents

module Ruby2JS
  class Converter

    # (if
    #   (true)
    #   (...)
    #   (...))

    handle :if do |condition, then_block, else_block|
      # return parse not condition if else_block and no then_block
      if else_block and not then_block
        return parse(s(:if, s(:not, condition), else_block, nil), @state) 
      end

      then_block ||= s(:nil)

      if @state == :statement
        begin
          scope, @scope = @scope, false
          mark = output_location

          # use short form when appropriate
          unless else_block or then_block.type == :begin
            put "if ("; parse condition; put ') '
            wrap { parse then_block, :statement }
          else
            put "if ("; parse condition; puts ') {'
            parse then_block, :statement
            sput '}'

            while else_block and else_block.type == :if
              condition, then_block, else_block = else_block.children
              if then_block
                put ' else if ('; parse condition; puts ') {'
                parse then_block, :statement
                sput '}'
              else
                put ' else if ('; parse s(:not, condition); puts ') {'
                parse else_block, :statement
                sput '}'
                else_block = nil
              end
            end

            if else_block
              puts ' else {'; parse else_block, :statement; sput '}'
            end
          end

          if scope
            vars = @vars.select {|key, value| value == :pending}.keys
            unless vars.empty?
              insert mark, "#{es2015 ? 'let' : 'var'} #{vars.join(', ')}#{@sep}"
              vars.each {|var| @vars[var] = true}
            end
          end
        ensure
          @scope = scope
        end
      else
        else_block ||= s(:nil)
        put '('; parse condition; put ' ? '; parse then_block
        put ' : '; parse else_block; put ')'
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
ruby2js-3.0.9 lib/ruby2js/converter/if.rb
ruby2js-3.0.8 lib/ruby2js/converter/if.rb
ruby2js-3.0.7 lib/ruby2js/converter/if.rb
ruby2js-3.0.6 lib/ruby2js/converter/if.rb
ruby2js-3.0.5 lib/ruby2js/converter/if.rb
ruby2js-3.0.4 lib/ruby2js/converter/if.rb
ruby2js-3.0.3 lib/ruby2js/converter/if.rb
ruby2js-3.0.2 lib/ruby2js/converter/if.rb
ruby2js-3.0.1 lib/ruby2js/converter/if.rb
ruby2js-3.0.0 lib/ruby2js/converter/if.rb