scala.reflect.internal.util.Position Scala Examples

The following examples show how to use scala.reflect.internal.util.Position. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ScaladocExtractor.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.sbt

import sbt.File

import scala.reflect.internal.util.Position
import scala.tools.nsc.Global
import scala.tools.nsc.doc.DocFactory
import scala.tools.nsc.doc.Settings
import scala.tools.nsc.doc.base.CommentFactoryBase
import scala.tools.nsc.doc.base.LinkTo
import scala.tools.nsc.doc.base.LinkToExternal
import scala.tools.nsc.doc.base.LinkToMember
import scala.tools.nsc.doc.base.MemberLookupBase
import scala.tools.nsc.doc.base.comment.Comment
import scala.tools.nsc.doc.model.MemberEntity
import scala.tools.nsc.reporters.AbstractReporter

object ScaladocExtractor {

  class ScaladocCommentFactory(compiler: Global, settings: Settings)
    extends CommentFactoryBase with MemberLookupBase {

    override val global: compiler.type = compiler

    override def internalLink(sym: global.Symbol, site: global.Symbol): Option[LinkTo] = None

    override def findExternalLink(sym: global.Symbol, name: String): Option[LinkToExternal] = None

    override def warnNoLink: Boolean = false

    override def toString(link: LinkTo): String = link.toString

    override def chooseLink(links: List[LinkTo]): LinkTo = {
      val members = links.collect {
        case linkToMember@LinkToMember(member: MemberEntity, _) => (member, linkToMember)
      }
      if (members.isEmpty) {
        links.head
      } else {
        members.min(Ordering[MemberEntity].on[(MemberEntity, LinkTo)](_._1))._2
      }
    }

    private[this] def parseComment(symbol: compiler.Symbol, docComment: compiler.DocComment): Comment = {
      parseAtSymbol(docComment.raw, "", docComment.pos, Some(symbol))
    }

    def getComments: Map[String, Comment] = {
      compiler.docComments.map { case (symbol, docComment) =>
        symbol.fullName -> parseComment(symbol, docComment)
      }.toMap
    }
  }

  def analyze(sourceFiles: Seq[File]): Map[String, Comment] = {
    val settings = new Settings(error => (), message => ())
    val scalaLibraryPath = ScalaLibraryLocator.getPath.getOrElse {
      throw new Exception("Could not get path to SBT's Scala library for Scaladoc generation")
    }
    
    settings.bootclasspath.append(scalaLibraryPath)
    settings.classpath.append(scalaLibraryPath)

    val reporter = new BlackHoleReporter(settings)
    val docFactory = new DocFactory(reporter, settings)
    val compiler = docFactory.compiler
    docFactory.makeUniverse(Left(sourceFiles.toList.map(_.getAbsolutePath)))

    val commentFactory = new ScaladocCommentFactory(compiler, settings)
    commentFactory.getComments
  }
}

class BlackHoleReporter(override val settings: Settings) extends AbstractReporter {
  override def display(pos: Position, msg: String, severity: Severity): Unit = ()
  override def displayPrompt(): Unit = ()
} 
Example 2
Source File: CompilerSetup.scala    From perf_tester   with Apache License 2.0 5 votes vote down vote up
package benchmarks

import java.io.File
import java.nio.file.{Files, Path}

import benchmarks.Main.rootPath

import scala.reflect.internal.util.Position
import scala.tools.nsc.{Global, Settings}
import scala.tools.nsc.reporters.Reporter
import scala.util.Try
import collection.JavaConverters._

case class CompilerSetup(rootPath: Path, providedScalacOptions: List[String]) {
  val outputDir: Path = rootPath.resolve("output")
  val currentOutput: Path = outputDir.resolve("classes")
	val scalacOptions = providedScalacOptions ++
    Try(Files.readAllLines(rootPath.resolve("scalac.opts")).asScala.flatMap(_.split(" +"))).getOrElse(Nil)

  IO.cleanDir(outputDir)
  Files.createDirectories(currentOutput)


  val cpJars = IO.jarsIn(rootPath.resolve("cpJars"))

  val reporter: Reporter = new Reporter { // We are ignoring all
    override protected def info0(pos: Position, msg: String, severity: this.Severity, force: Boolean): Unit = {
    //   println(s"[$severity] $pos: $msg") // Uncomment for to get compilation messages
    }
  }

  val settings: Settings = new Settings( msg => throw new RuntimeException(s"[ERROR] $msg") )
  configure(settings)

  val global: Global = new Global(settings, reporter)

  def configure(settings: Settings): Unit = {
    settings.outputDirs.setSingleOutput(currentOutput.toAbsolutePath.toString)
    settings.classpath.append(cpJars.mkString(File.pathSeparator))
    settings.processArguments(scalacOptions, processAll = true)
  }
} 
Example 3
Source File: Reporters.scala    From perf_tester   with Apache License 2.0 5 votes vote down vote up
package org.perftester.process.compiler

import scala.reflect.internal.util.Position
import scala.tools.nsc.reporters.Reporter

object Reporters {
  object noInfo extends Reporter { // We are ignoring all
    override protected def info0(pos: Position,
                                 msg: String,
                                 severity: this.Severity,
                                 force: Boolean): Unit = {
      println(s"[$severity] $pos: $msg")
    }
  }
} 
Example 4
Source File: SparkReplReporter.scala    From iolap   with Apache License 2.0 5 votes vote down vote up
package scala.tools.nsc
package interpreter

import reporters._
import SparkIMain._

import scala.reflect.internal.util.Position


  private var _truncationOK: Boolean = !intp.settings.verbose
  def truncationOK = _truncationOK
  def withoutTruncating[T](body: => T): T = {
    val saved = _truncationOK
    _truncationOK = false
    try body
    finally _truncationOK = saved
  }

  override def warning(pos: Position, msg: String): Unit = withoutTruncating(super.warning(pos, msg))
  override def error(pos: Position, msg: String): Unit   = withoutTruncating(super.error(pos, msg))

  override def printMessage(msg: String) {
    // Avoiding deadlock if the compiler starts logging before
    // the lazy val is complete.
    if (intp.isInitializeComplete) {
      if (intp.totalSilence) {
        if (isReplTrace)
          super.printMessage("[silent] " + msg)
      }
      else super.printMessage(msg)
    }
    else Console.println("[init] " + msg)
  }

  override def displayPrompt() {
    if (intp.totalSilence) ()
    else super.displayPrompt()
  }

} 
Example 5
Source File: SuppressingReporter.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package com.github.ghik.silencer

import scala.collection.mutable.ArrayBuffer
import scala.reflect.internal.util.{Position, SourceFile}
import scala.reflect.io.AbstractFile
import scala.tools.nsc.reporters.{FilteringReporter, ForwardingReporter}
import scala.util.matching.Regex

class SuppressingReporter(
  original: FilteringReporter,
  globalFilters: List[Regex],
  protected val lineContentFilters: List[Regex],
  protected val pathFilters: List[Regex],
  protected val sourceRoots: List[AbstractFile]
) extends ForwardingReporter(original) with SuppressingReporterBase {
  //Suppressions are sorted by end offset of their suppression ranges so that nested suppressions come before
  //their containing suppressions. This is ensured by FindSuppressions traverser in SilencerPlugin.
  //This order is important for proper unused @silent annotation detection.
  def isSuppressed(suppressions: List[Suppression], pos: Position, msg: String): Boolean =
    suppressions.find(_.suppresses(pos, msg)) match {
      case Some(suppression) =>
        suppression.used = true
        true
      case _ =>
        false
    }

  def setSuppressions(source: SourceFile, suppressions: List[Suppression]): Unit = {
    fileSuppressions(source) = suppressions
    for ((pos, msg) <- deferredWarnings.remove(source).getOrElse(Seq.empty))
      warning(pos, msg) // will invoke `filter`
  }

  override def reset(): Unit = {
    super.reset()
    deferredWarnings.clear()
    fileSuppressions.clear()
  }

  
  override def filter(pos: Position, msg: String, severity: Severity): Int = {
    def globallySuppressed: Boolean =
      matchesPathFilter(pos) || anyMatches(globalFilters, msg) || matchesLineContentFilter(pos)

    def locallySuppressed: Boolean = fileSuppressions.get(pos.source) match {
      case Some(suppressions) => isSuppressed(suppressions, pos, msg)
      case None =>
        deferredWarnings.getOrElseUpdate(pos.source, new ArrayBuffer) += ((pos, msg))
        true
    }

    if (severity == WARNING && (globallySuppressed || locallySuppressed)) 2
    else super.filter(pos, msg, severity)
  }
} 
Example 6
Source File: SuppressingReporterBase.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package com.github.ghik.silencer

import java.io.File

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.reflect.internal.util.{Position, SourceFile}
import scala.reflect.io.AbstractFile
import scala.tools.nsc.reporters.Reporter
import scala.util.matching.Regex

// Code that's shared between the version-dependent sources for 2.12 and 2.13
trait SuppressingReporterBase { self: Reporter =>
  protected def pathFilters: List[Regex]
  protected def lineContentFilters: List[Regex]
  protected def sourceRoots: List[AbstractFile]

  protected val deferredWarnings = new mutable.HashMap[SourceFile, ArrayBuffer[(Position, String)]]
  protected val fileSuppressions = new mutable.HashMap[SourceFile, List[Suppression]]
  protected val normalizedPathCache = new mutable.HashMap[SourceFile, String]

  def checkUnused(source: SourceFile): Unit =
    fileSuppressions(source).foreach(_.reportUnused(this))

  protected def relativize(dir: AbstractFile, child: AbstractFile): Option[String] = {
    val childPath = child.canonicalPath
    val dirPath = dir.canonicalPath + File.separator
    if (childPath.startsWith(dirPath)) Some(childPath.substring(dirPath.length)) else None
  }

  protected def matchesPathFilter(pos: Position): Boolean = pathFilters.nonEmpty && pos.isDefined && {
    val filePath = normalizedPathCache.getOrElseUpdate(pos.source, {
      val file = pos.source.file
      val relIt = sourceRoots.iterator.flatMap(relativize(_, file))
      val relPath = if (relIt.hasNext) relIt.next() else file.canonicalPath
      relPath.replace("\\", "/")
    })
    anyMatches(pathFilters, filePath)
  }

  protected def matchesLineContentFilter(pos: Position): Boolean =
    lineContentFilters.nonEmpty && pos.isDefined &&
      anyMatches(lineContentFilters, pos.source.lineToString(pos.line - 1))

  protected def anyMatches(patterns: List[Regex], value: String): Boolean =
    patterns.exists(_.findFirstIn(value).isDefined)
} 
Example 7
Source File: SuppressingReporter.scala    From silencer   with Apache License 2.0 5 votes vote down vote up
package com.github.ghik.silencer

import scala.collection.mutable.ArrayBuffer
import scala.reflect.internal.util.{Position, SourceFile}
import scala.reflect.io.AbstractFile
import scala.tools.nsc.reporters.Reporter
import scala.util.matching.Regex

class SuppressingReporter(
  original: Reporter,
  globalFilters: List[Regex],
  protected val lineContentFilters: List[Regex],
  protected val pathFilters: List[Regex],
  protected val sourceRoots: List[AbstractFile]
) extends Reporter with SuppressingReporterBase {
  //Suppressions are sorted by end offset of their suppression ranges so that nested suppressions come before
  //their containing suppressions. This is ensured by FindSuppressions traverser in SilencerPlugin.
  //This order is important for proper unused @silent annotation detection.
  def suppressOrForward(suppressions: List[Suppression], pos: Position, msg: String): Unit =
    suppressions.find(_.suppresses(pos, msg)) match {
      case Some(suppression) => suppression.used = true
      case None => original.warning(pos, msg)
    }

  def setSuppressions(source: SourceFile, suppressions: List[Suppression]): Unit = {
    fileSuppressions(source) = suppressions
    for ((pos, msg) <- deferredWarnings.remove(source).getOrElse(Seq.empty)) {
      suppressOrForward(suppressions, pos, msg)
    }
    updateCounts()
  }

  override def reset(): Unit = {
    super.reset()
    original.reset()
    deferredWarnings.clear()
    fileSuppressions.clear()
  }

  protected def info0(pos: Position, msg: String, severity: Severity, force: Boolean): Unit = {
    severity match {
      case INFO =>
        original.info(pos, msg, force)
      case WARNING if matchesPathFilter(pos) || anyMatches(globalFilters, msg) || matchesLineContentFilter(pos) =>
        ()
      case WARNING if !pos.isDefined =>
        original.warning(pos, msg)
      case WARNING if !fileSuppressions.contains(pos.source) =>
        deferredWarnings.getOrElseUpdate(pos.source, new ArrayBuffer) += ((pos, msg))
      case WARNING =>
        suppressOrForward(fileSuppressions(pos.source), pos, msg)
      case ERROR =>
        original.error(pos, msg)
    }
    updateCounts()
  }

  private def updateCounts(): Unit = {
    INFO.count = original.INFO.count
    WARNING.count = original.WARNING.count
    ERROR.count = original.ERROR.count
  }

  private def originalSeverity(severity: Severity): original.Severity = severity match {
    case INFO => original.INFO
    case WARNING => original.WARNING
    case ERROR => original.ERROR
  }

  override def hasErrors: Boolean =
    original.hasErrors || cancelled

  override def hasWarnings: Boolean =
    original.hasWarnings

  override def resetCount(severity: Severity): Unit = {
    super.resetCount(severity)
    original.resetCount(originalSeverity(severity))
  }

  override def flush(): Unit = {
    super.flush()
    original.flush()
  }
} 
Example 8
Source File: KernelReporter.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.kernel.util

import cats.data.Ior
import polynote.kernel.{CompileErrors, KernelReport, Pos}

import scala.collection.mutable.ListBuffer
import scala.reflect.internal.util.Position
import scala.tools.nsc.Settings
import scala.tools.nsc.reporters.AbstractReporter

case class KernelReporter(settings: Settings) extends AbstractReporter {

  private var _reports = new ListBuffer[KernelReport]()

  def display(pos: Position, msg: String, severity: Severity): Unit = _reports.synchronized {
    _reports += KernelReport(new Pos(pos), msg, severity.id)
  }

  def displayPrompt(): Unit = ()

  override def reset(): Unit = {
    super.reset()
    _reports.clear()
  }

  def reports: List[KernelReport] = _reports.synchronized(_reports.toList)

  private def captureState = State(_reports, INFO.count, WARNING.count, ERROR.count)
  private def restoreState(state: State): Unit = {
    _reports = state.reports
    INFO.count = state.infos
    WARNING.count = state.warns
    ERROR.count = state.warns
  }

  def attempt[T](fn: => T): Either[Throwable, T] = _reports.synchronized {
    val state = captureState
    reset()

    try {
      val result = Right(fn)

      if (hasErrors)
        throw CompileErrors(_reports.filter(_.severity == ERROR.id).toList)

      result
    } catch {
      case err: Throwable =>
        Left(err)
    } finally {
      restoreState(state)
    }
  }

  def attemptIor[T](fn: => T): Ior[Throwable, T] = _reports.synchronized {
    val state = captureState
    reset()

    try {
      val result = Ior.right(fn)

      if (hasErrors)
        result.putLeft(CompileErrors(_reports.filter(_.severity == ERROR.id).toList))
      else
        result

    } catch {
      case err: Throwable =>
        Ior.Left(err)
    } finally {
      restoreState(state)
    }
  }

  private case class State(reports: ListBuffer[KernelReport], infos: Int, warns: Int, errs: Int)
} 
Example 9
Source File: NscThief.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package scala.tools.nsc.interactive

import scala.reflect.internal.util.{Position, SourceFile}

object NscThief {
  def typedTree(global: Global, sourceFile: SourceFile): global.Tree = {
    val prevGlobalPhase = global.globalPhase
    global.globalPhase = global.currentRun.typerPhase
    val result = global.typedTree(sourceFile, forceReload = false)
    global.globalPhase = prevGlobalPhase
    result
  }

  def typedTreeAt(global: Global, pos: Position): global.Tree = {
    import global._
    val prevGlobalPhase = globalPhase
    global.globalPhase = currentRun.typerPhase
    val result = global.typedTreeAt(pos)
    global.globalPhase = prevGlobalPhase
    result
  }
} 
Example 10
Source File: FailOnWarningsReporter.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.clippy

import scala.reflect.internal.util.Position
import scala.tools.nsc.reporters.Reporter

class FailOnWarningsReporter(r: Reporter, warningMatcher: String => Option[Warning], colorsConfig: ColorsConfig)
    extends Reporter {
  override protected def info0(pos: Position, msg: String, severity: Severity, force: Boolean) = {
    val wrapped = DelegatingPosition.wrap(pos, colorsConfig)

    // cannot delegate to info0 as it's protected, hence special-casing on the possible severity values
    if (severity == INFO) {
      r.info(wrapped, msg, force)
    } else if (severity == WARNING) {
      warning(wrapped, msg)
    } else if (severity == ERROR) {
      error(wrapped, msg)
    } else {
      error(wrapped, s"UNKNOWN SEVERITY: $severity\n$msg")
    }
  }

  override def echo(msg: String)                   = r.echo(msg)
  override def comment(pos: Position, msg: String) = r.comment(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def hasErrors                           = r.hasErrors || cancelled
  override def reset() = {
    cancelled = false
    r.reset()
  }

  //

  override def echo(pos: Position, msg: String)     = r.echo(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def errorCount                           = r.errorCount
  override def warningCount                         = r.warningCount
  override def hasWarnings                          = r.hasWarnings
  override def flush()                              = r.flush()
  override def count(severity: Severity): Int       = r.count(conv(severity))
  override def resetCount(severity: Severity): Unit = r.resetCount(conv(severity))

  //

  private def conv(s: Severity): r.Severity = s match {
    case INFO    => r.INFO
    case WARNING => r.WARNING
    case ERROR   => r.ERROR
  }

  //
  override def warning(pos: Position, msg: String) = {
    val wrapped = DelegatingPosition.wrap(pos, colorsConfig)
    warningMatcher(msg) match {
      case Some(Warning(_, adviceOpt)) =>
        val finalMsg = adviceOpt.map(advice => msg + s"\nClippy advises: $advice").getOrElse(msg)
        r.error(wrapped, finalMsg)
      case None =>
        r.warning(wrapped, msg)
    }
  }

  override def error(pos: Position, msg: String) = {
    val wrapped = DelegatingPosition.wrap(pos, colorsConfig)
    r.error(wrapped, msg)
  }
} 
Example 11
Source File: InjectReporter.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.clippy

import scala.reflect.internal.util.Position
import scala.tools.nsc.plugins.PluginComponent
import scala.tools.nsc.{Global, Phase}


abstract class InjectReporter(
    handleError: (Position, String) => String,
    getFatalWarningAdvice: String => Option[Warning],
    superGlobal: Global
) extends PluginComponent {

  override val global = superGlobal
  def colorsConfig: ColorsConfig
  def isEnabled: Boolean
  override val runsAfter  = List[String]("parser")
  override val runsBefore = List[String]("namer")
  override val phaseName  = "inject-clippy-reporter"

  override def newPhase(prev: Phase) = new Phase(prev) {

    override def name = phaseName

    override def description = "Switches the reporter to Clippy's reporter chain"

    override def run(): Unit =
      if (isEnabled) {
        val r = global.reporter
        global.reporter = new FailOnWarningsReporter(
          new DelegatingReporter(r, handleError, colorsConfig),
          getFatalWarningAdvice,
          colorsConfig
        )
      }
  }

} 
Example 12
Source File: DelegatingReporter.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.clippy

import scala.reflect.internal.util.Position
import scala.tools.nsc.reporters.Reporter

class DelegatingReporter(r: Reporter, handleError: (Position, String) => String, colorsConfig: ColorsConfig)
    extends Reporter {
  override protected def info0(pos: Position, msg: String, severity: Severity, force: Boolean) = {
    val wrapped = DelegatingPosition.wrap(pos, colorsConfig)

    // cannot delegate to info0 as it's protected, hence special-casing on the possible severity values
    if (severity == INFO) {
      r.info(wrapped, msg, force)
    } else if (severity == WARNING) {
      warning(wrapped, msg)
    } else if (severity == ERROR) {
      error(wrapped, msg)
    } else {
      error(wrapped, s"UNKNOWN SEVERITY: $severity\n$msg")
    }
  }

  override def echo(msg: String)                   = r.echo(msg)
  override def comment(pos: Position, msg: String) = r.comment(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def hasErrors                           = r.hasErrors || cancelled
  override def reset() = {
    cancelled = false
    r.reset()
  }

  //

  override def echo(pos: Position, msg: String)     = r.echo(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def warning(pos: Position, msg: String)  = r.warning(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def errorCount                           = r.errorCount
  override def warningCount                         = r.warningCount
  override def hasWarnings                          = r.hasWarnings
  override def flush()                              = r.flush()
  override def count(severity: Severity): Int       = r.count(conv(severity))
  override def resetCount(severity: Severity): Unit = r.resetCount(conv(severity))

  //

  private def conv(s: Severity): r.Severity = s match {
    case INFO    => r.INFO
    case WARNING => r.WARNING
    case ERROR   => r.ERROR
  }

  //

  override def error(pos: Position, msg: String) = {
    val wrapped = DelegatingPosition.wrap(pos, colorsConfig)
    r.error(wrapped, handleError(wrapped, msg))
  }
} 
Example 13
Source File: DelegatingReporter.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.clippy

import scala.reflect.internal.util.Position
import scala.tools.nsc.reporters.Reporter

class DelegatingReporter(r: Reporter, handleError: (Position, String) => String, colorsConfig: ColorsConfig)
    extends Reporter {
  override protected def info0(pos: Position, msg: String, severity: Severity, force: Boolean) = {
    val wrapped = DelegatingPosition.wrap(pos, colorsConfig)

    // cannot delegate to info0 as it's protected, hence special-casing on the possible severity values
    if (severity == INFO) {
      r.info(wrapped, msg, force)
    } else if (severity == WARNING) {
      warning(wrapped, msg)
    } else if (severity == ERROR) {
      error(wrapped, msg)
    } else {
      error(wrapped, s"UNKNOWN SEVERITY: $severity\n$msg")
    }
  }

  override def echo(msg: String)                   = r.echo(msg)
  override def comment(pos: Position, msg: String) = r.comment(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def hasErrors                           = r.hasErrors || cancelled
  override def reset() = {
    cancelled = false
    r.reset()
  }

  //

  override def echo(pos: Position, msg: String)     = r.echo(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def warning(pos: Position, msg: String)  = r.warning(DelegatingPosition.wrap(pos, colorsConfig), msg)
  override def errorCount                           = r.errorCount
  override def warningCount                         = r.warningCount
  override def hasWarnings                          = r.hasWarnings
  override def flush()                              = r.flush()
  override def count(severity: Severity): Int       = r.count(conv(severity))
  override def resetCount(severity: Severity): Unit = r.resetCount(conv(severity))

  //

  private def conv(s: Severity): r.Severity = s match {
    case INFO    => r.INFO
    case WARNING => r.WARNING
    case ERROR   => r.ERROR
  }

  //

  override def error(pos: Position, msg: String) = {
    val wrapped = DelegatingPosition.wrap(pos, colorsConfig)
    r.error(wrapped, handleError(wrapped, msg))
  }
}