Skip to content

Instantly share code, notes, and snippets.

@pocke
Created April 27, 2019 11:23
Show Gist options
  • Save pocke/83005390d860e073335e7afaed0fe467 to your computer and use it in GitHub Desktop.
Save pocke/83005390d860e073335e7afaed0fe467 to your computer and use it in GitHub Desktop.
RubyVM::ASTハマりどころ

returnが消える

# return 1のreturnはあってもなくても変わらないので、消える。 def foo() return 1 if cond; something end なら消えない。
pp RubyVM::AbstractSyntaxTree.parse("def foo() return 1 end")
(SCOPE@1:0-1:27
 tbl: []
 args: nil
 body:
   (DEFN@1:0-1:27
    mid: :foo
    body:
      (SCOPE@1:0-1:27
       tbl: []
       args:
         (ARGS@1:7-1:8
          pre_num: 0
          pre_init: nil
          opt: nil
          first_post: nil
          post_num: 0
          post_init: nil
          rest: nil
          kw: nil
          kwrest: nil
          block: nil)
       body: (IF@1:10-1:23 (VCALL@1:22-1:23 :x) (LIT@1:17-1:18 1) nil))))

ifとunless, whileとuntilは違うnode type

lasgnとopasgn

pp RubyVM::AbstractSyntaxTree.parse("x = 1").children.last.children
pp RubyVM::AbstractSyntaxTree.parse("x += 1").children.last.children
[:x, (LIT@1:4-1:5 1)]
[:x, (CALL@1:0-1:6 (LVAR@1:0-1:1 :x) :+ (ARRAY@1:5-1:6 (LIT@1:5-1:6 1) nil))]

しれっとchildren[1]にlvarが登場してくるから気をつける必要がある。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment