Module: RubyParserStuff

Included in:
RubyParser::Parser
Defined in:
lib/ruby_parser_extras.rb

Defined Under Namespace

Classes: Environment, Keyword, StackState

Constant Summary collapse

VERSION =
"3.10.1"
ENCODING_ORDER =

This is in sorted order of occurrence according to charlock_holmes against 500k files, with UTF_8 forced to the top.

Overwrite this contstant if you need something different.

[
  Encoding::UTF_8, # moved to top to reflect default in 2.0
  Encoding::ISO_8859_1,
  Encoding::ISO_8859_2,
  Encoding::ISO_8859_9,
  Encoding::SHIFT_JIS,
  Encoding::WINDOWS_1252,
  Encoding::EUC_JP
]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#canonicalize_conditionsObject

Canonicalize conditionals. Eg:

not x ? a : b

becomes:

x ? b : a


332
333
334
# File 'lib/ruby_parser_extras.rb', line 332

def canonicalize_conditions
  @canonicalize_conditions
end

#commentsObject (readonly)

Returns the value of attribute comments.



13
14
15
# File 'lib/ruby_parser_extras.rb', line 13

def comments
  @comments
end

#envObject (readonly)

Returns the value of attribute env.



13
14
15
# File 'lib/ruby_parser_extras.rb', line 13

def env
  @env
end

#fileObject

Returns the value of attribute file.



12
13
14
# File 'lib/ruby_parser_extras.rb', line 12

def file
  @file
end

#in_defObject

Returns the value of attribute in_def.



12
13
14
# File 'lib/ruby_parser_extras.rb', line 12

def in_def
  @in_def
end

#in_singleObject

Returns the value of attribute in_single.



12
13
14
# File 'lib/ruby_parser_extras.rb', line 12

def in_single
  @in_single
end

#lexerObject

Returns the value of attribute lexer.



12
13
14
# File 'lib/ruby_parser_extras.rb', line 12

def lexer
  @lexer
end

Class Method Details

.deprecate(old, new) ⇒ Object



26
27
28
29
30
31
# File 'lib/ruby_parser_extras.rb', line 26

def self.deprecate old, new
  define_method old do |*args|
    warn "DEPRECATED: #{old} -> #{new} from #{caller.first}"
    send new, *args
  end
end

Instance Method Details

#arg_blk_pass(node1, node2) ⇒ Object

TODO: nuke



54
55
56
57
58
# File 'lib/ruby_parser_extras.rb', line 54

def arg_blk_pass node1, node2 # TODO: nuke
  node1 = s(:arglist, node1) unless [:arglist, :call_args, :array, :args].include? node1.sexp_type 
  node1 << node2 if node2
  node1
end

#arg_concat(node1, node2) ⇒ Object

TODO: nuke



60
61
62
63
64
# File 'lib/ruby_parser_extras.rb', line 60

def arg_concat node1, node2 # TODO: nuke
  raise "huh" unless node2
  node1 << s(:splat, node2).compact
  node1
end

#argl(x) ⇒ Object



480
481
482
483
# File 'lib/ruby_parser_extras.rb', line 480

def argl x
  x = s(:arglist, x) if x and x.sexp_type == :array
  x
end

#args(args) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/ruby_parser_extras.rb', line 143

def args args
  result = s(:args)

  args.each do |arg|
    case arg
    when Sexp then
      case arg.sexp_type
      when :args, :block, :array, :call_args then # HACK call_args mismatch
        result.concat arg.sexp_body
      when :block_arg then
        result << :"&#{arg.last}"
      when :shadow then
        if Sexp === result.last and result.last.sexp_type == :shadow then
          result.last << arg.last
        else
          result << arg
        end
      when :masgn, :block_pass, :hash then # HACK: remove. prolly call_args
        result << arg
      else
        raise "unhandled: #{arg.sexp_type} in #{args.inspect}"
      end
    when Symbol then
      name = arg.to_s.delete("&*")
      self.env[name.to_sym] = :lvar unless name.empty?
      result << arg
    when ",", "|", ";", "(", ")", nil then
      # ignore
    else
      raise "unhandled: #{arg.inspect} in #{args.inspect}"
    end
  end

  result
end

#array_to_hash(array) ⇒ Object



110
111
112
113
114
115
116
117
# File 'lib/ruby_parser_extras.rb', line 110

def array_to_hash array
  case array.sexp_type
  when :kwsplat then
    array
  else
    s(:hash, *array.sexp_body)
  end
end

#aryset(receiver, index) ⇒ Object



179
180
181
182
# File 'lib/ruby_parser_extras.rb', line 179

def aryset receiver, index
  index ||= s()
  s(:attrasgn, receiver, :"[]=", *index.sexp_body).compact # [].sexp_body => nil
end

#assignable(lhs, value = nil) ⇒ Object

Raises:

  • (SyntaxError)


184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/ruby_parser_extras.rb', line 184

def assignable(lhs, value = nil)
  id = lhs.to_sym unless Sexp === lhs
  id = id.to_sym if Sexp === id

  raise "write a test 1" if id.to_s =~ /^(?:self|nil|true|false|__LINE__|__FILE__)$/

  raise SyntaxError, "Can't change the value of #{id}" if
    id.to_s =~ /^(?:self|nil|true|false|__LINE__|__FILE__)$/

  result = case id.to_s
           when /^@@/ then
             asgn = in_def || in_single > 0
             s((asgn ? :cvasgn : :cvdecl), id)
           when /^@/ then
             s(:iasgn, id)
           when /^\$/ then
             s(:gasgn, id)
           when /^[A-Z]/ then
             s(:cdecl, id)
           else
             case self.env[id]
             when :lvar, :dvar, nil then
               s(:lasgn, id)
             else
               raise "wtf? unknown type: #{self.env[id]}"
             end
           end

  self.env[id] ||= :lvar if result.sexp_type == :lasgn

  result << value if value

  return result
end

#backref_assign_error(ref) ⇒ Object



485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/ruby_parser_extras.rb', line 485

def backref_assign_error ref
  # TODO: need a test for this... obviously
  case ref.sexp_type
  when :nth_ref then
    raise "write a test 2"
    raise SyntaxError, "Can't set variable %p" % ref.last
  when :back_ref then
    raise "write a test 3"
    raise SyntaxError, "Can't set back reference %p" % ref.last
  else
    raise "Unknown backref type: #{ref.inspect}"
  end
end

#block_append(head, tail) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/ruby_parser_extras.rb', line 219

def block_append(head, tail)
  return head if tail.nil?
  return tail if head.nil?

  line = [head.line, tail.line].compact.min

  head = remove_begin(head)
  head = s(:block, head) unless head.node_type == :block

  head.line = line
  head << tail
end

#block_dup_check(call_or_args, block) ⇒ Object



1110
1111
1112
1113
# File 'lib/ruby_parser_extras.rb', line 1110

def block_dup_check call_or_args, block
  syntax_error "Both block arg and actual block given." if
    block and call_or_args.block_pass?
end

#block_var(*args) ⇒ Object



87
88
89
90
91
# File 'lib/ruby_parser_extras.rb', line 87

def block_var *args
  result = self.args args
  result.sexp_type = :masgn
  result
end

#block_var18(ary, splat, block) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/ruby_parser_extras.rb', line 93

def block_var18 ary, splat, block
  ary ||= s(:array)

  if splat then
    splat = splat[1] unless Symbol === splat
    ary << "*#{splat}".to_sym
  end

  ary << "&#{block[1]}".to_sym if block

  if ary.length > 2 or ary.splat then # HACK
    s(:masgn, *ary.sexp_body)
  else
    ary.last
  end
end

#call_args(args) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/ruby_parser_extras.rb', line 119

def call_args args
  result = s(:call_args)

  args.each do |arg|
    case arg
    when Sexp then
      case arg.sexp_type
      when :array, :args, :call_args then # HACK? remove array at some point
        result.concat arg.sexp_body
      else
        result << arg
      end
    when Symbol then
      result << arg
    when ",", nil then
      # ignore
    else
      raise "unhandled: #{arg.inspect} in #{args.inspect}"
    end
  end

  result
end

#clean_mlhs(sexp) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ruby_parser_extras.rb', line 66

def clean_mlhs sexp
  case sexp.sexp_type
  when :masgn then
    if sexp.size == 2 and sexp[1].sexp_type == :array then
      s(:masgn, *sexp[1].sexp_body.map { |sub| clean_mlhs sub })
    else
      debug20 5
      sexp
    end
  when :gasgn, :iasgn, :lasgn, :cvasgn then
    if sexp.size == 2 then
      sexp.last
    else
      debug20 7
      sexp # optional value
    end
  else
    raise "unsupported type: #{sexp.inspect}"
  end
end

#cond(node) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/ruby_parser_extras.rb', line 232

def cond node
  return nil if node.nil?
  node = value_expr node

  case node.sexp_type
  when :lit then
    if Regexp === node.last then
      return s(:match, node)
    else
      return node
    end
  when :and then
    return s(:and, cond(node[1]), cond(node[2]))
  when :or then
    return s(:or,  cond(node[1]), cond(node[2]))
  when :dot2 then
    label = "flip#{node.hash}"
    env[label] = :lvar
    _, lhs, rhs = node
    return s(:flip2, lhs, rhs)
  when :dot3 then
    label = "flip#{node.hash}"
    env[label] = :lvar
    _, lhs, rhs = node
    return s(:flip3, lhs, rhs)
  else
    return node
  end
end

#debug20(n, v = nil, r = nil) ⇒ Object



22
23
24
# File 'lib/ruby_parser_extras.rb', line 22

def debug20 n, v = nil, r = nil
  raise "not yet #{n} #{v.inspect} => #{r.inspect}" unless $good20[n]
end

#do_parseObject

for pure ruby systems only



265
266
267
# File 'lib/ruby_parser_extras.rb', line 265

def do_parse
  _racc_do_parse_rb(_racc_setup, false)
end

#gettable(id) ⇒ Object



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
# File 'lib/ruby_parser_extras.rb', line 294

def gettable(id)
  lineno = id.lineno if id.respond_to? :lineno
  id = id.to_sym if String === id

  result = case id.to_s
           when /^@@/ then
             s(:cvar, id)
           when /^@/ then
             s(:ivar, id)
           when /^\$/ then
             s(:gvar, id)
           when /^[A-Z]/ then
             s(:const, id)
           else
             type = env[id]
             if type then
               s(type, id)
             else
               new_call(nil, id)
             end
           end

  result.line lineno if lineno

  raise "identifier #{id.inspect} is not valid" unless result

  result
end

#hack_encoding(str, extra = nil) ⇒ Object



1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
# File 'lib/ruby_parser_extras.rb', line 1046

def hack_encoding str, extra = nil
  encodings = ENCODING_ORDER.dup
  encodings.unshift(extra) unless extra.nil?

  # terrible, horrible, no good, very bad, last ditch effort.
  encodings.each do |enc|
    begin
      str.force_encoding enc
      if str.valid_encoding? then
        str.encode! Encoding::UTF_8
        break
      end
    rescue Encoding::InvalidByteSequenceError
      # do nothing
    rescue Encoding::UndefinedConversionError
      # do nothing
    end
  end

  # no amount of pain is enough for you.
  raise "Bad encoding. Need a magic encoding comment." unless
    str.encoding.name == "UTF-8"
end

#handle_encoding(str) ⇒ Object

Returns a UTF-8 encoded string after processing BOMs and magic encoding comments.

Holy crap… ok. Here goes:

Ruby’s file handling and encoding support is insane. We need to be able to lex a file. The lexer file is explicitly UTF-8 to make things cleaner. This allows us to deal with extended chars in class and method names. In order to do this, we need to encode all input source files as UTF-8. First, we look for a UTF-8 BOM by looking at the first line while forcing its encoding to ASCII-8BIT. If we find a BOM, we strip it and set the expected encoding to UTF-8. Then, we search for a magic encoding comment. If found, it overrides the BOM. Finally, we force the encoding of the input string to whatever was found, and then encode that to UTF-8 for compatibility with the lexer.



1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
# File 'lib/ruby_parser_extras.rb', line 1015

def handle_encoding str
  str = str.dup
  has_enc = str.respond_to? :encoding
  encoding = nil

  header = str.lines.first(2)
  header.map! { |s| s.force_encoding "ASCII-8BIT" } if has_enc

  first = header.first || ""
  encoding, str = "utf-8", str[3..-1] if first =~ /\A\xEF\xBB\xBF/

  encoding = $1.strip if header.find { |s|
    s[/^#.*?-\*-.*?coding:\s*([^ ;]+).*?-\*-/, 1] ||
    s[/^#.*(?:en)?coding(?:\s*[:=])\s*([\w-]+)/, 1]
  }

  if encoding then
    if has_enc then
      encoding.sub!(/utf-8-.+$/, 'utf-8') # HACK for stupid emacs formats
      hack_encoding str, encoding
    else
      warn "Skipping magic encoding comment"
    end
  else
    # nothing specified... ugh. try to encode as utf-8
    hack_encoding str if has_enc
  end

  str
end

#initialize(options = {}) ⇒ Object



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/ruby_parser_extras.rb', line 334

def initialize(options = {})
  super()

  v = self.class.name[/1[89]|2[01]/]

  self.lexer = RubyLexer.new v && v.to_i
  self.lexer.parser = self

  @env = RubyParserStuff::Environment.new
  @comments = []

  @canonicalize_conditions = true

  self.reset
end

#invert_block_call(val) ⇒ Object



1119
1120
1121
1122
1123
1124
1125
# File 'lib/ruby_parser_extras.rb', line 1119

def invert_block_call val
  (type, call), iter = val

  iter.insert 1, call

  [iter, s(type)]
end

#inverted?(val) ⇒ Boolean

Returns:

  • (Boolean)


1115
1116
1117
# File 'lib/ruby_parser_extras.rb', line 1115

def inverted? val
  [:return, :next, :break, :yield].include? val[0].sexp_type
end

#list_append(list, item) ⇒ Object

TODO: nuke me sigh



350
351
352
353
354
# File 'lib/ruby_parser_extras.rb', line 350

def list_append list, item # TODO: nuke me *sigh*
  return s(:array, item) unless list
  list = s(:array, list) unless Sexp === list && list.sexp_type == :array
  list << item
end

#list_prepend(item, list) ⇒ Object

TODO: nuke me sigh



356
357
358
359
360
# File 'lib/ruby_parser_extras.rb', line 356

def list_prepend item, list # TODO: nuke me *sigh*
  list = s(:array, list) unless Sexp === list && list.sexp_type == :array
  list.insert 1, item
  list
end

#literal_concat(head, tail) ⇒ Object

TODO: ugh. rewrite



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/ruby_parser_extras.rb', line 362

def literal_concat head, tail # TODO: ugh. rewrite
  return tail unless head
  return head unless tail

  htype, ttype = head.sexp_type, tail.sexp_type

  head = s(:dstr, '', head) if htype == :evstr

  case ttype
  when :str then
    if htype == :str
      head.last << tail.last
    elsif htype == :dstr and head.size == 2 then
      head.last << tail.last
    else
      head << tail
    end
  when :dstr then
    if htype == :str then
      lineno = head.line
      tail[1] = head.last + tail[1]
      head = tail
      head.line = lineno
    else
      tail.sexp_type = :array
      tail[1] = s(:str, tail[1])
      tail.delete_at 1 if tail[1] == s(:str, '')

      head.push(*tail.sexp_body)
    end
  when :evstr then
    if htype == :str then
      f, l = head.file, head.line
      head = s(:dstr, *head.sexp_body)
      head.file = f
      head.line = l
    end

    if head.size == 2 and tail.size > 1 and tail[1].sexp_type == :str then
      head.last << tail[1].last
      head.sexp_type = :str if head.size == 2 # HACK ?
    else
      head.push(tail)
    end
  else
    x = [head, tail]
    raise "unknown type: #{x.inspect}"
  end

  return head
end

#logical_op(type, left, right) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/ruby_parser_extras.rb', line 414

def logical_op type, left, right
  left = value_expr left

  if left and left.sexp_type == type and not left.paren then
    node, rhs = left, nil

    loop do
      _, _lhs, rhs = node
      break unless rhs && rhs.sexp_type == type and not rhs.paren
      node = rhs
    end

    node[2] = s(type, rhs, right)

    return left
  end

  return s(type, left, right)
end

#new_aref(val) ⇒ Object



437
438
439
440
441
442
443
444
445
446
# File 'lib/ruby_parser_extras.rb', line 437

def new_aref val
  val[2] ||= s(:arglist)
  val[2].sexp_type = :arglist if val[2].sexp_type == :array # REFACTOR
  if val[0].node_type == :self then
    result = new_call nil, :"[]", val[2]
  else
    result = new_call val[0], :"[]", val[2]
  end
  result
end

#new_assign(lhs, rhs) ⇒ Object



976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
# File 'lib/ruby_parser_extras.rb', line 976

def new_assign lhs, rhs
  return nil unless lhs

  rhs = value_expr rhs

  case lhs.sexp_type
  when :lasgn, :iasgn, :cdecl, :cvdecl, :gasgn, :cvasgn, :attrasgn, :safe_attrasgn then
    lhs << rhs
  when :const then
    lhs.sexp_type = :cdecl
    lhs << rhs
  else
    raise "unknown lhs #{lhs.inspect} w/ #{rhs.inspect}"
  end

  lhs
end

#new_attrasgn(recv, meth, call_op) ⇒ Object



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/ruby_parser_extras.rb', line 526

def new_attrasgn recv, meth, call_op
  meth = :"#{meth}="

  result = case call_op.to_sym
           when :'.'
             s(:attrasgn, recv, meth)
           when :'&.'
             s(:safe_attrasgn, recv, meth)
           else
             raise "unknown call operator: `#{type.inspect}`"
           end

  result.line = recv.line
  result
end

#new_body(val) ⇒ Object



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/ruby_parser_extras.rb', line 448

def new_body val
  body, resbody, elsebody, ensurebody = val

  result = body

  if resbody then
    result = s(:rescue)
    result << body if body

    res = resbody

    while res do
      result << res
      res = res.resbody(true)
    end

    result << elsebody if elsebody

    result.line = (body || resbody).line
  end

  if elsebody and not resbody then
    warning("else without rescue is useless")
    result = s(:begin, result) if result
    result = block_append(result, elsebody)
  end

  result = s(:ensure, result, ensurebody).compact if ensurebody

  result
end

#new_call(recv, meth, args = nil, call_op = :'.') ⇒ Object



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'lib/ruby_parser_extras.rb', line 499

def new_call recv, meth, args = nil, call_op = :'.'
  result = case call_op.to_sym
           when :'.'
             s(:call, recv, meth)
           when :'&.'
             s(:safe_call, recv, meth)
           else
             raise "unknown call operator: `#{type.inspect}`"
           end

  # TODO: need a test with f(&b) to produce block_pass
  # TODO: need a test with f(&b) { } to produce warning

  if args
    if [:arglist, :args, :array, :call_args].include? args.sexp_type
      result.concat args.sexp_body
    else
      result << args
    end
  end

  line = result.grep(Sexp).map(&:line).compact.min
  result.line = line if line

  result
end

#new_case(expr, body, line) ⇒ Object



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'lib/ruby_parser_extras.rb', line 542

def new_case expr, body, line
  result = s(:case, expr)

  while body and body.node_type == :when
    result << body
    body = body.delete_at 3
  end

  result[2..-1].each do |node|
    block = node.block(:delete)
    node.concat block.sexp_body if block
  end

  # else
  body = nil if body == s(:block)
  result << body

  result.line = line
  result
end

#new_class(val) ⇒ Object



563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/ruby_parser_extras.rb', line 563

def new_class val
  line, path, superclass, body = val[1], val[2], val[3], val[5]

  result = s(:class, path, superclass)

  if body then
    if body.sexp_type == :block then
      result.push(*body.sexp_body)
    else
      result.push body
    end
  end

  result.line = line
  result.comments = self.comments.pop
  result
end

#new_compstmt(val) ⇒ Object



581
582
583
584
585
# File 'lib/ruby_parser_extras.rb', line 581

def new_compstmt val
  result = void_stmts(val.grep(Sexp)[0])
  result = remove_begin(result) if result
  result
end

#new_defn(val) ⇒ Object



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/ruby_parser_extras.rb', line 587

def new_defn val
  (_, line), name, _, args, body, * = val
  body ||= s(:nil)

  result = s(:defn, name.to_sym, args)

  if body then
    if body.sexp_type == :block then
      result.push(*body.sexp_body)
    else
      result.push body
    end
  end

  args.line line
  result.line = line
  result.comments = self.comments.pop

  result
end

#new_defs(val) ⇒ Object



608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'lib/ruby_parser_extras.rb', line 608

def new_defs val
  recv, name, args, body = val[1], val[4], val[6], val[7]
  body ||= s(:nil)

  result = s(:defs, recv, name.to_sym, args)

  if body then
    if body.sexp_type == :block then
      result.push(*body.sexp_body)
    else
      result.push body
    end
  end

  result.line = recv.line
  result.comments = self.comments.pop
  result
end

#new_for(expr, var, body) ⇒ Object



627
628
629
630
631
# File 'lib/ruby_parser_extras.rb', line 627

def new_for expr, var, body
  result = s(:for, expr, var).line(var.line)
  result << body if body
  result
end

#new_hash(val) ⇒ Object



633
634
635
# File 'lib/ruby_parser_extras.rb', line 633

def new_hash val
  s(:hash, *val[2].values).line(val[1])
end

#new_if(c, t, f) ⇒ Object



637
638
639
640
641
642
# File 'lib/ruby_parser_extras.rb', line 637

def new_if c, t, f
  l = [c.line, t && t.line, f && f.line].compact.min
  c = cond c
  c, t, f = c.last, f, t if c.sexp_type == :not and canonicalize_conditions
  s(:if, c, t, f).line(l)
end

#new_iter(call, args, body) ⇒ Object



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# File 'lib/ruby_parser_extras.rb', line 644

def new_iter call, args, body
  body ||= nil

  args ||= s(:args)
  args = s(:args, args) if Symbol === args

  result = s(:iter)
  result << call if call
  result << args
  result << body if body

  args.sexp_type = :args unless args == 0

  result
end

#new_masgn(lhs, rhs, wrap = false) ⇒ Object



666
667
668
669
670
671
672
673
674
675
676
# File 'lib/ruby_parser_extras.rb', line 666

def new_masgn lhs, rhs, wrap = false
  _, ary = lhs

  rhs = value_expr(rhs)
  rhs = ary ? s(:to_ary, rhs) : s(:array, rhs) if wrap

  lhs.delete_at 1 if ary.nil?
  lhs << rhs

  lhs
end

#new_masgn_arg(rhs, wrap = false) ⇒ Object



660
661
662
663
664
# File 'lib/ruby_parser_extras.rb', line 660

def new_masgn_arg rhs, wrap = false
  rhs = value_expr(rhs)
  rhs = s(:to_ary, rhs) if wrap # HACK: could be array if lhs isn't right
  rhs
end

#new_match(lhs, rhs) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/ruby_parser_extras.rb', line 269

def new_match lhs, rhs
  if lhs then
    case lhs.sexp_type
    when :dregx, :dregx_once then
      return s(:match2, lhs, rhs).line(lhs.line)
    when :lit then
      return s(:match2, lhs, rhs).line(lhs.line) if Regexp === lhs.last
    end
  end

  if rhs then
    case rhs.sexp_type
    when :dregx, :dregx_once then
      return s(:match3, rhs, lhs).line(lhs.line)
    when :lit then
      return s(:match3, rhs, lhs).line(lhs.line) if Regexp === rhs.last
    end
  end

  return new_call(lhs, :"=~", argl(rhs)).line(lhs.line)
end

#new_module(val) ⇒ Object



678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# File 'lib/ruby_parser_extras.rb', line 678

def new_module val
  line, path, body = val[1], val[2], val[4]

  result = s(:module, path)

  if body then # REFACTOR?
    if body.sexp_type == :block then
      result.push(*body.sexp_body)
    else
      result.push body
    end
  end

  result.line = line
  result.comments = self.comments.pop
  result
end

#new_op_asgn(val) ⇒ Object



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
# File 'lib/ruby_parser_extras.rb', line 696

def new_op_asgn val
  lhs, asgn_op, arg = val[0], val[1].to_sym, val[2]
  name = lhs.value
  arg = remove_begin(arg)
  result = case asgn_op # REFACTOR
           when :"||" then
             lhs << arg
             s(:op_asgn_or, self.gettable(name), lhs)
           when :"&&" then
             lhs << arg
             s(:op_asgn_and, self.gettable(name), lhs)
           else
             # TODO: why [2] ?
             lhs[2] = new_call(self.gettable(name), asgn_op, argl(arg))
             lhs
           end
  result.line = lhs.line
  result
end

#new_op_asgn2(val) ⇒ Object



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/ruby_parser_extras.rb', line 716

def new_op_asgn2 val
  recv, call_op, meth, op, arg = val
  meth = :"#{meth}="

  result = case call_op.to_sym
           when :'.'
             s(:op_asgn2, recv, meth, op.to_sym, arg)
           when :'&.'
             s(:safe_op_asgn2, recv, meth, op.to_sym, arg)
           else
             raise "unknown call operator: `#{type.inspect}`"
           end

  result.line = recv.line
  result
end

#new_qsym_listObject



853
854
855
856
857
# File 'lib/ruby_parser_extras.rb', line 853

def new_qsym_list
  result = s(:array)
  self.lexer.fixup_lineno
  result
end

#new_qsym_list_entry(val) ⇒ Object



859
860
861
862
863
# File 'lib/ruby_parser_extras.rb', line 859

def new_qsym_list_entry val
  result = s(:lit, val[1].to_sym)
  self.lexer.fixup_lineno
  result
end

#new_qword_listObject



835
836
837
838
839
# File 'lib/ruby_parser_extras.rb', line 835

def new_qword_list
  result = s(:array)
  self.lexer.fixup_lineno
  result
end

#new_qword_list_entry(val) ⇒ Object



827
828
829
830
831
832
833
# File 'lib/ruby_parser_extras.rb', line 827

def new_qword_list_entry val
  str = val[1]
  str.force_encoding("ASCII-8BIT") unless str.valid_encoding? unless RUBY_VERSION < "1.9"
  result = s(:str, str)
  self.lexer.fixup_lineno
  result
end

#new_regexp(val) ⇒ Object



733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
# File 'lib/ruby_parser_extras.rb', line 733

def new_regexp val
  node = val[1] || s(:str, '')
  options = val[2]

  o, k = 0, nil
  options.split(//).uniq.each do |c| # FIX: this has a better home
    v = {
      'x' => Regexp::EXTENDED,
      'i' => Regexp::IGNORECASE,
      'm' => Regexp::MULTILINE,
      'o' => Regexp::ONCE,
      'n' => Regexp::ENC_NONE,
      'e' => Regexp::ENC_EUC,
      's' => Regexp::ENC_SJIS,
      'u' => Regexp::ENC_UTF8,
    }[c]
    raise "unknown regexp option: #{c}" unless v
    o += v

    # encoding options are ignored on 1.9+
    k = c if c =~ /[esu]/ if RUBY_VERSION < "1.9"
  end

  case node.sexp_type
  when :str then
    node.sexp_type = :lit
    node[1] = if k then
                Regexp.new(node[1], o, k)
              else
                begin
                  Regexp.new(node[1], o)
                rescue RegexpError => e
                  warn "WA\RNING: #{e.message} for #{node[1].inspect} #{options.inspect}"
                  begin
                    warn "WA\RNING: trying to recover with ENC_UTF8"
                    Regexp.new(node[1], Regexp::ENC_UTF8)
                  rescue RegexpError => e
                    warn "WA\RNING: trying to recover with ENC_NONE"
                    Regexp.new(node[1], Regexp::ENC_NONE)
                  end
                end
              end
  when :dstr then
    if options =~ /o/ then
      node.sexp_type = :dregx_once
    else
      node.sexp_type = :dregx
    end
    node << o if o and o != 0
  else
    node = s(:dregx, '', node);
    node.sexp_type = :dregx_once if options =~ /o/
    node << o if o and o != 0
  end

  node
end

#new_resbody(cond, body) ⇒ Object



791
792
793
794
795
796
797
798
# File 'lib/ruby_parser_extras.rb', line 791

def new_resbody cond, body
  if body && body.sexp_type == :block then
    body.shift # remove block and splat it in directly
  else
    body = [body]
  end
  s(:resbody, cond, *body).line cond.line
end

#new_sclass(val) ⇒ Object



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
# File 'lib/ruby_parser_extras.rb', line 800

def new_sclass val
  recv, in_def, in_single, body = val[3], val[4], val[6], val[7]

  result = s(:sclass, recv)

  if body then
    if body.sexp_type == :block then
      result.push(*body.sexp_body)
    else
      result.push body
    end
  end

  result.line = val[2]
  self.in_def = in_def
  self.in_single = in_single
  result
end

#new_string(val) ⇒ Object



819
820
821
822
823
824
825
# File 'lib/ruby_parser_extras.rb', line 819

def new_string val
  str = val[0]
  str.force_encoding("ASCII-8BIT") unless str.valid_encoding? unless RUBY_VERSION < "1.9"
  result = s(:str, str)
  self.lexer.fixup_lineno str.count("\n")
  result
end

#new_super(args) ⇒ Object



890
891
892
893
894
895
896
897
# File 'lib/ruby_parser_extras.rb', line 890

def new_super args
  if args && args.node_type == :block_pass then
    s(:super, args)
  else
    args ||= s(:arglist)
    s(:super, *args.sexp_body)
  end
end

#new_symbol_listObject



865
866
867
868
869
# File 'lib/ruby_parser_extras.rb', line 865

def new_symbol_list
  result = s(:array)
  self.lexer.fixup_lineno
  result
end

#new_symbol_list_entry(val) ⇒ Object



871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
# File 'lib/ruby_parser_extras.rb', line 871

def new_symbol_list_entry val
  _list, sym, _nil = val # TODO: use _list
  result = val[1]

  result ||= s(:str, "")

  case sym.sexp_type
  when :dstr then
    sym.sexp_type = :dsym
  when :str then
    sym = s(:lit, sym.last.to_sym)
  else
    debug20 24
    sym = s(:dsym, "", sym || s(:str, ""))
  end
  self.lexer.fixup_lineno
  sym
end

#new_undef(n, m = nil) ⇒ Object



899
900
901
902
903
904
905
# File 'lib/ruby_parser_extras.rb', line 899

def new_undef n, m = nil
  if m then
    block_append(n, s(:undef, m))
  else
    s(:undef, n)
  end
end

#new_until(block, expr, pre) ⇒ Object



907
908
909
# File 'lib/ruby_parser_extras.rb', line 907

def new_until block, expr, pre
  new_until_or_while :until, block, expr, pre
end

#new_until_or_while(type, block, expr, pre) ⇒ Object



911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
# File 'lib/ruby_parser_extras.rb', line 911

def new_until_or_while type, block, expr, pre
  other = type == :until ? :while : :until
  line = [block && block.line, expr.line].compact.min
  block, pre = block.last, false if block && block.sexp_type == :begin

  expr = cond expr

  result = unless expr.sexp_type == :not and canonicalize_conditions then
             s(type,  expr,      block, pre)
           else
             s(other, expr.last, block, pre)
           end

  result.line = line
  result
end

#new_when(cond, body) ⇒ Object



928
929
930
# File 'lib/ruby_parser_extras.rb', line 928

def new_when cond, body
  s(:when, cond, body)
end

#new_while(block, expr, pre) ⇒ Object



932
933
934
# File 'lib/ruby_parser_extras.rb', line 932

def new_while block, expr, pre
  new_until_or_while :while, block, expr, pre
end

#new_word_listObject



841
842
843
844
845
# File 'lib/ruby_parser_extras.rb', line 841

def new_word_list
  result = s(:array)
  self.lexer.fixup_lineno
  result
end

#new_word_list_entry(val) ⇒ Object



847
848
849
850
851
# File 'lib/ruby_parser_extras.rb', line 847

def new_word_list_entry val
  result = val[1].sexp_type == :evstr ? s(:dstr, "", val[1]) : val[1]
  self.lexer.fixup_lineno
  result
end

#new_xstring(str) ⇒ Object



936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
# File 'lib/ruby_parser_extras.rb', line 936

def new_xstring str
  if str then
    case str.sexp_type
    when :str
      str.sexp_type = :xstr
    when :dstr
      str.sexp_type = :dxstr
    else
      str = s(:dxstr, '', str)
    end
    str
  else
    s(:xstr, '')
  end
end

#new_yield(args = nil) ⇒ Object

Raises:

  • (SyntaxError)


952
953
954
955
956
957
958
959
960
961
962
963
964
# File 'lib/ruby_parser_extras.rb', line 952

def new_yield args = nil
  # TODO: raise args.inspect unless [:arglist].include? args.first # HACK
  raise "write a test 4" if args && args.node_type == :block_pass
  raise SyntaxError, "Block argument should not be given." if
    args && args.node_type == :block_pass

  args ||= s(:arglist)

  args.sexp_type = :arglist if [:call_args, :array].include? args.sexp_type
  args = s(:arglist, args) unless args.sexp_type == :arglist

  return s(:yield, *args.sexp_body)
end

#next_tokenObject



966
967
968
969
970
971
972
973
974
# File 'lib/ruby_parser_extras.rb', line 966

def next_token
  token = self.lexer.next_token

  if token and token.first != RubyLexer::EOF then
    return token
  else
    return [false, '$end']
  end
end

#on_error(et, ev, values) ⇒ Object



1179
1180
1181
1182
1183
1184
1185
1186
# File 'lib/ruby_parser_extras.rb', line 1179

def on_error(et, ev, values)
  super
rescue Racc::ParseError => e
  # I don't like how the exception obscures the error message
  e.message.replace "%s:%p :: %s" % [self.file, lexer.lineno, e.message.strip]
  warn e.message if $DEBUG
  raise
end

#process(str, file = "(string)", time = 10) ⇒ Object Also known as: parse

Parse str at path file and return a sexp. Raises Timeout::Error if it runs for more than time seconds.



1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
# File 'lib/ruby_parser_extras.rb', line 1074

def process(str, file = "(string)", time = 10)
  Timeout.timeout time do
    raise "bad val: #{str.inspect}" unless String === str

    str = handle_encoding str

    self.file = file.dup

    @yydebug = ENV.has_key? 'DEBUG'

    # HACK -- need to get tests passing more than have graceful code
    self.lexer.ss = RPStringScanner.new str

    do_parse
  end
end

#remove_begin(node) ⇒ Object



1093
1094
1095
1096
1097
1098
1099
1100
# File 'lib/ruby_parser_extras.rb', line 1093

def remove_begin node
  oldnode = node
  if node and node.sexp_type == :begin and node.size == 2 then
    node = node.last
    node.line = oldnode.line
  end
  node
end

#resetObject



1102
1103
1104
1105
1106
1107
1108
# File 'lib/ruby_parser_extras.rb', line 1102

def reset
  lexer.reset
  self.in_def = false
  self.in_single = 0
  self.env.reset
  self.comments.clear
end

#ret_args(node) ⇒ Object



1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
# File 'lib/ruby_parser_extras.rb', line 1127

def ret_args node
  if node then
    raise "write a test 5" if node.sexp_type == :block_pass

    raise SyntaxError, "block argument should not be given" if
      node.sexp_type == :block_pass

    node.sexp_type = :array if node.sexp_type == :call_args
    node = node.last if node.sexp_type == :array && node.size == 2

    # HACK matz wraps ONE of the FOUR splats in a newline to
    # distinguish. I use paren for now. ugh
    node = s(:svalue, node) if node.sexp_type == :splat and not node.paren
    node.sexp_type = :svalue if node.sexp_type == :arglist && node[1].sexp_type == :splat
  end

  node
end

#s(*args) ⇒ Object



1146
1147
1148
1149
1150
1151
# File 'lib/ruby_parser_extras.rb', line 1146

def s(*args)
  result = Sexp.new(*args)
  result.line ||= lexer.lineno if lexer.ss          # otherwise...
  result.file = self.file
  result
end

#syntax_error(msg) ⇒ Object Also known as: yyerror



50
51
52
# File 'lib/ruby_parser_extras.rb', line 50

def syntax_error msg
  raise RubyParser::SyntaxError, msg
end

#value_expr(oldnode) ⇒ Object

HACK



1153
1154
1155
1156
1157
1158
# File 'lib/ruby_parser_extras.rb', line 1153

def value_expr oldnode # HACK
  node = remove_begin oldnode
  node.line = oldnode.line if oldnode
  node[2] = value_expr node[2] if node and node.sexp_type == :if
  node
end

#void_stmts(node) ⇒ Object



1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
# File 'lib/ruby_parser_extras.rb', line 1160

def void_stmts node
  return nil unless node
  return node unless node.sexp_type == :block

  if node.respond_to? :sexp_body= then
    node.sexp_body = node.sexp_body.map { |n| remove_begin n }
  else
    node[1..-1] = node[1..-1].map { |n| remove_begin(n) }
  end

  node
end

#warning(s) ⇒ Object



1173
1174
1175
# File 'lib/ruby_parser_extras.rb', line 1173

def warning s
  # do nothing for now
end