Class: Opal::Nodes::IfNode

Inherits:
Base
  • Object
show all
Defined in:
opal/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

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_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 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 'opal/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



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'opal/lib/opal/nodes/if.rb', line 355

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



377
378
379
380
381
382
# File 'opal/lib/opal/nodes/if.rb', line 377

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

#compile_with_binary_andObject



120
121
122
123
124
125
126
127
128
129
130
131
# File 'opal/lib/opal/nodes/if.rb', line 120

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



133
134
135
136
137
138
139
140
141
142
143
144
# File 'opal/lib/opal/nodes/if.rb', line 133

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
# File 'opal/lib/opal/nodes/if.rb', line 29

def compile_with_if
  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

  if expects_expression?
    if scope.await_encountered
      wrap '(await (async function() {', '})())'
    else
      wrap '(function() {', '})()'
    end
  end
end

#compile_with_switchObject



336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'opal/lib/opal/nodes/if.rb', line 336

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), ") {"
    indent do
      compile_switch_case(@switch_test)
    end
    line "}"
  end
end

#compile_with_ternaryObject



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'opal/lib/opal/nodes/if.rb', line 102

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)


244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'opal/lib/opal/nodes/if.rb', line 244

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)


276
277
278
279
280
281
282
283
284
285
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
# File 'opal/lib/opal/nodes/if.rb', line 276

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)


88
89
90
# File 'opal/lib/opal/nodes/if.rb', line 88

def expects_expression?
  expr? || recv?
end

#falsyObject



76
77
78
# File 'opal/lib/opal/nodes/if.rb', line 76

def falsy
  returnify(false_body)
end

#handle_additional_switch_rules(additional_rules) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'opal/lib/opal/nodes/if.rb', line 262

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



80
81
82
83
84
85
86
# File 'opal/lib/opal/nodes/if.rb', line 80

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

#returning?(body) ⇒ Boolean

Returns:

  • (Boolean)


350
351
352
353
# File 'opal/lib/opal/nodes/if.rb', line 350

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

#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)


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

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)


147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'opal/lib/opal/nodes/if.rb', line 147

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



72
73
74
# File 'opal/lib/opal/nodes/if.rb', line 72

def truthy
  returnify(true_body)
end

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

Returns:

  • (Boolean)


315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'opal/lib/opal/nodes/if.rb', line 315

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