4

私は次のような単純な関数の束を含むGroovyファイルを持っています:

// useful functions
def myFunc1(String arg) {
    println("Hello " + arg)
}

def myFunc2(String arg) {
    println("Goodbye " + arg)
}

これから取得したい:

  • メソッド名
  • 引数
  • 関数の本文コード

(すべて単純な文字列なので、まだ何も実行する必要はありません。)

私はいくつかのRegexingに頼ろうとしていましたが、JVM言語(Scala)を使用しているので、Groovyコンパイラーのもののいくつかを使用してこれを「より良い」方法で実行できるかもしれないと考えました。

Groovyコードを動的にロードして実行することについてはかなりの情報があるようですが、ソースの内省についてはそれほど多くはありません。何か案は?

(「いい」方法に失敗した場合は、Scala-fooを受け入れて、情報を簡潔に解析します。)

4

1 に答える 1

6

これは機能し、AST で重要な各ノードを見つけるために必要なトークンの種類を示しています。それが理にかなっていることを願っています... 多くのGroovyダイナミズムを使用することで、Scalaへの移植が難しくなりすぎていないことを願っています:-(

import org.codehaus.groovy.antlr.*
import org.codehaus.groovy.antlr.parser.*
import static org.codehaus.groovy.antlr.parser.GroovyTokenTypes.*

def code = '''
// useful functions
def myFunc1(String arg) {
    println("Hello " + arg)
}

def myFunc2(arg, int arg2) {
    println("Goodbye " + arg)
}

public String stringify( int a ) {
  "$a"
}
'''

def lines = code.split( '\n' )

// Generate a GroovyRecognizer, compile an AST and assign it to 'ast'
def ast = new SourceBuffer().with { buff ->
  new UnicodeEscapingReader( new StringReader( code ), buff ).with { read ->
    read.lexer = new GroovyLexer( read )
    GroovyRecognizer.make( read.lexer ).with { parser ->
      parser.sourceBuffer = buff
      parser.compilationUnit()
      parser.AST
    }
  }
}

// Walks the ast looking for types
def findByPath( ast, types, multiple=false ) {
  [types.take( 1 )[ 0 ],types.drop(1)].with { head, tail ->
    if( tail ) {
      findByPath( ast*.childrenOfType( head ).flatten(), tail, multiple )
    }
    else {
      ast*.childrenOfType( head ).with { ret ->
        multiple ? ret[ 0 ] : ret.head()[0]
      }
    }
  }
}

// Walk through the returned ast
while( ast ) {
  def methodModifier = findByPath( ast, [ MODIFIERS   ] ).firstChild?.toStringTree() ?: 'public'
  def returnType     = findByPath( ast, [ TYPE, IDENT ] ) ?: 'Object'
  def methodName     = findByPath( ast, [ IDENT       ] )
  def body           = findByPath( ast, [ SLIST ] )
  def parameters     = findByPath( ast, [ PARAMETERS, PARAMETER_DEF ], true ).collect { param ->
    [ type: findByPath( param, [ TYPE ] ).firstChild?.toStringTree() ?: 'Object',
      name: findByPath( param, [ IDENT ] ) ]
  }

  def (y1,y2,x1,x2) = [ body.line - 1, body.lineLast - 1, body.column - 1, body.columnLast ]
  // Grab the text from the original string
  def snip = [  lines[ y1 ].drop( x1 ),                // First line prefix stripped
               *lines[ (y1+1)..<y2 ],                  // Mid lines
                lines[ y2 ].take( x2 ) ].join( '\n' )  // End line suffix stripped

  println '------------------------------'
  println "modifier: $methodModifier"
  println "returns:  $returnType"
  println "name:     $methodName"
  println "params:   $parameters"
  println "$snip\n"

  // Step to next branch and repeat
  ast = ast.nextSibling
}

次のように出力されます。

------------------------------
modifier: public
returns:  Object
name:     myFunc1
params:   [[type:String, name:arg]]
{
    println("Hello " + arg)
}

------------------------------
modifier: public
returns:  Object
name:     myFunc2
params:   [[type:Object, name:arg], [type:int, name:arg2]]
{
    println("Goodbye " + arg)
}

------------------------------
modifier: public
returns:  String
name:     stringify
params:   [[type:int, name:a]]
{
  "$a"
}

それが役立つこと、または正しい方向に向けることを願っています:-)

于 2012-06-18T23:24:43.197 に答える