lib/opal/nodes/constants.rb in opal-1.3.2 vs lib/opal/nodes/constants.rb in opal-1.4.0.alpha1

- old
+ new

@@ -10,16 +10,21 @@ children :const_scope, :name def compile if magical_data_const? push('$__END__') + elsif optimized_access? + helper :"#{name}" + push "$#{name}" + elsif const_scope == s(:cbase) + push "#{top_scope.absolute_const}('#{name}')" elsif const_scope - push '$$$(', recv(const_scope), ", '#{name}')" + push "#{top_scope.absolute_const}(", recv(const_scope), ", '#{name}')" elsif compiler.eval? - push "$$($nesting, '#{name}')" + push "#{scope.relative_access}('#{name}')" else - push "$$($nesting, '#{name}')" + push "#{scope.relative_access}('#{name}')" end end # Ruby has a magical const DATA # that should be processed in a different way: @@ -28,10 +33,21 @@ # 2. When current file doesn't have __END__ section # DATA const should be resolved to a regular ::DATA constant def magical_data_const? const_scope.nil? && name == :DATA && compiler.eof_content end + + OPTIMIZED_ACCESS_CONSTS = %i[ + BasicObject Object Module Class Opal Kernel NilClass + ].freeze + + # For a certain case of calls like `::Opal.coerce_to?` we can + # optimize the calls. We can be sure they are defined from the + # beginning. + def optimized_access? + const_scope == s(:cbase) && OPTIMIZED_ACCESS_CONSTS.include?(name) + end end # ::CONST # s(:const, s(:cbase), :CONST) class CbaseNode < Base @@ -46,13 +62,15 @@ handle :casgn children :base, :name, :value def compile + helper :const_set + if base - push 'Opal.const_set(', expr(base), ", '#{name}', ", expr(value), ')' + push '$const_set(', expr(base), ", '#{name}', ", expr(value), ')' else - push "Opal.const_set($nesting[0], '#{name}', ", expr(value), ')' + push "$const_set(#{scope.nesting}[0], '#{name}', ", expr(value), ')' end end end end end