Class: Minjs::Compressor::Compressor

Inherits:
Object
  • Object
show all
Includes:
Minjs
Defined in:
lib/minjs/compressor/compressor.rb

Overview

Compressor class

Constant Summary

Constants included from Minjs

VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Compressor

Returns a new instance of Compressor.



12
13
14
15
16
17
18
19
20
21
# File 'lib/minjs/compressor/compressor.rb', line 12

def initialize(options = {})
  @logger = options[:logger]
  if !@logger
    @logger = Logger.new(STDERR)
    @logger.level = (options[:debug_level] || Logger::WARN)
    @logger.formatter = proc{|severity, datetime, progname, message|
      "#{message}\n"
    }
  end
end

Instance Attribute Details

#progObject (readonly)

Returns the value of attribute prog.



10
11
12
# File 'lib/minjs/compressor/compressor.rb', line 10

def prog
  @prog
end

Instance Method Details

#add_remove_paren(node = @prog) ⇒ Object

Removes parenthesis if possible and add parentesis if need.



286
287
288
289
290
291
292
293
294
# File 'lib/minjs/compressor/compressor.rb', line 286

def add_remove_paren(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.respond_to? :remove_paren
      st.remove_paren
      st.add_paren
    end
  }
  self
end

#assignment_after_var(node = @prog) ⇒ Object

Moves assignment expression to variable statement’s initialiser if possible.

var a, b, c;
c = 1; a = 2;
=>
var c=1, a=2, b;


1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
# File 'lib/minjs/compressor/compressor.rb', line 1089

def assignment_after_var(node = @prog)
  retry_flag = true
  while retry_flag
    retry_flag = false
    node.traverse(nil) {|parent, st|
      if st.kind_of? ECMA262::StVar and parent.kind_of? ECMA262::SourceElements
        catch(:break){
          idx = parent.index(st) + 1
          while true
            st2 = parent[idx]
            if st2.kind_of? ECMA262::StEmpty or (st2.kind_of? ECMA262::StFunc and st2.decl?)
              idx +=1
              next
            elsif st2.kind_of? ECMA262::StExp and st2.exp.kind_of? ECMA262::ExpAssign
              if rewrite_var(st, st2.exp.val, st2.exp.val2)
                parent.replace(st2, ECMA262::StEmpty.new())
                retry_flag = true
              else
                throw :break
              end
              idx += 1
              next
            elsif st2.kind_of? ECMA262::StFor and st2.exp1.kind_of? ECMA262::ExpAssign
              if rewrite_var(st, st2.exp1.val, st2.exp1.val2)
                st2.replace(st2.exp1, nil)
                retry_flag = true
              else
                throw :break
              end
              throw  :break
            elsif st2.kind_of? ECMA262::StExp and st2.exp.kind_of? ECMA262::ExpComma
              exp_parent = st2
              exp = st2.exp

              while exp.val.kind_of? ECMA262::ExpComma
                exp_parent = exp
                exp = exp.val
              end

              if exp.val.kind_of? ECMA262::ExpAssign
                if rewrite_var(st, exp.val.val, exp.val.val2)
                  exp_parent.replace(exp, exp.val2)
                  retry_flag = true
                else
                  throw :break
                end
              else
                throw :break
              end
            else
              throw :break
            end
          end
        }
      end
    }
  end
  self
end

#block_to_statement(node = @prog) ⇒ Object

Converts Block to single statement if possible



341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/minjs/compressor/compressor.rb', line 341

def block_to_statement(node = @prog)
  remove_empty_statement
  then_to_block
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StBlock and !parent.kind_of?(ECMA262::StTry) and !parent.kind_of?(ECMA262::StIf) and !parent.kind_of?(ECMA262::StTryCatch)
        if st.to_statement?
          parent.replace(st, st.to_statement)
        end
    end
  }
  if_block_to_statement
end

#compress(data, options = {}) ⇒ Object

Compresses ECMAScript



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/minjs/compressor/compressor.rb', line 45

def compress(data, options = {})
  @logger.info '* parse'
  parse(data)

  if options[:only_parse]
    return
  end

  algo = [
    :reorder_function_decl,
    :simple_replacement,
    :reorder_var,
    :assignment_after_var,
    :grouping_statement,
    :block_to_statement,
    :reduce_if,
    :if_to_cond,
    :if_to_return2,
    :compress_var,
    :reduce_exp,
    :grouping_statement,
    :block_to_statement,
    :if_to_cond,
    :remove_then_or_else,
    :block_to_statement,
    :add_remove_paren,
  ]
  algo.each do |a|
    if (options.empty? || options[:all] || options[a]) && !options[("no_" + a.to_s).to_sym]
      @logger.info "* #{a}"
      __send__(a, @prog)
    end
  end

  @heading_comments.reverse.each do |c|
    @prog.source_elements.source_elements.unshift(c)
  end
  self
end

#compress_var(node = @prog) ⇒ Object

Compresses variable name as short as possible.

This method collects and counts all variables under the function/catch, then trying to rename var_vars(see bellow) to new name.

outer_vars

Variables which locate out of this function/catch(or global variable) Them name cannot be renamed

nesting_vars

Variables which locate in the function/catch of this function/catch. Them name cannot be renamed

var_vars

Variables which have same scope in this function/catch.

all_vars

All variables under this function/catch.

  1. If the new name is not in all_vars, the name can be renamed to it.

  2. If the new name belongs to var_vars, the name cannot be renamed.

  3. If the new name belongs to outer_vars the name cannot be renamed.

  4. If the new name belongs to nesting_vars, the name can be rename to it after renaming nesting_vars’s name to another name.



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
# File 'lib/minjs/compressor/compressor.rb', line 595

def compress_var(node = @prog)
  scopes = []
  func_scopes = []
  catch_scopes = []
  with_scopes = []

  node.traverse(nil) {|parent, st|
    st.parent = parent
  }

  #
  # ECMA262 10.2:
  #
  #  Usually a Lexical Environment is associated with some
  #  specific syntactic structure of ECMAScript code such as a
  #  FunctionDeclaration, a WithStatement, or a Catch clause of a
  #  TryStatement and a new Lexical Environment is created each
  #  time such code is evaluated.
  #
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StFunc
      func_scopes.push([parent, st])
      scopes.push([parent, st])
    elsif st.kind_of? ECMA262::StTryCatch
      catch_scopes.push([parent, st])
      scopes.push([parent, st])
    elsif st.kind_of? ECMA262::StWith
      with_scopes.push([parent, st])
    end
  }
  #
  # 10.2, 12.14
  #
  #eee = 'global';
  #function test()
  #{
  #  /*
  #    "eee" is local variable(belongs to this function)
  #    because var declaration is exist in this function.
  #    (see also catch's scope comment)
  #    So, global variable 'eee' is not changed.
  #  */
  #  eee = 'function';
  #  try{
  #    console.log(eee);	//=>function
  #    throw "exception";
  #  }
  #  catch(eee){
  #  /*
  #    The catch's variable scope will be created at execution time.
  #    so next var declaration should belong to "test" function.
  #  */
  #    var eee;
  #  /*
  #    In execution time, "eee" belongs to this 
  #    catch-clause's scope.
  #  */
  #    console.log(eee);	//=>exception
  #  /*
  #    Next function has its own scope and 'eee' belongs to its.
  #  */
  #    (function(){
  #      var eee;
  #      console.log(eee);	//=>undefined
  #    })();
  #  }
  #}
  #console.log(eee); 	//=>global
  #test();
  #
  scopes.reverse!

  # outer
  scopes = scopes.collect {|parent, st|
    if st.kind_of? ECMA262::StFunc or st.kind_of? ECMA262::StTryCatch
      outer = st.parent
      while outer
        if outer.kind_of? ECMA262::StFunc or outer.kind_of? ECMA262::StTryCatch
          break
        end
        outer = outer.parent
      end
    end
    if outer.nil?
      outer = @prog
    end
    [parent, st, outer]
  }

  # exe_context
  scopes.each {|parent, st, outer|
    if st.kind_of? ECMA262::StFunc
      st.exe_context = st.enter(outer.exe_context)
      st.traverse(nil) {|parent2, st2|
        if st2.kind_of? ECMA262::IdentifierName
          if st.decl? and st2 .eql? st.name
            ;
          elsif st.var_env.record.binding[st2.to_s.to_sym]
            st2.exe_context = st.exe_context
          end
        end
      }
    elsif st.kind_of? ECMA262::StTryCatch
      st.exe_context = st.enter(outer.exe_context)
      st.traverse(nil) {|parent2, st2|
        if st2.kind_of? ECMA262::IdentifierName
          if st2 == st.arg
            st2.exe_context = st.exe_context
          end
        end
      }
    end
  }

  scopes.each {|parent, st|
    exe_context = st.exe_context

    var_sym = :a
    all_vars = {}
    var_vars = {}
    var_vars_list = []
    outer_vars = {}
    nesting_vars = {}
    nesting_vars_list = []

    st.traverse(parent) {|parent2, st2|
      if st2.kind_of? ECMA262::IdentifierName
        var_name = st2.val.to_sym
        all_vars[var_name] ||= 0
        all_vars[var_name] += 1
        if st2.exe_context == nil #global
          outer_vars[var_name] ||= 0
          outer_vars[var_name] += 1
        elsif st2.exe_context.lex_env == @prog.exe_context.lex_env
          outer_vars[var_name] ||= 0
          outer_vars[var_name] += 1
        elsif st2.exe_context.lex_env == exe_context.lex_env
          var_vars[var_name] ||= 0
          var_vars[var_name] += 1
          var_vars_list.push(st2)
        else
          e = st2.exe_context.lex_env
          while e
            if e == exe_context.lex_env
              nesting_vars[var_name] ||= 0
              nesting_vars[var_name] += 1
              nesting_vars_list.push(st2)
              break
            end
            e = e.outer
            if e.nil?
              outer_vars[var_name] ||= 0
              outer_vars[var_name] += 1
              break
            end
          end
        end
      end
    }

#        puts "*" * 30
#        puts st.to_js
#        puts "*" * 30
#        puts "all_vars"
#        puts all_vars
#        puts "outer_vars"
#        puts outer_vars
#        puts "var_vars"
#        puts var_vars
#        puts "nesting_vars"
#        puts nesting_vars

    unless var_vars[:eval]
      eval_flag = false
      st.traverse(parent) {|parent2, st2|
        if st2.kind_of? ECMA262::ExpCall and st2.name.to_js({}) == "eval"
          eval_flag = true
          break
        end
        if st2.kind_of? ECMA262::StWith
          eval_flag = true
          break
        end
      }
      if eval_flag
        next
      end
    end
    #
    # sort var_vars
    #
    var_vars_array = var_vars.sort {|(k1,v1), (k2,v2)| v2 <=> v1}
    #
    # create renaming table
    #
    rename_table = {}
    var_vars_array.each {|name, count|
      if name.nil?
        next #bug?
      end
      if name.length == 1
        #STDERR.puts "#{name}=>#{count}"
        next
      end
      #STDERR.puts "trying to rename #{name}(#{count})"
      while true
        #condition b
        if outer_vars[var_sym]
        #STDERR.puts "outer_vars has #{var_sym}"
        elsif var_vars[var_sym]
          #STDERR.puts "var_vars has #{var_sym}(#{var_vars[var_sym]})"
        #condigion c
        else #condition a&d
          #STDERR.puts "->#{var_sym}"
          break
        end
        var_sym = next_sym(var_sym)
      end
      #rename nesting_vars
      if nesting_vars[var_sym]
        #STDERR.puts "nesting_vars has #{var_sym}"
        nesting_vars_list.each do |x|
          #raise 'error' if x.binding_env(x.exe_context.var_env).nil?
        end

        var_sym2 = "XXX#{var_sym.to_s}".to_sym
        while all_vars[var_sym2]
          var_sym2 = next_sym(var_sym2)
        end
        #STDERR.puts "#{var_sym}->#{var_sym2}"

        rl = {}
        nesting_vars_list.each do |x|
          if x.val.to_sym == var_sym
            _var_env = x.binding_env(x.exe_context.var_env)
            rl[_var_env] = true
          end
        end
        rl.keys.each do |_env|
          if _env && _env.record.binding[var_sym]
            _env.record.binding[var_sym2] = _env.record.binding[var_sym]
            _env.record.binding.delete var_sym
          end
        end

        nesting_vars_list.each do |x|
          if x.val.to_sym == var_sym
            x.instance_eval{
              @val = var_sym2
            }
          end
        end
      end
      rename_table[name] = var_sym
      var_sym = next_sym(var_sym)
    }
    var_vars_list.each {|st2|
      #raise 'error' if st2.binding_env(st2.exe_context.var_env).nil?
    }

    rename_table.each do |name, new_name|
      if name != new_name
        if exe_context.var_env.record.binding[name]
          exe_context.var_env.record.binding[new_name] = exe_context.var_env.record.binding[name]
          exe_context.var_env.record.binding.delete(name)
        end
        if exe_context.lex_env.record.binding[name]
          exe_context.lex_env.record.binding[new_name] = exe_context.lex_env.record.binding[name]
          exe_context.lex_env.record.binding.delete(name)
        end
      end
    end

    var_vars_list.each {|st2|
        st2.instance_eval{
          if rename_table[@val]
            @val = rename_table[@val]
            #raise 'error' if st2.binding_env(:var).nil?
            #raise st2.to_js if st2.binding_env(:lex).nil?
          end
        }
    }
  }
  node.traverse(nil) {|parent, st|
    st.parent = nil
  }
  self
end

#debugObject

debuging method



24
25
26
# File 'lib/minjs/compressor/compressor.rb', line 24

def debug
  puts @prog.to_js()
end

#grouping_statement(node = @prog) ⇒ Object

Groups statements in the block and reduce number of them as few as posibble.



167
168
169
170
171
172
173
174
175
# File 'lib/minjs/compressor/compressor.rb', line 167

def grouping_statement(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StatementList
      st.grouping
    end
  }
  add_remove_paren
  self
end

#if_block_to_statement(node = @prog) ⇒ Object

Converts If statement’s block to single statement if possible



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/minjs/compressor/compressor.rb', line 355

def if_block_to_statement(node = @prog)
  remove_empty_statement
  # The "else" cluase's block can be removed always
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StIf
      if st.else_st and st.else_st.kind_of? ECMA262::StBlock
        st.else_st.remove_empty_statement
      end

      if st.else_st and st.else_st.kind_of? ECMA262::StBlock and st.else_st.to_statement?
        st.replace(st.else_st, st.else_st.to_statement)
      end
    end
  }
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StIf
      if st.then_st and st.then_st.kind_of? ECMA262::StBlock
        st.then_st.remove_empty_statement
      end
      if !st.else_st and st.then_st.kind_of? ECMA262::StBlock and st.then_st.to_statement?
        st.replace(st.then_st, st.then_st.to_statement)
      elsif st.then_st.kind_of? ECMA262::StBlock and st.then_st.to_statement?
        _st = st.then_st
        st2 = st.then_st.to_statement
        while true
          if st2.kind_of? ECMA262::StVar or st2.kind_of? ECMA262::StEmpty or
            st2.kind_of? ECMA262::StExp or st2.kind_of? ECMA262::StBlock or
            st2.kind_of? ECMA262::StDoWhile or st2.kind_of? ECMA262::StSwitch or
            st2.kind_of? ECMA262::StContinue or st2.kind_of? ECMA262::StBreak or
            st2.kind_of? ECMA262::StReturn or st2.kind_of? ECMA262::StThrow or
            st2.kind_of? ECMA262::StTry or st2.kind_of? ECMA262::StDebugger
            st.replace(st.then_st, st.then_st.to_statement)
            break;
          elsif st2.kind_of? ECMA262::StWhile or
               st2.kind_of? ECMA262::StFor or
               st2.kind_of? ECMA262::StForIn or
               st2.kind_of? ECMA262::StForVar or
               st2.kind_of? ECMA262::StForInVar or
               st2.kind_of? ECMA262::StWith or
               st2.kind_of? ECMA262::StLabelled
            st2 = st2.statement
          elsif st2.kind_of? ECMA262::StIf
            if st2.else_st
              st2 = st2.else_st
            else
              break
            end
          else #?
            break
          end
        end
      end
    end
  }
  self
end

#if_to_cond(node = @prog) ⇒ Object

Note:

Sometimes, “conditional operator” will be shorter than “logical and operator”, because “conditional operator”‘s priority is lower than almost all other expressions.

Convers if statement to expression statement if possible.

if(a)b;else c;
=>
a?b:c

if(a)b
=>
a&&b;
  or
a?b:0;


429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/minjs/compressor/compressor.rb', line 429

def if_to_cond(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StIf
      if st.to_exp?
        t = ECMA262::StExp.new(st.to_exp({}))
        t2 = ECMA262::StExp.new(st.to_exp({cond: true}))
        if t2.to_js.length < t.to_js.length
          t = t2
        end
        add_remove_paren(t)
        simple_replacement(t)

        if t.to_js.length <= st.to_js.length
          parent.replace(st, t)
        end
      end
    end
  }
  if_to_return(node)
  self
end

#if_to_return(node = @prog) ⇒ Object

Converts ‘if statement’ to ‘return statement’

The condition is: ‘if statement’ which has ‘return statement’ in its then-clause or else-cluase to ‘return statement’

if(a)return b;else return c;
=>
return a?b:c;


460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/minjs/compressor/compressor.rb', line 460

def if_to_return(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StIf
      if st.to_return?
        t = st.to_return
        add_remove_paren(t)
        simple_replacement(t)
        if t.to_js.length <= st.to_js.length
          parent.replace(st, t)
        end
      end
    end
  }
  self
end

#if_to_return2(node = @prog) ⇒ Object

Optimize ‘if statement’.

The condition is: ‘if statement’ which has ‘return statement’ in its then-clause and its next statement is ‘return statement’

if(a)return b;
return c;
=>
return a?b:c;


487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/minjs/compressor/compressor.rb', line 487

def if_to_return2(node = @prog)
  node.traverse(nil) {|parent0, st0|
    if st0.kind_of? ECMA262::StatementList
      st0.remove_empty_statement
      st = st0.deep_dup
      while true
        #check last statement
        ls = st.statement_list[-1]
        ls2 = st.statement_list[-2]
        if st.kind_of? ECMA262::SourceElements and !(ls.kind_of? ECMA262::StReturn)
          ls2 = ls
          ls = ECMA262::StReturn.new(ECMA262::ExpVoid.new(ECMA262::ECMA262Numeric.new(0)))
        end
        break if ls.nil?
        break if ls2.nil?
        break if !ls.to_return?
        break if !ls2.kind_of?(ECMA262::StIf)
        break if ls2.else_st
        break if !ls2.then_st.to_return?

#            if !ls2.then_st.kind_of? ECMA262::StIf and !ls2.then_st.to_return?
#              break
#            end
#            if ls2.then_st.kind_of? ECMA262::StIf and !ls2.then_to_return?
#              break
#            end

        then_exp = ls2.then_st.to_return.exp
        else_exp = ls.to_return.exp
        then_exp = ECMA262::ExpVoid.new(ECMA262::ECMA262Numeric.new(0)) if then_exp.nil?
        else_exp = ECMA262::ExpVoid.new(ECMA262::ECMA262Numeric.new(0)) if else_exp.nil?
        if ls2.cond.kind_of? ECMA262::ExpLogicalNot
          cond = ECMA262::ExpCond.new(ls2.cond.val, else_exp, then_exp)
        else
          cond = ECMA262::ExpCond.new(ls2.cond, then_exp, else_exp)
        end
        ret = ECMA262::StReturn.new(cond)
        #puts ret.to_js
        #puts ls2.to_js
        st.replace(ls2, ret)
        st.remove(ls)
      end
      if st0.to_js.length > st.to_js.length
        parent0.replace(st0, st)
      end
    end
  }
  self
end

#parse(data) ⇒ Object

parses input elements and create node element tree

Parameters:

  • data (String)

    ECMAScript input element

Returns:

  • self



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/minjs/compressor/compressor.rb', line 89

def parse(data)
  @lex = Minjs::Lex::Parser.new(data, :logger => @logger)
  @global_var_env = ECMA262::LexEnv.new(outer: nil)
  @heading_comments = []

  while a = (@lex.comment || @lex.line_terminator || @lex.white_space)
    @heading_comments.push(a)
  end
  while @heading_comments.last == ECMA262::LIT_LINE_TERMINATOR and
        !(@heading_comments[-2].kind_of?(ECMA262::SingleLineComment))
    @heading_comments.pop
  end
  @prog = @lex.program(@global_var_env)
  @prog.exe_context = ECMA262::ExeContext.new

  remove_empty_statement
  @lex.clear_cache
  self
end

#reduce_exp(node = @prog) ⇒ Object

Reduces expression



885
886
887
888
889
890
891
892
# File 'lib/minjs/compressor/compressor.rb', line 885

def reduce_exp(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::Expression
      st.reduce(parent)
    end
  }
  self
end

#reduce_if(node = @prog) ⇒ Object

reduce if statement



981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'lib/minjs/compressor/compressor.rb', line 981

def reduce_if(node = @prog)
  retry_flag = true
  while retry_flag
    retry_flag = false
    node.traverse(nil) {|parent, st|
      if st.kind_of? ECMA262::StIf
        # if(a)
        #   if(b) ...;
        # if(a && b) ...;
        #
        if st.else_st.nil? and
          st.then_st.kind_of? ECMA262::StIf and st.then_st.else_st.nil?
          st.replace(st.cond, ECMA262::ExpLogicalAnd.new(st.cond, st.then_st.cond))
          st.replace(st.then_st, st.then_st.then_st)
        end
        #if(a)z;else;
        #if(a)z;else{}
        # => {if(a)z;}
        if st.else_st and st.else_st.empty?
          st.replace(st.else_st, nil)
          parent.replace(st, ECMA262::StBlock.new([st]))
          retry_flag = true
          break
        end
        #if(a);else z;
        #=>{if(!a)z};
        #if(a){}else z;
        #=>{if(!a)z};
        if st.then_st.empty? and st.else_st
          st.replace(st.cond, ECMA262::ExpLogicalNot.new(st.cond));
          else_st = st.else_st
          st.replace(st.else_st, nil)
          st.replace(st.then_st, else_st)
          parent.replace(st, ECMA262::StBlock.new([st]))
          retry_flag = true
          break
        end
        #if(a);
        # => a
        #if(a){}
        # => a
        if st.then_st.empty? and st.else_st.nil?
          parent.replace(st, ECMA262::StExp.new(st.cond))
        end
=begin
        #if(!(a&&b))
        #=>
        #if(!a||!b)
        if st.cond.kind_of? ECMA262::ExpLogicalNot and st.cond.val.kind_of? ECMA262::ExpParen and
          st.cond.val.val.kind_of? ECMA262::ExpLogicalAnd
          a = ECMA262::ExpLogicalNot.new(st.cond.val.val.val)
          b = ECMA262::ExpLogicalNot.new(st.cond.val.val.val2)
          r = ECMA262::ExpLogicalOr.new(a,b).add_remove_paren
          if r.to_js.length <= st.cond.to_js.length
            st.replace(st.cond, r)
          end
        end
        #if(!(a||b))
        #=>
        #if(!a&&!b)
        if st.cond.kind_of? ECMA262::ExpLogicalNot and st.cond.val.kind_of? ECMA262::ExpParen and
          st.cond.val.val.kind_of? ECMA262::ExpLogicalOr
          a = ECMA262::ExpLogicalNot.new(st.cond.val.val.val)
          b = ECMA262::ExpLogicalNot.new(st.cond.val.val.val2)
          r = ECMA262::ExpLogicalAnd.new(a,b).add_remove_paren
          if r.to_js.length <= st.cond.to_js.length
            st.replace(st.cond, r)
          end
        end
=end
        #if((a))
        if st.cond.kind_of? ECMA262::ExpParen
          st.replace(st.cond, st.cond.val)
        end
        #if(!!a)
        if st.cond.kind_of? ECMA262::ExpLogicalNot and st.cond.val.kind_of? ECMA262::ExpLogicalNot
          st.replace(st.cond, st.cond.val.val)
        end
      end
    }
  end
  block_to_statement
  self
end

#remove_empty_statement(node = @prog) ⇒ Object

Removes empty statement



35
36
37
38
39
40
41
42
# File 'lib/minjs/compressor/compressor.rb', line 35

def remove_empty_statement(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StatementList
      st.remove_empty_statement
    end
  }
  self
end

#remove_then_or_else(node = @prog) ⇒ Object

Optimize ‘if statement’.

The condition is: ‘if statement’ which has ‘return statement’ in its then-clause and its else-caluse has no ‘return statement’

if(a)return b;else c;
=>
if(a)return b;c;


547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/minjs/compressor/compressor.rb', line 547

def remove_then_or_else(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StIf and st.else_st and parent.kind_of? ECMA262::StatementList
      st.remove_empty_statement
      if (st.then_st.kind_of? ECMA262::StBlock and st.then_st[-1].kind_of? ECMA262::StReturn) or
         st.then_st.kind_of? ECMA262::StReturn
        idx = parent.index(st)
        parent[idx+1..0] = st.else_st
        st.replace(st.else_st, nil)
      elsif (st.else_st.kind_of? ECMA262::StBlock and st.else_st[-1].kind_of? ECMA262::StReturn) or
         st.else_st.kind_of? ECMA262::StReturn
        idx = parent.index(st)
        parent[idx+1..0] = st.then_st
        st.instance_eval{
          @then_st = @else_st
          @else_st = nil
          @cond = ECMA262::ExpLogicalNot.new(@cond)
        }
      end
    end
  }
  self
end

#reorder_function_decl(node = @prog) ⇒ Object

Moves function declaration to first of the scope.



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/minjs/compressor/compressor.rb', line 178

def reorder_function_decl(node = @prog)
  flist = []
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StFunc and parent.kind_of? ECMA262::StatementList and st.decl?
      if parent.index(st)
        flist.push([parent, st])
      end
    end
  }
  flist.reverse.each do |parent, st|
    parent.remove(st)
    sl = parent.statement_list
    if sl[0].kind_of? ECMA262::StExp and sl[0].exp.kind_of? ECMA262::ECMA262String and sl[0].exp.val == "use strict"
      sl[1,0] = st
    else
      sl.unshift(st)
    end
  end
  self
end

#reorder_var(node = @prog) ⇒ Object

Collect all variable statment in this scope and puts together one statement.

After collecting all variable, this method moves it to the best place in this scope.



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/minjs/compressor/compressor.rb', line 203

def reorder_var(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::Prog
      vars = nil
      var_env = st.var_env
      #
      # collect all of var variable in this function
      #
      var_vars = {}
      var_env.record.binding.each do|k, v|
        if v and v[:_parameter_list].nil? and !v[:value].kind_of?(ECMA262::StFunc)
          var_vars[k] = true
        end
      end
      #
      # traverse block and convert var statement to assignment expression
      # if variable has initializer
      #
      st.traverse(parent){|parent2, st2|
        if st2.kind_of? ECMA262::StVar and st2.var_env == var_env
          exp = nil
          st2.vars.each do |name, initializer|
            if initializer
              if exp.nil?
                exp = ECMA262::ExpAssign.new(name, initializer)
              else
                exp = ECMA262::ExpComma.new(exp, ECMA262::ExpAssign.new(name, initializer))
              end
            end
          end
          if exp
            parent2.replace(st2, ECMA262::StExp.new(exp))
          else
            parent2.replace(st2, ECMA262::StEmpty.new())
          end
        elsif st2.kind_of? ECMA262::StForVar and st2.var_env == var_env
          parent2.replace(st2, st2.to_st_for)
        elsif st2.kind_of? ECMA262::StForInVar and st2.var_env == var_env
          parent2.replace(st2, st2.to_st_for_in)
        end
      }
      if var_vars.length > 0
        elems = st.source_elements.source_elements
        v = ECMA262::StVar.new(
          var_env,
          var_vars.collect do |k, v|
            [ECMA262::IdentifierName.get(k)]
          end
        )

        idx = 0
        elems.each do |e|
          found = false
          if e.kind_of? ECMA262::StFunc and e.decl?
            ;
          elsif e.kind_of? ECMA262::StExp and e.exp.kind_of? ECMA262::ECMA262String and e.exp.val == "use strict"
            ;
          else
            e.traverse(nil){|pp, ee|
              if ee.kind_of? ECMA262::IdentifierName and var_vars[ee.val.to_sym]
                found = true
                break
              end
            }
          end
          break if found
          idx += 1
        end

        if idx == 0
          elems.unshift(v)
        else
          elems[idx..0] = v
        end
        st.source_elements.remove_empty_statement
      end
    end
    self
  }
  self
end

#simple_replacement(node = @prog) ⇒ Object

Simple replacement



895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
# File 'lib/minjs/compressor/compressor.rb', line 895

def simple_replacement(node = @prog)
  node.traverse(nil) {|parent, st|
    #
    #true => !0
    #false => !1
    #
    if st.kind_of? ECMA262::Boolean
      if st.true?
        parent.replace(st, ECMA262::ExpParen.new(ECMA262::ExpLogicalNot.new(ECMA262::ECMA262Numeric.new(0))))
      else
        parent.replace(st, ECMA262::ExpParen.new(ECMA262::ExpLogicalNot.new(ECMA262::ECMA262Numeric.new(1))))
      end
    #
    #if(true){<then>}else{<else>} => <then>
    #if(false){<then>}else{<else>} => <else>
    #
    elsif st.kind_of? ECMA262::StIf
      if st.cond.respond_to? :to_ecma262_boolean
        if st.cond.to_ecma262_boolean.nil?
          ;
        elsif st.cond.to_ecma262_boolean == true
          parent.replace(st, st.then_st)
        elsif st.cond.to_ecma262_boolean == false and st.else_st
          parent.replace(st, st.else_st)
        elsif st.cond.to_ecma262_boolean == false
          parent.replace(st, ECMA262::StEmpty.new)
        end
      end
    #
    # while(true) => for(;;)
    # while(false) => remove
    #
    elsif st.kind_of? ECMA262::StWhile and st.exp.respond_to? :to_ecma262_boolean
      if st.exp.to_ecma262_boolean.nil?
        ;
      elsif st.exp.to_ecma262_boolean
        parent.replace(st, ECMA262::StFor.new(nil,nil,nil, st.statement))
      else
        parent.replace(st, ECMA262::StEmpty.new)
      end
    #
    # new A() => (new A)
    #
    elsif st.kind_of? ECMA262::ExpNew and st.args and st.args.length == 0
      st.replace(st.args, nil)
      parent.add_paren.remove_paren
    #
    # !c?a:b => c?b:a
    # true?a:b => a
    # false?a:b => b
    #
    elsif st.kind_of? ECMA262::ExpCond
      if st.val.kind_of? ECMA262::ExpLogicalNot
        st.instance_eval{
          @val = @val.val
          t = @val2
          @val2 = @val3
          @val3 = t
        }
        simple_replacement(st)
      end

      if st.val.respond_to? :to_ecma262_boolean
        if st.val.to_ecma262_boolean.nil?
          ;
        elsif st.val.to_ecma262_boolean
          parent.replace(st, st.val2)
        else
          parent.replace(st, st.val3)
        end
      end
    #
    # A["B"] => A.N
    #
    elsif st.kind_of? ECMA262::ExpPropBrac and st.val2.kind_of? ECMA262::ECMA262String
      if @lex.idname?(st.val2.val)
        parent.replace(st, ECMA262::ExpProp.new(st.val, st.val2))
      elsif !st.val2.to_ecma262_number.nil? and (v=ECMA262::ECMA262Numeric.new(st.val2.to_ecma262_number)).to_ecma262_string == st.val2.to_ecma262_string
        st.replace(st.val2, v)
      end
    end
  }
  self
end

#then_to_block(node = @prog) ⇒ Object

Converts every statement of ‘then’ to block even if it contain only one statement.

To determine removing “block” is posibble or not is difficult. For example, next code’s if-block must not be removed, because “else” cluase combined to second “if” statement.

if(a){ //<= this block must not be removed
  while(true)
    if(b){
      ;
    }
}
else{
 ;
}

The next code’s while-block must not be removed, because “else” cluase combined to second “if” statement.

if(a)
  while(true){ //<= this block must not be removed
    if(b){
      ;
    }
  }
else{
 ;
}

To solve this problem, first, every then-clause without block converts to block statement. After converted, all blocks except then-clause can be removed safety.



330
331
332
333
334
335
336
337
338
# File 'lib/minjs/compressor/compressor.rb', line 330

def then_to_block(node = @prog)
  node.traverse(nil) {|parent, st|
    if st.kind_of? ECMA262::StIf
      if !st.then_st.kind_of?(ECMA262::StBlock)
        st.replace(st.then_st, ECMA262::StBlock.new([st.then_st]))
      end
    end
  }
end

#to_js(options = {}) ⇒ Object

Returns a ECMAScript string



29
30
31
32
# File 'lib/minjs/compressor/compressor.rb', line 29

def to_js(options = {})
  remove_empty_statement
  @prog.to_js(options).sub(/;;\Z/, ";")
end