aboutsummaryrefslogtreecommitdiff
path: root/compiler/src/dotty/tools/dotc/typer/Docstrings.scala
blob: 370844e65d9ff69630041bfbef438ca8078c4469 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package dotty.tools
package dotc
package typer

import core._
import Contexts._, Symbols._, Decorators._, Comments._
import util.Positions._
import ast.tpd

trait Docstrings { self: Typer =>

  /** The Docstrings typer will handle the expansion of `@define` and
    * `@inheritdoc` if there is a `DocContext` present as a property in the
    * supplied `ctx`.
    *
    * It will also type any `@usecase` available in function definitions.
    */
  def cookComments(syms: List[Symbol], owner: Symbol)(implicit ctx: Context): Unit =
    ctx.docCtx.foreach { docbase =>
      val relevantSyms = syms.filter(docbase.docstring(_).isDefined)
      relevantSyms.foreach { sym =>
        expandParentDocs(sym)
        val usecases = docbase.docstring(sym).map(_.usecases).getOrElse(Nil)

        usecases.foreach { usecase =>
          enterSymbol(createSymbol(usecase.untpdCode))

          typedStats(usecase.untpdCode :: Nil, owner) match {
            case List(df: tpd.DefDef) => usecase.tpdCode = df
            case _ => ctx.error("`@usecase` was not a valid definition", usecase.codePos)
          }
        }
      }
    }

  private def expandParentDocs(sym: Symbol)(implicit ctx: Context): Unit =
    ctx.docCtx.foreach { docCtx =>
      docCtx.docstring(sym).foreach { cmt =>
        def expandDoc(owner: Symbol): Unit = if (!cmt.isExpanded) {
          val tplExp = docCtx.templateExpander
          tplExp.defineVariables(sym)

          val newCmt = cmt
            .expand(tplExp.expandedDocComment(sym, owner, _))
            .withUsecases

          docCtx.addDocstring(sym, Some(newCmt))
        }

        if (sym ne NoSymbol) {
          expandParentDocs(sym.owner)
          expandDoc(sym.owner)
        }
      }
    }
}