Actually Shil's suggestion is a good way to go. You can cut and paste the following into the groovyConsole and it will run in the latest versions of Groovy:
import groovy.transform.ASTTest @ASTTest(phase=SEMANTIC_ANALYSIS, value={ def myMethod = node.methods.find { it.name == 'myMethod' } def from = myMethod.lineNumber def to = myMethod.lastLineNumber def lines = node.module.context.source.reader.readLines()[from-1..<to] println 'Source for myMethod:\n' + lines.join('\n') println 'Comment lines:' lines.findAll{ it.matches($/\s*//.*/$) }.each{ println it } }) class MyClass { def myMethod() { // my comment println 'Hello' } } println 'done' Output is: Source for myMethod: def myMethod() { // my comment println 'Hello' } Comment lines: // my comment done Cheers, Paul. On Wed, Sep 29, 2021 at 8:34 PM Shil Sinha <shil.si...@gmail.com> wrote: > For extracting source code, you might be able to modify this AST > transformation for your specific use case: SourceCodeASTTransformation > <https://github.com/shils/groovy-exp/blob/master/src/main/groovy/me/shils/internal/transform/SourceCodeASTTransformation.groovy> > (example > usage in the tests > <https://github.com/shils/groovy-exp/blob/master/src/test/groovy/me/shils/internal/transform/SourceCodeASTTransformationTest.groovy>). > I haven't touched this code since Groovy 2.4.x, so I can't guarantee it > works as intended in more recent versions. > > On Wed, Sep 29, 2021 at 8:55 AM Alessio Stalla <alessiosta...@gmail.com> > wrote: > >> I don't know about Groovy specifically, but most parsers discard comments >> (and whitespace, line endings, etc.) before building an AST. However, you >> can reconstruct the missing text if you have the position information of >> each AST node and the original source code available. >> >> On Wed, 29 Sept 2021 at 08:26, Saravanan Palanichamy <chava...@gmail.com> >> wrote: >> >>> Hello all, >>> >>> I am trying to do two things >>> >>> 1) Extract comments from inside a function code (not the function's >>> groovy doc, but comments embedded inside the function code itself) >>> 2) Extract the source code of the function itself >>> >>> For example >>> >>> /* Comments about myFunction *./ >>> void myFunction() { >>> // My first line in the function >>> myFirstLine() >>> >>> // My second line >>> secondLine() >>> } >>> >>> I want to extract the two // comments inside the function. I also want >>> to be able to get the entire source code of the function (so essentially >>> the entire code snippet above) as part of my AST transformations. Is that >>> possible? Thank you for your time >>> >>> regards >>> Saravanan >>> >>