Skip to content

Instantly share code, notes, and snippets.

@mtgto
Created March 22, 2013 16:58
Show Gist options
  • Save mtgto/5222948 to your computer and use it in GitHub Desktop.
Save mtgto/5222948 to your computer and use it in GitHub Desktop.
Scalaコンパイラを使ってクラスやメソッドの行数をチェックしてみようのテスト
/**
* Scalaコンパイラを使ってクラスやメソッドの行数をチェックしてみようのテスト
*
* コンパイラプラグインの使い方は以下のサイトを参考にしています。
* http://www.ne.jp/asahi/hishidama/home/tech/scala/cplugin/index.html
*
* 使い方
* 1. scalac-plugin.xmlをclassesに置く
* 2. コンパイル
* scalac -d classes CompilerPluginSample.scala
* 3. jarを作成
* jar cf compiler-plugin-sample.jar -C classes
* 4. 適当なScalaをプラグイン付きでコンパイル
* scalac -Xplugin:compiler-plugin-sample.jar hello.scala
*
* 念の為に書いておくと、これ使うと思ってる結果よりきつめに制限かかります (valで2行消費されたり)。
*/
package net.mtgto.scala.plugin
import scala.tools.nsc.{Global, Phase}
import scala.tools.nsc.plugins.{Plugin, PluginComponent}
class CompilerPluginSample(val global: Global) extends Plugin {
selfPlugin =>
import global._
override val name = "compiler-plugin-sample"
override val description = "scala compiler plugin sample"
override val components = List[PluginComponent](Component)
private object Component extends PluginComponent {
override val global: selfPlugin.global.type = selfPlugin.global
override val runsAfter = List("refchecks")
override val runsBefore = List("")
override val phaseName = selfPlugin.name
override def newPhase(prev: Phase) = new StdPhase(prev) {
override def name = selfPlugin.name
override def apply(unit: CompilationUnit): Unit = {
for (c @ ClassDef(mods, name, tparams, impl) <- unit.body) {
// 50行以内かをチェック
if (impl.body.size > 5000) {
unit.warning(c.pos, s"クラス $name の行数が50行を超えています")
}
}
for (d @ DefDef(mods, name, tparams, vparamss, tpt, rhs) <- unit.body) {
// 3行以内かをチェック
if (rhs.children.size > 3) {
unit.warning(d.pos, s"メソッド $name の行数が3行を超えています")
}
}
}
}
}
}
<plugin>
<name>compiler-plugin-sample</name>
<classname>net.mtgto.scala.plugin.CompilerPluginSample</classname>
</plugin>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment