简体   繁体   中英

How to ask an object to return its class and methods source as a string?

I want to find the source of a Class and its methods (including all variables too, local , instance, class , class instance etc) and return them as a string or a collection of strings.

I have found MethodNode>>sourceText and CompiledMethod>>sourceCode but I have no clue how to send these messages or if they are the messages I am looking for.

Also any pointers as to how to navigate the Pharo syntax by code using something like AST would be greatly appreciated.

First ask the class of your object, then ask, for example, all the methods defined in this class and then collect the source-code of each method:

'Pharo' class methods collect: [ :each | each sourceCode ]

You can find the relevant methods for other properties of your class in the accessing protocols of Behavior , a superclass of Class .

In addition to the answer of Martin there are also other ways of doing this for example

(Object compiledMethodAt: #printString) sourceCode

will return the source code for a specific method.

In case we want to navigate through the syntax using AST of a method:

( Object compiledMethodAt: #halt ) ast nodesDo:[ :node |  node inspect].

Take a look at RBProgramNode and its relevant subclasses to have taste what is possible for navigating and processing source code.

并且,根据您的确切需求,您应该注意特征,扩展方法和超类中定义的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM