Skip to content

Handle help, version and @file parameters in scalac and scaladoc #11476

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions compiler/src/dotty/tools/dotc/Driver.scala
Original file line number Diff line number Diff line change
Expand Up @@ -64,19 +64,30 @@ class Driver {

protected def sourcesRequired: Boolean = true

def setup(args: Array[String], rootCtx: Context): (List[AbstractFile], Context) = {
protected def command: CompilerCommand = ScalacCommand

/** Setup context with initialized settings from CLI arguments, then check if there are any settings that
* would change the default behaviour of the compiler.
*
* @return If there is no setting like `-help` preventing us from continuing compilation,
* this method returns a list of files to compile and an updated Context.
* If compilation should be interrupted, this method returns None.
*/
def setup(args: Array[String], rootCtx: Context): Option[(List[AbstractFile], Context)] = {
val ictx = rootCtx.fresh
val summary = CompilerCommand.distill(args)(using ictx)
val summary = command.distill(args, ictx.settings)(ictx.settingsState)(using ictx)
ictx.setSettings(summary.sstate)
MacroClassLoader.init(ictx)
Positioned.init(using ictx)

inContext(ictx) {
if !ctx.settings.YdropComments.value || ctx.mode.is(Mode.ReadComments) then
ictx.setProperty(ContextDoc, new ContextDocstrings)
val fileNames = CompilerCommand.checkUsage(summary, sourcesRequired)
val files = fileNames.map(ctx.getFile)
(files, fromTastySetup(files))
val fileNamesOrNone = command.checkUsage(summary, sourcesRequired)(using ctx.settings)(using ctx.settingsState)
fileNamesOrNone.map { fileNames =>
val files = fileNames.map(ctx.getFile)
(files, fromTastySetup(files))
}
}
}

Expand Down Expand Up @@ -182,8 +193,11 @@ class Driver {
* if compilation succeeded.
*/
def process(args: Array[String], rootCtx: Context): Reporter = {
val (files, compileCtx) = setup(args, rootCtx)
doCompile(newCompiler(using compileCtx), files)(using compileCtx)
setup(args, rootCtx) match
case Some((files, compileCtx)) =>
doCompile(newCompiler(using compileCtx), files)(using compileCtx)
case None =>
rootCtx.reporter
}

def main(args: Array[String]): Unit = {
Expand Down
25 changes: 15 additions & 10 deletions compiler/src/dotty/tools/dotc/Resident.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,21 @@ class Resident extends Driver {

final override def process(args: Array[String], rootCtx: Context): Reporter = {
@tailrec def loop(args: Array[String], prevCtx: Context): Reporter = {
var (files, ctx) = setup(args, prevCtx)
inContext(ctx) { doCompile(residentCompiler, files) }
var nextCtx = ctx
var line = getLine()
while (line == reset) {
nextCtx = rootCtx
line = getLine()
}
if (line.startsWith(quit)) ctx.reporter
else loop(line split "\\s+", nextCtx)
setup(args, prevCtx) match
case Some((files, ctx)) =>
inContext(ctx) {
doCompile(residentCompiler, files)
}
var nextCtx = ctx
var line = getLine()
while (line == reset) {
nextCtx = rootCtx
line = getLine()
}
if (line.startsWith(quit)) ctx.reporter
else loop(line split "\\s+", nextCtx)
case None =>
prevCtx.reporter
}
loop(args, rootCtx)
}
Expand Down
9 changes: 9 additions & 0 deletions compiler/src/dotty/tools/dotc/ScalacCommand.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package dotty.tools.dotc

import config.Properties._
import config.CompilerCommand

object ScalacCommand extends CompilerCommand:
override def cmdName: String = "scalac"
override def versionMsg: String = s"Scala compiler $versionString -- $copyrightString"
override def ifErrorsMsg: String = " scalac -help gives more information"
147 changes: 147 additions & 0 deletions compiler/src/dotty/tools/dotc/config/CliCommand.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package dotty.tools.dotc
package config

import java.nio.file.{Files, Paths}

import Settings._
import core.Contexts._
import Properties._

import scala.collection.JavaConverters._

trait CliCommand:

type ConcreteSettings <: CommonScalaSettings with Settings.SettingGroup

def versionMsg: String

def ifErrorsMsg: String

/** The name of the command */
def cmdName: String

def isHelpFlag(using settings: ConcreteSettings)(using SettingsState): Boolean

def helpMsg(using settings: ConcreteSettings)(using SettingsState, Context): String

private def explainAdvanced = """
|-- Notes on option parsing --
|Boolean settings are always false unless set.
|Where multiple values are accepted, they should be comma-separated.
| example: -Xplugin:plugin1,plugin2
|<phases> means one or a comma-separated list of:
| - (partial) phase names with an optional "+" suffix to include the next phase
| - the string "all"
| example: -Xprint:all prints all phases.
| example: -Xprint:typer,mixin prints the typer and mixin phases.
| example: -Ylog:erasure+ logs the erasure phase and the phase after the erasure phase.
| This is useful because during the tree transform of phase X, we often
| already are in phase X + 1.
"""

/** Distill arguments into summary detailing settings, errors and files to main */
def distill(args: Array[String], sg: Settings.SettingGroup)(ss: SettingsState = sg.defaultState)(using Context): ArgsSummary =
/**
* Expands all arguments starting with @ to the contents of the
* file named like each argument.
*/
def expandArg(arg: String): List[String] =
def stripComment(s: String) = s takeWhile (_ != '#')
val path = Paths.get(arg stripPrefix "@")
if (!Files.exists(path))
report.error(s"Argument file ${path.getFileName} could not be found")
Nil
else
val lines = Files.readAllLines(path) // default to UTF-8 encoding
val params = lines.asScala map stripComment mkString " "
CommandLineParser.tokenize(params)

// expand out @filename to the contents of that filename
def expandedArguments = args.toList flatMap {
case x if x startsWith "@" => expandArg(x)
case x => List(x)
}

sg.processArguments(expandedArguments, processAll = true, settingsState = ss)

/** Creates a help message for a subset of options based on cond */
protected def availableOptionsMsg(cond: Setting[?] => Boolean)(using settings: ConcreteSettings)(using SettingsState): String =
val ss = (settings.allSettings filter cond).toList sortBy (_.name)
val width = (ss map (_.name.length)).max
def format(s: String) = ("%-" + width + "s") format s
def helpStr(s: Setting[?]) =
def defaultValue = s.default match
case _: Int | _: String => s.default.toString
case _ =>
// For now, skip the default values that do not make sense for the end user.
// For example 'false' for the version command.
""

def formatSetting(name: String, value: String) =
if (value.nonEmpty)
// the format here is helping to make empty padding and put the additional information exactly under the description.
s"\n${format("")} $name: $value."
else
""
s"${format(s.name)} ${s.description}${formatSetting("Default", defaultValue)}${formatSetting("Choices", s.legalChoices)}"

ss.map(helpStr).mkString("", "\n", s"\n${format("@<file>")} A text file containing compiler arguments (options and source files).\n")

protected def shortUsage: String = s"Usage: $cmdName <options> <source files>"

protected def createUsageMsg(label: String, shouldExplain: Boolean, cond: Setting[?] => Boolean)(using settings: ConcreteSettings)(using SettingsState): String =
val prefix = List(
Some(shortUsage),
Some(explainAdvanced) filter (_ => shouldExplain),
Some(label + " options include:")
).flatten mkString "\n"

prefix + "\n" + availableOptionsMsg(cond)

protected def isStandard(s: Setting[?])(using settings: ConcreteSettings)(using SettingsState): Boolean =
!isAdvanced(s) && !isPrivate(s)
protected def isAdvanced(s: Setting[?])(using settings: ConcreteSettings)(using SettingsState): Boolean =
s.name.startsWith("-X") && s.name != "-X"
protected def isPrivate(s: Setting[?])(using settings: ConcreteSettings)(using SettingsState): Boolean =
s.name.startsWith("-Y") && s.name != "-Y"

/** Messages explaining usage and options */
protected def usageMessage(using settings: ConcreteSettings)(using SettingsState) =
createUsageMsg("where possible standard", shouldExplain = false, isStandard)
protected def xusageMessage(using settings: ConcreteSettings)(using SettingsState) =
createUsageMsg("Possible advanced", shouldExplain = true, isAdvanced)
protected def yusageMessage(using settings: ConcreteSettings)(using SettingsState) =
createUsageMsg("Possible private", shouldExplain = true, isPrivate)

protected def phasesMessage: String =
(new Compiler()).phases.map {
case List(single) => single.phaseName
case more => more.map(_.phaseName).mkString("{", ", ", "}")
}.mkString("\n")

/** Provide usage feedback on argument summary, assuming that all settings
* are already applied in context.
* @return Either Some list of files passed as arguments or None if further processing should be interrupted.
*/
def checkUsage(summary: ArgsSummary, sourcesRequired: Boolean)(using settings: ConcreteSettings)(using SettingsState, Context): Option[List[String]] =
// Print all warnings encountered during arguments parsing
summary.warnings.foreach(report.warning(_))

if summary.errors.nonEmpty then
summary.errors foreach (report.error(_))
report.echo(ifErrorsMsg)
None
else if settings.version.value then
report.echo(versionMsg)
None
else if isHelpFlag then
report.echo(helpMsg)
None
else if (sourcesRequired && summary.arguments.isEmpty)
report.echo(usageMessage)
None
else
Some(summary.arguments)

extension [T](setting: Setting[T])
protected def value(using ss: SettingsState): T = setting.valueIn(ss)
Loading