Class: TEALrb::Rewriters::IfRewriter

Inherits:
Rewriter
  • Object
show all
Defined in:
lib/tealrb/rewriters.rb

Instance Attribute Summary

Attributes inherited from Rewriter

#contract

Instance Method Summary collapse

Methods inherited from Rewriter

#rewrite

Instance Method Details

#on_if(node) ⇒ Object



201
202
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
# File 'lib/tealrb/rewriters.rb', line 201

def on_if(node)
  condition = node.children.first
  block = node.children[1]

  case node.loc.keyword.source
  when 'if', 'unless'
    @contract.if_count += 1
    @elsif_count ||= 0

    if node.loc.keyword.source == 'unless'
      replace(node.loc.keyword, ":if#{@contract.if_count}_condition;!")
    else
      replace(node.loc.keyword, ":if#{@contract.if_count}_condition;")
    end
    insert_before(block.source_range, ":if#{@contract.if_count}_logic;")

    case node.loc.else&.source
    when 'else'
      insert_after(condition.source_range, "; bz :if#{@contract.if_count}_else")
      insert_after(block.source_range, "; b :if#{@contract.if_count}_end")
      replace(node.loc.else, ":if#{@contract.if_count}_else;")
    when 'elsif'
      insert_after(condition.source_range, "; bz :if#{@contract.if_count}_elsif#{@elsif_count + 1}_condition")
      insert_after(block.source_range, "; b :if#{@contract.if_count}_end")
      replace(node.loc.else, ":if#{@contract.if_count}_elsif#{@elsif_count + 1}_condition;")
    else
      insert_after(condition.source_range, "; bz :if#{@contract.if_count}_end")
    end
    replace(node.loc.end, ":if#{@contract.if_count}_end")
  when 'elsif'
    @elsif_count += 1

    case node.loc.else&.source
    when 'else'
      insert_after(condition.source_range, "; bz :if#{@contract.if_count}_else")
      insert_after(block.source_range, "; b :if#{@contract.if_count}_end")
      replace(node.loc.else, ":if#{@contract.if_count}_else;")
    when 'elsif'
      insert_after(condition.source_range, "; bz :if#{@contract.if_count}_elsif#{@elsif_count + 1}_condition")
      insert_after(block.source_range, "; b :if#{@contract.if_count}_end")
      replace(node.loc.else, ":if#{@contract.if_count}_elsif#{@elsif_count + 1}_condition;")
    else
      insert_after(condition.source_range, "; bz :if#{@contract.if_count}_end")
    end

    insert_before(block.source_range, ":if#{@contract.if_count}_elsif#{@elsif_count}_logic;")
  end

  super
end