Class: Yoda::Parsing::SourceCutter::BlockFixer

Inherits:
Object
  • Object
show all
Defined in:
lib/yoda/parsing/source_cutter.rb

Instance Method Summary collapse

Instance Method Details

#process(remained_tokens, tokens_to_add) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/yoda/parsing/source_cutter.rb', line 192

def process(remained_tokens, tokens_to_add)
  fail CannotRecoverError, "Cannot resolve block error" if remained_tokens.empty?
  stack = []
  tokens_to_add = tokens_to_add.dup

  remained_tokens.each_with_index.reverse_each do |(token, _), i|
    case token
    when :kIF, :kUNLESS, :kWHILE, :kUNTIL, :kCLASS, :kFOR, :kBEGIN, :kCASE, :kCLASS, :kMODULE, :kDEF
      reduce(stack, tokens_to_add, :kEND)
    when :kDO
      next if i > 0 && [:kWHILE, :kUNTIL, :kFOR].include?(remained_tokens[i].first)
      reduce(stack, tokens_to_add, :kEND)
    when :kEND
      stack.push(:kEND)
    when :tLBRACE, :tLCURLY
      reduce(stack, tokens_to_add, :tRBRACE)
    when :tRBRACE, :tRCURLY
      stack.push(:tRBRACE)
    end
  end

  fail CannotRecoverError, "Block mismatch in existing source" unless stack.empty?
  tokens_to_add
end

#reduce(stack, tokens_to_add, expected) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
# File 'lib/yoda/parsing/source_cutter.rb', line 217

def reduce(stack, tokens_to_add, expected)
  if stack.empty?
    tokens_to_add.push(expected)
  else
    if stack.last == expected
      stack.pop
    else
      fail CannotRecoverError, "Block mismatch in existing source"
    end
  end
end