Search code examples
scalamacroscode-snippetsscala-macrosscala-3

Scala 3 macro to list source code of file


I'm developing a library and want to showcase some code in a small website. The code-snippets should be sourced directly from the same project, i.e. the code needs to be self-referencing.

I want to write a macro that, given a file or a classname returns a string with the file contents. How can I achieve this?


Solution

  • I would also accept giving a classname or type as argument

    Are you looking for such a macro?

    import scala.quoted.*
    
    inline def getContent[A]: String = ${getContentImpl[A]}
    
    def getContentImpl[A: Type](using Quotes): Expr[String] =
      import quotes.reflect.*
    
         // for the source specifically of A
      // val str = TypeRepr.of[A].typeSymbol.tree.pos.sourceCode.getOrElse(
      //   report.errorAndAbort("no source code")
      // )
    
         // for the whole source file containing the definition of A
      val str = TypeRepr.of[A].typeSymbol.pos.getOrElse(
        report.errorAndAbort("no symbol position")
      ).sourceFile.content.getOrElse(
        report.errorAndAbort("no source-file content")
      )
    
      Expr(str)
    
    // in a different file
    
    getContent[A]
    
    //import Macros.getContent
    //
    //object Main extends App {
    //  class A:
    //    def foo = 1
    //
    //  println(
    //    getContent[A]
    //  )
    //}
    

    How to convert scala code block to string? (Scala 2)