Class: Opal::Nodes::IfNode

Inherits:
Base
  • Object
show all
Defined in:
lib/opal/nodes/if.rb

Constant Summary collapse

SWITCH_TEST_MATCH =

Matches: case some_value_or_expression; when 123 Captures: [s(:int, 123), "$ret_or_1", s(:send, nil, :some_value_or_expression))]

AST::Matcher.new do
  s(:send,
    cap(s(%i[float int sym str true false nil], :*)),
    :===,
    s(:lvasgn, cap(:*), cap(:*))
  )
end
SWITCH_TEST_MATCH_CONTINUED =

Matches: case some_value_or_expression; when 123, 456; end Captures: [ s(:int, 123), "$ret_or_1", s(:send, nil, :some_value_or_expression)), …here we delegate to either SWITCH_BRANCH_TEST_MATCH or SWITCH_BRANCH_TEST_MATCH_CONTINUED ]

AST::Matcher.new do
  s(:if,
    s(:send,
      cap(s(%i[float int sym str true false nil], :*)),
      :===,
      s(:lvasgn, cap(:*), cap(:*))
    ),
    s(:true),
    cap(:*)
  )
end
SWITCH_BRANCH_TEST_MATCH =

Matches: when 456 (from case foo; when 123; when 456; end) Captures: [s(:int, 456), "$ret_or_1"]

AST::Matcher.new do
  s(:send,
    cap(s(%i[float int sym str true false nil], :*)),
    :===,
    s(:js_tmp, cap(:*))
  )
end
SWITCH_BRANCH_TEST_MATCH_CONTINUED =

Matches: when 456 Captures: [ s(:int, 789), "$ret_or_1", …here we delegate to either SWITCH_BRANCH_TEST_MATCH or SWITCH_BRANCH_TEST_MATCH_CONTINUED ]

AST::Matcher.new do
  s(:if,
    s(:send,
      cap(s(%i[float int sym str true false nil], :*)),
      :===,
      s(:js_tmp, cap(:*))
    ),
    s(:true),
    cap(:*)
  )
end

Instance Attribute Summary

Attributes inherited from Base

#compiler, #sexp, #type

Attributes included from Closure::NodeSupport

#closure

Instance Method Summary collapse

Methods inherited from Base

#add_gvar, #add_ivar, #add_local, #add_temp, children, #children, #class_variable_owner, #class_variable_owner_nesting_level, #comments, #compile_to_fragments, #error, #expr, #expr?, #expr_or_empty, #expr_or_nil, #fragment, handle, handlers, #has_rescue_else?, #helper, #in_ensure, #in_ensure?, #in_resbody, #in_resbody?, #in_rescue, #in_while?, #initialize, #process, #push, #recv, #recv?, #s, #scope, #source_location, #stmt, #stmt?, #top_scope, truthy_optimize?, #unshift, #while_loop, #with_temp, #wrap

Methods included from Closure::NodeSupport

#closure_is?, #compile_catcher, #generate_thrower, #generate_thrower_without_catcher, #in_closure, #pop_closure, #push_closure, #select_closure, #thrower

Methods included from Helpers

#current_indent, #empty_line, #indent, #js_truthy, #js_truthy_optimize, #line, #mid_to_jsid, #property, #valid_name?

Constructor Details

This class inherits a constructor from Opal::Nodes::Base

Instance Method Details

#compileObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/opal/nodes/if.rb', line 13

def compile
  if should_compile_as_simple_expression?
    if true_body == s(:true)
      compile_with_binary_or
    elsif false_body == s(:false)
      compile_with_binary_and
    else
      compile_with_ternary
    end
  elsif could_become_switch?
    compile_with_switch
  else
    compile_with_if
  end
end

#compile_switch_case(test) ⇒ Object



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/opal/nodes/if.rb', line 365

def compile_switch_case(test)
  line "case ", expr(test), ":"
  if @switch_additional_rules
    @switch_additional_rules.each do |rule|
      line "case ", expr(rule), ":"
    end
  end
  indent do
    line stmt(true_body)
    line "break;" if !true_body || !returning?(true_body)
  end
  if false_body
    if false_body.meta[:switch_default]
      compile_switch_default
    elsif false_body.meta[:switch_child]
      push stmt(false_body)
    end
  else
    push stmt(s(:nil))
  end
end

#compile_switch_defaultObject



387
388
389
390
391
392
# File 'lib/opal/nodes/if.rb', line 387

def compile_switch_default
  line "default:"
  indent do
    line stmt(false_body)
  end
end

#compile_with_binary_andObject



130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/opal/nodes/if.rb', line 130

def compile_with_binary_and
  if sexp.meta[:do_js_truthy_on_true_body]
    truthy = js_truthy(true_body || s(:nil))
  else
    truthy = expr(true_body || s(:nil))
  end

  push '('
  push js_truthy(test), ' && '
  push '(', truthy, ')'
  push ')'
end

#compile_with_binary_orObject



143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/opal/nodes/if.rb', line 143

def compile_with_binary_or
  if sexp.meta[:do_js_truthy_on_false_body]
    falsy = js_truthy(false_body || s(:nil))
  else
    falsy = expr(false_body || s(:nil))
  end

  push '('
  push js_truthy(test), ' || '
  push '(', falsy, ')'
  push ')'
end

#compile_with_ifObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
# File 'lib/opal/nodes/if.rb', line 29

def compile_with_if
  push_closure if expects_expression?

  truthy = self.truthy
  falsy = self.falsy

  if falsy && !truthy
    # Let's optimize a little bit `unless` calls.
    push 'if (!', js_truthy(test), ') {'
    falsy, truthy = truthy, falsy
  else
    push 'if (', js_truthy(test), ') {'
  end

  # skip if-body if no truthy sexp
  indent { line stmt(truthy) } if truthy

  if falsy
    if falsy.type == :if
      line '} else ', stmt(falsy)
    else
      line '} else {'
      indent do
        line stmt(falsy)
      end

      line '}'
    end
  else
    line '}'

    # This resolution isn't finite. Let's ensure this block
    # always return something if we expect a return
    line 'return nil;' if expects_expression?
  end

  pop_closure if expects_expression?

  if expects_expression?
    return_kw = 'return ' if returning_if?

    if scope.await_encountered
      wrap "#{return_kw}(await (async function() {", '})())'
    else
      wrap "#{return_kw}(function() {", '})()'
    end
  end
end

#compile_with_switchObject



346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/opal/nodes/if.rb', line 346

def compile_with_switch
  if sexp.meta[:switch_child]
    @switch_variable = sexp.meta[:switch_variable]
    @switch_additional_rules = sexp.meta[:switch_additional_rules]
    compile_switch_case(sexp.meta[:switch_test])
  else
    line "switch (", expr(@switch_first_test), ".valueOf()) {"
    indent do
      compile_switch_case(@switch_test)
    end
    line "}"
  end
end

#compile_with_ternaryObject



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/opal/nodes/if.rb', line 112

def compile_with_ternary
  truthy = true_body
  falsy = false_body

  push '('

  push js_truthy(test), ' ? '

  push '(', expr(truthy || s(:nil)), ') : '
  if !falsy || falsy.type == :if
    push expr(falsy || s(:nil))
  else
    push '(', expr(falsy || s(:nil)), ')'
  end

  push ')'
end

#could_become_switch?Boolean

Returns:

  • (Boolean)


254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/opal/nodes/if.rb', line 254

def could_become_switch?
  return false if expects_expression?

  return true if sexp.meta[:switch_child]

  test_match = SWITCH_TEST_MATCH.match(test) || SWITCH_TEST_MATCH_CONTINUED.match(test)
  return false unless test_match
  @switch_test, @switch_variable, @switch_first_test, additional_rules = *test_match

  additional_rules = handle_additional_switch_rules(additional_rules)
  return false unless additional_rules # It's ok for them to be empty, but false denotes a mismatch
  @switch_additional_rules = additional_rules

  return false unless valid_switch_body?(true_body)

  could_become_switch_branch?(false_body)
end

#could_become_switch_branch?(body) ⇒ Boolean

Returns:

  • (Boolean)


286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/opal/nodes/if.rb', line 286

def could_become_switch_branch?(body)
  if !body
    return true
  elsif body.type != :if
    if valid_switch_body?(body)
      body.meta[:switch_default] = true
      return true
    end
    return false
  end

  test, true_body, false_body = *body

  test_match = SWITCH_BRANCH_TEST_MATCH.match(test) || SWITCH_BRANCH_TEST_MATCH_CONTINUED.match(test)
  unless test_match
    if valid_switch_body?(body, true)
      body.meta[:switch_default] = true
      return true
    end
  end
  switch_test, switch_variable, additional_rules = *test_match

  switch_additional_rules = handle_additional_switch_rules(additional_rules)
  return false unless switch_additional_rules # It's ok for them to be empty, but false denotes a mismatch

  return false unless switch_variable == @switch_variable

  return false unless valid_switch_body?(true_body)
  return false unless could_become_switch_branch?(false_body)

  body.meta.merge!(switch_child: true,
                   switch_test: switch_test,
                   switch_variable: @switch_variable,
                   switch_additional_rules: switch_additional_rules
  )

  true
end

#expects_expression?Boolean

Returns:

  • (Boolean)


98
99
100
# File 'lib/opal/nodes/if.rb', line 98

def expects_expression?
  expr? || recv?
end

#falsyObject



86
87
88
# File 'lib/opal/nodes/if.rb', line 86

def falsy
  returnify(false_body)
end

#handle_additional_switch_rules(additional_rules) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/opal/nodes/if.rb', line 272

def handle_additional_switch_rules(additional_rules)
  switch_additional_rules = []
  while additional_rules
    match = SWITCH_BRANCH_TEST_MATCH.match(additional_rules) || SWITCH_BRANCH_TEST_MATCH_CONTINUED.match(additional_rules)
    return false unless match

    switch_test, switch_variable, additional_rules = *match
    return false unless switch_variable == @switch_variable

    switch_additional_rules << switch_test
  end
  switch_additional_rules
end

#returnify(body) ⇒ Object



90
91
92
93
94
95
96
# File 'lib/opal/nodes/if.rb', line 90

def returnify(body)
  if expects_expression? && body
    compiler.returns(body)
  else
    body
  end
end

#returning?(body) ⇒ Boolean

Returns:

  • (Boolean)


360
361
362
363
# File 'lib/opal/nodes/if.rb', line 360

def returning?(body)
  %i[return js_return next].include?(body.type) ||
    (body.type == :begin && %i[return js_return next].include?(body.children.last.type))
end

#returning_if?Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/opal/nodes/if.rb', line 78

def returning_if?
  @sexp.meta[:returning]
end

#should_compile_as_simple_expression?Boolean

There was a particular case in the past, that when we expected an expression from if, we always had to closure it. This produced an ugly code that was hard to minify. This addition tries to make a few cases compiled with a ternary operator instead and possibly a binary operator even?

Returns:

  • (Boolean)


108
109
110
# File 'lib/opal/nodes/if.rb', line 108

def should_compile_as_simple_expression?
  expects_expression? && simple?(true_body) && simple?(false_body)
end

#simple?(body) ⇒ Boolean

Let's ensure there are no control flow statements inside.

Returns:

  • (Boolean)


157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/opal/nodes/if.rb', line 157

def simple?(body)
  case body
  when AST::Node
    case body.type
    when :return, :js_return, :break, :next, :redo, :retry
      false
    when :xstr
      XStringNode.single_line?(
        XStringNode.strip_empty_children(body.children)
      )
    else
      body.children.all? { |i| simple?(i) }
    end
  else
    true
  end
end

#truthyObject



82
83
84
# File 'lib/opal/nodes/if.rb', line 82

def truthy
  returnify(true_body)
end

#valid_switch_body?(body, check_variable = false) ⇒ Boolean

Returns:

  • (Boolean)


325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/opal/nodes/if.rb', line 325

def valid_switch_body?(body, check_variable = false)
  case body
  when AST::Node
    case body.type
    when :break, :redo, :retry
      false
    when :iter, :while
      # Don't traverse the iters or whiles!
      true
    else
      body.children.all? { |i| valid_switch_body?(i, check_variable) }
    end
  when @switch_variable
    # Perhaps we ended abruptly and we lack a $ret_or variable... but sometimes
    # we can ignore this.
    !check_variable
  else
    true
  end
end