├── .github
└── workflows
│ └── scala.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.sbt
├── project
├── build.properties
└── plugins.sbt
└── src
├── main
├── java
│ └── com
│ │ └── github
│ │ └── takezoe
│ │ └── scaladoc
│ │ └── Scaladoc.java
├── resources
│ ├── plugin.properties
│ └── scalac-plugin.xml
├── scala-2
│ └── com
│ │ └── github
│ │ └── takezoe
│ │ └── scaladoc
│ │ └── EmbedScaladocAnnotationPlugin.scala
└── scala-3
│ └── com
│ └── github
│ └── takezoe
│ └── scaladoc
│ └── EmbedScaladocAnnotationPlugin.scala
└── test
└── scala
└── TestSpec.scala
/.github/workflows/scala.yml:
--------------------------------------------------------------------------------
1 | name: Scala CI
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | pull_request:
7 | branches: [ master ]
8 |
9 | jobs:
10 | build:
11 | runs-on: ubuntu-latest
12 | strategy:
13 | matrix:
14 | java: [8, 11]
15 | steps:
16 | - uses: actions/checkout@v2
17 | - name: Set up JDK
18 | uses: actions/setup-java@v1
19 | with:
20 | java-version: ${{ matrix.java }}
21 | - name: Setup sbt launcher
22 | uses: sbt/setup-sbt@v1
23 | - name: Run tests
24 | run: sbt +test
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 | *.log
3 | .ensime
4 | .ensime_cache
5 |
6 | # sbt specific
7 | dist/*
8 | target/
9 | lib_managed/
10 | src_managed/
11 | project/boot/
12 | project/plugins/project/
13 |
14 | # Scala-IDE specific
15 | .scala_dependencies
16 | .classpath
17 | .project
18 | .cache
19 | .settings
20 |
21 | # IntelliJ specific
22 | .idea/
23 | .idea_modules/
24 |
25 | # VSCode specific
26 | .vscode
27 |
28 | # Metals
29 | metals.sbt
30 | .metals
31 | .bloop
32 | .bsp
33 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # runtime-scaladoc-reader  [](https://maven-badges.herokuapp.com/maven-central/com.github.takezoe/runtime-scaladoc-reader_2.12) [](https://github.com/takezoe/runtime-scaladoc-reader/blob/master/LICENSE)
2 |
3 | Allows to read Scaladoc at runtime by embedding as annotation by the compiler plugin.
4 |
5 | ## Setup
6 |
7 | Add following configuration to your `build.sbt`:
8 |
9 | ```scala
10 | libraryDependencies += "com.github.takezoe" %% "runtime-scaladoc-reader" % "1.1.0"
11 |
12 | addCompilerPlugin("com.github.takezoe" %% "runtime-scaladoc-reader" % "1.1.0")
13 | ```
14 |
15 | ## Usage
16 |
17 | Assuming you have a below class which has Scaladoc:
18 |
19 | ```scala
20 | package com.github.takezoe
21 |
22 | /**
23 | * Hello, World!
24 | */
25 | class HelloWorld {
26 | ...
27 | }
28 | ```
29 |
30 | You can get Scaladoc at runtime as follows:
31 |
32 | ```scala
33 | import com.github.takezoe.HelloWorld
34 | import com.github.takezoe.scaladoc.Scaladoc
35 |
36 | val clazz = classOf[HelloWorld]
37 | val scaladoc = clazz.getAnnotation(classOf[Scaladoc])
38 |
39 | if(scaladoc != null){
40 | val comment: String = scaladoc.value()
41 | println(comment)
42 | }
43 | ```
44 |
45 | You can also get Scaladoc from `Method` and `Field` as same as `Class`.
46 |
--------------------------------------------------------------------------------
/build.sbt:
--------------------------------------------------------------------------------
1 | name := "runtime-scaladoc-reader"
2 |
3 | organization := "com.github.takezoe"
4 |
5 | version := "1.1.1-SNAPSHOT"
6 |
7 | crossScalaVersions := Seq("2.13.16", "2.12.20", "3.3.5")
8 | scalaVersion := crossScalaVersions.value.head
9 |
10 | libraryDependencies ++= {
11 | Seq(
12 | CrossVersion.partialVersion(scalaVersion.value) match {
13 | case Some((3, _)) => "org.scala-lang" % "scala3-compiler_3" % scalaVersion.value
14 | case _ => "org.scala-lang" % "scala-compiler" % scalaVersion.value
15 | },
16 | "org.scalatest" %% "scalatest" % "3.2.19" % Test
17 | )
18 | }
19 |
20 | Test / scalacOptions ++= {
21 | val jar = (Compile / packageBin).value
22 | Seq(s"-Xplugin:${jar.getAbsolutePath}", s"-Jdummy=${jar.lastModified}") // ensures recompile
23 | }
24 | Test / scalacOptions ++= {
25 | CrossVersion.partialVersion(scalaVersion.value) match {
26 | case Some((2, _)) => Seq("-Yrangepos")
27 | case _ => Seq.empty
28 | }
29 | }
30 | Compile / console / scalacOptions := Seq("-language:_", "-Xplugin:" + (Compile / packageBin).value)
31 | Test / console / scalacOptions := (Compile / console / scalacOptions).value
32 | Test / fork := true
33 |
34 | publishMavenStyle := true
35 |
36 | publishTo := {
37 | val nexus = "https://oss.sonatype.org/"
38 | if (version.value.trim.endsWith("SNAPSHOT"))
39 | Some("snapshots" at nexus + "content/repositories/snapshots")
40 | else
41 | Some("releases" at nexus + "service/local/staging/deploy/maven2")
42 | }
43 |
44 | Test / publishArtifact := false
45 |
46 | pomIncludeRepository := { _ => false }
47 |
48 | pomExtra := (
49 | https://github.com/takezoe/runtime-scaladoc-reader
50 |
51 |
52 | The Apache Software License, Version 2.0
53 | http://www.apache.org/licenses/LICENSE-2.0.txt
54 |
55 |
56 |
57 | https://github.com/takezoe/runtime-scaladoc-reader
58 | scm:git:https://github.com/takezoe/runtime-scaladoc-reader.git
59 |
60 |
61 |
62 | takezoe
63 | Naoki Takezoe
64 | takezoe_at_gmail.com
65 | +9
66 |
67 | )
68 |
--------------------------------------------------------------------------------
/project/build.properties:
--------------------------------------------------------------------------------
1 | sbt.version=1.10.11
2 |
--------------------------------------------------------------------------------
/project/plugins.sbt:
--------------------------------------------------------------------------------
1 | addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.3.1")
2 |
--------------------------------------------------------------------------------
/src/main/java/com/github/takezoe/scaladoc/Scaladoc.java:
--------------------------------------------------------------------------------
1 | package com.github.takezoe.scaladoc;
2 |
3 | import java.lang.annotation.*;
4 |
5 | @Target({ElementType.TYPE, ElementType.METHOD})
6 | @Retention(RetentionPolicy.RUNTIME)
7 | @Documented
8 | public @interface Scaladoc {
9 | String value();
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/resources/plugin.properties:
--------------------------------------------------------------------------------
1 | pluginClass=com.github.takezoe.scaladoc.EmbedScaladocAnnotationPlugin
--------------------------------------------------------------------------------
/src/main/resources/scalac-plugin.xml:
--------------------------------------------------------------------------------
1 |
2 | ReadScaladocPlugin
3 | com.github.takezoe.scaladoc.EmbedScaladocAnnotationPlugin
4 |
--------------------------------------------------------------------------------
/src/main/scala-2/com/github/takezoe/scaladoc/EmbedScaladocAnnotationPlugin.scala:
--------------------------------------------------------------------------------
1 | package com.github.takezoe.scaladoc
2 |
3 | import scala.tools.nsc
4 | import nsc.{Global, Phase}
5 | import nsc.plugins.Plugin
6 | import nsc.plugins.PluginComponent
7 | import scala.collection.mutable.ListBuffer
8 | import scala.tools.nsc.doc.ScaladocSyntaxAnalyzer
9 | import scala.tools.nsc.transform.Transform
10 |
11 | class EmbedScaladocAnnotationPlugin(val global: Global) extends Plugin {
12 | override val name: String = "EmbedScaladocAnnotation"
13 | override val description: String = ""
14 | override val components: List[PluginComponent] = List[PluginComponent](MyComponent)
15 |
16 | private object MyComponent extends PluginComponent with Transform {
17 | type GT = EmbedScaladocAnnotationPlugin.this.global.type
18 | override val global: GT = EmbedScaladocAnnotationPlugin.this.global
19 | override val phaseName: String = "EmbedScaladocAnnotation"
20 | override val runsAfter: List[String] = List("parser")
21 | override def newTransformer(unit: global.CompilationUnit): global.Transformer = new ScaladocTransformer
22 | import global._
23 |
24 |
25 | class ScaladocTransformer extends global.Transformer {
26 |
27 | val comments = new Comments()
28 |
29 | override def transformUnit(unit: CompilationUnit)= {
30 | if(unit.source.file.name.endsWith(".scala")){
31 | comments.parseComments(unit)
32 | super.transformUnit(unit)
33 | }
34 | }
35 |
36 | override def transform(tree: global.Tree): global.Tree = {
37 | tree match {
38 | case x @ PackageDef(_, _) => {
39 | x.copy(x.pid, List(insertImport) ++ x.stats.map(transform))
40 | }
41 | case x @ ClassDef(_, _, _, _) => {
42 | comments.getComment(x.pos) match {
43 | case Some(comment) =>
44 | val newAnnotations = createAnnotation(comment) :: x.mods.annotations
45 | val newMods = x.mods.copy(annotations = newAnnotations)
46 | val newBody = x.impl.body.map(transform)
47 | val newImpl = global.treeCopy.Template(x.impl, x.impl.parents, x.impl.self, newBody)
48 | global.treeCopy.ClassDef(tree, newMods, x.name, x.tparams, newImpl)
49 | case None =>
50 | val newBody = x.impl.body.map(transform)
51 | val newImpl = global.treeCopy.Template(x.impl, x.impl.parents, x.impl.self, newBody)
52 | global.treeCopy.ClassDef(tree, x.mods, x.name, x.tparams, newImpl)
53 | }
54 | }
55 | case x @ DefDef(_, _, _, _, _, _) => {
56 | comments.getComment(x.pos) match {
57 | case Some(comment) =>
58 | val newAnnotations = createAnnotation(comment) :: x.mods.annotations
59 | val newMods = x.mods.copy(annotations = newAnnotations)
60 | global.treeCopy.DefDef(tree, newMods, x.name, x.tparams, x.vparamss, x.tpt, x.rhs)
61 | case None => x
62 | }
63 | }
64 | case x @ ValDef(_, _, _, _) => {
65 | comments.getComment(x.pos) match {
66 | case Some(comment) =>
67 | val newAnnotations = createAnnotation(comment) :: x.mods.annotations
68 | val newMods = x.mods.copy(annotations = newAnnotations)
69 | global.treeCopy.ValDef(tree, newMods, x.name, x.tpt, x.rhs)
70 | case None => x
71 | }
72 | }
73 | case x @ ModuleDef(_, _, _) => {
74 | comments.getComment(x.pos) match {
75 | case Some(comment) =>
76 | val newAnnotations = createAnnotation(comment) :: x.mods.annotations
77 | val newMods = x.mods.copy(annotations = newAnnotations)
78 | val newBody = x.impl.body.map(transform)
79 | val newImpl = global.treeCopy.Template(x.impl, x.impl.parents, x.impl.self, newBody)
80 | global.treeCopy.ModuleDef(tree, newMods, x.name, newImpl)
81 | case None =>
82 | val newBody = x.impl.body.map(transform)
83 | val newImpl = global.treeCopy.Template(x.impl, x.impl.parents, x.impl.self, newBody)
84 | global.treeCopy.ModuleDef(tree, x.mods, x.name, newImpl)
85 | }
86 | }
87 | case x => super.transform(x)
88 | }
89 | }
90 |
91 | private def createAnnotation(comment: String): global.Tree =
92 | global.Apply(
93 | global.Select(global.New(global.Ident(global.newTypeName("Scaladoc"))),
94 | global.nme.CONSTRUCTOR),
95 | List(Literal(Constant(comment))))
96 |
97 | def insertImport: global.Tree = {
98 | val importSelectors = global.ImportSelector(
99 | global.newTermName("Scaladoc"), -1, global.newTermName("Scaladoc"), -1)
100 |
101 | global.Import(
102 | global.Select(global.Select(global.Select(global.Ident(
103 | global.newTermName("com")),
104 | global.newTermName("github")),
105 | global.newTermName("takezoe")),
106 | global.newTermName("scaladoc")), List(importSelectors))
107 | }
108 | }
109 |
110 | class Comments extends ScaladocSyntaxAnalyzer[global.type](global){
111 | val comments = ListBuffer[(Position, String)]()
112 |
113 | def getComment(pos: Position): Option[String] = {
114 | val tookComments = comments.takeWhile { case (x, _) => x.end < pos.start }
115 | comments --= (tookComments)
116 | tookComments.lastOption.map(_._2)
117 | }
118 |
119 | def parseComments(unit: CompilationUnit): Unit = {
120 | comments.clear()
121 |
122 | new ScaladocUnitParser(unit, Nil) {
123 | override def newScanner = new ScaladocUnitScanner(unit, Nil) {
124 | override def registerDocComment(str: String, pos: Position) = {
125 | comments += ((pos, str))
126 | }
127 | }
128 | }.parse()
129 | }
130 |
131 | override val runsAfter: List[String] = Nil
132 | override val runsRightAfter: Option[String] = None
133 | }
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/src/main/scala-3/com/github/takezoe/scaladoc/EmbedScaladocAnnotationPlugin.scala:
--------------------------------------------------------------------------------
1 | package com.github.takezoe.scaladoc
2 |
3 | import dotty.tools.dotc.plugins.{StandardPlugin, PluginPhase}
4 | import dotty.tools.dotc.ast.tpd.*
5 | import dotty.tools.dotc.core.Contexts.Context
6 | import dotty.tools.dotc.core.Constants.Constant
7 | import dotty.tools.dotc.core.Symbols.requiredClass
8 | import dotty.tools.dotc.core.StdNames.nme
9 | import dotty.tools.dotc.core.Comments.{Comment, docCtx}
10 | import dotty.tools.dotc.core.Annotations.Annotation
11 | import dotty.tools.dotc.typer.TyperPhase
12 | import dotty.tools.dotc.util.Spans
13 |
14 | class EmbedScaladocAnnotationPlugin extends StandardPlugin:
15 | override val name: String = "EmbedScaladocAnnotation"
16 | override val description: String = "Embeds Scaladoc comments as runtime annotations"
17 |
18 | override def init(options: List[String]): List[PluginPhase] =
19 | List(EmbedScaladocAnnotationPhase())
20 |
21 | class EmbedScaladocAnnotationPhase extends PluginPhase:
22 | val phaseName = "EmbedScaladocAnnotation"
23 | override val runsAfter = Set(TyperPhase.name)
24 | override val runsBefore = Set("checkUnusedPostTyper")
25 |
26 | private def addScaladocAnnotation(tree: DefTree)(using ctx: Context): Tree =
27 | ctx.docCtx.getOrElse:
28 | throw RuntimeException("Internal error: DocCtx could not be found and documentations are unavailable. Please report this issue to the maintainers.")
29 | .docstring(tree.symbol).foreach:
30 | case Comment(span, comment, _, _, _) =>
31 | val annotationSymbol = requiredClass("com.github.takezoe.scaladoc.Scaladoc")
32 | tree.symbol.addAnnotation(Annotation(annotationSymbol, List(Literal(Constant(comment))), span))
33 | tree
34 |
35 | override def transformValDef(tree: ValDef)(using Context): Tree =
36 | addScaladocAnnotation(tree)
37 |
38 | override def transformDefDef(tree: DefDef)(using Context): Tree =
39 | addScaladocAnnotation(tree)
40 |
41 | override def transformTypeDef(tree: TypeDef)(using Context): Tree =
42 | if tree.isClassDef then addScaladocAnnotation(tree) else tree
43 |
--------------------------------------------------------------------------------
/src/test/scala/TestSpec.scala:
--------------------------------------------------------------------------------
1 | import HelloWorld.InnerObject
2 | import org.scalatest.funsuite.AnyFunSuite
3 | import com.github.takezoe.scaladoc.Scaladoc
4 |
5 | class SetSuite extends AnyFunSuite {
6 |
7 | test("class scaladoc") {
8 | val clazz = classOf[HelloWorld]
9 | val scaladoc = clazz.getAnnotation(classOf[Scaladoc])
10 | val comment: String = scaladoc.value()
11 | assert(comment == """/**
12 | | * Hello, World!
13 | | */""".stripMargin)
14 | }
15 |
16 | test("object scaladoc") {
17 | val clazz = HelloWorld.getClass
18 | val scaladoc = clazz.getAnnotation(classOf[Scaladoc])
19 | val comment: String = scaladoc.value()
20 | assert(comment == """/**
21 | | * Hello, Companion!
22 | | */""".stripMargin)
23 | }
24 |
25 | test("field scaladoc") {
26 | val clazz = classOf[HelloWorld]
27 | val field = clazz.getDeclaredField("field")
28 | val scaladoc = field.getAnnotation(classOf[Scaladoc])
29 | val comment: String = scaladoc.value()
30 | assert(comment == """/**
31 | | * field
32 | | */""".stripMargin)
33 | }
34 |
35 | test("method scaladoc") {
36 | val clazz = classOf[HelloWorld]
37 | val method = clazz.getDeclaredMethod("method")
38 | val scaladoc = method.getAnnotation(classOf[Scaladoc])
39 | val comment: String = scaladoc.value()
40 | assert(comment == """/**
41 | | * method
42 | | */""".stripMargin)
43 | }
44 |
45 | test("inner class scaladoc") {
46 | val clazz = classOf[HelloWorld.InnerClass]
47 | val scaladoc = clazz.getAnnotation(classOf[Scaladoc])
48 | val comment: String = scaladoc.value()
49 | assert(comment == """/** Inner class comment */""".stripMargin)
50 | }
51 |
52 | test("inner object scaladoc") {
53 | val clazz = HelloWorld.InnerObject.getClass
54 | val scaladoc = clazz.getAnnotation(classOf[Scaladoc])
55 | val comment: String = scaladoc.value()
56 | assert(comment == """/** Inner object comment */""".stripMargin)
57 | }
58 |
59 | }
60 |
61 | /**
62 | * Hello, World!
63 | */
64 | class HelloWorld {
65 |
66 | /**
67 | * field
68 | */
69 | val field: String = ""
70 |
71 | /**
72 | * method
73 | */
74 | def method(): Unit = {
75 | }
76 |
77 | }
78 |
79 | /**
80 | * Hello, Companion!
81 | */
82 | object HelloWorld {
83 | /** Inner class comment */
84 | class InnerClass()
85 |
86 | /** Inner object comment */
87 | case object InnerObject {}
88 | }
89 |
--------------------------------------------------------------------------------