diff --git a/.github/settings.yml b/.github/settings.yml index 26421ab03e..4e6de5ac6d 100644 --- a/.github/settings.yml +++ b/.github/settings.yml @@ -251,6 +251,6 @@ branches: - "Rust Test Native (windows-latest)" - "Rust Test WASM" - "license/cla" - - "Vulnerability Scan" + # - "Vulnerability Scan" # CodeQL is temporarily disabled due to incompatibility enforce_admins: null restrictions: null diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index c78710a71e..a85d315695 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -1,13 +1,19 @@ name: "CodeQL" +# CodeQL is temporarily disabled because it seems that it is unable to discover +# code compiled with SBT. on: push: - branches: - - main - - "release/*" + branches-ignore: + - "**" + # branches: + # - main + # - "release/*" pull_request: - branches: - - "*" + branches-ignore: + - "**" +# branches: +# - "*" env: # Please ensure that this is in sync with graalVersion in build.sbt @@ -15,7 +21,7 @@ env: # Please ensure that this is in sync with javaVersion in build.sbt javaVersion: 11 # Please ensure that this is in sync with project/build.properties - sbtVersion: 1.3.13 + sbtVersion: 1.4.1 # Please ensure that this is in sync with rustVersion in build.sbt rustToolchain: nightly-2019-11-04 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 82a7542652..d6412b269b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,7 @@ env: # Please ensure that this is in sync with javaVersion in build.sbt javaVersion: 11 # Please ensure that this is in sync with project/build.properties - sbtVersion: 1.3.13 + sbtVersion: 1.4.1 # Please ensure that this is in sync with rustVersion in build.sbt rustToolchain: nightly-2019-11-04 diff --git a/.github/workflows/scala.yml b/.github/workflows/scala.yml index 8834b658cf..b2252e11aa 100644 --- a/.github/workflows/scala.yml +++ b/.github/workflows/scala.yml @@ -12,7 +12,7 @@ env: # Please ensure that this is in sync with javaVersion in build.sbt javaVersion: 11 # Please ensure that this is in sync with project/build.properties - sbtVersion: 1.3.13 + sbtVersion: 1.4.1 # Please ensure that this is in sync with rustVersion in build.sbt rustToolchain: nightly-2019-11-04 excludedPaths: | diff --git a/.gitignore b/.gitignore index c22543d624..110d369e07 100644 --- a/.gitignore +++ b/.gitignore @@ -96,6 +96,7 @@ bench-report.xml .editorconfig .bloop/ +.bsp/ ################# ## Build Cache ## diff --git a/.scalafmt.conf b/.scalafmt.conf index cfb9e23786..59e65fbe26 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -3,7 +3,7 @@ // All Scala files should be reformatted through this formatter before being // committed to the repositories. -version = "2.6.2" +version = "2.7.4" // Wrapping and Alignment align = most diff --git a/build.sbt b/build.sbt index 05a23a5e6e..381cec62f0 100644 --- a/build.sbt +++ b/build.sbt @@ -30,7 +30,9 @@ scalaVersion in ThisBuild := scalacVersion lazy val gatherLicenses = taskKey[Unit]("Gathers licensing information for relevant dependencies") -gatherLicenses := GatherLicenses.run.value +gatherLicenses := { + GatherLicenses.run.value +} lazy val verifyLicensePackages = taskKey[Unit]( "Verifies if the license package has been generated, " + @@ -38,27 +40,27 @@ lazy val verifyLicensePackages = ) verifyLicensePackages := GatherLicenses.verifyReports.value GatherLicenses.distributions := Seq( - Distribution( - "launcher", - file("distribution/launcher/THIRD-PARTY"), - Distribution.sbtProjects(launcher) - ), - Distribution( - "engine", - file("distribution/engine/THIRD-PARTY"), - Distribution.sbtProjects( - runtime, - `engine-runner`, - `project-manager`, - `language-server` - ) - ), - Distribution( - "std-lib-Base", - file("distribution/std-lib/Base/THIRD-PARTY"), - Distribution.sbtProjects(`std-bits`) + Distribution( + "launcher", + file("distribution/launcher/THIRD-PARTY"), + Distribution.sbtProjects(launcher) + ), + Distribution( + "engine", + file("distribution/engine/THIRD-PARTY"), + Distribution.sbtProjects( + runtime, + `engine-runner`, + `project-manager`, + `language-server` ) + ), + Distribution( + "std-lib-Base", + file("distribution/std-lib/Base/THIRD-PARTY"), + Distribution.sbtProjects(`std-bits`) ) +) GatherLicenses.licenseConfigurations := Set("compile") GatherLicenses.configurationRoot := file("tools/legal-review") @@ -68,7 +70,7 @@ lazy val openLegalReviewReport = "report in review mode in the browser." ) openLegalReviewReport := { - gatherLicenses.value + val _ = gatherLicenses.value GatherLicenses.runReportServer() } @@ -82,49 +84,49 @@ Global / onChangedBuildSource := ReloadOnSourceChanges // ============================================================================ javacOptions in ThisBuild ++= Seq( - "-encoding", // Provide explicit encoding (the next line) - "UTF-8", // Specify character encoding used by Java source files. - "-deprecation" // Shows a description of each use or override of a deprecated member or class. - ) + "-encoding", // Provide explicit encoding (the next line) + "UTF-8", // Specify character encoding used by Java source files. + "-deprecation" // Shows a description of each use or override of a deprecated member or class. +) scalacOptions in ThisBuild ++= Seq( - "-deprecation", // Emit warning and location for usages of deprecated APIs. - "-encoding", // Provide explicit encoding (the next line) - "utf-8", // Specify character encoding used by Scala source files. - "-explaintypes", // Explain type errors in more detail. - "-feature", // Emit warning and location for usages of features that should be imported explicitly. - "-language:existentials", // Existential types (besides wildcard types) can be written and inferred - "-language:experimental.macros", // Allow macro definition (besides implementation and application) - "-language:higherKinds", // Allow higher-kinded types - "-language:implicitConversions", // Allow definition of implicit functions called views - "-unchecked", // Enable additional warnings where generated code depends on assumptions. - "-Xcheckinit", // Wrap field accessors to throw an exception on uninitialized access. - "-Xlint:adapted-args", // Warn if an argument list is modified to match the receiver. - "-Xlint:constant", // Evaluation of a constant arithmetic expression results in an error. - "-Xlint:delayedinit-select", // Selecting member of DelayedInit. - "-Xlint:doc-detached", // A Scaladoc comment appears to be detached from its element. - "-Xlint:inaccessible", // Warn about inaccessible types in method signatures. - "-Xlint:infer-any", // Warn when a type argument is inferred to be `Any`. - "-Xlint:missing-interpolator", // A string literal appears to be missing an interpolator id. - "-Xlint:nullary-unit", // Warn when nullary methods return Unit. - "-Xlint:option-implicit", // Option.apply used implicit view. - "-Xlint:package-object-classes", // Class or object defined in package object. - "-Xlint:poly-implicit-overload", // Parameterized overloaded implicit methods are not visible as view bounds. - "-Xlint:private-shadow", // A private field (or class parameter) shadows a superclass field. - "-Xlint:stars-align", // Pattern sequence wildcard must align with sequence component. - "-Xlint:type-parameter-shadow", // A local type parameter shadows a type already in scope. - "-Xmacro-settings:-logging@org.enso", // Disable the debug logging globally. - "-Ywarn-dead-code", // Warn when dead code is identified. - "-Ywarn-extra-implicit", // Warn when more than one implicit parameter section is defined. - "-Ywarn-numeric-widen", // Warn when numerics are widened. - "-Ywarn-unused:imports", // Warn if an import selector is not referenced. - "-Ywarn-unused:implicits", // Warn if an implicit parameter is unused. - "-Ywarn-unused:locals", // Warn if a local definition is unused. - "-Ywarn-unused:patvars", // Warn if a variable bound in a pattern is unused. - "-Ywarn-unused:privates", // Warn if a private member is unused. - "-Ywarn-unused:params", // Warn if a value parameter is unused. - "-Xfatal-warnings" // Make warnings fatal so they don't make it onto main (use @nowarn for local suppression) - ) + "-deprecation", // Emit warning and location for usages of deprecated APIs. + "-encoding", // Provide explicit encoding (the next line) + "utf-8", // Specify character encoding used by Scala source files. + "-explaintypes", // Explain type errors in more detail. + "-feature", // Emit warning and location for usages of features that should be imported explicitly. + "-language:existentials", // Existential types (besides wildcard types) can be written and inferred + "-language:experimental.macros", // Allow macro definition (besides implementation and application) + "-language:higherKinds", // Allow higher-kinded types + "-language:implicitConversions", // Allow definition of implicit functions called views + "-unchecked", // Enable additional warnings where generated code depends on assumptions. + "-Xcheckinit", // Wrap field accessors to throw an exception on uninitialized access. + "-Xlint:adapted-args", // Warn if an argument list is modified to match the receiver. + "-Xlint:constant", // Evaluation of a constant arithmetic expression results in an error. + "-Xlint:delayedinit-select", // Selecting member of DelayedInit. + "-Xlint:doc-detached", // A Scaladoc comment appears to be detached from its element. + "-Xlint:inaccessible", // Warn about inaccessible types in method signatures. + "-Xlint:infer-any", // Warn when a type argument is inferred to be `Any`. + "-Xlint:missing-interpolator", // A string literal appears to be missing an interpolator id. + "-Xlint:nullary-unit", // Warn when nullary methods return Unit. + "-Xlint:option-implicit", // Option.apply used implicit view. + "-Xlint:package-object-classes", // Class or object defined in package object. + "-Xlint:poly-implicit-overload", // Parameterized overloaded implicit methods are not visible as view bounds. + "-Xlint:private-shadow", // A private field (or class parameter) shadows a superclass field. + "-Xlint:stars-align", // Pattern sequence wildcard must align with sequence component. + "-Xlint:type-parameter-shadow", // A local type parameter shadows a type already in scope. + "-Xmacro-settings:-logging@org.enso", // Disable the debug logging globally. + "-Ywarn-dead-code", // Warn when dead code is identified. + "-Ywarn-extra-implicit", // Warn when more than one implicit parameter section is defined. + "-Ywarn-numeric-widen", // Warn when numerics are widened. + "-Ywarn-unused:imports", // Warn if an import selector is not referenced. + "-Ywarn-unused:implicits", // Warn if an implicit parameter is unused. + "-Ywarn-unused:locals", // Warn if a local definition is unused. + "-Ywarn-unused:patvars", // Warn if a variable bound in a pattern is unused. + "-Ywarn-unused:privates", // Warn if a private member is unused. + "-Ywarn-unused:params", // Warn if a value parameter is unused. + "-Xfatal-warnings" // Make warnings fatal so they don't make it onto main (use @nowarn for local suppression) +) val jsSettings = Seq( scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.ESModule) } @@ -391,10 +393,10 @@ lazy val flexer = crossProject(JVMPlatform, JSPlatform) version := "0.1", resolvers += Resolver.sonatypeRepo("releases"), libraryDependencies ++= scalaCompiler ++ Seq( - "com.google.guava" % "guava" % guavaVersion exclude ("com.google.code.findbugs", "jsr305"), - "org.typelevel" %%% "cats-core" % catsVersion, - "org.typelevel" %%% "kittens" % kittensVersion - ) + "com.google.guava" % "guava" % guavaVersion exclude ("com.google.code.findbugs", "jsr305"), + "org.typelevel" %%% "cats-core" % catsVersion, + "org.typelevel" %%% "kittens" % kittensVersion + ) ) .jsSettings(jsSettings) @@ -406,13 +408,13 @@ lazy val `syntax-definition` = crossProject(JVMPlatform, JSPlatform) .settings( scalacOptions ++= Seq("-Ypatmat-exhaust-depth", "off"), libraryDependencies ++= monocle ++ scalaCompiler ++ Seq( - "org.typelevel" %%% "cats-core" % catsVersion, - "org.typelevel" %%% "kittens" % kittensVersion, - "com.lihaoyi" %%% "scalatags" % scalatagsVersion, - "io.circe" %%% "circe-core" % circeVersion, - "io.circe" %%% "circe-generic" % circeVersion, - "io.circe" %%% "circe-parser" % circeVersion - ) + "org.typelevel" %%% "cats-core" % catsVersion, + "org.typelevel" %%% "kittens" % kittensVersion, + "com.lihaoyi" %%% "scalatags" % scalatagsVersion, + "io.circe" %%% "circe-core" % circeVersion, + "io.circe" %%% "circe-generic" % circeVersion, + "io.circe" %%% "circe-parser" % circeVersion + ) ) .jsSettings(jsSettings) @@ -432,21 +434,21 @@ lazy val syntax = crossProject(JVMPlatform, JSPlatform) version := "0.1", logBuffered := false, libraryDependencies ++= Seq( - "org.scalatest" %%% "scalatest" % scalatestVersion % Test, - "com.lihaoyi" %%% "pprint" % pprintVersion, - "io.circe" %%% "circe-core" % circeVersion, - "io.circe" %%% "circe-generic" % circeVersion, - "io.circe" %%% "circe-parser" % circeVersion - ), + "org.scalatest" %%% "scalatest" % scalatestVersion % Test, + "com.lihaoyi" %%% "pprint" % pprintVersion, + "io.circe" %%% "circe-core" % circeVersion, + "io.circe" %%% "circe-generic" % circeVersion, + "io.circe" %%% "circe-parser" % circeVersion + ), (Compile / compile) := (Compile / compile) - .dependsOn(RecompileParser.run(`syntax-definition`)) - .value, + .dependsOn(RecompileParser.run(`syntax-definition`)) + .value, (Test / compile) := (Test / compile) - .dependsOn(RecompileParser.run(`syntax-definition`)) - .value, + .dependsOn(RecompileParser.run(`syntax-definition`)) + .value, (Benchmark / compile) := (Benchmark / compile) - .dependsOn(RecompileParser.run(`syntax-definition`)) - .value + .dependsOn(RecompileParser.run(`syntax-definition`)) + .value ) .jvmSettings( inConfig(Benchmark)(Defaults.testSettings), @@ -455,9 +457,9 @@ lazy val syntax = crossProject(JVMPlatform, JSPlatform) libraryDependencies += "com.storm-enroute" %% "scalameter" % scalameterVersion % "bench", testFrameworks := List( - new TestFramework("org.scalatest.tools.Framework"), - new TestFramework("org.scalameter.ScalaMeterFramework") - ), + new TestFramework("org.scalatest.tools.Framework"), + new TestFramework("org.scalameter.ScalaMeterFramework") + ), bench := (test in Benchmark).tag(Exclusive).value ) .jsSettings( @@ -479,10 +481,10 @@ lazy val `text-buffer` = project .configs(Test) .settings( libraryDependencies ++= Seq( - "org.typelevel" %% "cats-core" % catsVersion, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test - ) + "org.typelevel" %% "cats-core" % catsVersion, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test + ) ) lazy val graph = (project in file("lib/scala/graph/")) @@ -491,18 +493,18 @@ lazy val graph = (project in file("lib/scala/graph/")) .settings( version := "0.1", resolvers ++= Seq( - Resolver.sonatypeRepo("releases"), - Resolver.sonatypeRepo("snapshots") - ), + Resolver.sonatypeRepo("releases"), + Resolver.sonatypeRepo("snapshots") + ), scalacOptions += "-Ymacro-annotations", libraryDependencies ++= scalaCompiler ++ Seq( - "com.chuusai" %% "shapeless" % shapelessVersion, - "io.estatico" %% "newtype" % newtypeVersion, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, - "com.github.julien-truffaut" %% "monocle-core" % monocleVersion, - "org.apache.commons" % "commons-lang3" % commonsLangVersion - ), + "com.chuusai" %% "shapeless" % shapelessVersion, + "io.estatico" %% "newtype" % newtypeVersion, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, + "com.github.julien-truffaut" %% "monocle-core" % monocleVersion, + "org.apache.commons" % "commons-lang3" % commonsLangVersion + ), addCompilerPlugin( "org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full ), @@ -517,11 +519,11 @@ lazy val pkg = (project in file("lib/scala/pkg")) mainClass in (Compile, run) := Some("org.enso.pkg.Main"), version := "0.1", libraryDependencies ++= circe ++ Seq( - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "nl.gn0s1s" %% "bump" % bumpVersion, - "io.circe" %% "circe-yaml" % circeYamlVersion, // separate from other circe deps because its independent project with its own versioning - "commons-io" % "commons-io" % commonsIoVersion - ) + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "nl.gn0s1s" %% "bump" % bumpVersion, + "io.circe" %% "circe-yaml" % circeYamlVersion, // separate from other circe deps because its independent project with its own versioning + "commons-io" % "commons-io" % commonsIoVersion + ) ) lazy val `akka-native` = project @@ -530,8 +532,8 @@ lazy val `akka-native` = project .settings( version := "0.1", libraryDependencies ++= Seq( - akkaActor - ), + akkaActor + ), // Note [Native Image Workaround for GraalVM 20.2] libraryDependencies += "org.graalvm.nativeimage" % "svm" % graalVersion % "provided" ) @@ -542,15 +544,15 @@ lazy val `logging-service` = project .settings( version := "0.1", libraryDependencies ++= Seq( - "org.slf4j" % "slf4j-api" % slf4jVersion, - "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, - akkaStream, - akkaHttp, - "io.circe" %%% "circe-core" % circeVersion, - "io.circe" %%% "circe-parser" % circeVersion, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.graalvm.nativeimage" % "svm" % graalVersion % "provided" - ) + "org.slf4j" % "slf4j-api" % slf4jVersion, + "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, + akkaStream, + akkaHttp, + "io.circe" %%% "circe-core" % circeVersion, + "io.circe" %%% "circe-parser" % circeVersion, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.graalvm.nativeimage" % "svm" % graalVersion % "provided" + ) ) .settings( if (Platform.isWindows) @@ -566,9 +568,9 @@ lazy val cli = project .settings( version := "0.1", libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.typelevel" %% "cats-core" % catsVersion - ), + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.typelevel" %% "cats-core" % catsVersion + ), parallelExecution in Test := false ) @@ -578,16 +580,16 @@ lazy val `version-output` = (project in file("lib/scala/version-output")) ) .settings( Compile / sourceGenerators += Def.task { - val file = (Compile / sourceManaged).value / "buildinfo" / "Info.scala" - BuildInfo - .writeBuildInfoFile( - file, - state.value.log, - ensoVersion, - scalacVersion, - graalVersion - ) - }.taskValue + val file = (Compile / sourceManaged).value / "buildinfo" / "Info.scala" + BuildInfo + .writeBuildInfoFile( + file, + state.value.log, + ensoVersion, + scalacVersion, + graalVersion + ) + }.taskValue ) lazy val `project-manager` = (project in file("lib/scala/project-manager")) @@ -609,18 +611,18 @@ lazy val `project-manager` = (project in file("lib/scala/project-manager")) libraryDependencies ++= akka, libraryDependencies ++= circe, libraryDependencies ++= Seq( - "com.typesafe" % "config" % typesafeConfigVersion, - "com.github.pureconfig" %% "pureconfig" % pureconfigVersion, - "ch.qos.logback" % "logback-classic" % logbackClassicVersion, - "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, - "dev.zio" %% "zio" % zioVersion, - "dev.zio" %% "zio-interop-cats" % zioInteropCatsVersion, - "commons-cli" % "commons-cli" % commonsCliVersion, - "commons-io" % "commons-io" % commonsIoVersion, - "com.beachape" %% "enumeratum-circe" % enumeratumCirceVersion, - "com.miguno.akka" %% "akka-mock-scheduler" % akkaMockSchedulerVersion % Test, - "org.mockito" %% "mockito-scala" % mockitoScalaVersion % Test - ), + "com.typesafe" % "config" % typesafeConfigVersion, + "com.github.pureconfig" %% "pureconfig" % pureconfigVersion, + "ch.qos.logback" % "logback-classic" % logbackClassicVersion, + "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, + "dev.zio" %% "zio" % zioVersion, + "dev.zio" %% "zio-interop-cats" % zioInteropCatsVersion, + "commons-cli" % "commons-cli" % commonsCliVersion, + "commons-io" % "commons-io" % commonsIoVersion, + "com.beachape" %% "enumeratum-circe" % enumeratumCirceVersion, + "com.miguno.akka" %% "akka-mock-scheduler" % akkaMockSchedulerVersion % Test, + "org.mockito" %% "mockito-scala" % mockitoScalaVersion % Test + ), addCompilerPlugin( "org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full ) @@ -641,17 +643,17 @@ lazy val `project-manager` = (project in file("lib/scala/project-manager")) case _ => MergeStrategy.first }, assemblyOption in assembly := (assemblyOption in assembly).value - .copy( - prependShellScript = Some( - defaultUniversalScript( - shebang = false, - javaOpts = Seq("-Dtruffle.class.path.append=runtime.jar") - ) + .copy( + prependShellScript = Some( + defaultUniversalScript( + shebang = false, + javaOpts = Seq("-Dtruffle.class.path.append=runtime.jar") ) - ), + ) + ), assembly := assembly - .dependsOn(runtime / assembly) - .value + .dependsOn(runtime / assembly) + .value ) .dependsOn(`version-output`) .dependsOn(pkg) @@ -688,10 +690,10 @@ lazy val `json-rpc-server` = project libraryDependencies ++= akka, libraryDependencies ++= circe, libraryDependencies ++= Seq( - "io.circe" %% "circe-literal" % circeVersion, - akkaTestkit % Test, - "org.scalatest" %% "scalatest" % scalatestVersion % Test - ) + "io.circe" %% "circe-literal" % circeVersion, + akkaTestkit % Test, + "org.scalatest" %% "scalatest" % scalatestVersion % Test + ) ) lazy val `json-rpc-server-test` = project @@ -700,10 +702,10 @@ lazy val `json-rpc-server-test` = project libraryDependencies ++= akka, libraryDependencies ++= circe, libraryDependencies ++= Seq( - "io.circe" %% "circe-literal" % circeVersion, - akkaTestkit, - "org.scalatest" %% "scalatest" % scalatestVersion - ) + "io.circe" %% "circe-literal" % circeVersion, + akkaTestkit, + "org.scalatest" %% "scalatest" % scalatestVersion + ) ) .dependsOn(`json-rpc-server`) @@ -711,9 +713,9 @@ lazy val testkit = project .in(file("lib/scala/testkit")) .settings( libraryDependencies ++= Seq( - "org.apache.commons" % "commons-lang3" % commonsLangVersion, - "org.scalatest" %% "scalatest" % scalatestVersion - ) + "org.apache.commons" % "commons-lang3" % commonsLangVersion, + "org.scalatest" %% "scalatest" % scalatestVersion + ) ) lazy val `core-definition` = (project in file("lib/scala/core-definition")) @@ -726,13 +728,13 @@ lazy val `core-definition` = (project in file("lib/scala/core-definition")) logBuffered in Test := false, scalacOptions += "-Ymacro-annotations", libraryDependencies ++= jmh ++ Seq( - "com.chuusai" %% "shapeless" % shapelessVersion, - "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, - "org.scalactic" %% "scalactic" % scalacticVersion % Test, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.typelevel" %% "cats-core" % catsVersion, - "com.github.julien-truffaut" %% "monocle-core" % monocleVersion - ), + "com.chuusai" %% "shapeless" % shapelessVersion, + "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, + "org.scalactic" %% "scalactic" % scalacticVersion % Test, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.typelevel" %% "cats-core" % catsVersion, + "com.github.julien-truffaut" %% "monocle-core" % monocleVersion + ), addCompilerPlugin( "org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full ), @@ -749,11 +751,11 @@ lazy val searcher = project .configs(Test) .settings( libraryDependencies ++= jmh ++ Seq( - "com.typesafe.slick" %% "slick" % slickVersion, - "org.xerial" % "sqlite-jdbc" % sqliteVersion, - "ch.qos.logback" % "logback-classic" % logbackClassicVersion % Test, - "org.scalatest" %% "scalatest" % scalatestVersion % Test - ) + "com.typesafe.slick" %% "slick" % slickVersion, + "org.xerial" % "sqlite-jdbc" % sqliteVersion, + "ch.qos.logback" % "logback-classic" % logbackClassicVersion % Test, + "org.scalatest" %% "scalatest" % scalatestVersion % Test + ) ) .configs(Benchmark) .settings( @@ -796,11 +798,11 @@ lazy val `polyglot-api` = project Seq(s"-Dtruffle.class.path.append=$runtimeClasspath") }, libraryDependencies ++= Seq( - "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided", - "com.google.flatbuffers" % "flatbuffers-java" % flatbuffersVersion, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test - ), + "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided", + "com.google.flatbuffers" % "flatbuffers-java" % flatbuffersVersion, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test + ), libraryDependencies ++= jackson, addCompilerPlugin( "org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full @@ -818,23 +820,23 @@ lazy val `polyglot-api` = project lazy val `language-server` = (project in file("engine/language-server")) .settings( libraryDependencies ++= akka ++ circe ++ Seq( - "ch.qos.logback" % "logback-classic" % logbackClassicVersion, - "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, - "io.circe" %% "circe-generic-extras" % circeGenericExtrasVersion, - "io.circe" %% "circe-literal" % circeVersion, - "org.bouncycastle" % "bcpkix-jdk15on" % bcpkixJdk15Version, - "dev.zio" %% "zio" % zioVersion, - "io.methvin" % "directory-watcher" % directoryWatcherVersion, - "com.beachape" %% "enumeratum-circe" % enumeratumCirceVersion, - "com.google.flatbuffers" % "flatbuffers-java" % flatbuffersVersion, - "commons-io" % "commons-io" % commonsIoVersion, - akkaTestkit % Test, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, - "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided" - ), + "ch.qos.logback" % "logback-classic" % logbackClassicVersion, + "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, + "io.circe" %% "circe-generic-extras" % circeGenericExtrasVersion, + "io.circe" %% "circe-literal" % circeVersion, + "org.bouncycastle" % "bcpkix-jdk15on" % bcpkixJdk15Version, + "dev.zio" %% "zio" % zioVersion, + "io.methvin" % "directory-watcher" % directoryWatcherVersion, + "com.beachape" %% "enumeratum-circe" % enumeratumCirceVersion, + "com.google.flatbuffers" % "flatbuffers-java" % flatbuffersVersion, + "commons-io" % "commons-io" % commonsIoVersion, + akkaTestkit % Test, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, + "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided" + ), testOptions in Test += Tests - .Argument(TestFrameworks.ScalaCheck, "-minSuccessfulTests", "1000"), + .Argument(TestFrameworks.ScalaCheck, "-minSuccessfulTests", "1000"), GenerateFlatbuffers.flatcVersion := flatbuffersVersion, sourceGenerators in Compile += GenerateFlatbuffers.task ) @@ -844,8 +846,8 @@ lazy val `language-server` = (project in file("engine/language-server")) bench := (test in Benchmark).value, libraryDependencies += "com.storm-enroute" %% "scalameter" % scalameterVersion % "bench", testFrameworks ++= List( - new TestFramework("org.scalameter.ScalaMeterFramework") - ) + new TestFramework("org.scalameter.ScalaMeterFramework") + ) ) .dependsOn(`polyglot-api`) .dependsOn(`json-rpc-server`) @@ -866,20 +868,20 @@ lazy val parser = (project in file("lib/scala/parser")) fork := true, Cargo.rustVersion := rustVersion, Compile / compile / compileInputs := (Compile / compile / compileInputs) - .dependsOn(Cargo("build --project parser")) - .value, + .dependsOn(Cargo("build --project parser")) + .value, javaOptions += { val root = baseDirectory.value.getParentFile.getParentFile.getParentFile s"-Djava.library.path=$root/target/rust/debug" }, libraryDependencies ++= Seq( - "com.storm-enroute" %% "scalameter" % scalameterVersion % "bench", - "org.scalatest" %%% "scalatest" % scalatestVersion % Test - ), + "com.storm-enroute" %% "scalameter" % scalameterVersion % "bench", + "org.scalatest" %%% "scalatest" % scalatestVersion % Test + ), testFrameworks := List( - new TestFramework("org.scalatest.tools.Framework"), - new TestFramework("org.scalameter.ScalaMeterFramework") - ) + new TestFramework("org.scalatest.tools.Framework"), + new TestFramework("org.scalameter.ScalaMeterFramework") + ) ) .dependsOn(ast) @@ -895,48 +897,48 @@ lazy val runtime = (project in file("engine/runtime")) scalacOptions += "-Ymacro-annotations", scalacOptions ++= Seq("-Ypatmat-exhaust-depth", "off"), libraryDependencies ++= circe ++ jmh ++ jaxb ++ Seq( - "com.chuusai" %% "shapeless" % shapelessVersion, - "org.apache.commons" % "commons-lang3" % commonsLangVersion, - "org.apache.tika" % "tika-core" % tikaVersion, - "org.graalvm.sdk" % "graal-sdk" % graalVersion % "provided", - "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided", - "org.graalvm.truffle" % "truffle-api" % graalVersion % "provided", - "org.graalvm.truffle" % "truffle-dsl-processor" % graalVersion % "provided", - "org.graalvm.truffle" % "truffle-tck" % graalVersion % "provided", - "org.graalvm.truffle" % "truffle-tck-common" % graalVersion % "provided", - "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, - "org.scalactic" %% "scalactic" % scalacticVersion % Test, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - "org.graalvm.truffle" % "truffle-api" % graalVersion % Benchmark, - "org.typelevel" %% "cats-core" % catsVersion, - "eu.timepit" %% "refined" % refinedVersion - ), + "com.chuusai" %% "shapeless" % shapelessVersion, + "org.apache.commons" % "commons-lang3" % commonsLangVersion, + "org.apache.tika" % "tika-core" % tikaVersion, + "org.graalvm.sdk" % "graal-sdk" % graalVersion % "provided", + "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided", + "org.graalvm.truffle" % "truffle-api" % graalVersion % "provided", + "org.graalvm.truffle" % "truffle-dsl-processor" % graalVersion % "provided", + "org.graalvm.truffle" % "truffle-tck" % graalVersion % "provided", + "org.graalvm.truffle" % "truffle-tck-common" % graalVersion % "provided", + "org.scalacheck" %% "scalacheck" % scalacheckVersion % Test, + "org.scalactic" %% "scalactic" % scalacticVersion % Test, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + "org.graalvm.truffle" % "truffle-api" % graalVersion % Benchmark, + "org.typelevel" %% "cats-core" % catsVersion, + "eu.timepit" %% "refined" % refinedVersion + ), // Note [Unmanaged Classpath] Compile / unmanagedClasspath += (`core-definition` / Compile / packageBin).value, Test / unmanagedClasspath += (`core-definition` / Compile / packageBin).value, Compile / compile / compileInputs := (Compile / compile / compileInputs) - .dependsOn(CopyTruffleJAR.preCompileTask) - .value, + .dependsOn(CopyTruffleJAR.preCompileTask) + .value, Compile / compile := FixInstrumentsGeneration.patchedCompile - .dependsOn(FixInstrumentsGeneration.preCompileTask) - .dependsOn(`core-definition` / Compile / packageBin) - .value, + .dependsOn(FixInstrumentsGeneration.preCompileTask) + .dependsOn(`core-definition` / Compile / packageBin) + .value, // Note [Classpath Separation] Test / javaOptions ++= Seq( - "-Dgraalvm.locatorDisabled=true", - s"--upgrade-module-path=${file("engine/runtime/build-cache/truffle-api.jar").absolutePath}" - ), + "-Dgraalvm.locatorDisabled=true", + s"--upgrade-module-path=${file("engine/runtime/build-cache/truffle-api.jar").absolutePath}" + ), bootstrap := CopyTruffleJAR.bootstrapJARs.value, Global / onLoad := EnvironmentCheck.addVersionCheck( - graalVersion, - javaVersion - )((Global / onLoad).value) + graalVersion, + javaVersion + )((Global / onLoad).value) ) .settings( (Compile / javacOptions) ++= Seq( - "-s", - (Compile / sourceManaged).value.getAbsolutePath - ), + "-s", + (Compile / sourceManaged).value.getAbsolutePath + ), addCompilerPlugin( "org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full ), @@ -947,27 +949,26 @@ lazy val runtime = (project in file("engine/runtime")) ) .settings( (Compile / compile) := (Compile / compile) - .dependsOn(Def.task { (Compile / sourceManaged).value.mkdirs }) - .value + .dependsOn(Def.task { (Compile / sourceManaged).value.mkdirs }) + .value ) .settings( (Runtime / compile) := (Runtime / compile) - .dependsOn(`std-bits` / Compile / packageBin) - .value + .dependsOn(`std-bits` / Compile / packageBin) + .value ) .settings( - logBuffered := false, bench := (test in Benchmark).tag(Exclusive).value, benchOnly := Def.inputTaskDyn { - import complete.Parsers.spaceDelimited - val name = spaceDelimited("").parsed match { - case List(name) => name - case _ => throw new IllegalArgumentException("Expected one argument.") - } - Def.task { - (testOnly in Benchmark).toTask(" -- -z " + name).value - } - }.evaluated, + import complete.Parsers.spaceDelimited + val name = spaceDelimited("").parsed match { + case List(name) => name + case _ => throw new IllegalArgumentException("Expected one argument.") + } + Def.task { + (testOnly in Benchmark).toTask(" -- -z " + name).value + } + }.evaluated, parallelExecution in Benchmark := false ) .settings( @@ -1038,40 +1039,40 @@ lazy val `engine-runner` = project MergeStrategy.first }, assemblyOption in assembly := (assemblyOption in assembly).value - .copy( - prependShellScript = Some( - defaultUniversalScript( - shebang = false, - javaOpts = truffleRunOptions ++ - Seq("-Dtruffle.class.path.append=runtime.jar") - ) + .copy( + prependShellScript = Some( + defaultUniversalScript( + shebang = false, + javaOpts = truffleRunOptions ++ + Seq("-Dtruffle.class.path.append=runtime.jar") ) - ), + ) + ), commands += WithDebugCommand.withDebug, inConfig(Compile)(truffleRunOptionsSettings), libraryDependencies ++= Seq( - "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided", - "org.graalvm.truffle" % "truffle-api" % graalVersion % "provided", - "commons-cli" % "commons-cli" % commonsCliVersion, - "com.monovore" %% "decline" % declineVersion, - "org.jline" % "jline" % jlineVersion, - "org.typelevel" %% "cats-core" % catsVersion - ), + "org.graalvm.sdk" % "polyglot-tck" % graalVersion % "provided", + "org.graalvm.truffle" % "truffle-api" % graalVersion % "provided", + "commons-cli" % "commons-cli" % commonsCliVersion, + "com.monovore" %% "decline" % declineVersion, + "org.jline" % "jline" % jlineVersion, + "org.typelevel" %% "cats-core" % catsVersion + ), connectInput in run := true ) .settings( buildNativeImage := NativeImage - .buildNativeImage( - "enso", - staticOnLinux = false, - Seq("-H:IncludeResources=.*Main.enso$") - ) - .value + .buildNativeImage( + "enso", + staticOnLinux = false, + Seq("-H:IncludeResources=.*Main.enso$") + ) + .value ) .settings( assembly := assembly - .dependsOn(runtime / assembly) - .value + .dependsOn(runtime / assembly) + .value ) .dependsOn(`version-output`) .dependsOn(pkg) @@ -1085,48 +1086,48 @@ lazy val launcher = project .settings( resolvers += Resolver.bintrayRepo("gn0s1s", "releases"), libraryDependencies ++= Seq( - "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, - "org.typelevel" %% "cats-core" % catsVersion, - "nl.gn0s1s" %% "bump" % bumpVersion, - "org.apache.commons" % "commons-compress" % commonsCompressVersion, - "org.scalatest" %% "scalatest" % scalatestVersion % Test, - akkaHttp, - akkaSLF4J - ) + "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, + "org.typelevel" %% "cats-core" % catsVersion, + "nl.gn0s1s" %% "bump" % bumpVersion, + "org.apache.commons" % "commons-compress" % commonsCompressVersion, + "org.scalatest" %% "scalatest" % scalatestVersion % Test, + akkaHttp, + akkaSLF4J + ) ) .settings( buildNativeImage := NativeImage - .buildNativeImage( - "enso", - staticOnLinux = true, - Seq( - "-J-Xmx4G", - "--enable-all-security-services", // Note [HTTPS in the Launcher] - "-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog", - "-H:IncludeResources=.*Main.enso$", - "--initialize-at-run-time=" + - "akka.protobuf.DescriptorProtos," + - "com.typesafe.config.impl.ConfigImpl$EnvVariablesHolder," + - "com.typesafe.config.impl.ConfigImpl$SystemPropertiesHolder," + - "org.enso.loggingservice.WSLoggerManager$" // Note [WSLoggerManager Shutdown Hook] - ) + .buildNativeImage( + "enso", + staticOnLinux = true, + Seq( + "-J-Xmx4G", + "--enable-all-security-services", // Note [HTTPS in the Launcher] + "-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog", + "-H:IncludeResources=.*Main.enso$", + "--initialize-at-run-time=" + + "akka.protobuf.DescriptorProtos," + + "com.typesafe.config.impl.ConfigImpl$EnvVariablesHolder," + + "com.typesafe.config.impl.ConfigImpl$SystemPropertiesHolder," + + "org.enso.loggingservice.WSLoggerManager$" // Note [WSLoggerManager Shutdown Hook] ) - .value, + ) + .value, test in assembly := {}, assemblyOutputPath in assembly := file("launcher.jar") ) .settings( (Test / test) := (Test / test) - .dependsOn( - NativeImage.incrementalNativeImageBuild( - buildNativeImage, - "enso" - ) + .dependsOn( + NativeImage.incrementalNativeImageBuild( + buildNativeImage, + "enso" ) - .dependsOn( - LauncherShimsForTest.prepare(rustcVersion = rustVersion) - ) - .value, + ) + .dependsOn( + LauncherShimsForTest.prepare(rustcVersion = rustVersion) + ) + .value, parallelExecution in Test := false ) .dependsOn(cli) @@ -1144,19 +1145,19 @@ lazy val `std-bits` = project Compile / packageBin / artifactPath := `std-lib-polyglot-root` / "std-bits.jar", libraryDependencies ++= Seq( - "com.ibm.icu" % "icu4j" % icuVersion - ), + "com.ibm.icu" % "icu4j" % icuVersion + ), Compile / packageBin := Def.task { - val result = (Compile / packageBin).value - StdBits - .copyDependencies( - `std-lib-polyglot-root`, - "std-bits.jar", - ignoreScalaLibrary = true - ) - .value - result - }.value + val result = (Compile / packageBin).value + StdBits + .copyDependencies( + `std-lib-polyglot-root`, + "std-bits.jar", + ignoreScalaLibrary = true + ) + .value + result + }.value ) /* Note [HTTPS in the Launcher] diff --git a/engine/language-server/src/main/resources/logback.xml b/engine/language-server/src/main/resources/logback.xml index 6438014b07..0b49034d1b 100644 --- a/engine/language-server/src/main/resources/logback.xml +++ b/engine/language-server/src/main/resources/logback.xml @@ -1,16 +1,16 @@ - - - - %d{HH:mm:ss.SSS} %-5level [%-15thread] %-36logger{36} %msg%n - - + + + + %d{HH:mm:ss.SSS} %-5level [%-15thread] %-36logger{36} %msg%n + + - + - - - + + + diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerComponent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerComponent.scala index 478db7428f..e9f8130fb1 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerComponent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerComponent.scala @@ -18,8 +18,7 @@ import org.enso.languageserver.runtime.RuntimeKiller.{ import scala.concurrent.duration._ import scala.concurrent.{Await, Future} -/** - * A lifecycle component used to start and stop a Language Server. +/** A lifecycle component used to start and stop a Language Server. * * @param config a LS config */ @@ -124,16 +123,15 @@ class LanguageServerComponent(config: LanguageServerConfig) _ <- start() } yield ComponentRestarted - private val logError: PartialFunction[Throwable, Unit] = { - case th => logger.error("An error occurred during stopping server", th) + private val logError: PartialFunction[Throwable, Unit] = { case th => + logger.error("An error occurred during stopping server", th) } } object LanguageServerComponent { - /** - * A running server context. + /** A running server context. * * @param mainModule a main module containing all components of the server * @param jsonBinding a http binding for rpc protocol diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerConfig.scala b/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerConfig.scala index c2fe9e90e6..54f58a1ebb 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerConfig.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/boot/LanguageServerConfig.scala @@ -4,8 +4,7 @@ import java.util.UUID import scala.concurrent.ExecutionContext -/** - * The config of the running Language Server instance. +/** The config of the running Language Server instance. * * @param interface a interface that the server listen to * @param rpcPort a rpc port that the server listen to diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/boot/LifecycleComponent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/boot/LifecycleComponent.scala index b31696c62f..7165505506 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/boot/LifecycleComponent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/boot/LifecycleComponent.scala @@ -8,27 +8,23 @@ import org.enso.languageserver.boot.LifecycleComponent.{ import scala.concurrent.Future -/** - * An abstraction for components that can be started and stopped. +/** An abstraction for components that can be started and stopped. */ trait LifecycleComponent { - /** - * Starts asynchronously a server. + /** Starts asynchronously a server. * * @return a notice that the server started successfully */ def start(): Future[ComponentStarted.type] - /** - * Stops asynchronously a server. + /** Stops asynchronously a server. * * @return a notice that the server stopped successfully */ def stop(): Future[ComponentStopped.type] - /** - * Restarts asynchronously a server. + /** Restarts asynchronously a server. * * @return a notice that the server restarted successfully */ @@ -38,18 +34,15 @@ trait LifecycleComponent { object LifecycleComponent { - /** - * Signals that component was started. + /** Signals that component was started. */ case object ComponentStarted - /** - * Signals that component was stopped. + /** Signals that component was stopped. */ case object ComponentStopped - /** - * Signals that component was restarted. + /** Signals that component was restarted. */ case object ComponentRestarted diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/boot/MainModule.scala b/engine/language-server/src/main/scala/org/enso/languageserver/boot/MainModule.scala index 606b1f8cd1..124de4493d 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/boot/MainModule.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/boot/MainModule.scala @@ -41,8 +41,7 @@ import scala.concurrent.Future import scala.concurrent.duration._ import scala.util.{Failure, Success} -/** - * A main module containing all components of the server. +/** A main module containing all components of the server. * * @param serverConfig configuration for the language server */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityApi.scala index 2c0113b9c3..e4c0a78479 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityApi.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.capability import org.enso.languageserver.data.CapabilityRegistration import org.enso.jsonrpc.{Error, HasParams, HasResult, Method, Unused} -/** - * The capability JSON RPC API provided by the language server. +/** The capability JSON RPC API provided by the language server. * See [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] * for message specifications. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityProtocol.scala index 2eb5a7c858..189eb73abd 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityProtocol.scala @@ -6,8 +6,7 @@ import org.enso.languageserver.session.JsonSession object CapabilityProtocol { - /** - * Requests the Language Server grant a new capability to a client. + /** Requests the Language Server grant a new capability to a client. * * @param rpcSession the client to grant the capability to. * @param registration the capability to grant. @@ -17,31 +16,26 @@ object CapabilityProtocol { registration: CapabilityRegistration ) - /** - * Signals capability acquisition status. + /** Signals capability acquisition status. */ sealed trait AcquireCapabilityResponse - /** - * Confirms client that capability has been acquired. + /** Confirms client that capability has been acquired. */ case object CapabilityAcquired extends AcquireCapabilityResponse - /** - * Signals that capability acquisition request cannot be processed. + /** Signals that capability acquisition request cannot be processed. */ case object CapabilityAcquisitionBadRequest extends AcquireCapabilityResponse - /** - * Signals about capability acquisition error. + /** Signals about capability acquisition error. * * @param error file system failure */ case class CapabilityAcquisitionFileSystemFailure(error: FileSystemFailure) extends AcquireCapabilityResponse - /** - * Notifies the Language Server about a client releasing a capability. + /** Notifies the Language Server about a client releasing a capability. * * @param rpcSession the client releasing the capability. * @param capability the capability being released. @@ -51,36 +45,30 @@ object CapabilityProtocol { capability: CapabilityRegistration ) - /** - * Signals capability release status. + /** Signals capability release status. */ sealed trait ReleaseCapabilityResponse - /** - * Confirms client that capability has been released. + /** Confirms client that capability has been released. */ case object CapabilityReleased extends ReleaseCapabilityResponse - /** - * Signals that capability release request cannot be processed. + /** Signals that capability release request cannot be processed. */ case object CapabilityReleaseBadRequest extends ReleaseCapabilityResponse - /** - * Signals that requested capability is not acquired. + /** Signals that requested capability is not acquired. */ case object CapabilityNotAcquiredResponse extends ReleaseCapabilityResponse - /** - * A notification sent by the Language Server, notifying a client about + /** A notification sent by the Language Server, notifying a client about * a capability being taken away from them. * * @param capability the capability being released. */ case class CapabilityForceReleased(capability: CapabilityRegistration) - /** - * A notification sent by the Language Server, notifying a client about a new + /** A notification sent by the Language Server, notifying a client about a new * capability being granted to them. * * @param registration the capability being granted. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityRouter.scala b/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityRouter.scala index 7c6ef3f346..e4dfa255a7 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityRouter.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/capability/CapabilityRouter.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.data.{ import org.enso.languageserver.monitoring.MonitoringProtocol.{Ping, Pong} import org.enso.languageserver.util.UnhandledLogging -/** - * A content based router that routes each capability request to the +/** A content based router that routes each capability request to the * correct recipient based on the capability object. * * @param bufferRegistry the recipient of buffer capability requests @@ -71,8 +70,7 @@ class CapabilityRouter( object CapabilityRouter { - /** - * Creates a configuration object used to create a [[CapabilityRouter]] + /** Creates a configuration object used to create a [[CapabilityRouter]] * * @param bufferRegistry a buffer registry ref * @param receivesTreeUpdatesHandler the recipient of `receivesTreeUpdates` diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/data/Capability.scala b/engine/language-server/src/main/scala/org/enso/languageserver/data/Capability.scala index 4155e68a69..ccb26cc921 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/data/Capability.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/data/Capability.scala @@ -5,15 +5,13 @@ import io.circe._ import org.enso.languageserver.filemanager.Path import org.enso.languageserver.runtime.ExecutionApi.ContextId -/** - * A superclass for all capabilities in the system. +/** A superclass for all capabilities in the system. * @param method method name used to identify the capability. */ sealed abstract class Capability(val method: String) //TODO[MK]: Migrate to actual Path, once it is implemented. -/** - * A capability allowing the user to modify a given file. +/** A capability allowing the user to modify a given file. * @param path the file path this capability is granted for. */ case class CanEdit(path: Path) extends Capability(CanEdit.methodName) @@ -22,8 +20,7 @@ object CanEdit { val methodName = "text/canEdit" } -/** - * A capability allowing user to receive file events. +/** A capability allowing user to receive file events. * * @param path path to watch. */ @@ -34,8 +31,7 @@ object ReceivesTreeUpdates { val methodName = "file/receivesTreeUpdates" } -/** - * A capability allowing user to modify the execution context. +/** A capability allowing user to modify the execution context. * * @param contextId identifier of an execution conatext */ @@ -46,8 +42,7 @@ object CanModify { val methodName = "executionContext/canModify" } -/** - * A capability allowing user to receive events from the execution context. +/** A capability allowing user to receive events from the execution context. * * @param contextId identifier of an execution conatext */ @@ -79,8 +74,7 @@ object ReceivesSuggestionsDatabaseUpdates { val methodName = "search/receivesSuggestionsDatabaseUpdates" } -/** - * A capability registration object, used to identify acquired capabilities. +/** A capability registration object, used to identify acquired capabilities. * * @param capability the registered capability. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/data/Config.scala b/engine/language-server/src/main/scala/org/enso/languageserver/data/Config.scala index f6be892d88..0c067cbf15 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/data/Config.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/data/Config.scala @@ -13,8 +13,7 @@ import org.enso.languageserver.filemanager.{ import scala.concurrent.duration._ import scala.util.Try -/** - * Configuration of the path watcher. +/** Configuration of the path watcher. * * @param timeout path watcher operations timeout * @param restartTimeout timeout before watcher is restarted on error @@ -29,8 +28,7 @@ case class PathWatcherConfig( object PathWatcherConfig { - /** - * Default path watcher config. + /** Default path watcher config. */ def apply(): PathWatcherConfig = PathWatcherConfig( @@ -40,8 +38,7 @@ object PathWatcherConfig { ) } -/** - * Configuration of the file manager. +/** Configuration of the file manager. * * @param timeout IO operation timeout * @param parallelism number of processes working with the file system @@ -50,8 +47,7 @@ case class FileManagerConfig(timeout: FiniteDuration, parallelism: Int) object FileManagerConfig { - /** - * Default file manager config. + /** Default file manager config. * * @param timeout IO operation timeout */ @@ -62,8 +58,7 @@ object FileManagerConfig { ) } -/** - * Configuration of the execution context. +/** Configuration of the execution context. * * @param requestTimeout timeout of requests to the engine */ @@ -71,8 +66,7 @@ case class ExecutionContextConfig(requestTimeout: FiniteDuration) object ExecutionContextConfig { - /** - * Default execution context config. + /** Default execution context config. */ def apply(): ExecutionContextConfig = ExecutionContextConfig( @@ -80,8 +74,7 @@ object ExecutionContextConfig { ) } -/** - * Configuration of directories for storing internal files. +/** Configuration of directories for storing internal files. * * @param root the root directory path */ @@ -103,8 +96,7 @@ object DirectoriesConfig { val DataDirectory: String = ".enso" val SuggestionsDatabaseFile: String = "suggestions.db" - /** - * Create default data directory config + /** Create default data directory config * * @param root the root directory path * @return default data directory config @@ -113,8 +105,7 @@ object DirectoriesConfig { new DirectoriesConfig(new File(root)) } -/** - * The config of the running Language Server instance. +/** The config of the running Language Server instance. * * @param contentRoots a mapping between content root id and absolute path to * the content root @@ -137,13 +128,12 @@ case class Config( .toRight(ContentRootNotFound) def findRelativePath(path: File): Option[Path] = - contentRoots.view.flatMap { - case (id, root) => - if (path.toPath.startsWith(root.toPath)) { - Some(Path(id, root.toPath.relativize(path.toPath))) - } else { - None - } + contentRoots.view.flatMap { case (id, root) => + if (path.toPath.startsWith(root.toPath)) { + Some(Path(id, root.toPath.relativize(path.toPath))) + } else { + None + } }.headOption } diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/data/ContentBasedVersioning.scala b/engine/language-server/src/main/scala/org/enso/languageserver/data/ContentBasedVersioning.scala index 5dc8201cb8..948cf8ff0c 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/data/ContentBasedVersioning.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/data/ContentBasedVersioning.scala @@ -1,20 +1,17 @@ package org.enso.languageserver.data -/** - * A content-based versioning calculator. +/** A content-based versioning calculator. */ trait ContentBasedVersioning { - /** - * Evaluates content-based version of document. + /** Evaluates content-based version of document. * * @param content a textual content * @return a string representation of a digest */ def evalVersion(content: String): String - /** - * Evaluates content-based version of document. + /** Evaluates content-based version of document. * * @param content a textual content * @return a digest diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/data/Sha3_224VersionCalculator.scala b/engine/language-server/src/main/scala/org/enso/languageserver/data/Sha3_224VersionCalculator.scala index 7fb22f3492..f3a17a1d18 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/data/Sha3_224VersionCalculator.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/data/Sha3_224VersionCalculator.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.data import org.bouncycastle.jcajce.provider.digest.SHA3 import org.bouncycastle.util.encoders.Hex -/** - * SHA3-224 digest calculator. +/** SHA3-224 digest calculator. */ object Sha3_224VersionCalculator extends ContentBasedVersioning { diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/data/package.scala b/engine/language-server/src/main/scala/org/enso/languageserver/data/package.scala index 9aa44f7965..0c88f56a61 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/data/package.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/data/package.scala @@ -4,8 +4,7 @@ import java.util.UUID package object data { - /** - * A type representing the internal id of a client. + /** A type representing the internal id of a client. */ type ClientId = UUID diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/effect/Exec.scala b/engine/language-server/src/main/scala/org/enso/languageserver/effect/Exec.scala index 7a2d56c746..1ae16db16e 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/effect/Exec.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/effect/Exec.scala @@ -8,21 +8,18 @@ import zio.blocking.blocking import scala.concurrent.{Future, Promise} import scala.concurrent.duration.FiniteDuration -/** - * Abstract entity that executes effects `F`. +/** Abstract entity that executes effects `F`. */ trait Exec[-F[_, _]] { - /** - * Execute Zio effect. + /** Execute Zio effect. * * @param op effect to execute * @return a future containing either a failure or a result */ def exec[E, A](op: F[E, A]): Future[Either[E, A]] - /** - * Execute Zio effect with timeout. + /** Execute Zio effect with timeout. * * @param timeout execution timeout * @param op effect to execute @@ -33,23 +30,20 @@ trait Exec[-F[_, _]] { op: F[E, A] ): Future[Either[E, A]] - /** - * Execute long running task in background. + /** Execute long running task in background. * * @param op effect to execute */ def exec_[E, A](op: F[E, A]): Unit } -/** - * Executor of Zio effects. +/** Executor of Zio effects. * * @param runtime zio runtime */ case class ZioExec(runtime: Runtime[ZEnv]) extends Exec[ZioExec.IO] { - /** - * Execute Zio effect. + /** Execute Zio effect. * * @param op effect to execute * @return a future containing either a failure or a result @@ -65,8 +59,7 @@ case class ZioExec(runtime: Runtime[ZEnv]) extends Exec[ZioExec.IO] { promise.future } - /** - * Execute Zio effect with timeout. + /** Execute Zio effect with timeout. * * @param timeout execution timeout * @param op effect to execute @@ -91,8 +84,7 @@ case class ZioExec(runtime: Runtime[ZEnv]) extends Exec[ZioExec.IO] { promise.future } - /** - * Execute long running task in background. + /** Execute long running task in background. * * @param op effect to execute */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/event/BufferEvent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/event/BufferEvent.scala index 00faae3a89..cfa7b195e4 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/event/BufferEvent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/event/BufferEvent.scala @@ -2,20 +2,17 @@ package org.enso.languageserver.event import org.enso.languageserver.filemanager.Path -/** - * Base trait for all buffer events. +/** Base trait for all buffer events. */ sealed trait BufferEvent extends Event -/** - * Notifies the Language Server when new file is opened for editing. +/** Notifies the Language Server when new file is opened for editing. * * @param path the path to a file */ case class BufferOpened(path: Path) extends BufferEvent -/** - * Notifies the Language Server when a file is closed for editing. +/** Notifies the Language Server when a file is closed for editing. * * @param path the path to a file */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/event/Event.scala b/engine/language-server/src/main/scala/org/enso/languageserver/event/Event.scala index f3752b50fe..2001fef8be 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/event/Event.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/event/Event.scala @@ -1,6 +1,5 @@ package org.enso.languageserver.event -/** - * Base trait for all server events. +/** Base trait for all server events. */ trait Event diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/event/ExecutionContextEvent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/event/ExecutionContextEvent.scala index b8d5efd6fc..6cad4e2412 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/event/ExecutionContextEvent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/event/ExecutionContextEvent.scala @@ -4,13 +4,11 @@ import java.util.UUID import org.enso.languageserver.data.ClientId -/** - * Base trait for all execution context events. +/** Base trait for all execution context events. */ sealed trait ExecutionContextEvent extends Event -/** - * Notifies the Language Server about a new execution context. +/** Notifies the Language Server about a new execution context. * * @param contextId the id of newly created context * @param owner the id of the owner of the context @@ -18,8 +16,7 @@ sealed trait ExecutionContextEvent extends Event case class ExecutionContextCreated(contextId: UUID, owner: ClientId) extends ExecutionContextEvent -/** - * Notifies the Language Server about a termination of an execution context. +/** Notifies the Language Server about a termination of an execution context. * * @param contextId the id of terminated context * @param owner the id of the owner of the context diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/event/SessionEvent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/event/SessionEvent.scala index c7e0a069f7..3d311c977f 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/event/SessionEvent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/event/SessionEvent.scala @@ -2,35 +2,30 @@ package org.enso.languageserver.event import org.enso.languageserver.session.{BinarySession, JsonSession} -/** - * Base trait for all session events. +/** Base trait for all session events. */ sealed trait SessionEvent extends Event -/** - * Notifies the Language Server about a new rpc session. +/** Notifies the Language Server about a new rpc session. * * @param session an object representing a client session */ case class JsonSessionInitialized(session: JsonSession) extends SessionEvent -/** - * Notifies the Language Server about a client disconnecting rpc session. +/** Notifies the Language Server about a client disconnecting rpc session. * The client may not send any further messages after this one. * * @param session an object representing a client session */ case class JsonSessionTerminated(session: JsonSession) extends SessionEvent -/** - * Notifies the Language Server about a new data session. +/** Notifies the Language Server about a new data session. * * @param session an object representing a client session */ case class BinarySessionInitialized(session: BinarySession) extends SessionEvent -/** - * Notifies the Language Server about a client disconnecting data session. +/** Notifies the Language Server about a client disconnecting data session. * The client may not send any further messages after this one. * * @param session an object representing a client session diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/DirectoryTree.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/DirectoryTree.scala index 22f7c58ed6..ab5ca8c4e4 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/DirectoryTree.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/DirectoryTree.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.filemanager import java.io.File -/** - * A representation of tree structures of files and directories. +/** A representation of tree structures of files and directories. * * @param path to the directory * @param name of the directory @@ -19,8 +18,7 @@ case class DirectoryTree( object DirectoryTree { - /** - * Create [[DirectoryTree]] from [[FileSystemApi.DirectoryEntry]] + /** Create [[DirectoryTree]] from [[FileSystemApi.DirectoryEntry]] * converting absolute pathes to ones relative to project root. * * @param root path to the project root diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileAttributes.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileAttributes.scala index 4056a717be..e2961410ca 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileAttributes.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileAttributes.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.filemanager import java.io.File import java.time.OffsetDateTime -/** - * A representation of the attributes of a file. +/** A representation of the attributes of a file. * * @param creationTime creation time * @param lastAccessTime last access time @@ -25,8 +24,7 @@ case class FileAttributes( object FileAttributes { - /** - * Create attributes from filesystem attributes [[FileSystemApi.Attributes]]. + /** Create attributes from filesystem attributes [[FileSystemApi.Attributes]]. * * @param root a root path * @param path a path to the file system object diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileDeletedEvent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileDeletedEvent.scala index 228a3024c7..3f96131785 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileDeletedEvent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileDeletedEvent.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.filemanager import org.enso.languageserver.event.Event -/** - * A notification about successful file deletion action +/** A notification about successful file deletion action * * @param file the deleted file */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileEvent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileEvent.scala index d48a264336..c51479de5b 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileEvent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileEvent.scala @@ -4,8 +4,7 @@ import java.io.File import enumeratum._ -/** - * A representation of filesystem event. +/** A representation of filesystem event. * * @param path path to the file system object * @param kind type of file system event @@ -14,8 +13,7 @@ case class FileEvent(path: Path, kind: FileEventKind) object FileEvent { - /** - * Conversion from file system event. + /** Conversion from file system event. * * @param root a project root * @param base a watched path @@ -33,32 +31,27 @@ object FileEvent { ) } -/** - * Type of a file event. +/** Type of a file event. */ sealed trait FileEventKind extends EnumEntry object FileEventKind extends Enum[FileEventKind] with CirceEnum[FileEventKind] { - /** - * Event type indicating file creation. + /** Event type indicating file creation. */ case object Added extends FileEventKind - /** - * Event type indicating file deletion. + /** Event type indicating file deletion. */ case object Removed extends FileEventKind - /** - * Event type indicating file modification. + /** Event type indicating file modification. */ case object Modified extends FileEventKind override val values = findValues - /** - * Create [[FileEventKind]] from [[WatcherAdapter.EventType]]. + /** Create [[FileEventKind]] from [[WatcherAdapter.EventType]]. * * @param eventType file system event type * @return file event kind diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManager.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManager.scala index dcb3947e87..95ea5e6bf1 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManager.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManager.scala @@ -9,8 +9,7 @@ import org.enso.languageserver.monitoring.MonitoringProtocol.{Ping, Pong} import org.enso.languageserver.util.UnhandledLogging import zio._ -/** - * Handles the [[FileManagerProtocol]] messages, executes the [[FileSystem]] +/** Handles the [[FileManagerProtocol]] messages, executes the [[FileSystem]] * effects and forms the responses. * * @param config configuration @@ -96,7 +95,7 @@ class FileManager( () case FileManagerProtocol.CreateFile( - FileSystemObject.Directory(name, path) + FileSystemObject.Directory(name, path) ) => val result = for { diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerApi.scala index e855190be2..daa93a7be3 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerApi.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.filemanager import org.enso.jsonrpc.{Error, HasParams, HasResult, Method, Unused} -/** - * The file manager JSON RPC API provided by the language server. +/** The file manager JSON RPC API provided by the language server. * See [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] * for message specifications. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerProtocol.scala index b3fc9fe11c..883b45e02e 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileManagerProtocol.scala @@ -5,73 +5,63 @@ import java.util.UUID object FileManagerProtocol { - /** - * Transfer object containing textual contents of the file with its path. + /** Transfer object containing textual contents of the file with its path. * * @param path a path to a file * @param content the textual contents */ case class TextualFileContent(path: File, content: String) - /** - * Transfer object containing binary contents of the file with its path. + /** Transfer object containing binary contents of the file with its path. * * @param path a path to a file * @param contents the binary contents */ case class BinaryFileContent(path: File, contents: Array[Byte]) - /** - * Gets all content roots. + /** Gets all content roots. */ case object GetContentRoots - /** - * Response containing all content roots. + /** Response containing all content roots. * * @param contentRoots content roots */ case class ContentRootsResult(contentRoots: Set[UUID]) - /** - * Requests the Language Server write textual content to an arbitrary file. + /** Requests the Language Server write textual content to an arbitrary file. * * @param path a path to a file * @param content a textual content */ case class WriteFile(path: Path, content: String) - /** - * Requests the Language Server write binary contents to an arbitrary file. + /** Requests the Language Server write binary contents to an arbitrary file. * * @param path a path to a file * @param contents binary contents */ case class WriteBinaryFile(path: Path, contents: Array[Byte]) - /** - * Signals file manipulation status. + /** Signals file manipulation status. * * @param result either file system failure or unit representing success */ case class WriteFileResult(result: Either[FileSystemFailure, Unit]) - /** - * Requests the Language Server read a file. + /** Requests the Language Server read a file. * * @param path a path to a file */ case class ReadFile(path: Path) - /** - * Requests the Language Server to read a binary content of a file. + /** Requests the Language Server to read a binary content of a file. * * @param path a path to a file */ case class ReadBinaryFile(path: Path) - /** - * Returns a result of reading a file. + /** Returns a result of reading a file. * * @param result either file system failure or content of a file */ @@ -79,8 +69,7 @@ object FileManagerProtocol { result: Either[FileSystemFailure, TextualFileContent] ) - /** - * Returns a result of reading binary contents of a file. + /** Returns a result of reading binary contents of a file. * * @param result either file system failure or content of a file */ @@ -88,87 +77,75 @@ object FileManagerProtocol { result: Either[FileSystemFailure, BinaryFileContent] ) - /** - * Requests the Language Server create a file system object. + /** Requests the Language Server create a file system object. * * @param `object` a file system object */ case class CreateFile(`object`: FileSystemObject) - /** - * Returns a result of creating a file system object. + /** Returns a result of creating a file system object. * * @param result either file system failure or unit representing success */ case class CreateFileResult(result: Either[FileSystemFailure, Unit]) - /** - * Requests the Language Server delete a file system object. + /** Requests the Language Server delete a file system object. * * @param path a path to a file */ case class DeleteFile(path: Path) - /** - * Returns a result of deleting a file system object. + /** Returns a result of deleting a file system object. * * @param result either file system failure or unit representing success */ case class DeleteFileResult(result: Either[FileSystemFailure, Unit]) - /** - * Requests the Language Server copy a file system object. + /** Requests the Language Server copy a file system object. * * @param from a path to the source * @param to a path to the destination */ case class CopyFile(from: Path, to: Path) - /** - * Returns a result of copying a file system object. + /** Returns a result of copying a file system object. * * @param result either file system failure or unit representing success */ case class CopyFileResult(result: Either[FileSystemFailure, Unit]) - /** - * Requests the Language Server move a file system object. + /** Requests the Language Server move a file system object. * * @param from a path to the source * @param to a path to the destination */ case class MoveFile(from: Path, to: Path) - /** - * Returns a result of moving a file system object. + /** Returns a result of moving a file system object. * * @param result either file system failure or unit representing success */ case class MoveFileResult(result: Either[FileSystemFailure, Unit]) - /** - * Requests the Language Server to check the existence of file system object. + /** Requests the Language Server to check the existence of file system object. * * @param path a path to a file */ case class ExistsFile(path: Path) - /** - * Returns a result of checking the existence of file system object. + /** Returns a result of checking the existence of file system object. * * @param result either file system failure or file existence flag */ case class ExistsFileResult(result: Either[FileSystemFailure, Boolean]) - /** - * Requests the Language Server to list a directory contents. + /** Requests the Language Server to list a directory contents. * * @param path to the file system object */ case class ListFile(path: Path) - /** - * Returns a tree representation of a file system object. + /** Returns a tree representation of a file system object. * * @param result either file system failure or directory tree */ @@ -176,29 +153,25 @@ object FileManagerProtocol { result: Either[FileSystemFailure, Vector[FileSystemObject]] ) - /** - * Requests the Language Server to get a tree of a file system object. + /** Requests the Language Server to get a tree of a file system object. * * @param path to the file system object */ case class TreeFile(path: Path, depth: Option[Int]) - /** - * Returns a tree representation of a file system object. + /** Returns a tree representation of a file system object. * * @param result either file system failure or directory tree */ case class TreeFileResult(result: Either[FileSystemFailure, DirectoryTree]) - /** - * Requests the Language Server to get attributes of a file system object. + /** Requests the Language Server to get attributes of a file system object. * * @param path to the file system object */ case class InfoFile(path: Path) - /** - * Returns an attributes of a file system object. + /** Returns an attributes of a file system object. * * @param result either file system failure or attributes */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala index 1b468e3b5b..1205a77861 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystem.scala @@ -11,8 +11,7 @@ import zio.blocking.effectBlocking import scala.collection.mutable -/** - * File manipulation facility. +/** File manipulation facility. * * @tparam F represents target monad */ @@ -20,8 +19,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { import FileSystemApi._ - /** - * Writes textual content to a file. + /** Writes textual content to a file. * * @param file path to the file * @param content a textual content of the file @@ -34,7 +32,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { effectBlocking(FileUtils.write(file, content, "UTF-8")) .mapError(errorHandling) - /** @inheritdoc **/ + /** @inheritdoc */ override def writeBinary( file: File, contents: Array[Byte] @@ -42,8 +40,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { effectBlocking(FileUtils.writeByteArrayToFile(file, contents)) .mapError(errorHandling) - /** - * Reads the contents of a textual file. + /** Reads the contents of a textual file. * * @param file path to the file * @return either [[FileSystemFailure]] or the content of a file as a String @@ -52,15 +49,14 @@ class FileSystem extends FileSystemApi[BlockingIO] { effectBlocking(FileUtils.readFileToString(file, "UTF-8")) .mapError(errorHandling) - /** @inheritdoc **/ + /** @inheritdoc */ override def readBinary( file: File ): BlockingIO[FileSystemFailure, Array[Byte]] = effectBlocking(FileUtils.readFileToByteArray(file)) .mapError(errorHandling) - /** - * Deletes the specified file or directory recursively. + /** Deletes the specified file or directory recursively. * * @param file path to the file or directory * @return either [[FileSystemFailure]] or Unit @@ -74,8 +70,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { } }.mapError(errorHandling) - /** - * Creates an empty file with parent directory. + /** Creates an empty file with parent directory. * * @param file path to the file * @return @@ -90,8 +85,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { effectBlocking(file.createNewFile(): Unit) .mapError(errorHandling) - /** - * Creates a directory, including any necessary but nonexistent parent + /** Creates a directory, including any necessary but nonexistent parent * directories. * * @param file path to the file @@ -103,8 +97,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { effectBlocking(FileUtils.forceMkdir(file)) .mapError(errorHandling) - /** - * Copy a file or directory recursively. + /** Copy a file or directory recursively. * * @param from a path to the source * @param to a path to the destination. If from is a file, then to @@ -127,8 +120,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { }.mapError(errorHandling) } - /** - * Move a file or directory recursively + /** Move a file or directory recursively * * @param from a path to the source * @param to a path to the destination @@ -146,8 +138,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { } }.mapError(errorHandling) - /** - * Checks if the specified file exists. + /** Checks if the specified file exists. * * @param file path to the file or directory * @return either [[FileSystemFailure]] or file existence flag @@ -156,8 +147,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { effectBlocking(Files.exists(file.toPath)) .mapError(errorHandling) - /** - * List contents of a given path. + /** List contents of a given path. * * @param path to the file system object * @return either [[FileSystemFailure]] or list of entries @@ -181,8 +171,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { IO.fail(FileNotFound) } - /** - * Returns tree of a given path. + /** Returns tree of a given path. * * @param path to the file system object * @param depth maximum depth of a directory tree @@ -214,8 +203,7 @@ class FileSystem extends FileSystemApi[BlockingIO] { } } - /** - * Returns attributes of a given path. + /** Returns attributes of a given path. * * @param path to the file system object * @return either [[FileSystemFailure]] or file attributes @@ -247,8 +235,7 @@ object FileSystem { import FileSystemApi._ - /** - * Represent a depth limit when recursively traversing a directory. + /** Represent a depth limit when recursively traversing a directory. */ sealed private trait Depth { @@ -281,8 +268,7 @@ object FileSystem { UnlimitedDepth } - /** - * Represents subdirectory in the tree algorithm. + /** Represents subdirectory in the tree algorithm. * * @param entry subdir entry * @param level subdir depth level @@ -294,8 +280,7 @@ object FileSystem { visited: Vector[SymbolicLinkEntry] ) - /** - * Read an entry without following the symlinks. + /** Read an entry without following the symlinks. */ private def readEntry(path: Path): Entry = { if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) { @@ -314,8 +299,7 @@ object FileSystem { } } - /** - * Read the target of a symlink. + /** Read the target of a symlink. */ private def readSymbolicLink(path: Path): Entry = { if (Files.isRegularFile(path)) { @@ -327,8 +311,7 @@ object FileSystem { } } - /** - * Returns the entries of the provided path. Symlinks are not resolved. + /** Returns the entries of the provided path. Symlinks are not resolved. * * @param path to the directory * @return list of entries @@ -344,8 +327,7 @@ object FileSystem { .sortBy(_.path) } - /** - * Makes BFS traversal and updates provided directory [[DirectoryEntry]]. + /** Makes BFS traversal and updates provided directory [[DirectoryEntry]]. * Symlinks are resolved. Returned [[SymbolicLinkEntry]] indicates a loop. * * @param directory current directory diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala index 0d3b72b516..75c3936bce 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemApi.scala @@ -9,8 +9,7 @@ import org.enso.languageserver.effect.BlockingIO import scala.collection.mutable.ArrayBuffer -/** - * File manipulation API. +/** File manipulation API. * * @tparam F represents target monad */ @@ -18,8 +17,7 @@ trait FileSystemApi[F[_, _]] { import FileSystemApi._ - /** - * Writes textual content to a file. + /** Writes textual content to a file. * * @param file path to the file * @param content a textual content of the file @@ -30,8 +28,7 @@ trait FileSystemApi[F[_, _]] { content: String ): F[FileSystemFailure, Unit] - /** - * Writes binary content to a file. + /** Writes binary content to a file. * * @param file path to the file * @param contents a binary content of the file @@ -42,16 +39,14 @@ trait FileSystemApi[F[_, _]] { contents: Array[Byte] ): BlockingIO[FileSystemFailure, Unit] - /** - * Reads the contents of a textual file. + /** Reads the contents of a textual file. * * @param file path to the file * @return either [[FileSystemFailure]] or the content of a file as a String */ def read(file: File): F[FileSystemFailure, String] - /** - * Reads the contents of a binary file. + /** Reads the contents of a binary file. * * @param file path to the file * @return either [[FileSystemFailure]] or the content of a file as a byte @@ -59,24 +54,21 @@ trait FileSystemApi[F[_, _]] { */ def readBinary(file: File): BlockingIO[FileSystemFailure, Array[Byte]] - /** - * Deletes the specified file or directory recursively. + /** Deletes the specified file or directory recursively. * * @param file path to the file or directory * @return either [[FileSystemFailure]] or Unit */ def delete(file: File): F[FileSystemFailure, Unit] - /** - * Creates an empty file with parent directory. + /** Creates an empty file with parent directory. * * @param file path to the file * @return */ def createFile(file: File): F[FileSystemFailure, Unit] - /** - * Creates a directory, including any necessary but nonexistent parent + /** Creates a directory, including any necessary but nonexistent parent * directories. * * @param file path to the file @@ -84,8 +76,7 @@ trait FileSystemApi[F[_, _]] { */ def createDirectory(file: File): F[FileSystemFailure, Unit] - /** - * Copy a file or directory recursively + /** Copy a file or directory recursively * * @param from a path to the source * @param to a path to the destination @@ -96,8 +87,7 @@ trait FileSystemApi[F[_, _]] { to: File ): F[FileSystemFailure, Unit] - /** - * Move a file or directory recursively + /** Move a file or directory recursively * * @param from a path to the source * @param to a path to the destination @@ -108,24 +98,21 @@ trait FileSystemApi[F[_, _]] { to: File ): F[FileSystemFailure, Unit] - /** - * Checks if the specified file exists. + /** Checks if the specified file exists. * * @param file path to the file or directory * @return either [[FileSystemFailure]] or file existence flag */ def exists(file: File): F[FileSystemFailure, Boolean] - /** - * List contents of a given path. + /** List contents of a given path. * * @param path to the file system object * @return either [[FileSystemFailure]] or list of entries */ def list(path: File): F[FileSystemFailure, Vector[Entry]] - /** - * Returns contents of a given path. + /** Returns contents of a given path. * * @param path to the file system object * @param depth maximum depth of a directory tree @@ -136,8 +123,7 @@ trait FileSystemApi[F[_, _]] { depth: Option[Int] ): F[FileSystemFailure, DirectoryEntry] - /** - * Returns attributes of a given path. + /** Returns attributes of a given path. * * @param path to the file system object * @return either [[FileSystemFailure]] or file attributes @@ -147,8 +133,7 @@ trait FileSystemApi[F[_, _]] { object FileSystemApi { - /** - * An object representing abstract file system entry. + /** An object representing abstract file system entry. */ sealed trait Entry { def path: Path @@ -156,8 +141,7 @@ object FileSystemApi { object Entry { - /** - * Creates [[Entry]] from file system attributes. + /** Creates [[Entry]] from file system attributes. * * @param path a path to the file system object * @param attrs a file system attributes @@ -173,8 +157,7 @@ object FileSystemApi { } } - /** - * An entry representing a directory. + /** An entry representing a directory. * * @param path to the directory * @param children a paths to the children entries @@ -188,35 +171,30 @@ object FileSystemApi { DirectoryEntry(path, ArrayBuffer()) } - /** - * An entry representing a directory with contents truncated. + /** An entry representing a directory with contents truncated. * * @param path to the directory */ case class DirectoryEntryTruncated(path: Path) extends Entry - /** - * An entry representing a symbolic link. + /** An entry representing a symbolic link. * * @param path to the symlink * @param target of the symlink. */ case class SymbolicLinkEntry(path: Path, target: Path) extends Entry - /** - * An entry representing a file. + /** An entry representing a file. * * @param path to the file */ case class FileEntry(path: Path) extends Entry - /** - * Unrecognized file system entry. Example is a broken symlink. + /** Unrecognized file system entry. Example is a broken symlink. */ case class OtherEntry(path: Path) extends Entry - /** - * Basic attributes of an [[Entry]]. + /** Basic attributes of an [[Entry]]. * * @param creationTime creation time * @param lastAccessTime last access time @@ -234,8 +212,7 @@ object FileSystemApi { object Attributes { - /** - * Creates attributes using the `FileTime` time. + /** Creates attributes using the `FileTime` time. * * @param creationTime creation time * @param lastAccessTime last access time @@ -259,8 +236,7 @@ object FileSystemApi { byteSize = byteSize ) - /** - * Creates [[Attributes]] from file system attributes + /** Creates [[Attributes]] from file system attributes * * @param path to the file system object * @param attributes of a file system object diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailure.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailure.scala index e3474e6e7e..de077e61d4 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailure.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailure.scala @@ -1,42 +1,34 @@ package org.enso.languageserver.filemanager -/** - * Represents file system failures. +/** Represents file system failures. */ sealed trait FileSystemFailure -/** - * Informs that the requested content root cannot be found. +/** Informs that the requested content root cannot be found. */ case object ContentRootNotFound extends FileSystemFailure -/** - * Signals that a user doesn't have access to a file. +/** Signals that a user doesn't have access to a file. */ case object AccessDenied extends FileSystemFailure -/** - * Signals that the file cannot be found. +/** Signals that the file cannot be found. */ case object FileNotFound extends FileSystemFailure -/** - * Signals that the file already exists. +/** Signals that the file already exists. */ case object FileExists extends FileSystemFailure -/** - * Signal that the operation timed out. +/** Signal that the operation timed out. */ case object OperationTimeout extends FileSystemFailure -/** - * Signal that the provided path is not directory. +/** Signal that the provided path is not directory. */ case object NotDirectory extends FileSystemFailure -/** - * Signals file system specific errors. +/** Signals file system specific errors. * * @param reason a reason of failure */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailureMapper.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailureMapper.scala index 120140773e..a92a4254ac 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailureMapper.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemFailureMapper.scala @@ -13,8 +13,7 @@ import org.enso.languageserver.protocol.json.ErrorApi object FileSystemFailureMapper { - /** - * Maps [[FileSystemFailure]] into JSON RPC error. + /** Maps [[FileSystemFailure]] into JSON RPC error. * * @param fileSystemFailure file system specific failure * @return JSON RPC error diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemObject.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemObject.scala index b7296f5a4f..1c09fcf8b5 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemObject.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/FileSystemObject.scala @@ -4,23 +4,20 @@ import io.circe.generic.auto._ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Json} -/** - * A representation of filesystem object. +/** A representation of filesystem object. */ sealed trait FileSystemObject object FileSystemObject { - /** - * Represents a directory. + /** Represents a directory. * * @param name a name of the directory * @param path a path to the directory */ case class Directory(name: String, path: Path) extends FileSystemObject - /** - * Represents a symbolic link that creates a loop. + /** Represents a symbolic link that creates a loop. * * @param name a name of the symlink * @param path a path to the symlink @@ -30,16 +27,14 @@ object FileSystemObject { case class SymlinkLoop(name: String, path: Path, target: Path) extends FileSystemObject - /** - * Represents a file. + /** Represents a file. * * @param name a name of the file * @param path a path to the file */ case class File(name: String, path: Path) extends FileSystemObject - /** - * Represents unrecognized object. Example is a broken symlink. + /** Represents unrecognized object. Example is a broken symlink. */ case class Other(name: String, path: Path) extends FileSystemObject diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/Path.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/Path.scala index 01e0014147..b448c42319 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/Path.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/Path.scala @@ -5,8 +5,7 @@ import java.nio import java.nio.file.Paths import java.util.UUID -/** - * A representation of a path relative to a specified content root. +/** A representation of a path relative to a specified content root. * * @param rootId a content root id that the path is relative to * @param segments path segments @@ -14,8 +13,8 @@ import java.util.UUID case class Path(rootId: UUID, segments: Vector[String]) { def toFile(rootPath: File): File = - segments.foldLeft(rootPath) { - case (parent, child) => new File(parent, child) + segments.foldLeft(rootPath) { case (parent, child) => + new File(parent, child) } def toFile(rootPath: File, fileName: String): File = { @@ -38,8 +37,7 @@ object Path { b.result().filter(_.nonEmpty) } - /** - * Get path relative to the root. + /** Get path relative to the root. * * @param root a root path * @param base a path relative to the root @@ -49,8 +47,7 @@ object Path { def getRelativePath(root: File, base: Path, path: nio.file.Path): Path = Path(base.rootId, root.toPath.relativize(path)) - /** - * Get path relative to the root, and return a parent path. + /** Get path relative to the root, and return a parent path. * * @param root a root path * @param base a path relative to the root diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcher.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcher.scala index aeeca4a782..058b26b972 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcher.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcher.scala @@ -23,8 +23,7 @@ import zio._ import scala.concurrent.Await -/** - * Starts [[WatcherAdapter]], handles errors, converts and sends +/** Starts [[WatcherAdapter]], handles errors, converts and sends * events to the client. * * @param config configuration @@ -55,33 +54,32 @@ final class PathWatcher( override def receive: Receive = uninitializedStage - private def uninitializedStage: Receive = { - case WatchPath(path, clients) => - val pathToWatchResult = config - .findContentRoot(path.rootId) - .map(path.toFile(_)) - val result: BlockingIO[FileSystemFailure, Unit] = - for { - pathToWatch <- IO.fromEither(pathToWatchResult) - _ <- validatePath(pathToWatch) - watcher <- IO.fromEither(buildWatcher(pathToWatch)) - _ <- IO.fromEither(startWatcher(watcher)) - } yield () + private def uninitializedStage: Receive = { case WatchPath(path, clients) => + val pathToWatchResult = config + .findContentRoot(path.rootId) + .map(path.toFile(_)) + val result: BlockingIO[FileSystemFailure, Unit] = + for { + pathToWatch <- IO.fromEither(pathToWatchResult) + _ <- validatePath(pathToWatch) + watcher <- IO.fromEither(buildWatcher(pathToWatch)) + _ <- IO.fromEither(startWatcher(watcher)) + } yield () - exec - .exec(result) - .map { - case Right(()) => CapabilityAcquired - case Left(err) => CapabilityAcquisitionFileSystemFailure(err) - } - .pipeTo(sender()) - - pathToWatchResult match { - case Right(root) => - context.become(initializedStage(root, path, clients)) - case Left(_) => - context.stop(self) + exec + .exec(result) + .map { + case Right(()) => CapabilityAcquired + case Left(err) => CapabilityAcquisitionFileSystemFailure(err) } + .pipeTo(sender()) + + pathToWatchResult match { + case Right(root) => + context.become(initializedStage(root, path, clients)) + case Left(_) => + context.stop(self) + } } private def initializedStage( @@ -178,8 +176,7 @@ final class PathWatcher( object PathWatcher { - /** - * Counter for unsuccessful file watcher restarts. + /** Counter for unsuccessful file watcher restarts. * * @param maxRestarts maximum restart attempts */ @@ -187,33 +184,28 @@ object PathWatcher { private var restartCount: Int = 0 - /** - * Return current restart count. + /** Return current restart count. */ def count: Int = restartCount - /** - * Increment restart count. + /** Increment restart count. */ def inc(): Unit = restartCount += 1 - /** - * Reset restart count. + /** Reset restart count. */ def reset(): Unit = restartCount = 0 - /** - * Return true if we hit the maximum number of restarts. + /** Return true if we hit the maximum number of restarts. */ def canRestart: Boolean = restartCount < maxRestarts } - /** - * Creates a configuration object used to create a [[PathWatcher]]. + /** Creates a configuration object used to create a [[PathWatcher]]. * * @param config configuration * @param fs file system diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcherProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcherProtocol.scala index 0aac105b58..5d18674dee 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcherProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/PathWatcherProtocol.scala @@ -4,8 +4,7 @@ import akka.actor.ActorRef object PathWatcherProtocol { - /** - * Requests event manager to watch the path. + /** Requests event manager to watch the path. * * @param path path to watch */ @@ -17,13 +16,11 @@ object PathWatcherProtocol { WatchPath(path, Set(client)) } - /** - * Requests event manager to stop watching. + /** Requests event manager to stop watching. */ case class UnwatchPath(client: ActorRef) - /** - * Returns a file event result. + /** Returns a file event result. * * @param result file event */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/ReceivesTreeUpdatesHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/ReceivesTreeUpdatesHandler.scala index 0fd5a119d3..9bb82c4fbc 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/ReceivesTreeUpdatesHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/ReceivesTreeUpdatesHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.data.{ import org.enso.languageserver.effect._ import org.enso.languageserver.util.UnhandledLogging -/** - * Handles `receivesTreeUpdates` capabilities acquisition and release. +/** Handles `receivesTreeUpdates` capabilities acquisition and release. * * == Implementation == * @@ -64,8 +63,8 @@ final class ReceivesTreeUpdatesHandler( private def withStore(store: Store): Receive = { case AcquireCapability( - client, - CapabilityRegistration(ReceivesTreeUpdates(path)) + client, + CapabilityRegistration(ReceivesTreeUpdates(path)) ) => store.getWatcher(path) match { case Some(watcher) => @@ -83,8 +82,8 @@ final class ReceivesTreeUpdatesHandler( } case ReleaseCapability( - client, - CapabilityRegistration(ReceivesTreeUpdates(path)) + client, + CapabilityRegistration(ReceivesTreeUpdates(path)) ) => store.getWatcher(path) match { case Some(watcher) => @@ -100,15 +99,13 @@ final class ReceivesTreeUpdatesHandler( object ReceivesTreeUpdatesHandler { - /** - * Internal state of a [[ReceivesTreeUpdatesHandler]]. + /** Internal state of a [[ReceivesTreeUpdatesHandler]]. * * @param watchers mappings of a path watcher with a path */ case class Store(watchers: Map[Path, ActorRef]) { - /** - * Returns watcher associated with the provided path. + /** Returns watcher associated with the provided path. * * @param path watched path * @return optional watcher associated with this path @@ -116,8 +113,7 @@ object ReceivesTreeUpdatesHandler { def getWatcher(path: Path): Option[ActorRef] = watchers.get(path) - /** - * Add new watcher with the path to the store. + /** Add new watcher with the path to the store. * * @param watcher path watcher * @param path watched path @@ -126,8 +122,7 @@ object ReceivesTreeUpdatesHandler { def addWatcher(watcher: ActorRef, path: Path): Store = copy(watchers = watchers + (path -> watcher)) - /** - * Remove watcher from the store. + /** Remove watcher from the store. * * @param watcher path watcher * @return updated store @@ -142,8 +137,7 @@ object ReceivesTreeUpdatesHandler { new Store(Map()) } - /** - * Creates a configuration object used to create a + /** Creates a configuration object used to create a * [[ReceivesTreeUpdatesHandler]]. * * @param config configuration diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/WatcherAdapter.scala b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/WatcherAdapter.scala index 374e708185..1d470e3ea9 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/WatcherAdapter.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/filemanager/WatcherAdapter.scala @@ -5,8 +5,7 @@ import java.nio.file.Path import io.methvin.watcher._ import zio._ -/** - * Watches the root with subdirectories and executes callback on file event. +/** Watches the root with subdirectories and executes callback on file event. * * @param root directory to watch * @param eventCallback callback that fires on the file system events @@ -26,20 +25,17 @@ final class WatcherAdapter( .listener(this) .build() - /** - * Start watcher. + /** Start watcher. */ def start(): IO[Throwable, Unit] = IO(watcher.watch()) - /** - * Stop watcher. + /** Stop watcher. */ def stop(): IO[Throwable, Unit] = IO(watcher.close()) - /** - * A callback executed by `DirectoryWatcher` on file system event. + /** A callback executed by `DirectoryWatcher` on file system event. */ override def onEvent(event: DirectoryChangeEvent): Unit = { WatcherEvent @@ -54,15 +50,13 @@ final class WatcherAdapter( object WatcherAdapter { - /** - * Type of a file event. + /** Type of a file event. */ sealed trait EventType private object EventType { - /** - * Creates [[EventType]] from file system event type. + /** Creates [[EventType]] from file system event type. * * @param eventType file system event type * @return watcher event type @@ -76,23 +70,19 @@ object WatcherAdapter { } } - /** - * Event type indicating file creation. + /** Event type indicating file creation. */ case object EventTypeCreate extends EventType - /** - * Event type indicating file modification. + /** Event type indicating file modification. */ case object EventTypeModify extends EventType - /** - * Event type indicating file deletion. + /** Event type indicating file deletion. */ case object EventTypeDelete extends EventType - /** - * Object representing file system event. + /** Object representing file system event. * * @param path path to the file system object * @param eventType event type @@ -101,8 +91,7 @@ object WatcherAdapter { object WatcherEvent { - /** - * Conversion form file system event to [[WatcherEvent]] + /** Conversion form file system event to [[WatcherEvent]] * * @param event file system event * @return watcher event @@ -113,8 +102,7 @@ object WatcherAdapter { .map(WatcherEvent(event.path(), _)) } - /** - * Object representing en error. + /** Object representing en error. * * @param exception an error */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketControlProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketControlProtocol.scala index 6642e8ba68..78c28c7b2b 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketControlProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketControlProtocol.scala @@ -2,44 +2,37 @@ package org.enso.languageserver.http.server import akka.actor.ActorRef -/** - * A web socket control protocol used to manage connections created by +/** A web socket control protocol used to manage connections created by * a [[BinaryWebSocketServer]]. */ object BinaryWebSocketControlProtocol { - /** - * Base trait for web socket events. + /** Base trait for web socket events. */ sealed trait WsEvent - /** - * Base trait for web socket commands. + /** Base trait for web socket commands. */ sealed trait WsCommand - /** - * Signals that a connection has been closed. + /** Signals that a connection has been closed. */ case object ConnectionClosed extends WsEvent - /** - * Signals connection failure. + /** Signals connection failure. * * @param throwable a throwable */ case class ConnectionFailed(throwable: Throwable) extends WsEvent - /** - * Signals that a connection has been established. + /** Signals that a connection has been established. * * @param outboundChannel an outbound sender */ case class OutboundStreamEstablished(outboundChannel: ActorRef) extends WsEvent - /** - * Command that closes a connection. + /** Command that closes a connection. */ case object CloseConnection extends WsCommand diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketServer.scala b/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketServer.scala index da589ad8cb..d0a0d95eea 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketServer.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/http/server/BinaryWebSocketServer.scala @@ -28,8 +28,7 @@ import org.enso.languageserver.util.binary.{ import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future} -/** - * A web socket server using a binary protocol. +/** A web socket server using a binary protocol. * * @param decoder a decoder for inbound packets * @param encoder an encoder for outbound packets @@ -68,8 +67,7 @@ class BinaryWebSocketServer[A, B]( } } - /** - * Binds this server instance to a given port and interface, allowing + /** Binds this server instance to a given port and interface, allowing * future connections. * * @param interface the interface to bind to. @@ -150,8 +148,7 @@ class BinaryWebSocketServer[A, B]( object BinaryWebSocketServer { - /** - * A configuration object for properties of the [[BinaryWebSocketServer]]. + /** A configuration object for properties of the [[BinaryWebSocketServer]]. * * @param outgoingBufferSize the number of messages buffered internally * if the downstream connection is lagging behind. @@ -167,8 +164,7 @@ object BinaryWebSocketServer { case object Config { - /** - * Creates a default instance of [[Config]]. + /** Creates a default instance of [[Config]]. * * @return a default config. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/http/server/ConnectionControllerFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/http/server/ConnectionControllerFactory.scala index ba7fedd387..89bc1d3beb 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/http/server/ConnectionControllerFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/http/server/ConnectionControllerFactory.scala @@ -3,13 +3,11 @@ package org.enso.languageserver.http.server import akka.actor.ActorRef import akka.http.scaladsl.model.RemoteAddress -/** - * A factory of connection controllers. +/** A factory of connection controllers. */ trait ConnectionControllerFactory { - /** - * Creates a connection controller that acts as front controller. + /** Creates a connection controller that acts as front controller. * * @param clientIp a client ip that the connection controller is created for * @return actor ref of created connection controller diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputApi.scala index 078b03b255..2e837e0172 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputApi.scala @@ -1,8 +1,7 @@ package org.enso.languageserver.io import org.enso.jsonrpc.{HasParams, HasResult, Method, Unused} -/** - * The input/output JSON RPC API provided by the language server. +/** The input/output JSON RPC API provided by the language server. * * @see [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputProtocol.scala index dfa9c49dc5..25ce8946f0 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/io/InputOutputProtocol.scala @@ -4,23 +4,20 @@ import org.enso.languageserver.data.ClientId object InputOutputProtocol { - /** - * A command to the output controller responsible for redirecting an output. + /** A command to the output controller responsible for redirecting an output. * * @param clientId the client that the redirection is performed for */ case class RedirectOutput(clientId: ClientId) - /** - * A command to the output controller responsible for suppressing a + /** A command to the output controller responsible for suppressing a * redirection of an output. * * @param clientId the client that the suppression is performed for */ case class SuppressOutput(clientId: ClientId) - /** - * A notification that signals that new output was appended to the stdout or + /** A notification that signals that new output was appended to the stdout or * stderr. * * @param output the new data @@ -28,8 +25,7 @@ object InputOutputProtocol { */ case class OutputAppended(output: String, outputKind: OutputKind) - /** - * A command that feeds the standard input. + /** A command that feeds the standard input. * * @param input the data that feeds stdin * @param isLineTerminated signals if the input is terminated with a line @@ -37,8 +33,7 @@ object InputOutputProtocol { */ case class FeedStandardInput(input: String, isLineTerminated: Boolean) - /** - * Signals that a user program is blocked by `IO.readln` operation. + /** Signals that a user program is blocked by `IO.readln` operation. */ case object WaitingForStandardInput diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/io/InputRedirectionController.scala b/engine/language-server/src/main/scala/org/enso/languageserver/io/InputRedirectionController.scala index 62b0fbd6b4..02bfdd0482 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/io/InputRedirectionController.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/io/InputRedirectionController.scala @@ -23,8 +23,7 @@ import org.enso.languageserver.io.ObservablePipedInputStream.{ import org.enso.languageserver.session.SessionRouter.DeliverToJsonController import org.enso.languageserver.util.UnhandledLogging -/** - * A stdin redirection controller responsible for feeding stdin and notifying +/** A stdin redirection controller responsible for feeding stdin and notifying * execution context owners that executed program is blocked on `IO.readln`. * * @param stdIn a stream from which programs read its input data @@ -70,16 +69,15 @@ class InputRedirectionController( case ReadBlocked => log.debug("Blocked read detected") - liveContexts foreach { - case ContextData(_, owner) => - sessionRouter ! DeliverToJsonController( - owner, - WaitingForStandardInput - ) + liveContexts foreach { case ContextData(_, owner) => + sessionRouter ! DeliverToJsonController( + owner, + WaitingForStandardInput + ) } } - /** @inheritdoc **/ + /** @inheritdoc */ override def update(event: InputStreamEvent): Unit = { self ! event } override def preRestart(reason: Throwable, message: Option[Any]): Unit = { @@ -97,8 +95,7 @@ object InputRedirectionController { private case class ContextData(contextId: UUID, owner: ClientId) - /** - * Creates a configuration object used to create a + /** Creates a configuration object used to create a * [[InputRedirectionController]]. * * @param stdIn a stream from which programs read its input data diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservableOutputStream.scala b/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservableOutputStream.scala index 03ff432086..a292ca6ee4 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservableOutputStream.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservableOutputStream.scala @@ -4,8 +4,7 @@ import java.io.OutputStream import org.enso.languageserver.io.ObservableOutputStream.OutputObserver -/** - * An observable output stream of bytes. It accepts output bytes +/** An observable output stream of bytes. It accepts output bytes * and sends them to attached observers. Observers can dynamically * subscribe and unsubscribe for output bytes. It's thread-safe. */ @@ -15,19 +14,19 @@ class ObservableOutputStream extends OutputStream { private var observers = Set.empty[OutputObserver] - /** @inheritdoc **/ + /** @inheritdoc */ override def write(byte: Int): Unit = lock.synchronized { notify(Array[Byte](byte.toByte)) } - /** @inheritdoc **/ + /** @inheritdoc */ override def write(bytes: Array[Byte]): Unit = lock.synchronized { if (bytes.length > 0) { notify(bytes) } } - /** @inheritdoc **/ + /** @inheritdoc */ override def write(bytes: Array[Byte], off: Int, len: Int): Unit = lock.synchronized { if (len > 0) { @@ -37,8 +36,7 @@ class ObservableOutputStream extends OutputStream { } } - /** - * Attaches an output observer. + /** Attaches an output observer. * * @param observer the observer that subscribe for output bytes */ @@ -46,8 +44,7 @@ class ObservableOutputStream extends OutputStream { observers += observer } - /** - * Detaches an output observer. + /** Detaches an output observer. * * @param observer the observer that was subscribed for output bytes */ @@ -63,14 +60,12 @@ class ObservableOutputStream extends OutputStream { object ObservableOutputStream { - /** - * Defines an updating interface for objects that should be notified of new + /** Defines an updating interface for objects that should be notified of new * data accepted by an output stream. */ trait OutputObserver { - /** - * Method used to notify an observer about output changes. + /** Method used to notify an observer about output changes. * * @param output the new data */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservablePipedInputStream.scala b/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservablePipedInputStream.scala index 3a8da9b371..9946015834 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservablePipedInputStream.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/io/ObservablePipedInputStream.scala @@ -10,8 +10,7 @@ import org.enso.languageserver.io.ObservablePipedInputStream.{ ReadBlocked } -/** - * An observable piped input stream connected to a observable output stream. +/** An observable piped input stream connected to a observable output stream. * This stream provides data bytes that are written to the output stream. * It notifies observers when read operation waits for output stream. The * stream stores buffered bytes in a rope-like immutable data structure that @@ -31,7 +30,7 @@ class ObservablePipedInputStream(sink: ObservableOutputStream) private var buffer: ByteString = ByteString.empty - /** @inheritdoc **/ + /** @inheritdoc */ override def read(): Int = lock.synchronized { waitForBuffer() val byte = buffer.head @@ -40,10 +39,10 @@ class ObservablePipedInputStream(sink: ObservableOutputStream) byte.toInt } - /** @inheritdoc **/ + /** @inheritdoc */ override def read(array: Array[Byte]): Int = read(array, 0, array.length) - /** @inheritdoc **/ + /** @inheritdoc */ override def read(array: Array[Byte], off: Int, len: Int): Int = lock.synchronized { waitForBuffer() @@ -61,12 +60,12 @@ class ObservablePipedInputStream(sink: ObservableOutputStream) lock.wait() } - /** @inheritdoc **/ + /** @inheritdoc */ override def available(): Int = lock.synchronized { buffer.length } - /** @inheritdoc **/ + /** @inheritdoc */ override def update(output: Array[Byte]): Unit = lock.synchronized { buffer = ByteString.createBuilder .append(buffer) @@ -75,8 +74,7 @@ class ObservablePipedInputStream(sink: ObservableOutputStream) lock.notifyAll() } - /** - * Attaches an input observer. + /** Attaches an input observer. * * @param observer the observer that subscribe for input events */ @@ -84,8 +82,7 @@ class ObservablePipedInputStream(sink: ObservableOutputStream) observers += observer } - /** - * Detaches an input observer. + /** Detaches an input observer. * * @param observer the observer that was subscribed for input events */ @@ -102,25 +99,21 @@ class ObservablePipedInputStream(sink: ObservableOutputStream) object ObservablePipedInputStream { - /** - * Base trait of input stream events. + /** Base trait of input stream events. */ sealed trait InputStreamEvent - /** - * Signals that read operation is blocked and waits for data provided by + /** Signals that read operation is blocked and waits for data provided by * connected output stream. */ case object ReadBlocked extends InputStreamEvent - /** - * Defines an updating interface for objects that should be notified of + /** Defines an updating interface for objects that should be notified of * events fired by the input stream. */ trait InputObserver { - /** - * Method used to notify an observer about input events. + /** Method used to notify an observer about input events. * * @param event the input stream event */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputKind.scala b/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputKind.scala index 6a97d02480..696baeb7f5 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputKind.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputKind.scala @@ -1,19 +1,16 @@ package org.enso.languageserver.io -/** - * A base trait for output kind. +/** A base trait for output kind. */ sealed trait OutputKind object OutputKind { - /** - * Standard output is a stream to which a program writes its output data. + /** Standard output is a stream to which a program writes its output data. */ case object StandardOutput extends OutputKind - /** - * Standard error is output stream used by programs to write error messages + /** Standard error is output stream used by programs to write error messages * or status information. */ case object StandardError extends OutputKind diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputRedirectionController.scala b/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputRedirectionController.scala index e089c66966..d14c005262 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputRedirectionController.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/io/OutputRedirectionController.scala @@ -13,8 +13,7 @@ import org.enso.languageserver.io.OutputRedirectionController.CharOutputAppended import org.enso.languageserver.session.SessionRouter.DeliverToJsonController import org.enso.languageserver.util.UnhandledLogging -/** - * A redirection controller that listen to stdout or stderr data changes and +/** A redirection controller that listen to stdout or stderr data changes and * dispatches new output to clients that has redirected stdout or err. * * @param outputStream stdout or stderr @@ -57,7 +56,7 @@ class OutputRedirectionController( context.become(running(subscribers - session.clientId)) } - /** @inheritdoc **/ + /** @inheritdoc */ override def update(output: Array[Byte]): Unit = self ! CharOutputAppended(new String(output)) @@ -76,8 +75,7 @@ object OutputRedirectionController { private case class CharOutputAppended(output: String) - /** - * Creates a configuration object used to create a + /** Creates a configuration object used to create a * [[OutputRedirectionController]]. * * @param outputStream stdout or stderr diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringApi.scala index 11d80c167f..aaad6eb968 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringApi.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.monitoring import org.enso.jsonrpc.{HasParams, HasResult, Method, Unused} -/** - * The monitoring JSON RPC API provided by the language server. +/** The monitoring JSON RPC API provided by the language server. * See [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] * for message specifications. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringProtocol.scala index b3c7632fa0..4f2db86a73 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/monitoring/MonitoringProtocol.scala @@ -2,13 +2,11 @@ package org.enso.languageserver.monitoring object MonitoringProtocol { - /** - * A ping command. + /** A ping command. */ case object Ping - /** - * A pong reply. + /** A pong reply. */ case object Pong diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionController.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionController.scala index cf1422074e..2eb4b2d85a 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionController.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionController.scala @@ -47,8 +47,7 @@ import org.enso.languageserver.util.binary.DecodingFailure.{ import scala.annotation.unused import scala.concurrent.duration._ -/** - * An actor handling data communications between a single client and the +/** An actor handling data communications between a single client and the * language server. It acts as a front controller responsible for handling * all incoming requests and dispatching commands. * diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionControllerFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionControllerFactory.scala index a051deddea..3da3e33ef2 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionControllerFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/BinaryConnectionControllerFactory.scala @@ -4,16 +4,15 @@ import akka.actor.{ActorRef, ActorSystem, Props} import akka.http.scaladsl.model.RemoteAddress import org.enso.languageserver.http.server.ConnectionControllerFactory -/** - * A factory for binary connection controllers. +/** A factory for binary connection controllers. * * @param system an actor system that hosts created connection controllers */ -class BinaryConnectionControllerFactory(fileManager: ActorRef)( - implicit system: ActorSystem +class BinaryConnectionControllerFactory(fileManager: ActorRef)(implicit + system: ActorSystem ) extends ConnectionControllerFactory { - /** @inheritdoc **/ + /** @inheritdoc */ override def createController(clientIp: RemoteAddress.IP): ActorRef = { system.actorOf(Props(new BinaryConnectionController(clientIp, fileManager))) } diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/InboundMessageDecoder.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/InboundMessageDecoder.scala index 89de138044..473a388352 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/InboundMessageDecoder.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/InboundMessageDecoder.scala @@ -10,12 +10,11 @@ import org.enso.languageserver.util.binary.DecodingFailure.{ } import org.enso.languageserver.util.binary.{BinaryDecoder, DecodingFailure} -/** - * A decoder for an [[InboundMessage]]. +/** A decoder for an [[InboundMessage]]. */ object InboundMessageDecoder extends BinaryDecoder[InboundMessage] { - /** @inheritdoc **/ + /** @inheritdoc */ override def decode( bytes: ByteBuffer ): Either[DecodingFailure, InboundMessage] = diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoUuidFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoUuidFactory.scala index 7348964486..bbd801626d 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoUuidFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/EnsoUuidFactory.scala @@ -7,8 +7,7 @@ import org.enso.languageserver.protocol.binary.EnsoUUID object EnsoUuidFactory { - /** - * Creates EnsoUUID inside a [[FlatBufferBuilder]]. + /** Creates EnsoUUID inside a [[FlatBufferBuilder]]. * * @param uuid a uuid to serialize * @param builder a class that helps build a FlatBuffer representation of @@ -24,8 +23,7 @@ object EnsoUuidFactory { ) } - /** - * Creates an [[EnsoUUID]] inside a [[FlatBufferBuilder]]. + /** Creates an [[EnsoUUID]] inside a [[FlatBufferBuilder]]. * * @param uuid a uuid to serialize * @param builder a class that helps build a FlatBuffer representation of diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/ErrorFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/ErrorFactory.scala index d0e68a0b18..9df5e22b62 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/ErrorFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/ErrorFactory.scala @@ -9,24 +9,21 @@ import org.enso.languageserver.protocol.binary.{EnsoUUID, Error} object ErrorFactory { - /** - * Creates a ReceivedCorruptedDataError inside a [[FlatBufferBuilder]]. + /** Creates a ReceivedCorruptedDataError inside a [[FlatBufferBuilder]]. * * @return an FlatBuffer representation of the created error */ def createReceivedCorruptedDataError(): ByteBuffer = createGenericError(1, "Received corrupted data") - /** - * Creates a ReceivedEmptyPayloadError inside a [[FlatBufferBuilder]]. + /** Creates a ReceivedEmptyPayloadError inside a [[FlatBufferBuilder]]. * * @return an FlatBuffer representation of the created error */ def createReceivedEmptyPayloadError(): ByteBuffer = createGenericError(2, "Received empty payload in the inbound message") - /** - * Creates a ServiceError inside a [[FlatBufferBuilder]]. + /** Creates a ServiceError inside a [[FlatBufferBuilder]]. * * @return an FlatBuffer representation of the created error */ @@ -35,8 +32,7 @@ object ErrorFactory { ): ByteBuffer = createGenericError(0, "Service error", maybeCorrelationId) - /** - * Creates a visualisation expression error as a binary packet. + /** Creates a visualisation expression error as a binary packet. * * @param msg an error message * @return an FlatBuffer representation of the created error @@ -47,8 +43,7 @@ object ErrorFactory { s"Evaluation of the visualisation failed [$msg]" ) - /** - * Creates a generic error inside a [[FlatBufferBuilder]]. + /** Creates a generic error inside a [[FlatBufferBuilder]]. * * @param code an error code * @param message an error textual message diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/FileContentsReplyFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/FileContentsReplyFactory.scala index dbcc31bd0b..71e9cfbc9c 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/FileContentsReplyFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/FileContentsReplyFactory.scala @@ -10,8 +10,7 @@ import org.enso.languageserver.protocol.binary.EnsoUUID object FileContentsReplyFactory { - /** - * Creates a [[FileContentsReply]] inside a [[FlatBufferBuilder]]. + /** Creates a [[FileContentsReply]] inside a [[FlatBufferBuilder]]. * * @param contents the binary contents of a file * @param correlationId correlation id used to correlate a response with a diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/OutboundMessageFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/OutboundMessageFactory.scala index 0415631109..e61f4d2b2c 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/OutboundMessageFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/OutboundMessageFactory.scala @@ -8,8 +8,7 @@ import org.enso.languageserver.protocol.binary.EnsoUUID object OutboundMessageFactory { - /** - * Creates an [[OutboundMessage]] inside a [[FlatBufferBuilder]]. + /** Creates an [[OutboundMessage]] inside a [[FlatBufferBuilder]]. * * @param messageId a unique id of the message sent from the server * @param maybeCorrelationId an optional correlation id used to correlate diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/SuccessReplyFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/SuccessReplyFactory.scala index 958a87d472..f5c014e0b7 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/SuccessReplyFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/SuccessReplyFactory.scala @@ -9,8 +9,7 @@ import org.enso.languageserver.protocol.binary.{EnsoUUID, Success} object SuccessReplyFactory { - /** - * Creates a [[Success]] inside a [[FlatBufferBuilder]]. + /** Creates a [[Success]] inside a [[FlatBufferBuilder]]. * * @param builder a class that helps build a FlatBuffer representation of * complex objects @@ -22,8 +21,7 @@ object SuccessReplyFactory { Success.endSuccess(builder) } - /** - * Creates a [[Success]] inside a [[FlatBufferBuilder]]. + /** Creates a [[Success]] inside a [[FlatBufferBuilder]]. * * @param correlationId correlation id used to correlate a response with a * request diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/VisualisationUpdateFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/VisualisationUpdateFactory.scala index 1bfc55e1a5..1a145a1ca9 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/VisualisationUpdateFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/binary/factory/VisualisationUpdateFactory.scala @@ -12,8 +12,7 @@ import org.enso.languageserver.runtime.ContextRegistryProtocol.{ object VisualisationUpdateFactory { - /** - * Creates a [[VisualisationUpdate]] inside a [[FlatBufferBuilder]]. + /** Creates a [[VisualisationUpdate]] inside a [[FlatBufferBuilder]]. * * @param update a visualisation update * @param builder a class that helps build a FlatBuffer representation of @@ -21,8 +20,8 @@ object VisualisationUpdateFactory { * @return an offset pointing to the FlatBuffer representation of the * created object */ - def create(update: VisualisationUpdate)( - implicit builder: FlatBufferBuilder + def create(update: VisualisationUpdate)(implicit + builder: FlatBufferBuilder ): Int = { val ctx = createVisualisationCtx(update.visualisationContext) val data = @@ -34,8 +33,7 @@ object VisualisationUpdateFactory { ) } - /** - * Creates a [[VisualisationContext]] inside a [[FlatBufferBuilder]]. + /** Creates a [[VisualisationContext]] inside a [[FlatBufferBuilder]]. * * @param ctx a VisualisationContext * @param builder a class that helps build a FlatBuffer representation of @@ -43,8 +41,8 @@ object VisualisationUpdateFactory { * @return an offset pointing to the FlatBuffer representation of the * created object */ - def createVisualisationCtx(ctx: VisualisationContext)( - implicit builder: FlatBufferBuilder + def createVisualisationCtx(ctx: VisualisationContext)(implicit + builder: FlatBufferBuilder ): Int = { BinaryVisualisationContext.startVisualisationContext(builder) BinaryVisualisationContext.addContextId( diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/ErrorApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/ErrorApi.scala index de2f7f3f9f..16e72fa6bc 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/ErrorApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/ErrorApi.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.protocol.json import org.enso.jsonrpc.Error -/** - * Generic errors provided by the language server. +/** Generic errors provided by the language server. * * @see [[https://github.com/enso-org/enso/blob/main/docs/language-server/protocol-language-server.md#errors---language-server]] */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionController.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionController.scala index df24524382..3c18945544 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionController.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionController.scala @@ -61,8 +61,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration._ -/** - * An actor handling communications between a single client and the language +/** An actor handling communications between a single client and the language * server. * * @param connectionId the internal connection id. @@ -309,8 +308,7 @@ class JsonConnectionController( object JsonConnectionController { - /** - * Creates a configuration object used to create a [[JsonConnectionController]]. + /** Creates a configuration object used to create a [[JsonConnectionController]]. * * @param connectionId the internal connection id. * @param bufferRegistry a router that dispatches text editing requests diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionControllerFactory.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionControllerFactory.scala index 3a96a7c944..766750df91 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionControllerFactory.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonConnectionControllerFactory.scala @@ -5,8 +5,7 @@ import java.util.UUID import akka.actor.{ActorRef, ActorSystem} import org.enso.jsonrpc.ClientControllerFactory -/** - * Language server client controller factory. +/** Language server client controller factory. * * @param bufferRegistry the buffer registry actor ref * @param capabilityRouter the capability router actor ref @@ -25,8 +24,7 @@ class JsonConnectionControllerFactory( )(implicit system: ActorSystem) extends ClientControllerFactory { - /** - * Creates a client controller actor. + /** Creates a client controller actor. * * @param clientId the internal client id. * @return diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonRpc.scala b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonRpc.scala index b77f4b3c6b..05513dba3b 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonRpc.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/protocol/json/JsonRpc.scala @@ -20,8 +20,7 @@ import org.enso.languageserver.text.TextApi._ object JsonRpc { - /** - * A description of supported JSON RPC messages. + /** A description of supported JSON RPC messages. */ val protocol: Protocol = Protocol.empty .registerRequest(Ping) diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/ProjectNameChangedEvent.scala b/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/ProjectNameChangedEvent.scala index 6484a662fb..b81ba021b0 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/ProjectNameChangedEvent.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/ProjectNameChangedEvent.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.refactoring import org.enso.languageserver.event.Event -/** - * An event notifying that project name has changed. +/** An event notifying that project name has changed. * * @param oldName the old name of the project * @param newName the new project name diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/RefactoringApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/RefactoringApi.scala index 2d07d54fe8..9feb72526e 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/RefactoringApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/refactoring/RefactoringApi.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.refactoring import org.enso.jsonrpc.{HasParams, HasResult, Method, Unused} -/** - * The refactoring JSON RPC API provided by the language server. +/** The refactoring JSON RPC API provided by the language server. * See [[https://github.com/luna/enso/blob/main/docs/language-server/README.md]] * for message specifications. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/RequestTimeout.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/RequestTimeout.scala index 39cd9f4e7c..3b7a700ed7 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/RequestTimeout.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/RequestTimeout.scala @@ -1,6 +1,5 @@ package org.enso.languageserver.requesthandler -/** - * Signals that operation has timed out. +/** Signals that operation has timed out. */ case object RequestTimeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/AcquireCapabilityHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/AcquireCapabilityHandler.scala index 2f3387b0e3..507451ae7f 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/AcquireCapabilityHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/AcquireCapabilityHandler.scala @@ -18,8 +18,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `capability/acquire` commands. +/** A request handler for `capability/acquire` commands. * * @param capabilityRouter a router that dispatches capability requests * @param timeout a request timeout @@ -80,8 +79,7 @@ class AcquireCapabilityHandler( object AcquireCapabilityHandler { - /** - * Creates a configuration object used to create a [[AcquireCapabilityHandler]] + /** Creates a configuration object used to create a [[AcquireCapabilityHandler]] * * @param capabilityRouter a router that dispatches capability requests * @param requestTimeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/ReleaseCapabilityHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/ReleaseCapabilityHandler.scala index e73658aa3e..3f372b0a9d 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/ReleaseCapabilityHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/capability/ReleaseCapabilityHandler.scala @@ -20,8 +20,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `capability/release` commands. +/** A request handler for `capability/release` commands. * * @param capabilityRouter a router that dispatches capability requests * @param timeout a request timeout @@ -75,8 +74,7 @@ class ReleaseCapabilityHandler( object ReleaseCapabilityHandler { - /** - * Creates a configuration object used to create a [[ReleaseCapabilityHandler]] + /** Creates a configuration object used to create a [[ReleaseCapabilityHandler]] * * @param capabilityRouter a router that dispatches capability requests * @param requestTimeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/CreateHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/CreateHandler.scala index 346626490f..60892a760a 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/CreateHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/CreateHandler.scala @@ -19,8 +19,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/create` commands. +/** A request handler for `executionContext/create` commands. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. @@ -75,8 +74,7 @@ class CreateHandler( object CreateHandler { - /** - * Creates configuration object used to create a [[CreateHandler]]. + /** Creates configuration object used to create a [[CreateHandler]]. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/DestroyHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/DestroyHandler.scala index 3bb260904a..a7b6315b37 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/DestroyHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/DestroyHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/destroy` commands. +/** A request handler for `executionContext/destroy` commands. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. @@ -36,9 +35,9 @@ class DestroyHandler( private def requestStage: Receive = { case Request( - ExecutionContextDestroy, - id, - params: ExecutionContextDestroy.Params + ExecutionContextDestroy, + id, + params: ExecutionContextDestroy.Params ) => contextRegistry ! DestroyContextRequest(session, params.contextId) val cancellable = @@ -70,8 +69,7 @@ class DestroyHandler( object DestroyHandler { - /** - * Creates configuration object used to create a [[DestroyHandler]]. + /** Creates configuration object used to create a [[DestroyHandler]]. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PopHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PopHandler.scala index 2a716e4ccf..1c8889a4c9 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PopHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PopHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/push` commands. +/** A request handler for `executionContext/push` commands. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. @@ -66,8 +65,7 @@ class PopHandler( object PopHandler { - /** - * Creates configuration object used to create a [[PopHandler]]. + /** Creates configuration object used to create a [[PopHandler]]. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PushHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PushHandler.scala index 68b168b585..2603467856 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PushHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/PushHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/push` commands. +/** A request handler for `executionContext/push` commands. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. @@ -36,9 +35,9 @@ class PushHandler( private def requestStage: Receive = { case Request( - ExecutionContextPush, - id, - params: ExecutionContextPush.Params + ExecutionContextPush, + id, + params: ExecutionContextPush.Params ) => contextRegistry ! PushContextRequest( session, @@ -74,8 +73,7 @@ class PushHandler( object PushHandler { - /** - * Creates configuration object used to create a [[PushHandler]]. + /** Creates configuration object used to create a [[PushHandler]]. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/RecomputeHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/RecomputeHandler.scala index 0956a375cf..c26e74abeb 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/RecomputeHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/executioncontext/RecomputeHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/recompute` commands. +/** A request handler for `executionContext/recompute` commands. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. @@ -36,9 +35,9 @@ class RecomputeHandler( private def requestStage: Receive = { case Request( - ExecutionContextRecompute, - id, - params: ExecutionContextRecompute.Params + ExecutionContextRecompute, + id, + params: ExecutionContextRecompute.Params ) => contextRegistry ! RecomputeContextRequest( session, @@ -74,8 +73,7 @@ class RecomputeHandler( object RecomputeHandler { - /** - * Creates configuration object used to create a [[RecomputeHandler]]. + /** Creates configuration object used to create a [[RecomputeHandler]]. * * @param timeout request timeout * @param contextRegistry a reference to the context registry. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/InfoFileHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/InfoFileHandler.scala index 38c5398f7d..7cb16adc33 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/InfoFileHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/InfoFileHandler.scala @@ -13,8 +13,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `file/info` command. +/** A request handler for `file/info` command. * * @param requestTimeout a request timeout * @param fileManager a file system manager actor @@ -69,8 +68,7 @@ class InfoFileHandler(requestTimeout: FiniteDuration, fileManager: ActorRef) object InfoFileHandler { - /** - * Creates a configuration object used to create a [[InfoFileHandler]] + /** Creates a configuration object used to create a [[InfoFileHandler]] * * @param requestTimeout a request timeout * @param fileManager a file system manager actor diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBinaryFileHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBinaryFileHandler.scala index bb00b8defa..57ff14e62c 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBinaryFileHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/ReadBinaryFileHandler.scala @@ -20,8 +20,7 @@ import org.enso.languageserver.util.file.PathUtils import scala.concurrent.duration.FiniteDuration -/** - * A request handler for [[ReadFileCommand]]. +/** A request handler for [[ReadFileCommand]]. * * @param requestTimeout a request timeout * @param fileManager a file system manager actor @@ -39,15 +38,14 @@ class ReadBinaryFileHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: InboundMessage => - val payload = - msg.payload(new ReadFileCommand).asInstanceOf[ReadFileCommand] - val path = PathUtils.convertBinaryPath(payload.path()) - fileManager ! FileManagerProtocol.ReadBinaryFile(path) - val cancellable = context.system.scheduler - .scheduleOnce(requestTimeout, self, RequestTimeout) - context.become(responseStage(msg.messageId(), cancellable)) + private def requestStage: Receive = { case msg: InboundMessage => + val payload = + msg.payload(new ReadFileCommand).asInstanceOf[ReadFileCommand] + val path = PathUtils.convertBinaryPath(payload.path()) + fileManager ! FileManagerProtocol.ReadBinaryFile(path) + val cancellable = context.system.scheduler + .scheduleOnce(requestTimeout, self, RequestTimeout) + context.become(responseStage(msg.messageId(), cancellable)) } private def responseStage( @@ -90,8 +88,7 @@ class ReadBinaryFileHandler( object ReadBinaryFileHandler { - /** - * Creates a configuration object used to create a [[ReadBinaryFileHandler]] + /** Creates a configuration object used to create a [[ReadBinaryFileHandler]] * * @param timeout a request timeout * @param fileManager a file system manager actor diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/WriteBinaryFileHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/WriteBinaryFileHandler.scala index c292e2fe8e..e9a6d2e825 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/WriteBinaryFileHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/file/WriteBinaryFileHandler.scala @@ -20,8 +20,7 @@ import org.enso.languageserver.util.file.PathUtils import scala.concurrent.duration.FiniteDuration -/** - * A request handler for [[WriteFileCommand]]. +/** A request handler for [[WriteFileCommand]]. * * @param requestTimeout a request timeout * @param fileManager a file system manager actor @@ -39,18 +38,17 @@ class WriteBinaryFileHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: InboundMessage => - val payload = - msg.payload(new WriteFileCommand).asInstanceOf[WriteFileCommand] - val path = PathUtils.convertBinaryPath(payload.path()) - val bytes = payload.contentsAsByteBuffer() - val contents = Array.fill[Byte](bytes.remaining())(0) - bytes.get(contents) - fileManager ! FileManagerProtocol.WriteBinaryFile(path, contents) - val cancellable = context.system.scheduler - .scheduleOnce(requestTimeout, self, RequestTimeout) - context.become(responseStage(msg.messageId(), cancellable)) + private def requestStage: Receive = { case msg: InboundMessage => + val payload = + msg.payload(new WriteFileCommand).asInstanceOf[WriteFileCommand] + val path = PathUtils.convertBinaryPath(payload.path()) + val bytes = payload.contentsAsByteBuffer() + val contents = Array.fill[Byte](bytes.remaining())(0) + bytes.get(contents) + fileManager ! FileManagerProtocol.WriteBinaryFile(path, contents) + val cancellable = context.system.scheduler + .scheduleOnce(requestTimeout, self, RequestTimeout) + context.become(responseStage(msg.messageId(), cancellable)) } private def responseStage( @@ -92,8 +90,7 @@ class WriteBinaryFileHandler( object WriteBinaryFileHandler { - /** - * Creates a configuration object used to create a [[WriteBinaryFileHandler]] + /** Creates a configuration object used to create a [[WriteBinaryFileHandler]] * * @param timeout a request timeout * @param fileManager a file system manager actor diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/FeedStandardInputHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/FeedStandardInputHandler.scala index 25fb7ad1dc..babfa099f7 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/FeedStandardInputHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/FeedStandardInputHandler.scala @@ -6,8 +6,7 @@ import org.enso.languageserver.io.InputOutputApi.FeedStandardInput import org.enso.languageserver.io.InputOutputProtocol import org.enso.languageserver.util.UnhandledLogging -/** - * A request handler for `io/feedStandardInput` commands. +/** A request handler for `io/feedStandardInput` commands. * * @param stdInController the stdin redirection controller */ @@ -30,8 +29,7 @@ class FeedStandardInputHandler(stdInController: ActorRef) object FeedStandardInputHandler { - /** - * Creates a configuration object used to create a + /** Creates a configuration object used to create a * [[FeedStandardInputHandler]]. * * @param stdInController the stdin redirection controller diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdErrHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdErrHandler.scala index 9b764f083d..831bd97890 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdErrHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdErrHandler.scala @@ -7,8 +7,7 @@ import org.enso.languageserver.io.InputOutputApi.RedirectStandardError import org.enso.languageserver.io.InputOutputProtocol import org.enso.languageserver.util.UnhandledLogging -/** - * A request handler for `io/redirectStandardError` commands. +/** A request handler for `io/redirectStandardError` commands. * * @param stdErrController an output redirection controller * @param clientId a client requesting redirection @@ -29,8 +28,7 @@ class RedirectStdErrHandler(stdErrController: ActorRef, clientId: ClientId) object RedirectStdErrHandler { - /** - * Creates a configuration object used to create a [[RedirectStdErrHandler]]. + /** Creates a configuration object used to create a [[RedirectStdErrHandler]]. * * @param stdErrController an output redirection controller * @param clientId a client requesting redirection diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdOutHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdOutHandler.scala index 32fdc400ae..b09d13e058 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdOutHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/RedirectStdOutHandler.scala @@ -7,8 +7,7 @@ import org.enso.languageserver.io.InputOutputApi.RedirectStandardOutput import org.enso.languageserver.io.InputOutputProtocol import org.enso.languageserver.util.UnhandledLogging -/** - * A request handler for `io/redirectStandardOutput` commands. +/** A request handler for `io/redirectStandardOutput` commands. * * @param stdOutController an output redirection controller * @param clientId a client requesting redirection @@ -29,8 +28,7 @@ class RedirectStdOutHandler(stdOutController: ActorRef, clientId: ClientId) object RedirectStdOutHandler { - /** - * Creates a configuration object used to create a [[RedirectStdOutHandler]]. + /** Creates a configuration object used to create a [[RedirectStdOutHandler]]. * * @param stdOutController an output redirection controller * @param clientId a client requesting redirection diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdErrHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdErrHandler.scala index c1df787ee5..a2f414180a 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdErrHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdErrHandler.scala @@ -7,8 +7,7 @@ import org.enso.languageserver.io.InputOutputApi.SuppressStandardError import org.enso.languageserver.io.InputOutputProtocol import org.enso.languageserver.util.UnhandledLogging -/** - * A request handler for `io/suppressStandardError` commands. +/** A request handler for `io/suppressStandardError` commands. * * @param stdErrController an output redirection controller * @param clientId a client requesting redirection @@ -29,8 +28,7 @@ class SuppressStdErrHandler(stdErrController: ActorRef, clientId: ClientId) object SuppressStdErrHandler { - /** - *Creates a configuration object used to create a [[SuppressStdErrHandler]]. + /** Creates a configuration object used to create a [[SuppressStdErrHandler]]. * * @param stdErrController an output redirection controller * @param clientId a client requesting redirection diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdOutHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdOutHandler.scala index b214cb192b..59ab61a4c4 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdOutHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/io/SuppressStdOutHandler.scala @@ -7,8 +7,7 @@ import org.enso.languageserver.io.InputOutputApi.SuppressStandardOutput import org.enso.languageserver.io.InputOutputProtocol import org.enso.languageserver.util.UnhandledLogging -/** - * A request handler for `io/suppressStandardOutput` commands. +/** A request handler for `io/suppressStandardOutput` commands. * * @param stdOutController an output redirection controller * @param clientId a client requesting redirection @@ -28,8 +27,7 @@ class SuppressStdOutHandler(stdOutController: ActorRef, clientId: ClientId) object SuppressStdOutHandler { - /** - * Creates a configuration object used to create a [[SuppressStdOutHandler]]. + /** Creates a configuration object used to create a [[SuppressStdOutHandler]]. * * @param stdOutController an output redirection controller * @param clientId a client requesting redirection diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/monitoring/PingHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/monitoring/PingHandler.scala index 351d7ffeb0..ae13cf78f6 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/monitoring/PingHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/monitoring/PingHandler.scala @@ -8,8 +8,7 @@ import org.enso.languageserver.requesthandler.RequestTimeout import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `heartbeat/ping` commands. +/** A request handler for `heartbeat/ping` commands. * * @param subsystems a list of monitored subsystems * @param timeout a request timeout @@ -63,8 +62,7 @@ class PingHandler( object PingHandler { - /** - * Creates a configuration object used to create a [[PingHandler]] + /** Creates a configuration object used to create a [[PingHandler]] * * @param subsystems a list of monitored subsystems * @param timeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/refactoring/RenameProjectHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/refactoring/RenameProjectHandler.scala index 852e61fcfd..6d5e9b65af 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/refactoring/RenameProjectHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/refactoring/RenameProjectHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `refactoring/renameProject` commands. +/** A request handler for `refactoring/renameProject` commands. * * @param timeout a request timeout * @param runtimeConnector a reference to the runtime connector @@ -66,8 +65,7 @@ class RenameProjectHandler(timeout: FiniteDuration, runtimeConnector: ActorRef) object RenameProjectHandler { - /** - * Creates configuration object used to create a [[RenameProjectHandler]]. + /** Creates configuration object used to create a [[RenameProjectHandler]]. * * @param timeout request timeout * @param runtimeConnector reference to the runtime connector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/CompletionHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/CompletionHandler.scala index 6eaad38ec3..fe1088b570 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/CompletionHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/CompletionHandler.scala @@ -13,8 +13,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `search/completion` command. +/** A request handler for `search/completion` command. * * @param timeout request timeout * @param suggestionsHandler a reference to the suggestions handler @@ -80,8 +79,7 @@ class CompletionHandler( object CompletionHandler { - /** - * Creates configuration object used to create a [[CompletionHandler]]. + /** Creates configuration object used to create a [[CompletionHandler]]. * * @param timeout request timeout * @param suggestionsHandler a reference to the suggestions handler diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseHandler.scala index d78c21f6b0..cfe238ba64 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseHandler.scala @@ -13,8 +13,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `search/getSuggestionsDatabase` command. +/** A request handler for `search/getSuggestionsDatabase` command. * * @param timeout request timeout * @param suggestionsHandler a reference to the suggestions handler @@ -70,8 +69,7 @@ class GetSuggestionsDatabaseHandler( object GetSuggestionsDatabaseHandler { - /** - * Creates configuration object used to create a + /** Creates configuration object used to create a * [[GetSuggestionsDatabaseHandler]]. * * @param timeout request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseVersionHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseVersionHandler.scala index 4605407999..985f6f71a1 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseVersionHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/GetSuggestionsDatabaseVersionHandler.scala @@ -13,8 +13,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `search/getSuggestionsDatabaseVersion` command. +/** A request handler for `search/getSuggestionsDatabaseVersion` command. * * @param timeout request timeout * @param suggestionsHandler a reference to the suggestions handler @@ -70,8 +69,7 @@ class GetSuggestionsDatabaseVersionHandler( object GetSuggestionsDatabaseVersionHandler { - /** - * Creates configuration object used to create a + /** Creates configuration object used to create a * [[GetSuggestionsDatabaseVersionHandler]]. * * @param timeout request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/InvalidateSuggestionsDatabaseHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/InvalidateSuggestionsDatabaseHandler.scala index a8bcabc17d..027cdd5bbe 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/InvalidateSuggestionsDatabaseHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/search/InvalidateSuggestionsDatabaseHandler.scala @@ -17,8 +17,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `search/invalidateSuggestionsDatabase` command. +/** A request handler for `search/invalidateSuggestionsDatabase` command. * * @param timeout request timeout * @param suggestionsHandler a reference to the suggestions handler @@ -75,8 +74,7 @@ class InvalidateSuggestionsDatabaseHandler( object InvalidateSuggestionsDatabaseHandler { - /** - * Creates configuration object used to create a + /** Creates configuration object used to create a * [[InvalidateSuggestionsDatabaseHandler]]. * * @param timeout request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/session/InitProtocolConnectionHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/session/InitProtocolConnectionHandler.scala index bb74f7b20e..b15c5fd81a 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/session/InitProtocolConnectionHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/session/InitProtocolConnectionHandler.scala @@ -11,8 +11,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `session/initProtocolConnection` commands. +/** A request handler for `session/initProtocolConnection` commands. * * @param fileManager a file manager reference * @param timeout a request timeout @@ -60,8 +59,7 @@ class InitProtocolConnectionHandler( object InitProtocolConnectionHandler { - /** - * Creates a configuration object used to create a [[InitProtocolConnectionHandler]] + /** Creates a configuration object used to create a [[InitProtocolConnectionHandler]] * * @param fileManager a file manager reference * @param timeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/ApplyEditHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/ApplyEditHandler.scala index c6fd7ca22f..c583519e2c 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/ApplyEditHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/ApplyEditHandler.scala @@ -12,8 +12,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `text/applyEdit` commands. +/** A request handler for `text/applyEdit` commands. * * @param bufferRegistry a router that dispatches text editing requests * @param timeout a request timeout @@ -81,8 +80,7 @@ class ApplyEditHandler( object ApplyEditHandler { - /** - * Creates a configuration object used to create a [[ApplyEditHandler]] + /** Creates a configuration object used to create a [[ApplyEditHandler]] * * @param bufferRegistry a router that dispatches text editing requests * @param requestTimeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/CloseFileHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/CloseFileHandler.scala index 325bff1498..71fd469b70 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/CloseFileHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/CloseFileHandler.scala @@ -12,8 +12,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `text/closeFile` commands. +/** A request handler for `text/closeFile` commands. * * @param bufferRegistry a router that dispatches text editing requests * @param timeout a request timeout @@ -63,8 +62,7 @@ class CloseFileHandler( object CloseFileHandler { - /** - * Creates a configuration object used to create a [[CloseFileHandler]] + /** Creates a configuration object used to create a [[CloseFileHandler]] * * @param bufferRegistry a router that dispatches text editing requests * @param requestTimeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/OpenFileHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/OpenFileHandler.scala index c67f6b523e..310f1a7479 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/OpenFileHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/OpenFileHandler.scala @@ -16,8 +16,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `text/openFile` commands. +/** A request handler for `text/openFile` commands. * * @param bufferRegistry a router that dispatches text editing requests * @param timeout a request timeout @@ -75,8 +74,7 @@ class OpenFileHandler( object OpenFileHandler { - /** - * Creates a configuration object used to create a [[OpenFileHandler]] + /** Creates a configuration object used to create a [[OpenFileHandler]] * * @param bufferRegistry a router that dispatches text editing requests * @param requestTimeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/SaveFileHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/SaveFileHandler.scala index bfc3879a93..08e191b2cb 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/SaveFileHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/text/SaveFileHandler.scala @@ -18,8 +18,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `text/save` commands. +/** A request handler for `text/save` commands. * * @param bufferRegistry a router that dispatches text editing requests * @param timeout a request timeout @@ -94,8 +93,7 @@ class SaveFileHandler( object SaveFileHandler { - /** - * Creates a configuration object used to create a [[SaveFileHandler]]. + /** Creates a configuration object used to create a [[SaveFileHandler]]. * * @param bufferRegistry a router that dispatches text editing requests * @param requestTimeout a request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/AttachVisualisationHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/AttachVisualisationHandler.scala index f9de3b3aec..65dcd392ac 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/AttachVisualisationHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/AttachVisualisationHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/attachVisualisation` commands. +/** A request handler for `executionContext/attachVisualisation` commands. * * @param clientId an unique identifier of the client * @param timeout request timeout @@ -71,8 +70,7 @@ class AttachVisualisationHandler( object AttachVisualisationHandler { - /** - * Creates configuration object used to create a [[AttachVisualisationHandler]]. + /** Creates configuration object used to create a [[AttachVisualisationHandler]]. * * @param clientId an unique identifier of the client * @param timeout request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/DetachVisualisationHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/DetachVisualisationHandler.scala index 45f5ca4964..85a350e1da 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/DetachVisualisationHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/DetachVisualisationHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/detachVisualisation` commands. +/** A request handler for `executionContext/detachVisualisation` commands. * * @param clientId an unique identifier of the client * @param timeout request timeout @@ -71,8 +70,7 @@ class DetachVisualisationHandler( object DetachVisualisationHandler { - /** - * Creates configuration object used to create a [[DetachVisualisationHandler]]. + /** Creates configuration object used to create a [[DetachVisualisationHandler]]. * * @param clientId an unique identifier of the client * @param timeout request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/ModifyVisualisationHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/ModifyVisualisationHandler.scala index badc6c02c2..cf922cd77a 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/ModifyVisualisationHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/requesthandler/visualisation/ModifyVisualisationHandler.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `executionContext/modifyVisualisation` commands. +/** A request handler for `executionContext/modifyVisualisation` commands. * * @param clientId an unique identifier of the client * @param timeout request timeout @@ -70,8 +69,7 @@ class ModifyVisualisationHandler( object ModifyVisualisationHandler { - /** - * Creates configuration object used to create a [[ModifyVisualisationHandler]]. + /** Creates configuration object used to create a [[ModifyVisualisationHandler]]. * * @param clientId an unique identifier of the client * @param timeout request timeout diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextEventsListener.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextEventsListener.scala index 9ac271b2e4..a9c9fe9258 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextEventsListener.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextEventsListener.scala @@ -24,8 +24,7 @@ import org.enso.searcher.SuggestionsRepo import scala.concurrent.Future import scala.concurrent.duration._ -/** - * EventListener listens event stream for the notifications from the runtime +/** EventListener listens event stream for the notifications from the runtime * and send updates to the client. The listener is created per context, and * only handles the notifications with the given `contextId`. * @@ -122,9 +121,8 @@ final class ContextEventsListener( val methodPointerToSuggestion = methodPointers .zip(suggestionIds) - .collect { - case (ptr, Some(suggestionId)) => - ptr -> suggestionId + .collect { case (ptr, Some(suggestionId)) => + ptr -> suggestionId } .toMap val valueUpdates = expressionUpdates.map { update => @@ -155,8 +153,7 @@ final class ContextEventsListener( case RunExpressionUpdates if expressionUpdates.isEmpty => } - /** - * Convert the runtime failure message to the context registry protocol + /** Convert the runtime failure message to the context registry protocol * representation. * * @param error the error message @@ -170,8 +167,7 @@ final class ContextEventsListener( error.file.flatMap(config.findRelativePath) ) - /** - * Convert the runtime diagnostic message to the context registry protocol + /** Convert the runtime diagnostic message to the context registry protocol * representation. * * @param diagnostic the diagnostic message @@ -188,8 +184,7 @@ final class ContextEventsListener( diagnostic.stack.map(toStackTraceElement) ) - /** - * Convert the runtime diagnostic type to the context registry protocol + /** Convert the runtime diagnostic type to the context registry protocol * representation. * * @param kind the diagnostic type @@ -203,8 +198,7 @@ final class ContextEventsListener( case Api.DiagnosticType.Warning() => ExecutionDiagnosticKind.Warning } - /** - * Convert the runtime stack trace element to the context registry protocol + /** Convert the runtime stack trace element to the context registry protocol * representation. * * @param element the runtime stack trace element @@ -225,8 +219,7 @@ object ContextEventsListener { /** The action to process the expression updates. */ case object RunExpressionUpdates - /** - * Creates a configuration object used to create a [[ContextEventsListener]]. + /** Creates a configuration object used to create a [[ContextEventsListener]]. * * @param config the language server configuration * @param repo the suggestions repo diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistry.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistry.scala index ee68346f32..a5f6e103de 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistry.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistry.scala @@ -17,8 +17,7 @@ import org.enso.searcher.SuggestionsRepo import scala.concurrent.Future -/** - * Registry handles execution context requests and communicates with runtime +/** Registry handles execution context requests and communicates with runtime * connector. * * == Implementation == @@ -301,8 +300,7 @@ object ContextRegistry { Store(Map(), Map()) } - /** - * Creates a configuration object used to create a [[ContextRegistry]]. + /** Creates a configuration object used to create a [[ContextRegistry]]. * * @param repo the suggestions repo * @param config language server configuration diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistryProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistryProtocol.scala index 43871c31f0..6eb9e2f8e7 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistryProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ContextRegistryProtocol.scala @@ -11,27 +11,23 @@ import org.enso.text.editing.model object ContextRegistryProtocol { - /** - * Trait indicating failure response. + /** Trait indicating failure response. */ sealed trait Failure - /** - * A request to the context registry to create a new execution context. + /** A request to the context registry to create a new execution context. * * @param rpcSession reference to the client */ case class CreateContextRequest(rpcSession: JsonSession) - /** - * A response about creation of a new execution context. + /** A response about creation of a new execution context. * * @param contextId the newly created context's id */ case class CreateContextResponse(contextId: ContextId) - /** - * A request to the context registry to delete an execution context. + /** A request to the context registry to delete an execution context. * * @param rpcSession reference to the client */ @@ -40,15 +36,13 @@ object ContextRegistryProtocol { contextId: ContextId ) - /** - * A response about deletion of an execution context. + /** A response about deletion of an execution context. * * @param contextId the newly created context's id */ case class DestroyContextResponse(contextId: ContextId) - /** - * A request to the context registry to push an execution context + /** A request to the context registry to push an execution context * down the stack. * * @param rpcSession reference to the client @@ -61,15 +55,13 @@ object ContextRegistryProtocol { stackItem: StackItem ) - /** - * A response about pushing the new item to the stack. + /** A response about pushing the new item to the stack. * * @param contextId execution context identifier */ case class PushContextResponse(contextId: ContextId) - /** - * A request to the context registry to move an execution context + /** A request to the context registry to move an execution context * up the stack. * * @param rpcSession reference to the client @@ -77,15 +69,13 @@ object ContextRegistryProtocol { */ case class PopContextRequest(rpcSession: JsonSession, contextId: ContextId) - /** - * A response about popping the stack. + /** A response about popping the stack. * * @param contextId execution context identifier */ case class PopContextResponse(contextId: ContextId) - /** - * A request to the context registry to recompute an execution context. + /** A request to the context registry to recompute an execution context. * * @param rpcSession reference to the client * @param contextId execution context identifier @@ -97,15 +87,13 @@ object ContextRegistryProtocol { invalidatedExpressions: Option[InvalidatedExpressions] ) - /** - * A response about recomputing the context. + /** A response about recomputing the context. * * @param contextId execution context identifier */ case class RecomputeContextResponse(contextId: ContextId) - /** - * A notification that new information about some expressions is available. + /** A notification that new information about some expressions is available. * * @param contextId execution context identifier * @param updates a list of updated expressions @@ -115,34 +103,29 @@ object ContextRegistryProtocol { updates: Vector[ExpressionValueUpdate] ) - /** - * Signals that user doesn't have access to the requested context. + /** Signals that user doesn't have access to the requested context. */ case object AccessDenied extends Failure - /** - * Signals that context was not found. + /** Signals that context was not found. * * @param contextId execution context identifier */ case class ContextNotFound(contextId: ContextId) extends Failure - /** - * Signals about file system error. + /** Signals about file system error. * * @param error file system failure */ case class FileSystemError(error: FileSystemFailure) extends Failure - /** - * Signals that stack is empty. + /** Signals that stack is empty. * * @param contextId execution context identifier */ case class EmptyStackError(contextId: ContextId) extends Failure - /** - * Signals that stack item is invalid in this context. + /** Signals that stack item is invalid in this context. * * @param contextId execution context identifier */ @@ -160,8 +143,7 @@ object ContextRegistryProtocol { override val values = findValues } - /** - * The element in the stack trace. + /** The element in the stack trace. * * @param functionName the function containing the stack call * @param path the location of a file @@ -173,8 +155,7 @@ object ContextRegistryProtocol { location: Option[model.Range] ) - /** - * A diagnostic message produced as a compilation outcome. + /** A diagnostic message produced as a compilation outcome. * * @param kind the type of diagnostic message * @param message the error message @@ -190,16 +171,14 @@ object ContextRegistryProtocol { stack: Vector[ExecutionStackTraceElement] ) - /** - * A critical failure when attempting to execute a context. + /** A critical failure when attempting to execute a context. * * @param message the error message * @param path the location of a file producing the error */ case class ExecutionFailure(message: String, path: Option[Path]) - /** - * Signals about a critical failure in a context execution. + /** Signals about a critical failure in a context execution. * * @param contextId execution context identifier * @param failure the error description @@ -209,8 +188,7 @@ object ContextRegistryProtocol { failure: ExecutionFailure ) - /** - * Signals the status of a context execution. + /** Signals the status of a context execution. * * @param contextId execution context identifier * @param diagnostics the list of diagnostic messages @@ -220,8 +198,7 @@ object ContextRegistryProtocol { diagnostics: Seq[ExecutionDiagnostic] ) - /** - * Requests the language server to attach a visualisation to the expression + /** Requests the language server to attach a visualisation to the expression * specified by `expressionId`. * * @param clientId the requester id @@ -237,13 +214,11 @@ object ContextRegistryProtocol { visualisationConfig: VisualisationConfiguration ) - /** - * Signals that attaching a visualisation has succeeded. + /** Signals that attaching a visualisation has succeeded. */ case object VisualisationAttached - /** - * Requests the language server to detach a visualisation from the expression + /** Requests the language server to detach a visualisation from the expression * specified by `expressionId`. * * @param clientId the requester id @@ -258,13 +233,11 @@ object ContextRegistryProtocol { expressionId: UUID ) - /** - * Signals that detaching a visualisation has succeeded. + /** Signals that detaching a visualisation has succeeded. */ case object VisualisationDetached - /** - * Requests the language server to modify a visualisation. + /** Requests the language server to modify a visualisation. * * @param clientId the requester id * @param visualisationId an identifier of a visualisation @@ -277,13 +250,11 @@ object ContextRegistryProtocol { visualisationConfig: VisualisationConfiguration ) - /** - * Signals that a visualisation modification has succeeded. + /** Signals that a visualisation modification has succeeded. */ case object VisualisationModified - /** - * Represents a visualisation context. + /** Represents a visualisation context. * * @param visualisationId a visualisation identifier * @param contextId a context identifier @@ -295,8 +266,7 @@ object ContextRegistryProtocol { expressionId: UUID ) - /** - * An event signaling a visualisation update. + /** An event signaling a visualisation update. * * @param visualisationContext a visualisation context * @param data a visualisation data @@ -306,28 +276,24 @@ object ContextRegistryProtocol { data: Array[Byte] ) - /** - * Signals that a module cannot be found. + /** Signals that a module cannot be found. * * @param moduleName the module name */ case class ModuleNotFound(moduleName: String) extends Failure - /** - * Signals that visualisation cannot be found. + /** Signals that visualisation cannot be found. */ case object VisualisationNotFound extends Failure - /** - * Signals that an expression specified in a [[AttachVisualisation]] or + /** Signals that an expression specified in a [[AttachVisualisation]] or * a [[ModifyVisualisation]] cannot be evaluated. * * @param message the reason of the failure */ case class VisualisationExpressionFailed(message: String) extends Failure - /** - * Signals that an evaluation of a code responsible for generating + /** Signals that an evaluation of a code responsible for generating * visualisation data failed. * * @param contextId a context identifier diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExecutionApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExecutionApi.scala index 0b97b8f5c7..7d05273795 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExecutionApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExecutionApi.scala @@ -7,8 +7,7 @@ import org.enso.languageserver.data.CapabilityRegistration import org.enso.languageserver.filemanager.Path import org.enso.languageserver.runtime.ContextRegistryProtocol.ExecutionDiagnostic -/** - * The execution JSON RPC API provided by the language server. +/** The execution JSON RPC API provided by the language server. * * @see [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExpressionValueUpdate.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExpressionValueUpdate.scala index 6e8fa61653..334673c576 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExpressionValueUpdate.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/ExpressionValueUpdate.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.runtime import org.enso.languageserver.runtime.ExecutionApi.ExpressionId -/** - * An update containing information about expression. +/** An update containing information about expression. * * @param expressionId the id of updated expression * @param `type` the updated type of expression diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/InvalidatedExpressions.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/InvalidatedExpressions.scala index eb55fd93c4..4487717699 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/InvalidatedExpressions.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/InvalidatedExpressions.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.runtime import io.circe.syntax._ import io.circe.{Decoder, DecodingFailure, Encoder} -/** - * A request to invalidate expressions. +/** A request to invalidate expressions. */ sealed trait InvalidatedExpressions @@ -12,8 +11,7 @@ object InvalidatedExpressions { import ExecutionApi._ - /** - * A request to invalidate all expressions. + /** A request to invalidate all expressions. */ case object All extends InvalidatedExpressions { @@ -30,8 +28,7 @@ object InvalidatedExpressions { } } - /** - * A request to invalidate a list of expressions. + /** A request to invalidate a list of expressions. * * @param value the list of expressions to invalidate */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/MethodPointer.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/MethodPointer.scala index 7ea0e8f534..3ccba81b5e 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/MethodPointer.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/MethodPointer.scala @@ -1,7 +1,6 @@ package org.enso.languageserver.runtime -/** - * An object pointing to a method definition. +/** An object pointing to a method definition. * * @param module the module of the method file * @param definedOnType method type diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeConnector.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeConnector.scala index f41a4ef856..b68cdd1cab 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeConnector.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeConnector.scala @@ -8,8 +8,7 @@ import org.enso.languageserver.runtime.RuntimeConnector.Destroy import org.enso.polyglot.runtime.Runtime import org.graalvm.polyglot.io.MessageEndpoint -/** - * An actor managing a connection to Enso's runtime server. +/** An actor managing a connection to Enso's runtime server. */ class RuntimeConnector extends Actor @@ -25,8 +24,7 @@ class RuntimeConnector case _ => stash() } - /** - * Performs communication between runtime and language server. + /** Performs communication between runtime and language server. * Requests are sent from language server to runtime, * responses are forwarded from runtime to the sender. * @@ -55,28 +53,24 @@ class RuntimeConnector object RuntimeConnector { - /** - * Protocol message to pass the runtime connection to the actor. + /** Protocol message to pass the runtime connection to the actor. * * @param engineConnection the open runtime connection. */ case class Initialize(engineConnection: MessageEndpoint) - /** - * Protocol message to inform the actor about the connection being closed. + /** Protocol message to inform the actor about the connection being closed. */ case object Destroy - /** - * Helper for creating instances of the [[RuntimeConnector]] actor. + /** Helper for creating instances of the [[RuntimeConnector]] actor. * * @return a [[Props]] instance for the newly created actor. */ def props: Props = Props(new RuntimeConnector) - /** - * Endpoint implementation used to handle connections with the runtime. + /** Endpoint implementation used to handle connections with the runtime. * * @param actor the actor ref to pass received messages to. * @param peerEndpoint the runtime server's connection end. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeFailureMapper.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeFailureMapper.scala index 41a1df2363..2cf0a8125b 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeFailureMapper.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeFailureMapper.scala @@ -8,8 +8,7 @@ import org.enso.jsonrpc.Error object RuntimeFailureMapper { - /** - * Maps registry error into JSON RPC error. + /** Maps registry error into JSON RPC error. * * @param error registry error * @return JSON RPC error @@ -34,8 +33,7 @@ object RuntimeFailureMapper { VisualisationExpressionError(msg) } - /** - * Maps runtime Api error into a registry error. + /** Maps runtime Api error into a registry error. * * @param error runtime Api error * @return registry error diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeKiller.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeKiller.scala index 3bfff06d14..53b98a06e4 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeKiller.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/RuntimeKiller.scala @@ -11,8 +11,7 @@ import org.graalvm.polyglot.Context import scala.concurrent.duration._ import scala.util.control.NonFatal -/** - * An actor that shuts the runtime down. It implements a routine responsible +/** An actor that shuts the runtime down. It implements a routine responsible * for disposing of runtime resources and closing the Truffle context in a * resilient manner. * @@ -28,17 +27,16 @@ class RuntimeKiller(runtimeConnector: ActorRef, truffleContext: Context) override def receive: Receive = idle() - private def idle(): Receive = { - case ShutDownRuntime => - log.info("Shutting down the runtime server") - runtimeConnector ! Api.Request( - UUID.randomUUID(), - Api.ShutDownRuntimeServer() - ) - val cancellable = - context.system.scheduler - .scheduleOnce(5.seconds, self, ResourceDisposalTimeout) - context.become(shuttingDownRuntimeServer(sender(), cancellable)) + private def idle(): Receive = { case ShutDownRuntime => + log.info("Shutting down the runtime server") + runtimeConnector ! Api.Request( + UUID.randomUUID(), + Api.ShutDownRuntimeServer() + ) + val cancellable = + context.system.scheduler + .scheduleOnce(5.seconds, self, ResourceDisposalTimeout) + context.become(shuttingDownRuntimeServer(sender(), cancellable)) } private def shuttingDownRuntimeServer( @@ -54,9 +52,11 @@ class RuntimeKiller(runtimeConnector: ActorRef, truffleContext: Context) shutDownTruffle(replyTo) } - private def shuttingDownTruffle(replyTo: ActorRef, retryCount: Int): Receive = { - case TryToStopTruffle => - shutDownTruffle(replyTo, retryCount) + private def shuttingDownTruffle( + replyTo: ActorRef, + retryCount: Int + ): Receive = { case TryToStopTruffle => + shutDownTruffle(replyTo, retryCount) } private def shutDownTruffle(replyTo: ActorRef, retryCount: Int = 0): Unit = { @@ -83,28 +83,23 @@ class RuntimeKiller(runtimeConnector: ActorRef, truffleContext: Context) object RuntimeKiller { - /** - * Number of retries to close a Truffle context. + /** Number of retries to close a Truffle context. */ val MaxRetries = 3 - /** - * A command that starts shutting down the Runtime server. + /** A command that starts shutting down the Runtime server. */ case object ShutDownRuntime - /** - * A base trait for ADT of a shutdown result. + /** A base trait for ADT of a shutdown result. */ sealed trait RuntimeShutdownResult - /** - * Signals that the Runtime stopped gracefully. + /** Signals that the Runtime stopped gracefully. */ case object RuntimeGracefullyStopped extends RuntimeShutdownResult - /** - * Signals that it is impossible to shut the runtime down. + /** Signals that it is impossible to shut the runtime down. */ case object RuntimeNotStopped extends RuntimeShutdownResult @@ -112,8 +107,7 @@ object RuntimeKiller { private case object TryToStopTruffle - /** - * Creates configuration object used to create a [[RuntimeKiller]]. + /** Creates configuration object used to create a [[RuntimeKiller]]. * * @param runtimeConnector a proxy to the runtime * @param truffleContext a Truffle context diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/StackItem.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/StackItem.scala index c4d61239eb..cecad26bff 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/StackItem.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/StackItem.scala @@ -6,15 +6,13 @@ import io.circe.generic.auto._ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Json} -/** - * A representation of an executable position in code. +/** A representation of an executable position in code. */ sealed trait StackItem object StackItem { - /** - * A call performed at the top of the stack, to initialize the context. + /** A call performed at the top of the stack, to initialize the context. * * @param methodPointer points to a method definition * @param thisArgumentExpression optional argument @@ -26,8 +24,7 @@ object StackItem { positionalArgumentsExpressions: Vector[String] ) extends StackItem - /** - * A call corresponding to "entering a function call". + /** A call corresponding to "entering a function call". * * @param expressionId an expression identifier */ @@ -56,9 +53,9 @@ object StackItem { implicit val encoder: Encoder[StackItem] = Encoder.instance[StackItem] { case ExplicitCall( - methodPointer, - thisArgumentExpression, - positionalArgumentsExpressions + methodPointer, + thisArgumentExpression, + positionalArgumentsExpressions ) => Json.obj( CodecField.Type -> CodecType.ExplicitCall.asJson, diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationApi.scala index 15e26f8492..593288a92f 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationApi.scala @@ -4,8 +4,7 @@ import java.util.UUID import org.enso.jsonrpc.{HasParams, HasResult, Method, Unused} -/** - * The visualisation JSON RPC API provided by the language server. +/** The visualisation JSON RPC API provided by the language server. * * @see [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationConfiguration.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationConfiguration.scala index b40f79f2c1..c70a504279 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationConfiguration.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/VisualisationConfiguration.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.runtime import java.util.UUID -/** - * A configuration object for properties of the visualisation. +/** A configuration object for properties of the visualisation. * * @param executionContextId an execution context of the visualisation * @param visualisationModule a qualified name of the module containing diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/AttachVisualisationHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/AttachVisualisationHandler.scala index 4f93495ee2..7461f7ec84 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/AttachVisualisationHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/AttachVisualisationHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for attach visualisation commands. +/** A request handler for attach visualisation commands. * * @param timeout request timeout * @param runtime reference to the runtime connector @@ -30,12 +29,11 @@ class AttachVisualisationHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.AttachVisualisation => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.AttachVisualisation => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -61,8 +59,7 @@ class AttachVisualisationHandler( object AttachVisualisationHandler { - /** - * Creates configuration object used to create a [[AttachVisualisationHandler]]. + /** Creates configuration object used to create a [[AttachVisualisationHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime connector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/CreateContextHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/CreateContextHandler.scala index 2ca55b636a..2879f45d2a 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/CreateContextHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/CreateContextHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for create context commands. +/** A request handler for create context commands. * * @param timeout request timeout * @param runtime reference to the runtime connector @@ -30,12 +29,11 @@ final class CreateContextHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.CreateContextRequest => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.CreateContextRequest => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -60,8 +58,7 @@ final class CreateContextHandler( object CreateContextHandler { - /** - * Creates configuration object used to create a [[CreateContextHandler]]. + /** Creates configuration object used to create a [[CreateContextHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime connector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DestroyContextHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DestroyContextHandler.scala index 9a4311443a..cc0bc0e316 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DestroyContextHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DestroyContextHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for destroy context commands. +/** A request handler for destroy context commands. * * @param timeout request timeout * @param runtime reference to the runtime conector @@ -30,12 +29,11 @@ final class DestroyContextHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.DestroyContextRequest => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.DestroyContextRequest => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -60,8 +58,7 @@ final class DestroyContextHandler( object DestroyContextHandler { - /** - * Creates a configuration object used to create [[DestroyContextHandler]]. + /** Creates a configuration object used to create [[DestroyContextHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime conector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DetachVisualisationHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DetachVisualisationHandler.scala index e87d2227cc..698ed845b6 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DetachVisualisationHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/DetachVisualisationHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for detach visualisation commands. +/** A request handler for detach visualisation commands. * * @param timeout request timeout * @param runtime reference to the runtime connector @@ -30,12 +29,11 @@ class DetachVisualisationHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.DetachVisualisation => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.DetachVisualisation => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -61,8 +59,7 @@ class DetachVisualisationHandler( object DetachVisualisationHandler { - /** - * Creates configuration object used to create a [[DetachVisualisationHandler]]. + /** Creates configuration object used to create a [[DetachVisualisationHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime connector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/ModifyVisualisationHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/ModifyVisualisationHandler.scala index 211952eb92..53eef6345d 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/ModifyVisualisationHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/ModifyVisualisationHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for modify visualisation commands. +/** A request handler for modify visualisation commands. * * @param timeout request timeout * @param runtime reference to the runtime connector @@ -30,12 +29,11 @@ class ModifyVisualisationHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.ModifyVisualisation => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.ModifyVisualisation => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -61,8 +59,7 @@ class ModifyVisualisationHandler( object ModifyVisualisationHandler { - /** - * Creates configuration object used to create a [[ModifyVisualisationHandler]]. + /** Creates configuration object used to create a [[ModifyVisualisationHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime connector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PopContextHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PopContextHandler.scala index 66e42a3fb0..aea7155720 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PopContextHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PopContextHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for push commands. +/** A request handler for push commands. * * @param timeout request timeout * @param runtime reference to the runtime conector @@ -30,12 +29,11 @@ final class PopContextHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.PopContextRequest => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.PopContextRequest => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -60,8 +58,7 @@ final class PopContextHandler( object PopContextHandler { - /** - * Creates a configuration object used to create [[PopContextHandler]]. + /** Creates a configuration object used to create [[PopContextHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime conector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PushContextHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PushContextHandler.scala index f9c5b190f1..5f720cbdb0 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PushContextHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/PushContextHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for push commands. +/** A request handler for push commands. * * @param timeout request timeout * @param runtime reference to the runtime conector @@ -30,12 +29,11 @@ final class PushContextHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.PushContextRequest => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.PushContextRequest => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -60,8 +58,7 @@ final class PushContextHandler( object PushContextHandler { - /** - * Creates a configuration object used to create [[PushContextHandler]]. + /** Creates a configuration object used to create [[PushContextHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime conector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/RecomputeContextHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/RecomputeContextHandler.scala index 283549da77..fe0c39490b 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/RecomputeContextHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/runtime/handler/RecomputeContextHandler.scala @@ -13,8 +13,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for recompute commands. +/** A request handler for recompute commands. * * @param timeout request timeout * @param runtime reference to the runtime connector @@ -30,12 +29,11 @@ final class RecomputeContextHandler( override def receive: Receive = requestStage - private def requestStage: Receive = { - case msg: Api.RecomputeContextRequest => - runtime ! Api.Request(UUID.randomUUID(), msg) - val cancellable = - context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) - context.become(responseStage(sender(), cancellable)) + private def requestStage: Receive = { case msg: Api.RecomputeContextRequest => + runtime ! Api.Request(UUID.randomUUID(), msg) + val cancellable = + context.system.scheduler.scheduleOnce(timeout, self, RequestTimeout) + context.become(responseStage(sender(), cancellable)) } private def responseStage( @@ -60,8 +58,7 @@ final class RecomputeContextHandler( object RecomputeContextHandler { - /** - * Creates configuration object used to create a [[RecomputeContextHandler]]. + /** Creates configuration object used to create a [[RecomputeContextHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime connector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/search/ModuleNameBuilder.scala b/engine/language-server/src/main/scala/org/enso/languageserver/search/ModuleNameBuilder.scala index 1fadf45342..33f3deac2e 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/search/ModuleNameBuilder.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/search/ModuleNameBuilder.scala @@ -6,8 +6,7 @@ import scala.util.Try object ModuleNameBuilder { - /** - * Build the module name from the file path. + /** Build the module name from the file path. * * @param projectName the project name * @param root the project root directory @@ -20,8 +19,7 @@ object ModuleNameBuilder { } } - /** - * Extract segments related to the module from the file path. + /** Extract segments related to the module from the file path. * * @param root the project root directory * @param file the module file path @@ -40,8 +38,7 @@ object ModuleNameBuilder { } } - /** - * Get the module name from the file path. + /** Get the module name from the file path. * * @param file the module file path * @return the module name @@ -51,8 +48,7 @@ object ModuleNameBuilder { fileName.substring(0, fileName.lastIndexOf('.')) } - /** - * Convert the list of segments to a module name. + /** Convert the list of segments to a module name. * * @param segments the list of segments * @return the fully qualified module name diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchApi.scala index d8a244230e..d0b36d4b97 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchApi.scala @@ -11,8 +11,7 @@ import org.enso.languageserver.search.SearchProtocol.{ import org.enso.text.editing.model.Position -/** - * The execution JSON RPC API provided by the language server. +/** The execution JSON RPC API provided by the language server. * * @see `docs/language-server/protocol-language-server.md` */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchFailureMapper.scala b/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchFailureMapper.scala index 3d02e389ea..a71c26f4b4 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchFailureMapper.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchFailureMapper.scala @@ -11,8 +11,7 @@ import org.enso.languageserver.search.SearchProtocol.{ object SearchFailureMapper { - /** - * Maps [[SearchFailure]] into JSON RPC error. + /** Maps [[SearchFailure]] into JSON RPC error. * * @param searchError the search specific failure * @return JSON RPC error diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchProtocol.scala index 2fb978c757..5e5ab980a1 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/search/SearchProtocol.scala @@ -193,8 +193,7 @@ object SearchProtocol { } } - /** - * The entry in the suggestions database. + /** The entry in the suggestions database. * * @param id the suggestion id * @param suggestion the suggestion @@ -203,8 +202,7 @@ object SearchProtocol { object SuggestionDatabaseEntry { - /** - * Create the database entry from the polyglot suggestion entry. + /** Create the database entry from the polyglot suggestion entry. * * @param entry the suggestion entry * @return the database entry diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/search/SuggestionsHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/search/SuggestionsHandler.scala index 0499cdb481..e8216fd6bd 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/search/SuggestionsHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/search/SuggestionsHandler.scala @@ -33,8 +33,7 @@ import org.enso.text.editing.model.Position import scala.concurrent.Future import scala.util.{Failure, Success} -/** - * The handler of search requests. +/** The handler of search requests. * * Handler initializes the database and responds to the search requests. * @@ -98,11 +97,10 @@ final class SuggestionsHandler( context.system.eventStream .subscribe(self, InitializedEvent.SuggestionsRepoInitialized.getClass) - config.contentRoots.foreach { - case (_, contentRoot) => - PackageManager.Default - .fromDirectory(contentRoot) - .foreach(pkg => self ! ProjectNameUpdated(pkg.config.name)) + config.contentRoots.foreach { case (_, contentRoot) => + PackageManager.Default + .fromDirectory(contentRoot) + .foreach(pkg => self ! ProjectNameUpdated(pkg.config.name)) } } @@ -178,13 +176,12 @@ final class SuggestionsHandler( .flatMap(update => update.expressionType.map(update.expressionId -> _)) suggestionsRepo .updateAll(types) - .map { - case (version, updatedIds) => - val updates = types.zip(updatedIds).collect { - case ((_, typeValue), Some(suggestionId)) => - SuggestionsDatabaseUpdate.Modify(suggestionId, typeValue) - } - SuggestionsDatabaseUpdateNotification(version, updates) + .map { case (version, updatedIds) => + val updates = types.zip(updatedIds).collect { + case ((_, typeValue), Some(suggestionId)) => + SuggestionsDatabaseUpdate.Modify(suggestionId, typeValue) + } + SuggestionsDatabaseUpdateNotification(version, updates) } .onComplete { case Success(notification) => @@ -208,12 +205,11 @@ final class SuggestionsHandler( case GetSuggestionsDatabase => suggestionsRepo.getAll - .map { - case (version, entries) => - GetSuggestionsDatabaseResult( - version, - entries.map(SuggestionDatabaseEntry(_)) - ) + .map { case (version, entries) => + GetSuggestionsDatabaseResult( + version, + entries.map(SuggestionDatabaseEntry(_)) + ) } .pipeTo(sender()) @@ -241,14 +237,13 @@ final class SuggestionsHandler( module => suggestionsRepo .removeByModule(module) - .map { - case (version, ids) => - Right( - SuggestionsDatabaseUpdateNotification( - version, - ids.map(SuggestionsDatabaseUpdate.Remove) - ) + .map { case (version, ids) => + Right( + SuggestionsDatabaseUpdateNotification( + version, + ids.map(SuggestionsDatabaseUpdate.Remove) ) + ) } ) .onComplete { @@ -290,8 +285,7 @@ final class SuggestionsHandler( context.become(initialized(name, clients)) } - /** - * Transition the initialization process. + /** Transition the initialization process. * * @param state current initialization state */ @@ -303,8 +297,7 @@ final class SuggestionsHandler( } } - /** - * Handle the suggestions database update. + /** Handle the suggestions database update. * * Function applies notification updates on the suggestions database and * builds the notification to the user @@ -362,8 +355,7 @@ final class SuggestionsHandler( } } - /** - * Build the module name from the requested file path. + /** Build the module name from the requested file path. * * @param projectName the project name * @param path the requested file path @@ -387,15 +379,13 @@ final class SuggestionsHandler( object SuggestionsHandler { - /** - * The notification about the project name update. + /** The notification about the project name update. * * @param projectName the new project name */ case class ProjectNameUpdated(projectName: String) - /** - * The initialization state of the handler. + /** The initialization state of the handler. * * @param project the project name * @param suggestions the initialization event of the suggestions repo @@ -405,8 +395,7 @@ object SuggestionsHandler { suggestions: Option[InitializedEvent.SuggestionsRepoInitialized.type] = None ) { - /** - * Check if all the components are initialized. + /** Check if all the components are initialized. * * @return the project name */ @@ -417,8 +406,7 @@ object SuggestionsHandler { } yield name } - /** - * Creates a configuration object used to create a [[SuggestionsHandler]]. + /** Creates a configuration object used to create a [[SuggestionsHandler]]. * * @param config the server configuration * @param suggestionsRepo the suggestions repo diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/search/handler/InvalidateModulesIndexHandler.scala b/engine/language-server/src/main/scala/org/enso/languageserver/search/handler/InvalidateModulesIndexHandler.scala index bc1bc798ae..cf73d4dcf8 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/search/handler/InvalidateModulesIndexHandler.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/search/handler/InvalidateModulesIndexHandler.scala @@ -11,8 +11,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.duration.FiniteDuration -/** - * A request handler for invalidate modules index command. +/** A request handler for invalidate modules index command. * * @param timeout request timeout * @param runtime reference to the runtime connector @@ -61,8 +60,7 @@ final class InvalidateModulesIndexHandler( object InvalidateModulesIndexHandler { - /** - * Creates a configuration object used to create [[InvalidateModulesIndexHandler]]. + /** Creates a configuration object used to create [[InvalidateModulesIndexHandler]]. * * @param timeout request timeout * @param runtime reference to the runtime conector diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/session/BinarySession.scala b/engine/language-server/src/main/scala/org/enso/languageserver/session/BinarySession.scala index c5fa2fbd8f..2f5e640349 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/session/BinarySession.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/session/BinarySession.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.session import akka.actor.ActorRef import org.enso.languageserver.data.ClientId -/** - * An object representing a client connected to the language server via data +/** An object representing a client connected to the language server via data * protocol. * * @param clientId the internal id of this client diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/session/JsonSession.scala b/engine/language-server/src/main/scala/org/enso/languageserver/session/JsonSession.scala index df3ceed300..ae7829ee2f 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/session/JsonSession.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/session/JsonSession.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.session import akka.actor.ActorRef import org.enso.languageserver.data.ClientId -/** - * An object representing a client connected to the language server via RPC +/** An object representing a client connected to the language server via RPC * protocol. * * @param clientId the internal id of this client diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/session/Session.scala b/engine/language-server/src/main/scala/org/enso/languageserver/session/Session.scala index d217ec331f..ce257ed52d 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/session/Session.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/session/Session.scala @@ -2,8 +2,7 @@ package org.enso.languageserver.session import org.enso.languageserver.data.ClientId -/** - * An object representing a client connected to the language server via both +/** An object representing a client connected to the language server via both * rpc and data protocol. * * @param clientId the internal id of this client diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionApi.scala index 74b1993ed3..3c55154ca0 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionApi.scala @@ -4,8 +4,7 @@ import java.util.UUID import org.enso.jsonrpc.{Error, HasParams, HasResult, Method} -/** - * The connection management JSON RPC API provided by the language server. +/** The connection management JSON RPC API provided by the language server. * See [[https://github.com/enso-org/enso/blob/main/docs/language-server/protocol-language-server.md#connection-management]] * for message specifications. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionRouter.scala b/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionRouter.scala index 620dc7f755..859f861022 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionRouter.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/session/SessionRouter.scala @@ -14,8 +14,7 @@ import org.enso.languageserver.session.SessionRouter.{ DeliverToJsonController } -/** - * A content based router that routes arbitrary messages to the session +/** A content based router that routes arbitrary messages to the session * controller identified by the client id. */ class SessionRouter extends Actor { @@ -71,8 +70,7 @@ class SessionRouter extends Actor { object SessionRouter { - /** - * A command used to deliver an arbitrary `payload` to a rpc controller + /** A command used to deliver an arbitrary `payload` to a rpc controller * identified by the client id. * * @param clientId the internal client identifier @@ -81,8 +79,7 @@ object SessionRouter { */ case class DeliverToJsonController[A](clientId: ClientId, payload: A) - /** - * A command used to deliver an arbitrary `payload` to a data controller + /** A command used to deliver an arbitrary `payload` to a data controller * identified by the client id. * * @param clientId the internal client identifier @@ -91,8 +88,7 @@ object SessionRouter { */ case class DeliverToBinaryController[A](clientId: ClientId, payload: A) - /** - * Creates configuration object used to create a [[SessionRouter]]. + /** Creates configuration object used to create a [[SessionRouter]]. * * @return a configuration object */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/text/Buffer.scala b/engine/language-server/src/main/scala/org/enso/languageserver/text/Buffer.scala index 9e26d6d110..11fb6ec637 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/text/Buffer.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/text/Buffer.scala @@ -5,8 +5,7 @@ import java.io.File import org.enso.languageserver.data.ContentBasedVersioning import org.enso.text.buffer.Rope -/** - * A buffer state representation. +/** A buffer state representation. * * @param file the file linked to the buffer. * @param contents the contents of the buffer. @@ -17,8 +16,7 @@ case class Buffer(file: File, contents: Rope, version: Buffer.Version) object Buffer { type Version = String - /** - * Creates a new buffer with a freshly generated version. + /** Creates a new buffer with a freshly generated version. * * @param file the file linked to the buffer. * @param contents the contents of this buffer. @@ -31,8 +29,7 @@ object Buffer { )(implicit versionCalculator: ContentBasedVersioning): Buffer = Buffer(file, contents, versionCalculator.evalVersion(contents.toString)) - /** - * Creates a new buffer with a freshly generated version. + /** Creates a new buffer with a freshly generated version. * * @param file the file linked to the buffer. * @param contents the contents of this buffer. diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/text/BufferRegistry.scala b/engine/language-server/src/main/scala/org/enso/languageserver/text/BufferRegistry.scala index 707ca56c64..d52fd66f0d 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/text/BufferRegistry.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/text/BufferRegistry.scala @@ -26,8 +26,7 @@ import org.enso.searcher.FileVersionsRepo import scala.concurrent.Future -/** - * An actor that routes request regarding text editing to the right buffer. +/** An actor that routes request regarding text editing to the right buffer. * It creates a buffer actor, if a buffer doesn't exists. * * == Implementation == @@ -140,8 +139,7 @@ class BufferRegistry( object BufferRegistry { - /** - * Creates a configuration object used to create a [[BufferRegistry]] + /** Creates a configuration object used to create a [[BufferRegistry]] * * @param versionsRepo a repo containing versions of indexed files * @param fileManager a file manager actor diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/text/CollaborativeBuffer.scala b/engine/language-server/src/main/scala/org/enso/languageserver/text/CollaborativeBuffer.scala index bc3ffdc402..aa1af27732 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/text/CollaborativeBuffer.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/text/CollaborativeBuffer.scala @@ -41,8 +41,7 @@ import scala.concurrent.Future import scala.concurrent.duration._ import scala.language.postfixOps -/** - * An actor enabling multiple users edit collaboratively a file. +/** An actor enabling multiple users edit collaboratively a file. * * @param bufferPath a path to a file * @param versionsRepo a repo containing versions of indexed files @@ -73,11 +72,10 @@ class CollaborativeBuffer( override def receive: Receive = uninitialized - private def uninitialized: Receive = { - case OpenFile(client, path) => - context.system.eventStream.publish(BufferOpened(path)) - log.info(s"Buffer opened for $path [client:${client.clientId}]") - readFile(client, path) + private def uninitialized: Receive = { case OpenFile(client, path) => + context.system.eventStream.publish(BufferOpened(path)) + log.info(s"Buffer opened for $path [client:${client.clientId}]") + readFile(client, path) } private def waitingForFileContent( @@ -409,8 +407,7 @@ object CollaborativeBuffer { case object IOTimeout - /** - * Creates a configuration object used to create a [[CollaborativeBuffer]] + /** Creates a configuration object used to create a [[CollaborativeBuffer]] * * @param bufferPath a path to a file * @param versionsRepo a repo containing versions of indexed files diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/text/FileEdit.scala b/engine/language-server/src/main/scala/org/enso/languageserver/text/FileEdit.scala index 8c8122227a..955fffa867 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/text/FileEdit.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/text/FileEdit.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.text import org.enso.languageserver.filemanager.Path import org.enso.text.editing.model.TextEdit -/** - * A representation of a batch of edits to a file, versioned. +/** A representation of a batch of edits to a file, versioned. * * @param path a path of a file * @param edits a series of edits to a file diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/text/TextApi.scala b/engine/language-server/src/main/scala/org/enso/languageserver/text/TextApi.scala index 1ff25a3c7c..9f6ea13e87 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/text/TextApi.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/text/TextApi.scala @@ -4,8 +4,7 @@ import org.enso.languageserver.data.CapabilityRegistration import org.enso.languageserver.filemanager.Path import org.enso.jsonrpc.{Error, HasParams, HasResult, Method, Unused} -/** - * The text editing JSON RPC API provided by the language server. +/** The text editing JSON RPC API provided by the language server. * See [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] * for message specifications. */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/text/TextProtocol.scala b/engine/language-server/src/main/scala/org/enso/languageserver/text/TextProtocol.scala index f3455ab923..3e7dbfc7b5 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/text/TextProtocol.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/text/TextProtocol.scala @@ -37,58 +37,48 @@ object TextProtocol { */ case class CloseFile(clientId: ClientId, path: Path) - /** - * Signals file close status. + /** Signals file close status. */ sealed trait CloseFileResult - /** - * Confirms that a file was successfully closed. + /** Confirms that a file was successfully closed. */ case object FileClosed extends CloseFileResult - /** - * Signals that a file wasn't opened. + /** Signals that a file wasn't opened. */ case object FileNotOpened - /** - * Requests the language server to apply a series of edits to the buffer. + /** Requests the language server to apply a series of edits to the buffer. * * @param clientId the client closing the file. * @param edit a diff describing changes made to a file */ case class ApplyEdit(clientId: ClientId, edit: FileEdit) - /** - * Signals the result of applying a series of edits. + /** Signals the result of applying a series of edits. */ sealed trait ApplyEditResult - /** - * Signals that all edits were applied successfully. + /** Signals that all edits were applied successfully. */ case object ApplyEditSuccess extends ApplyEditResult - /** - * A base trait for all failures regarding editing. + /** A base trait for all failures regarding editing. */ sealed trait ApplyEditFailure extends ApplyEditResult - /** - * Signals that the client doesn't hold write lock to the buffer. + /** Signals that the client doesn't hold write lock to the buffer. */ case object WriteDenied extends ApplyEditFailure - /** - * Signals that validation has failed for a series of edits. + /** Signals that validation has failed for a series of edits. * * @param msg a validation message */ case class TextEditValidationFailed(msg: String) extends ApplyEditFailure - /** - * Signals that version provided by a client doesn't match to the version + /** Signals that version provided by a client doesn't match to the version * computed by the server. * * @param clientVersion a version send by the client @@ -99,8 +89,7 @@ object TextProtocol { serverVersion: Buffer.Version ) extends ApplyEditFailure - /** - * A notification sent by the Language Server, notifying a client about + /** A notification sent by the Language Server, notifying a client about * edits made by the write lock holder. * * @param changes a series of edits @@ -119,23 +108,19 @@ object TextProtocol { currentVersion: Buffer.Version ) - /** - * Signals the result of saving a file. + /** Signals the result of saving a file. */ sealed trait SaveFileResult - /** - * Signals that saving a file was executed successfully. + /** Signals that saving a file was executed successfully. */ case object FileSaved extends SaveFileResult - /** - * Signals that the client doesn't hold write lock to the buffer. + /** Signals that the client doesn't hold write lock to the buffer. */ case object SaveDenied extends SaveFileResult - /** - * Signals that version provided by a client doesn't match to the version + /** Signals that version provided by a client doesn't match to the version * computed by the server. * * @param clientVersion a version send by the client @@ -146,8 +131,7 @@ object TextProtocol { serverVersion: Buffer.Version ) extends SaveFileResult - /** - * Signals that saving a file failed due to IO error. + /** Signals that saving a file failed due to IO error. * * @param fsFailure a filesystem failure */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/util/Logging.scala b/engine/language-server/src/main/scala/org/enso/languageserver/util/Logging.scala index 2a1dd754e9..be428d1ba1 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/util/Logging.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/util/Logging.scala @@ -84,8 +84,7 @@ object Logging { private val ROOT_LOGGER = "org.enso" - /** - * Set log level for the application root logger. + /** Set log level for the application root logger. * * @param level the log level * @return the new log level diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryDecoder.scala b/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryDecoder.scala index b83f865376..97555da1ad 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryDecoder.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryDecoder.scala @@ -2,15 +2,13 @@ package org.enso.languageserver.util.binary import java.nio.ByteBuffer -/** - * A type class that provides a way to decode bytes to value of type `A`. +/** A type class that provides a way to decode bytes to value of type `A`. * * @tparam A a result type */ trait BinaryDecoder[+A] { - /** - * Decodes serialized format of type `A`. + /** Decodes serialized format of type `A`. * * @param bytes a byte buffer containing serialized format of type `A` * @return either a decoding failure or a value of type `A` diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryEncoder.scala b/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryEncoder.scala index 4fb93dc8f2..5bd0582073 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryEncoder.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/BinaryEncoder.scala @@ -2,15 +2,13 @@ package org.enso.languageserver.util.binary import java.nio.ByteBuffer -/** - * A type class that provides a way to encode a value of type `A` to bytes. +/** A type class that provides a way to encode a value of type `A` to bytes. * * @tparam A an input type */ trait BinaryEncoder[-A] { - /** - * Encodes a value of type 'A' to bytes. + /** Encodes a value of type 'A' to bytes. * * @param msg a message to encode * @return a byte buffer containing serialized format of type `A` @@ -21,8 +19,7 @@ trait BinaryEncoder[-A] { object BinaryEncoder { - /** - * An encoder that returns input value. + /** An encoder that returns input value. */ val empty: BinaryEncoder[ByteBuffer] = identity diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/DecodingFailure.scala b/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/DecodingFailure.scala index 4234a83229..112cf45b49 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/DecodingFailure.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/util/binary/DecodingFailure.scala @@ -1,24 +1,20 @@ package org.enso.languageserver.util.binary -/** - * Base trait signaling decoding failure. +/** Base trait signaling decoding failure. */ sealed trait DecodingFailure object DecodingFailure { - /** - * Signals an empty payload in the byte stream. + /** Signals an empty payload in the byte stream. */ case object EmptyPayload extends DecodingFailure - /** - * Signals that data is corrupted. + /** Signals that data is corrupted. */ case object DataCorrupted extends DecodingFailure - /** - * Represents an undefined decoding failure. + /** Represents an undefined decoding failure. * * @param throwable a throwable */ diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/util/file/PathUtils.scala b/engine/language-server/src/main/scala/org/enso/languageserver/util/file/PathUtils.scala index 2b82b3aa73..d0c50d7e20 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/util/file/PathUtils.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/util/file/PathUtils.scala @@ -5,8 +5,7 @@ import org.enso.languageserver.protocol.binary.{Path => BinaryPath} object PathUtils { - /** - * Converts a path generated by the FlatBuffers lib. to value of type [[Path]]. + /** Converts a path generated by the FlatBuffers lib. to value of type [[Path]]. * * @param path a binary path * @return diff --git a/engine/language-server/src/main/scala/org/enso/languageserver/util/file/UuidUtils.scala b/engine/language-server/src/main/scala/org/enso/languageserver/util/file/UuidUtils.scala index c940b8a862..23ffa8a024 100644 --- a/engine/language-server/src/main/scala/org/enso/languageserver/util/file/UuidUtils.scala +++ b/engine/language-server/src/main/scala/org/enso/languageserver/util/file/UuidUtils.scala @@ -6,8 +6,7 @@ import org.enso.languageserver.protocol.binary.EnsoUUID object UuidUtils { - /** - * Converts an [[EnsoUUID]] to a JVM [[UUID]]. + /** Converts an [[EnsoUUID]] to a JVM [[UUID]]. * * @param uuid a flatbuffers representation of uuid * @return [[UUID]] diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/data/Sha3224VersionCalculatorSpec.scala b/engine/language-server/src/test/scala/org/enso/languageserver/data/Sha3224VersionCalculatorSpec.scala index 2154ba047d..493fc8da6b 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/data/Sha3224VersionCalculatorSpec.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/data/Sha3224VersionCalculatorSpec.scala @@ -6,7 +6,9 @@ import org.scalatest.matchers.must.Matchers class Sha3224VersionCalculatorSpec extends AnyFlatSpec with Matchers { "A Sha3Digest" should "produce SHA3-224 digest" in { - Sha3_224VersionCalculator.evalVersion(" ") mustBe "4cb5f87b01b38adc0e6f13f915668c2394cb1fb7a2795635b894dda1" + Sha3_224VersionCalculator.evalVersion( + " " + ) mustBe "4cb5f87b01b38adc0e6f13f915668c2394cb1fb7a2795635b894dda1" Sha3_224VersionCalculator.evalVersion( "The quick brown fox jumps over the lazy dog" ) mustBe "d15dadceaa4d5d7bb3b48f446421d542e08ad8887305e28d58335795" diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/effect/Effects.scala b/engine/language-server/src/test/scala/org/enso/languageserver/effect/Effects.scala index 4be1124110..bb27c7e1a9 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/effect/Effects.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/effect/Effects.scala @@ -3,8 +3,7 @@ package org.enso.languageserver.effect import scala.concurrent.Await import scala.concurrent.duration._ -/** - * Functions helping to manage effects in tests. +/** Functions helping to manage effects in tests. */ trait Effects { diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/requesthandler/monitoring/PingHandlerSpec.scala b/engine/language-server/src/test/scala/org/enso/languageserver/requesthandler/monitoring/PingHandlerSpec.scala index 6a64fefe70..0487f46469 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/requesthandler/monitoring/PingHandlerSpec.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/requesthandler/monitoring/PingHandlerSpec.scala @@ -61,7 +61,7 @@ class PingHandlerSpec system.stop(actorUnderTest) } - it must "stop without replying when some of subsystems don't reply on time" taggedAs(Flaky) in { + it must "stop without replying when some of subsystems don't reply on time" taggedAs Flaky in { //given val subsystem1 = TestProbe() val subsystem2 = TestProbe() diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/search/SuggestionsHandlerSpec.scala b/engine/language-server/src/test/scala/org/enso/languageserver/search/SuggestionsHandlerSpec.scala index 3f7435d27f..c7d159c56d 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/search/SuggestionsHandlerSpec.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/search/SuggestionsHandlerSpec.scala @@ -182,7 +182,8 @@ class SuggestionsHandlerSpec "search entries by empty search query" taggedAs Retry in withDb { (config, repo, _, _, handler) => - val (_, inserted) = Await.result(repo.insertAll(Suggestions.all), Timeout) + val (_, inserted) = + Await.result(repo.insertAll(Suggestions.all), Timeout) handler ! SearchProtocol.Completion( file = mkModulePath(config, "Foo", "Main.enso"), position = Position(0, 0), @@ -191,12 +192,12 @@ class SuggestionsHandlerSpec tags = None ) - expectMsg( - SearchProtocol.CompletionResult( - 4L, - Seq(inserted(0).get, inserted(1).get) + expectMsg( + SearchProtocol.CompletionResult( + 4L, + Seq(inserted(0).get, inserted(1).get) + ) ) - ) } "search entries by self type" taggedAs Retry in withDb { diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryFileManipulationTest.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryFileManipulationTest.scala index ee36181f8c..20c2e2948c 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryFileManipulationTest.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryFileManipulationTest.scala @@ -28,7 +28,7 @@ class BinaryFileManipulationTest extends BaseBinaryServerTest with FlakySpec { "A WriteFileCommand" must { - "persist binary contents of a file" taggedAs(Flaky) in { + "persist binary contents of a file" taggedAs Flaky in { //given val requestId = UUID.randomUUID() val filename = "foo.bin" diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryServerTestKit.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryServerTestKit.scala index 926b67a171..109c954beb 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryServerTestKit.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinaryServerTestKit.scala @@ -80,12 +80,18 @@ abstract class BinaryServerTestKit .map { frame: ByteBuffer => BinaryMessage(ByteString(frame)) } private val sink: Sink[Message, NotUsed] = Flow[Message] - .collect { - case BinaryMessage.Strict(data) => data.asByteBuffer + .collect { case BinaryMessage.Strict(data) => + data.asByteBuffer } - .to(Sink.actorRef[ByteBuffer](outActor.ref, PoisonPill, { _: Any => - PoisonPill - })) + .to( + Sink.actorRef[ByteBuffer]( + outActor.ref, + PoisonPill, + { _: Any => + PoisonPill + } + ) + ) private val flow = Flow.fromSinkAndSource(sink, source) diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinarySessionManagementTest.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinarySessionManagementTest.scala index 85d433f17c..86943bc65d 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinarySessionManagementTest.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/BinarySessionManagementTest.scala @@ -20,7 +20,7 @@ class BinarySessionManagementTest extends BaseBinaryServerTest with FlakySpec { "Session Init cmd" must { - "return empty SessionInitResponse" taggedAs(Flaky) in { + "return empty SessionInitResponse" taggedAs Flaky in { //given val client = newWsClient() val clientId = UUID.randomUUID() diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/VisualisationProtocolTest.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/VisualisationProtocolTest.scala index 6583f77aaf..810d4d236b 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/VisualisationProtocolTest.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/VisualisationProtocolTest.scala @@ -24,7 +24,7 @@ class VisualisationProtocolTest "A visualisation binary protocol" must { - "push visualisation updates when controller receives notification" taggedAs(Flaky) in { + "push visualisation updates when controller receives notification" taggedAs Flaky in { //given val client = newWsClient() val data = Array[Byte](1, 2, 3) diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/PathFactory.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/PathFactory.scala index e20cb0bc4f..fda74c723b 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/PathFactory.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/binary/factory/PathFactory.scala @@ -8,14 +8,13 @@ import org.enso.languageserver.protocol.binary.factory.EnsoUuidFactory object PathFactory { - def create(rootId: UUID, segments: Seq[String])( - implicit builder: FlatBufferBuilder + def create(rootId: UUID, segments: Seq[String])(implicit + builder: FlatBufferBuilder ): Int = { val segmentOffsets = - segments.foldRight(List.empty[Int]) { - case (segment, tail) => - val offset = builder.createString(segment) - offset :: tail + segments.foldRight(List.empty[Int]) { case (segment, tail) => + val offset = builder.createString(segment) + offset :: tail } val segmentsOffset = Path.createSegmentsVector(builder, segmentOffsets.toArray) diff --git a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/json/VisualisationOperationsTest.scala b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/json/VisualisationOperationsTest.scala index 83709dda54..1ff571595f 100644 --- a/engine/language-server/src/test/scala/org/enso/languageserver/websocket/json/VisualisationOperationsTest.scala +++ b/engine/language-server/src/test/scala/org/enso/languageserver/websocket/json/VisualisationOperationsTest.scala @@ -38,8 +38,12 @@ class VisualisationOperationsTest extends BaseServerTest { val requestId = runtimeConnectorProbe.receiveN(1).head match { case Api.Request( - requestId, - Api.AttachVisualisation(`visualisationId`, `expressionId`, config) + requestId, + Api.AttachVisualisation( + `visualisationId`, + `expressionId`, + config + ) ) => config.expression shouldBe visualisationConfig.expression config.visualisationModule shouldBe visualisationConfig.visualisationModule @@ -113,12 +117,12 @@ class VisualisationOperationsTest extends BaseServerTest { val requestId = runtimeConnectorProbe.receiveN(1).head match { case Api.Request( - requestId, - Api.DetachVisualisation( - `contextId`, - `visualisationId`, - `expressionId` - ) + requestId, + Api.DetachVisualisation( + `contextId`, + `visualisationId`, + `expressionId` + ) ) => requestId @@ -191,8 +195,8 @@ class VisualisationOperationsTest extends BaseServerTest { val requestId = runtimeConnectorProbe.receiveN(1).head match { case Api.Request( - requestId, - Api.ModifyVisualisation(`visualisationId`, config) + requestId, + Api.ModifyVisualisation(`visualisationId`, config) ) => config.expression shouldBe visualisationConfig.expression config.visualisationModule shouldBe visualisationConfig.visualisationModule diff --git a/engine/launcher/native-image-config/jni-config.json b/engine/launcher/native-image-config/jni-config.json index 3da6f910c9..b9b4d35133 100644 --- a/engine/launcher/native-image-config/jni-config.json +++ b/engine/launcher/native-image-config/jni-config.json @@ -2,8 +2,14 @@ { "name": "java.lang.ClassLoader", "methods": [ - { "name": "getPlatformClassLoader", "parameterTypes": [] }, - { "name": "loadClass", "parameterTypes": ["java.lang.String"] } + { + "name": "getPlatformClassLoader", + "parameterTypes": [] + }, + { + "name": "loadClass", + "parameterTypes": ["java.lang.String"] + } ] }, { diff --git a/engine/launcher/native-image-config/reflect-config.json b/engine/launcher/native-image-config/reflect-config.json index 353bee804b..1f738ff9dc 100644 --- a/engine/launcher/native-image-config/reflect-config.json +++ b/engine/launcher/native-image-config/reflect-config.json @@ -22,7 +22,12 @@ }, { "name": "akka.actor.DefaultSupervisorStrategy", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "akka.actor.LightArrayRevolverScheduler", @@ -39,7 +44,12 @@ }, { "name": "akka.actor.LightArrayRevolverScheduler$TaskHolder", - "fields": [{ "name": "task", "allowUnsafeAccess": true }] + "fields": [ + { + "name": "task", + "allowUnsafeAccess": true + } + ] }, { "name": "akka.actor.LightArrayRevolverScheduler$TaskQueue[]" @@ -68,25 +78,42 @@ }, { "name": "akka.actor.Props$EmptyActor", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "akka.actor.RepointableActorRef", "fields": [ - { "name": "_cellDoNotCallMeDirectly", "allowUnsafeAccess": true }, - { "name": "_lookupDoNotCallMeDirectly", "allowUnsafeAccess": true } + { + "name": "_cellDoNotCallMeDirectly", + "allowUnsafeAccess": true + }, + { + "name": "_lookupDoNotCallMeDirectly", + "allowUnsafeAccess": true + } ] }, { "name": "akka.dispatch.AbstractNodeQueue", "fields": [ - { "name": "_tailDoNotCallMeDirectly", "allowUnsafeAccess": true } + { + "name": "_tailDoNotCallMeDirectly", + "allowUnsafeAccess": true + } ] }, { "name": "akka.dispatch.AbstractNodeQueue$Node", "fields": [ - { "name": "_nextDoNotCallMeDirectly", "allowUnsafeAccess": true } + { + "name": "_nextDoNotCallMeDirectly", + "allowUnsafeAccess": true + } ] }, { @@ -107,14 +134,23 @@ { "name": "akka.dispatch.Mailbox", "fields": [ - { "name": "_statusDoNotCallMeDirectly", "allowUnsafeAccess": true }, - { "name": "_systemQueueDoNotCallMeDirectly", "allowUnsafeAccess": true } + { + "name": "_statusDoNotCallMeDirectly", + "allowUnsafeAccess": true + }, + { + "name": "_systemQueueDoNotCallMeDirectly", + "allowUnsafeAccess": true + } ] }, { "name": "akka.dispatch.MessageDispatcher", "fields": [ - { "name": "_inhabitantsDoNotCallMeDirectly", "allowUnsafeAccess": true }, + { + "name": "_inhabitantsDoNotCallMeDirectly", + "allowUnsafeAccess": true + }, { "name": "_shutdownScheduleDoNotCallMeDirectly", "allowUnsafeAccess": true @@ -147,7 +183,12 @@ }, { "name": "akka.event.DeadLetterListener", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "akka.event.DefaultLoggingFilter", @@ -182,7 +223,12 @@ }, { "name": "akka.event.slf4j.Slf4jLogger", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "akka.event.slf4j.Slf4jLoggingFilter", @@ -198,15 +244,30 @@ }, { "name": "akka.http.DefaultParsingErrorHandler$", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "akka.http.impl.engine.client.PoolMasterActor", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "akka.io.InetAddressDnsProvider", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "akka.io.InetAddressDnsResolver", @@ -242,14 +303,23 @@ { "name": "akka.pattern.PromiseActorRef", "fields": [ - { "name": "_stateDoNotCallMeDirectly", "allowUnsafeAccess": true }, - { "name": "_watchedByDoNotCallMeDirectly", "allowUnsafeAccess": true } + { + "name": "_stateDoNotCallMeDirectly", + "allowUnsafeAccess": true + }, + { + "name": "_watchedByDoNotCallMeDirectly", + "allowUnsafeAccess": true + } ] }, { "name": "akka.routing.ConsistentHashingPool", "methods": [ - { "name": "", "parameterTypes": ["com.typesafe.config.Config"] } + { + "name": "", + "parameterTypes": ["com.typesafe.config.Config"] + } ] }, { @@ -258,7 +328,10 @@ { "name": "akka.routing.RoundRobinPool", "methods": [ - { "name": "", "parameterTypes": ["com.typesafe.config.Config"] } + { + "name": "", + "parameterTypes": ["com.typesafe.config.Config"] + } ] }, { @@ -268,47 +341,72 @@ { "name": "akka.serialization.BooleanSerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { "name": "akka.serialization.ByteArraySerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { "name": "akka.serialization.ByteStringSerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { "name": "akka.serialization.DisabledJavaSerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { "name": "akka.serialization.IntSerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { "name": "akka.serialization.LongSerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { "name": "akka.serialization.SerializationExtension$", - "fields": [{ "name": "MODULE$" }] + "fields": [ + { + "name": "MODULE$" + } + ] }, { "name": "akka.serialization.StringSerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { @@ -319,7 +417,11 @@ }, { "name": "akka.stream.SystemMaterializer$", - "fields": [{ "name": "MODULE$" }] + "fields": [ + { + "name": "MODULE$" + } + ] }, { "name": "akka.stream.impl.BatchingInputBuffer[]" @@ -333,7 +435,10 @@ { "name": "akka.stream.serialization.StreamRefSerializer", "methods": [ - { "name": "", "parameterTypes": ["akka.actor.ExtendedActorSystem"] } + { + "name": "", + "parameterTypes": ["akka.actor.ExtendedActorSystem"] + } ] }, { @@ -350,27 +455,57 @@ }, { "name": "com.sun.crypto.provider.AESCipher$General", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "com.sun.crypto.provider.DHParameters", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "com.sun.crypto.provider.TlsKeyMaterialGenerator", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "com.sun.crypto.provider.TlsMasterSecretGenerator", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "com.sun.crypto.provider.TlsPrfGenerator$V12", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "com.typesafe.sslconfig.ssl.NoopHostnameVerifier", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "java.io.Serializable" @@ -389,7 +524,12 @@ }, { "name": "java.lang.String", - "fields": [{ "name": "value", "allowUnsafeAccess": true }] + "fields": [ + { + "name": "value", + "allowUnsafeAccess": true + } + ] }, { "name": "java.lang.String[]" @@ -441,66 +581,143 @@ }, { "name": "javax.security.auth.x500.X500Principal", - "fields": [{ "name": "thisX500Name" }], + "fields": [ + { + "name": "thisX500Name" + } + ], "methods": [ - { "name": "", "parameterTypes": ["sun.security.x509.X500Name"] } + { + "name": "", + "parameterTypes": ["sun.security.x509.X500Name"] + } ] }, { "name": "org.apache.commons.compress.archivers.zip.AsiExtraField", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.JarMarker", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.ResourceAlignmentExtraField", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.UnicodeCommentExtraField", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.UnicodePathExtraField", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X000A_NTFS", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X0014_X509Certificates", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X0015_CertificateIdForFile", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X0016_CertificateIdForCentralDirectory", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X0017_StrongEncryptionHeader", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X0019_EncryptionRecipientCertificateList", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X5455_ExtendedTimestamp", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.X7875_NewUnix", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "org.apache.commons.compress.archivers.zip.Zip64ExtendedInformationExtraField", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "scala.Boolean" @@ -523,91 +740,201 @@ }, { "name": "sun.security.pkcs12.PKCS12KeyStore", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.pkcs12.PKCS12KeyStore$DualFormatPKCS12", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.DSA$SHA224withDSA", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.DSA$SHA256withDSA", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.JavaKeyStore$DualFormatJKS", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.JavaKeyStore$JKS", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.NativePRNG", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.SHA", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.SHA2$SHA224", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.SHA2$SHA256", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.SHA5$SHA384", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.SHA5$SHA512", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.X509Factory", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.provider.certpath.PKIXCertPathValidator", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.rsa.RSAKeyFactory$Legacy", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.rsa.RSAPSSSignature", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.rsa.RSASignature$SHA224withRSA", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.rsa.RSASignature$SHA256withRSA", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.ssl.KeyManagerFactoryImpl$SunX509", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.ssl.SSLContextImpl$DefaultSSLContext", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.ssl.SSLContextImpl$TLS12Context", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.ssl.TrustManagerFactoryImpl$PKIXFactory", - "methods": [{ "name": "", "parameterTypes": [] }] + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] }, { "name": "sun.security.util.ObjectIdentifier" diff --git a/engine/launcher/native-image-config/resource-config.json b/engine/launcher/native-image-config/resource-config.json index 044086ab6f..f78e9fc155 100644 --- a/engine/launcher/native-image-config/resource-config.json +++ b/engine/launcher/native-image-config/resource-config.json @@ -1,11 +1,23 @@ { "resources": [ - { "pattern": "\\QMETA-INF/MANIFEST.MF\\E" }, - { "pattern": "\\Qakka-http-version.conf\\E" }, - { "pattern": "\\Qapplication.conf\\E" }, - { "pattern": "\\Qorg/slf4j/impl/StaticLoggerBinder.class\\E" }, - { "pattern": "\\Qreference.conf\\E" }, - { "pattern": "\\Qversion.conf\\E" } + { + "pattern": "\\QMETA-INF/MANIFEST.MF\\E" + }, + { + "pattern": "\\Qakka-http-version.conf\\E" + }, + { + "pattern": "\\Qapplication.conf\\E" + }, + { + "pattern": "\\Qorg/slf4j/impl/StaticLoggerBinder.class\\E" + }, + { + "pattern": "\\Qreference.conf\\E" + }, + { + "pattern": "\\Qversion.conf\\E" + } ], "bundles": [] } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/CurrentVersion.scala b/engine/launcher/src/main/scala/org/enso/launcher/CurrentVersion.scala index 27806198d5..6b5ae93556 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/CurrentVersion.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/CurrentVersion.scala @@ -4,8 +4,7 @@ import buildinfo.Info import nl.gn0s1s.bump.SemVer import com.typesafe.scalalogging.Logger -/** - * Helper object that allows to get the current launcher version. +/** Helper object that allows to get the current launcher version. * * In development-mode it allows to override the returned version for testing * purposes. @@ -16,13 +15,11 @@ object CurrentVersion { throw new IllegalStateException("Cannot parse the built-in version.") } - /** - * Version of the launcher. + /** Version of the launcher. */ def version: SemVer = currentVersion - /** - * Override launcher version with the provided one. + /** Override launcher version with the provided one. * * Internal helper method used for testing. It should be called before any * calls to [[version]]. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/Environment.scala b/engine/launcher/src/main/scala/org/enso/launcher/Environment.scala index ec719310ac..ee441e949f 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/Environment.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/Environment.scala @@ -7,16 +7,14 @@ import com.typesafe.scalalogging.Logger import scala.util.Try -/** - * Gathers some helper methods querying the system environment. +/** Gathers some helper methods querying the system environment. * * The default implementations should be used most of the time, but it is a * trait so that the functions can be overridden in tests. */ trait Environment { - /** - * Returns a list of system-dependent plugin extensions. + /** Returns a list of system-dependent plugin extensions. * * By default, on Unix plugins should have no extensions. On Windows, `.exe` * `.bat` and `.cmd` are supported. @@ -26,8 +24,7 @@ trait Environment { Seq(".exe", ".bat", ".cmd") else Seq() - /** - * Returns a list of directories that can be ignored when traversing the + /** Returns a list of directories that can be ignored when traversing the * system PATH looking for plugins. * * These could be system directories that should not contain plguins anyway, @@ -36,8 +33,7 @@ trait Environment { def getIgnoredPathDirectories: Seq[Path] = if (OS.isWindows) Seq(Path.of("C:\\Windows")) else Seq() - /** - * Queries the system environment for the given variable that should + /** Queries the system environment for the given variable that should * represent a valid filesystem path. * * If it is not defined or is not a valid path, returns None. @@ -58,16 +54,14 @@ trait Environment { getEnvVar(key).flatMap(parsePathWithWarning) } - /** - * Returns the system PATH, if available. + /** Returns the system PATH, if available. */ def getSystemPath: Seq[Path] = getEnvVar("PATH") .map(_.split(File.pathSeparatorChar).toSeq.flatMap(safeParsePath)) .getOrElse(Seq()) - /** - * Returns the location of the HOME directory on Unix systems. + /** Returns the location of the HOME directory on Unix systems. * * Should not be called on Windows, as the concept of HOME should be handled * differently there. @@ -88,8 +82,7 @@ trait Environment { } } - /** - * Returns the location of the local application data directory + /** Returns the location of the local application data directory * (`%LocalAppData%`) on Windows. * * Should not be called on platforms other than Windows, as this concept is @@ -111,8 +104,7 @@ trait Environment { } } - /** - * Queries the system environment for the given variable. + /** Queries the system environment for the given variable. * * If it is not defined or empty, returns None. */ @@ -122,8 +114,7 @@ trait Environment { else Some(value) } - /** - * Tries to parse a path string and returns Some(path) on success. + /** Tries to parse a path string and returns Some(path) on success. * * We prefer silent failures here (returning None and skipping that entry), * as we don't want to fail the whole command if the PATH contains some @@ -132,8 +123,7 @@ trait Environment { private def safeParsePath(str: String): Option[Path] = Try(Path.of(str)).toOption - /** - * Returns the path to the running program. + /** Returns the path to the running program. * * It is intended for usage in native binary builds, where it returns the * path to the binary executable that is running. When running on the JVM, @@ -143,13 +133,11 @@ trait Environment { def getPathToRunningExecutable: Path } -/** - * The default [[Environment]] implementation. +/** The default [[Environment]] implementation. */ object Environment extends Environment { - /** - * @inheritdoc + /** @inheritdoc */ override def getPathToRunningExecutable: Path = executablePathOverride.getOrElse(executablePath) @@ -169,8 +157,7 @@ object Environment extends Environment { private var executablePathOverride: Option[Path] = None - /** - * Overrides the return value of [[getPathToRunningExecutable]] with the + /** Overrides the return value of [[getPathToRunningExecutable]] with the * provided path. * * Internal method used for testing. It should be called as early as diff --git a/engine/launcher/src/main/scala/org/enso/launcher/FileSystem.scala b/engine/launcher/src/main/scala/org/enso/launcher/FileSystem.scala index 758fba4b56..5522bcb8df 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/FileSystem.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/FileSystem.scala @@ -17,16 +17,14 @@ import scala.jdk.StreamConverters._ import scala.util.Using import com.typesafe.scalalogging.Logger -/** - * Gathers some helper methods that are used for interaction with the +/** Gathers some helper methods that are used for interaction with the * filesystem. */ object FileSystem { private val logger = Logger[FileSystem.type] - /** - * Returns a sequence of files in the given directory (without traversing it + /** Returns a sequence of files in the given directory (without traversing it * recursively). * * If the directory does not exist, returns an empty sequence. @@ -35,28 +33,24 @@ object FileSystem { if (!Files.exists(dir)) Seq() else Using(Files.list(dir))(_.toScala(Factory.arrayFactory).toSeq).get - /** - * Writes a String to a file at the given `path`, creating the file if + /** Writes a String to a file at the given `path`, creating the file if * necessary. */ def writeTextFile(path: Path, content: String): Unit = { Using(new PrintWriter(path.toFile)) { writer => writer.write(content) }.get } - /** - * Copies a directory recursively. + /** Copies a directory recursively. */ def copyDirectory(source: Path, destination: Path): Unit = FileUtils.copyDirectory(source.toFile, destination.toFile) - /** - * Copies a file, overwriting the destination if it already existed. + /** Copies a file, overwriting the destination if it already existed. */ def copyFile(source: Path, destination: Path): Unit = FileUtils.copyFile(source.toFile, destination.toFile) - /** - * Checks if the given `file` is executable and tries to fix it if it is not. + /** Checks if the given `file` is executable and tries to fix it if it is not. */ def ensureIsExecutable(file: Path): Unit = { if (!Files.isExecutable(file)) { @@ -79,8 +73,7 @@ object FileSystem { } } - /** - * Parses POSIX file permissions stored in a binary format into a set of Java + /** Parses POSIX file permissions stored in a binary format into a set of Java * enumerations corresponding to these permissions. */ def decodePOSIXPermissions(mode: Int): java.util.Set[PosixFilePermission] = { @@ -124,8 +117,7 @@ object FileSystem { res } - /** - * Runs the `action` with a parameter representing a temporary directory + /** Runs the `action` with a parameter representing a temporary directory * created for it. * * The temporary directory is removed afterwards. @@ -146,21 +138,18 @@ object FileSystem { } } - /** - * Removes a directory recursively. + /** Removes a directory recursively. */ def removeDirectory(dir: Path): Unit = FileUtils.deleteDirectory(dir.toFile) - /** - * Removes a directory recursively, does not fail if it does not exist. + /** Removes a directory recursively, does not fail if it does not exist. */ def removeDirectoryIfExists(dir: Path): Unit = if (Files.exists(dir)) FileUtils.deleteDirectory(dir.toFile) - /** - * Removes a directory only if it is empty. + /** Removes a directory only if it is empty. * * Returned value indicates if the directory has been removed. */ @@ -173,23 +162,20 @@ object FileSystem { false } - /** - * Removes a file, if it exists, does not fail if it does not exist. + /** Removes a file, if it exists, does not fail if it does not exist. */ def removeFileIfExists(path: Path): Unit = if (Files.exists(path)) Files.delete(path) - /** - * Registers the directory to be removed when the program exits normally. + /** Registers the directory to be removed when the program exits normally. * * The directory is only removed if it is empty. */ def removeEmptyDirectoryOnExit(dir: Path): Unit = dir.toFile.deleteOnExit() - /** - * Checks if the directory contains any entries. + /** Checks if the directory contains any entries. */ def isDirectoryEmpty(dir: Path): Boolean = { def hasEntries = @@ -197,8 +183,7 @@ object FileSystem { Files.isDirectory(dir) && !hasEntries } - /** - * Tries to move a directory from `source` to `destination` atomically. + /** Tries to move a directory from `source` to `destination` atomically. * * May not be actually atomic. */ @@ -207,8 +192,7 @@ object FileSystem { Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE) } - /** - * Syntax allowing to write nested paths in a more readable and concise way. + /** Syntax allowing to write nested paths in a more readable and concise way. */ implicit class PathSyntax(val path: Path) extends AnyVal { def /(other: String): Path = path.resolve(other) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/InfoLogger.scala b/engine/launcher/src/main/scala/org/enso/launcher/InfoLogger.scala index 025ef94379..60fd96d696 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/InfoLogger.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/InfoLogger.scala @@ -3,8 +3,7 @@ package org.enso.launcher import com.typesafe.scalalogging.Logger import org.enso.cli.CLIOutput -/** - * Handles displaying of user-facing information. +/** Handles displaying of user-facing information. * * Info-level messages are used to communicate with the user. They are handled * in a special way, so that they are displayed to the user regardless of @@ -14,8 +13,7 @@ object InfoLogger { private val logger = Logger("launcher") - /** - * Prints an info level message. + /** Prints an info level message. * * If the default logger is set-up to display info-messages, they are send to * the logger, otherwise they are printed to stdout. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/Launcher.scala b/engine/launcher/src/main/scala/org/enso/launcher/Launcher.scala index 175d532a34..40eeef2b0d 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/Launcher.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/Launcher.scala @@ -25,8 +25,7 @@ import org.enso.launcher.upgrade.LauncherUpgrader import org.enso.loggingservice.LogLevel import org.enso.version.{VersionDescription, VersionDescriptionParameter} -/** - * Implements launcher commands that are run from CLI and can be affected by +/** Implements launcher commands that are run from CLI and can be affected by * the global CLI options. * * @param cliOptions the global CLI options to use for the commands @@ -49,8 +48,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { private lazy val upgrader = LauncherUpgrader.default(cliOptions) upgrader.runCleanup(isStartup = true) - /** - * Creates a new project with the given `name` in the given `path`. + /** Creates a new project with the given `name` in the given `path`. * * If `path` is not set, the project is created in a directory called `name` * in the current directory. @@ -100,8 +98,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { exitCode } - /** - * Prints a list of installed engines. + /** Prints a list of installed engines. */ def listEngines(): Int = { for (engine <- componentsManager.listInstalledEngines()) { @@ -111,8 +108,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Prints a list of installed runtimes. + /** Prints a list of installed runtimes. */ def listRuntimes(): Int = { for (runtime <- componentsManager.listInstalledRuntimes()) { @@ -128,8 +124,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Prints a summary of installed components and their dependencies. + /** Prints a summary of installed components and their dependencies. */ def listSummary(): Int = { for (engine <- componentsManager.listInstalledEngines()) { @@ -143,8 +138,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Installs the specified engine `version`. + /** Installs the specified engine `version`. * * Also installs the required runtime if it wasn't already installed. */ @@ -158,8 +152,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Installs the latest available version of the engine. + /** Installs the latest available version of the engine. * * Also installs the required runtime if it wasn't already installed. */ @@ -169,8 +162,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { installEngine(latest) } - /** - * Uninstalls the specified engine `version`. + /** Uninstalls the specified engine `version`. * * If a runtime is not used by any engines anymore, it is also removed. */ @@ -180,8 +172,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Runs the Enso REPL. + /** Runs the Enso REPL. * * If ran outside of a project, uses the default configured version. If run * inside a project or provided with an explicit projectPath, the Enso @@ -217,8 +208,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { exitCode } - /** - * Runs an Enso script or project. + /** Runs an Enso script or project. * * If ran inside a project without a path, or with a path pointing to a * project, runs that project. If the provided path points to a file, that @@ -254,8 +244,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { exitCode } - /** - * Runs the Language Server. + /** Runs the Language Server. * * Unless overridden, uses the Enso version associated with the project * located at `options.path`. @@ -295,8 +284,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { exitCode } - /** - * Updates the global configuration. + /** Updates the global configuration. * * If `value` is an empty string, the `key` is removed from the configuration * (if it exists). If `value` is non-empty the key is added or updated in the @@ -320,8 +308,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Prints the value of `key` from the global configuration. + /** Prints the value of `key` from the global configuration. * * If the `key` is not set in the config, sets exit code to 1 and prints a * warning. @@ -337,8 +324,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { } } - /** - * Sets the default Enso version. + /** Sets the default Enso version. */ def setDefaultVersion(defaultVersion: DefaultVersion): Int = { configurationManager.updateConfig { config => @@ -358,16 +344,14 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Prints the default Enso version. + /** Prints the default Enso version. */ def printDefaultVersion(): Int = { println(configurationManager.defaultVersion) 0 } - /** - * Installs the Enso distribution. + /** Installs the Enso distribution. */ def installDistribution( doNotRemoveOldLauncher: Boolean, @@ -383,16 +367,14 @@ case class Launcher(cliOptions: GlobalCLIOptions) { 0 } - /** - * Uninstalls the Enso distribution. + /** Uninstalls the Enso distribution. */ def uninstallDistribution(): Int = { DistributionUninstaller.default(cliOptions).uninstall() 0 } - /** - * Displays the version string of the launcher. + /** Displays the version string of the launcher. * * @param hideEngineVersion if set, does not look for installed engines to * display the current version; this can be used to @@ -449,8 +431,7 @@ case class Launcher(cliOptions: GlobalCLIOptions) { ) } - /** - * Performs a self-upgrade. + /** Performs a self-upgrade. * * If a `version` is specified, installs that version. If the version is * older than the current one, a downgrade is performed. If no `version` is @@ -480,14 +461,12 @@ case class Launcher(cliOptions: GlobalCLIOptions) { } } -/** - * Gathers launcher commands which do not depend on the global CLI options. +/** Gathers launcher commands which do not depend on the global CLI options. */ object Launcher { private val workingDirectory: Path = Path.of(".") - /** - * Checks if the launcher is running in portable mode and exits if it is not. + /** Checks if the launcher is running in portable mode and exits if it is not. */ def ensurePortable(): Unit = { if (!DistributionManager.isRunningPortable) { diff --git a/engine/launcher/src/main/scala/org/enso/launcher/OS.scala b/engine/launcher/src/main/scala/org/enso/launcher/OS.scala index 5b91aede18..d56d77ce26 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/OS.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/OS.scala @@ -3,71 +3,59 @@ package org.enso.launcher import com.typesafe.scalalogging.Logger import io.circe.{Decoder, DecodingFailure} -/** - * Represents one of the supported platforms (operating systems). +/** Represents one of the supported platforms (operating systems). */ sealed trait OS { - /** - * Name of this operating system as included in the configuration. + /** Name of this operating system as included in the configuration. */ def configName: String - /** - * Checks if the provided `os.name` matches this operating system. + /** Checks if the provided `os.name` matches this operating system. */ def matches(osName: String): Boolean = osName.toLowerCase.contains(configName) } -/** - * Gathers helper functions useful for dealing with platform-specific +/** Gathers helper functions useful for dealing with platform-specific * behaviour. */ object OS { private val logger = Logger[OS.type] - /** - * Represents the Linux operating system. + /** Represents the Linux operating system. */ case object Linux extends OS { - /** - * @inheritdoc + /** @inheritdoc */ def configName: String = "linux" } - /** - * Represents the macOS operating system. + /** Represents the macOS operating system. */ case object MacOS extends OS { - /** - * @inheritdoc + /** @inheritdoc */ def configName: String = "macos" - /** - * @inheritdoc + /** @inheritdoc */ override def matches(osName: String): Boolean = osName.toLowerCase.contains("mac") } - /** - * Represents the Windows operating system. + /** Represents the Windows operating system. */ case object Windows extends OS { - /** - * @inheritdoc + /** @inheritdoc */ def configName: String = "windows" } - /** - * Checks if the application is being run on Windows. + /** Checks if the application is being run on Windows. */ def isWindows: Boolean = operatingSystem == OS.Windows @@ -75,8 +63,7 @@ object OS { def isUNIX: Boolean = operatingSystem == OS.Linux || operatingSystem == OS.MacOS - /** - * Returns which [[OS]] this program is running on. + /** Returns which [[OS]] this program is running on. */ lazy val operatingSystem: OS = detectOS @@ -124,8 +111,7 @@ object OS { } } - /** - * Name of the architecture that the program is running on. + /** Name of the architecture that the program is running on. * * Currently the Launcher Native Image builds only support amd64 * architecture, so it is hardcoded here. In the future, more architectures @@ -138,15 +124,13 @@ object OS { */ val architecture: String = "amd64" - /** - * Wraps the base executable name with an optional platform-dependent + /** Wraps the base executable name with an optional platform-dependent * extension. */ def executableName(baseName: String): String = if (isWindows) baseName + ".exe" else baseName - /** - * A [[Decoder]] instance allowing to parse the OS name from JSON and YAML + /** A [[Decoder]] instance allowing to parse the OS name from JSON and YAML * configuration. */ implicit val decoder: Decoder[OS] = { json => diff --git a/engine/launcher/src/main/scala/org/enso/launcher/archive/Archive.scala b/engine/launcher/src/main/scala/org/enso/launcher/archive/Archive.scala index 1f5997bdbe..9e4df9723d 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/archive/Archive.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/archive/Archive.scala @@ -25,8 +25,7 @@ import org.enso.launcher.{FileSystem, OS} import scala.util.{Try, Using} -/** - * Contains utilities related to the extraction of various archive file +/** Contains utilities related to the extraction of various archive file * formats. * * Currently it supports extracting ZIP files and gzipped TAR archives. @@ -35,8 +34,7 @@ object Archive { private val logger = Logger[Archive.type] - /** - * Extracts the archive at `archivePath` to `destinationDirectory`. + /** Extracts the archive at `archivePath` to `destinationDirectory`. * * Behaves in the same way as the other [[extractArchive]] overload, but it * tries to determine the archive format automatically based on the filename. @@ -73,8 +71,7 @@ object Archive { } } - /** - * Extracts the archive at `archivePath` to `destinationDirectory`. + /** Extracts the archive at `archivePath` to `destinationDirectory`. * * The extraction is run in a background thread, the function returns * immediately with a [[TaskProgress]] instance that can be used to track @@ -113,8 +110,7 @@ object Archive { } } - /** - * Iterates over entries of the archive at `archivePath`. + /** Iterates over entries of the archive at `archivePath`. * * The iteration is run in a background thread, the function returns * immediately with a [[TaskProgress]] instance that can be used to track @@ -143,8 +139,7 @@ object Archive { } } - /** - * Iterates over entries of the archive at `archivePath`. + /** Iterates over entries of the archive at `archivePath`. * * The iteration is run in a background thread, the function returns * immediately with a [[TaskProgress]] instance that can be used to track @@ -239,8 +234,7 @@ object Archive { taskProgress } - /** - * Tries to get the POSIX file permissions associated with that `entry`. + /** Tries to get the POSIX file permissions associated with that `entry`. */ private def getMode(entry: ApacheArchiveEntry): Option[Int] = entry match { @@ -254,8 +248,7 @@ object Archive { None } - /** - * Opens the archive at `path` and executes the provided action. + /** Opens the archive at `path` and executes the provided action. * * The action is given an [[ArchiveInputStream]] that can be used to read * from the archive and a [[ReadProgress]] instance which indicates how many @@ -286,8 +279,7 @@ object Archive { } } - /** - * Parses the name of the entry inside of the archive into a relative path. + /** Parses the name of the entry inside of the archive into a relative path. * * The specification does not restrict entry names to valid paths, but * empirical testing shows that paths in the archives we need to support are diff --git a/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveEntry.scala b/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveEntry.scala index 6a9a9c8413..e6aa715421 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveEntry.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveEntry.scala @@ -2,26 +2,22 @@ package org.enso.launcher.archive import java.nio.file.Path -/** - * An archive entry that is provided to the callback when iterating over an +/** An archive entry that is provided to the callback when iterating over an * archive. */ trait ArchiveEntry { - /** - * Specifies if the entry represents a directory. + /** Specifies if the entry represents a directory. * * If false, it represents a normal file. */ def isDirectory: Boolean - /** - * Relative path of the entry inside of the archive. + /** Relative path of the entry inside of the archive. */ def relativePath: Path - /** - * Extracts the entry to the provided destination. + /** Extracts the entry to the provided destination. * * The destination specifies the full path to the extracted entry including * its new filename, not just a parent directory. On UNIX platforms, the diff --git a/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveFormat.scala b/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveFormat.scala index c03a9f7bee..8f8ec286e0 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveFormat.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/archive/ArchiveFormat.scala @@ -2,24 +2,20 @@ package org.enso.launcher.archive import java.nio.file.Path -/** - * Enumeration of supported archive formats. +/** Enumeration of supported archive formats. */ sealed trait ArchiveFormat object ArchiveFormat { - /** - * ZIP file format. + /** ZIP file format. */ case object ZIP extends ArchiveFormat - /** - * Represents a gzipped TAR archive. + /** Represents a gzipped TAR archive. */ case object TarGz extends ArchiveFormat - /** - * Tries to infer one of the supported archive formats based on the filename. + /** Tries to infer one of the supported archive formats based on the filename. * * Returns None if it is unable to determine a known format. */ diff --git a/engine/launcher/src/main/scala/org/enso/launcher/archive/FileProgressInputStream.scala b/engine/launcher/src/main/scala/org/enso/launcher/archive/FileProgressInputStream.scala index 4d9f0a47fd..c871b4ffd2 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/archive/FileProgressInputStream.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/archive/FileProgressInputStream.scala @@ -5,14 +5,12 @@ import java.nio.file.{Files, Path} import org.enso.launcher.internal.ProgressInputStream -/** - * A helper that allows to create a [[ProgressInputStream]] for a file located +/** A helper that allows to create a [[ProgressInputStream]] for a file located * at the given path. */ object FileProgressInputStream { - /** - * Creates a [[ProgressInputStream]] reading from the file at `path`. + /** Creates a [[ProgressInputStream]] reading from the file at `path`. * * The read progress depends on how many bytes have been read from the file. * The total size is determined from the file size as returned by the diff --git a/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/ArchiveIterator.scala b/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/ArchiveIterator.scala index b31ac7926a..0a93e5d584 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/ArchiveIterator.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/ArchiveIterator.scala @@ -2,24 +2,21 @@ package org.enso.launcher.archive.internal import org.apache.commons.compress.archivers.{ArchiveEntry, ArchiveInputStream} -/** - * Wraps an [[ArchiveInputStream]] to get an [[Iterator]] which produces +/** Wraps an [[ArchiveInputStream]] to get an [[Iterator]] which produces * non-null archive entries. */ case class ArchiveIterator( archiveInputStream: ArchiveInputStream ) extends Iterator[ArchiveEntry] { - /** - * @inheritdoc + /** @inheritdoc */ override def hasNext: Boolean = { findNext() nextEntry.isDefined } - /** - * @inheritdoc + /** @inheritdoc */ override def next(): ArchiveEntry = { findNext() @@ -35,8 +32,7 @@ case class ArchiveIterator( private var nextEntry: Option[ArchiveEntry] = None private var finished: Boolean = false - /** - * Tries to move to the next entry. If it is `null` then it means the + /** Tries to move to the next entry. If it is `null` then it means the * [[archiveInputStream]] has run out of entries. */ private def findNext(): Unit = { diff --git a/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/BaseRenamer.scala b/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/BaseRenamer.scala index c09d0e32f3..d6b4ffa64f 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/BaseRenamer.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/archive/internal/BaseRenamer.scala @@ -2,8 +2,7 @@ package org.enso.launcher.archive.internal import java.nio.file.Path -/** - * Acts as a function that renames the base of the provided paths to the +/** Acts as a function that renames the base of the provided paths to the * `newBase`. * * It changes the first component of the provided paths to the provided @@ -16,8 +15,7 @@ import java.nio.file.Path class BaseRenamer(newBase: Path) extends (Path => Path) { var lastRoot: Option[Path] = None - /** - * Changes the path by renaming its base component. + /** Changes the path by renaming its base component. */ override def apply(path: Path): Path = { if (path.getNameCount < 1) { diff --git a/engine/launcher/src/main/scala/org/enso/launcher/cli/Arguments.scala b/engine/launcher/src/main/scala/org/enso/launcher/cli/Arguments.scala index 38a1c70276..d8c0d45d55 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/cli/Arguments.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/cli/Arguments.scala @@ -7,8 +7,7 @@ import org.enso.loggingservice.LogLevel object Arguments { - /** - * [[Argument]] instance that tries to parse the String as a [[SemVer]] + /** [[Argument]] instance that tries to parse the String as a [[SemVer]] * version string. */ implicit val semverArgument: Argument[SemVer] = (string: String) => diff --git a/engine/launcher/src/main/scala/org/enso/launcher/cli/GlobalCLIOptions.scala b/engine/launcher/src/main/scala/org/enso/launcher/cli/GlobalCLIOptions.scala index 33b2667763..822ed9622d 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/cli/GlobalCLIOptions.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/cli/GlobalCLIOptions.scala @@ -5,8 +5,7 @@ import org.enso.cli.arguments.{Argument, OptsParseError} import org.enso.launcher.cli.GlobalCLIOptions.InternalOptions import org.enso.loggingservice.LogLevel -/** - * Gathers settings set by the global CLI options. +/** Gathers settings set by the global CLI options. * * @param autoConfirm if this flag is set, the program should not ask the user * any questions but proceed with the default values, that @@ -33,8 +32,7 @@ object GlobalCLIOptions { val USE_JSON = "json" val COLOR_MODE = "color" - /** - * Internal options that are remembered to pass them to launcher child + /** Internal options that are remembered to pass them to launcher child * processes. */ case class InternalOptions( @@ -42,8 +40,7 @@ object GlobalCLIOptions { loggerConnectUri: Option[Uri] ) { - /** - * Creates command line options that can be passed to a launcher process to + /** Creates command line options that can be passed to a launcher process to * set the same options. */ def toOptions: Seq[String] = { @@ -60,8 +57,7 @@ object GlobalCLIOptions { val LOG_LEVEL = "launcher-log-level" val CONNECT_LOGGER = "internal-connect-logger" - /** - * Converts the [[GlobalCLIOptions]] to a sequence of arguments that can be + /** Converts the [[GlobalCLIOptions]] to a sequence of arguments that can be * added to a launcher invocation to set the same options. */ def toOptions(config: GlobalCLIOptions): Seq[String] = { @@ -74,24 +70,20 @@ object GlobalCLIOptions { } } -/** - * Describes possible modes of color display in console output. +/** Describes possible modes of color display in console output. */ sealed trait ColorMode object ColorMode { - /** - * Never use color escape sequences in the output. + /** Never use color escape sequences in the output. */ case object Never extends ColorMode - /** - * Enable color output if it seems to be supported. + /** Enable color output if it seems to be supported. */ case object Auto extends ColorMode - /** - * Always use escape sequences in the output, even if the program thinks they + /** Always use escape sequences in the output, even if the program thinks they * are unsupported. * * May be useful if output is piped to other programs that know how to handle @@ -99,8 +91,7 @@ object ColorMode { */ case object Always extends ColorMode - /** - * [[Argument]] instance used to parse [[ColorMode]] from CLI. + /** [[Argument]] instance used to parse [[ColorMode]] from CLI. */ implicit val argument: Argument[ColorMode] = { case "never" => Right(Never) @@ -115,8 +106,7 @@ object ColorMode { ) } - /** - * Creates command line options that can be passed to a launcher process to + /** Creates command line options that can be passed to a launcher process to * inherit our color mode. */ def toOptions(colorMode: ColorMode): Seq[String] = { diff --git a/engine/launcher/src/main/scala/org/enso/launcher/cli/InternalOpts.scala b/engine/launcher/src/main/scala/org/enso/launcher/cli/InternalOpts.scala index bc309480bd..ec4b0dd001 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/cli/InternalOpts.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/cli/InternalOpts.scala @@ -13,8 +13,7 @@ import org.enso.launcher.releases.EnsoRepository import org.enso.launcher.upgrade.LauncherUpgrader import org.enso.launcher.{CurrentVersion, Environment, FileSystem, OS} -/** - * Implements internal options that the launcher may use when running another +/** Implements internal options that the launcher may use when running another * instance of itself. * * These options are used primarily to implement workarounds for @@ -78,8 +77,7 @@ object InternalOpts { private var inheritEmulateRepository: Option[Path] = None private var inheritShouldWaitForAssets: Boolean = false - /** - * Removes internal testing options that should not be preserved in the called executable. + /** Removes internal testing options that should not be preserved in the called executable. * * In release mode, this is an identity function, since these internal options are not permitted anyway. */ @@ -109,8 +107,7 @@ object InternalOpts { } } - /** - * Additional top level options that are internal to the launcher and should + /** Additional top level options that are internal to the launcher and should * not be used by users directly. * * They are used to implement workarounds for install / upgrade on Windows. @@ -189,8 +186,7 @@ object InternalOpts { } } - /** - * Internal options used for testing. + /** Internal options used for testing. * * Disabled in release mode. */ @@ -231,8 +227,7 @@ object InternalOpts { } - /** - * Specifies options that are inherited by the process that is launched when + /** Specifies options that are inherited by the process that is launched when * continuing the upgrade. */ private def optionsToInherit: Seq[String] = { @@ -247,21 +242,18 @@ object InternalOpts { repositoryPath ++ waitForAssets } - /** - * Returns a helper class that allows to run the launcher located at the + /** Returns a helper class that allows to run the launcher located at the * provided path invoking the internal options. */ def runWithNewLauncher(pathToNewLauncher: Path): Runner = new Runner(pathToNewLauncher) - /** - * A helper class used for running the workarounds using another launcher + /** A helper class used for running the workarounds using another launcher * executable. */ class Runner private[InternalOpts] (pathToNewLauncher: Path) { - /** - * Tells the installed launcher to try to remove the old launcher + /** Tells the installed launcher to try to remove the old launcher * executable. * * It retries for a few seconds to give the process running the old @@ -284,8 +276,7 @@ object InternalOpts { ) } - /** - * Tells the temporary launcher to remove the original launcher executable + /** Tells the temporary launcher to remove the original launcher executable * and possibly its parent directory. * * The parent directory is removed if it is empty or only contains an empty @@ -304,15 +295,14 @@ object InternalOpts { Seq(s"--$FINISH_UNINSTALL_PARENT", parent.toAbsolutePath.toString) ) val command = Seq( - pathToNewLauncher.toAbsolutePath.toString, - s"--$FINISH_UNINSTALL", - executablePath.toAbsolutePath.toString - ) ++ parentParam.getOrElse(Seq()) + pathToNewLauncher.toAbsolutePath.toString, + s"--$FINISH_UNINSTALL", + executablePath.toAbsolutePath.toString + ) ++ parentParam.getOrElse(Seq()) runDetachedAndExit(command) } - /** - * Tells the launcher to continue a multi-step upgrade. + /** Tells the launcher to continue a multi-step upgrade. * * Creates an instance of [[LauncherUpgrader]] and invokes * [[LauncherUpgrader.internalContinueUpgrade]]. @@ -331,20 +321,19 @@ object InternalOpts { val inheritOpts = GlobalCLIOptions.toOptions(globalCLIOptions) ++ optionsToInherit val command = Seq( - pathToNewLauncher.toAbsolutePath.toString, - s"--$CONTINUE_UPGRADE", - targetVersion.toString, - s"--$UPGRADE_ORIGINAL_PATH", - originalPath.toAbsolutePath.normalize.toString - ) ++ inheritOpts + pathToNewLauncher.toAbsolutePath.toString, + s"--$CONTINUE_UPGRADE", + targetVersion.toString, + s"--$UPGRADE_ORIGINAL_PATH", + originalPath.toAbsolutePath.normalize.toString + ) ++ inheritOpts runAndWaitForResult(command) } } private val retryBaseAmount = 30 - /** - * Tries to remove the file at `oldExecutablePath`, retrying several times if + /** Tries to remove the file at `oldExecutablePath`, retrying several times if * needed. * * On failure retries every 0.5s for 15s in total. That retry mechanism is in diff --git a/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherApplication.scala b/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherApplication.scala index 281e0e6b73..4486aa0ca1 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherApplication.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherApplication.scala @@ -22,8 +22,7 @@ import org.enso.launcher.installation.{ import org.enso.launcher.locking.DefaultResourceManager import org.enso.loggingservice.LogLevel -/** - * Defines the CLI commands and options for the program. +/** Defines the CLI commands and options for the program. * * Each command is parametrized with a config that describes global CLI options * set at the top-level and returns an integer which determines the programs @@ -571,8 +570,7 @@ object LauncherApplication { } } - /** - * Application initializer that is run after handling of the internal + /** Application initializer that is run after handling of the internal * options. */ private def initializeApp(): Unit = { diff --git a/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherLogging.scala b/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherLogging.scala index 344b981568..0ffdce5813 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherLogging.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/cli/LauncherLogging.scala @@ -17,19 +17,16 @@ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, Future, Promise} -/** - * Manages setting up the logging service within the launcher. +/** Manages setting up the logging service within the launcher. */ object LauncherLogging { private val logger = Logger[LauncherLogging.type] - /** - * Default logl level to use if none is provided. + /** Default logl level to use if none is provided. */ val defaultLogLevel: LogLevel = LogLevel.Warning - /** - * Sets up launcher's logging service as either a server that gathers other + /** Sets up launcher's logging service as either a server that gathers other * component's logs or a client that forwards them further. * * Forwarding logs to another server in the launcher is an internal, @@ -60,8 +57,7 @@ object LauncherLogging { } } - /** - * Sets up a fallback logger that just logs to stderr. + /** Sets up a fallback logger that just logs to stderr. * * It can be used when the application has failed to parse the CLI options * and does not know which logger to set up. @@ -77,8 +73,7 @@ object LauncherLogging { private val loggingServiceEndpointPromise = Promise[Option[Uri]]() - /** - * Returns a [[Uri]] of the logging service that launched components can + /** Returns a [[Uri]] of the logging service that launched components can * connect to. * * Points to the local server if it has been set up, or to the endpoint that @@ -90,8 +85,7 @@ object LauncherLogging { def loggingServiceEndpoint(): Future[Option[Uri]] = loggingServiceEndpointPromise.future - /** - * Returns a printer for outputting the logs to the standard error. + /** Returns a printer for outputting the logs to the standard error. */ private def stderrPrinter( globalCLIOptions: GlobalCLIOptions, @@ -113,8 +107,7 @@ object LauncherLogging { val printExceptionsInStderr = implicitly[Ordering[LogLevel]].compare(logLevel, LogLevel.Debug) >= 0 - /** - * Creates a stderr printer and a file printer if a log file can be opened. + /** Creates a stderr printer and a file printer if a log file can be opened. * * This is a `def` on purpose, as even if the service fails, the printers * are shut down, so the fallback must create new instances. @@ -170,8 +163,7 @@ object LauncherLogging { } } - /** - * Connects this launcher to an external logging service. + /** Connects this launcher to an external logging service. * * Currently, this is an internal function used mostly for testing purposes. * It is not a user-facing API. @@ -208,8 +200,7 @@ object LauncherLogging { } } - /** - * Waits until the logging service has been set-up. + /** Waits until the logging service has been set-up. * * Due to limitations of how the logging service is implemented, it can only * be terminated after it has been set up. @@ -218,8 +209,7 @@ object LauncherLogging { Await.ready(loggingServiceEndpointPromise.future, 5.seconds) } - /** - * Turns off the main logging service, falling back to just a stderr backend. + /** Turns off the main logging service, falling back to just a stderr backend. * * This method should be called as part of uninstalling the distribution. The * server can be safely shutdown as during uninstallation no other components @@ -235,8 +225,7 @@ object LauncherLogging { ) } - /** - * Shuts down the logging service gracefully. + /** Shuts down the logging service gracefully. */ def tearDown(): Unit = LoggingServiceManager.tearDown() diff --git a/engine/launcher/src/main/scala/org/enso/launcher/cli/Main.scala b/engine/launcher/src/main/scala/org/enso/launcher/cli/Main.scala index ca7572a8b8..b2c7be8c21 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/cli/Main.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/cli/Main.scala @@ -5,8 +5,7 @@ import org.enso.cli.CLIOutput import org.enso.launcher.locking.DefaultResourceManager import org.enso.launcher.upgrade.LauncherUpgrader -/** - * Defines the entry point for the launcher. +/** Defines the entry point for the launcher. */ object Main { private def setup(): Unit = @@ -27,8 +26,7 @@ object Main { private val logger = Logger[Main.type] - /** - * Entry point of the application. + /** Entry point of the application. */ def main(args: Array[String]): Unit = { setup() @@ -46,8 +44,7 @@ object Main { exit(exitCode) } - /** - * Exits the program in a safe way. + /** Exits the program in a safe way. * * This should be used ofer `sys.exit` to ensure that all services are * terminated gracefully and locks are released quickly (as the OS cleanup diff --git a/engine/launcher/src/main/scala/org/enso/launcher/cli/PluginManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/cli/PluginManager.scala index 2e19091feb..319a9c7645 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/cli/PluginManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/cli/PluginManager.scala @@ -9,14 +9,12 @@ import org.enso.launcher.{Environment, FileSystem} import scala.sys.process._ import scala.util.Try -/** - * Implements an [[arguments.PluginManager]] using the given +/** Implements an [[arguments.PluginManager]] using the given * [[Environment]]. */ class PluginManager(env: Environment) extends arguments.PluginManager { - /** - * Checks if the provided name represents a valid plugin and tries to run it. + /** Checks if the provided name represents a valid plugin and tries to run it. * * @param name name of the plugin * @param args arguments that should be passed to it @@ -36,16 +34,14 @@ class PluginManager(env: Environment) extends arguments.PluginManager { ) } - /** - * @inheritdoc + /** @inheritdoc */ override def hasPlugin(name: String): Boolean = findPlugin(name).isDefined private val pluginPrefix = "enso-" private val synopsisOption: String = "--synopsis" - /** - * Traverses all directories in the system PATH, looking for executable files + /** Traverses all directories in the system PATH, looking for executable files * which names start with `enso-`. A valid plugin must support a `synopsis` * option, i.e. running `enso-foo --synopsis` should return a short * description of the plugin and return with exit code 0 for the plugin to be @@ -65,13 +61,11 @@ class PluginManager(env: Environment) extends arguments.PluginManager { } yield CommandHelp(pluginName, description.synopsis) } - /** - * @inheritdoc + /** @inheritdoc */ override def pluginsNames(): Seq[String] = pluginsHelp().map(_.name) - /** - * A short description of a plugin consisting of its command name and + /** A short description of a plugin consisting of its command name and * synopsis. */ case class PluginDescription(executableName: String, synopsis: String) @@ -80,8 +74,7 @@ class PluginManager(env: Environment) extends arguments.PluginManager { : collection.mutable.HashMap[String, Option[PluginDescription]] = collection.mutable.HashMap.empty - /** - * Checks if the plugin with the given name is installed and valid. + /** Checks if the plugin with the given name is installed and valid. * * It tries to execute it (checking various command extensions depending on * the OS) and check if it returns a synopsis. @@ -121,8 +114,7 @@ class PluginManager(env: Environment) extends arguments.PluginManager { None } - /** - * Returns a sequence of possible commands a plugin with the given name may + /** Returns a sequence of possible commands a plugin with the given name may * be called by. */ private def pluginCommandsForName(name: String): Seq[String] = @@ -144,8 +136,7 @@ class PluginManager(env: Environment) extends arguments.PluginManager { } } -/** - * Default implementation of the [[PluginManager]] using the default +/** Default implementation of the [[PluginManager]] using the default * [[Environment]]. */ object PluginManager extends PluginManager(Environment) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsException.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsException.scala index 6b66d5d37e..cfe5db217c 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsException.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsException.scala @@ -4,14 +4,12 @@ import nl.gn0s1s.bump.SemVer import org.enso.launcher.CurrentVersion import org.enso.launcher.cli.GlobalCLIOptions -/** - * A base class for exceptions caused by [[ComponentsManager]] logic. +/** A base class for exceptions caused by [[ComponentsManager]] logic. */ sealed class ComponentsException(message: String, cause: Throwable = null) extends RuntimeException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = { val causeMessage = if (cause != null) s" (Caused by: $cause)" else "" @@ -19,20 +17,17 @@ sealed class ComponentsException(message: String, cause: Throwable = null) } } -/** - * Represents an installation failure. +/** Represents an installation failure. */ case class InstallationError(message: String, cause: Throwable = null) extends ComponentsException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = s"Installation failed: $message" } -/** - * Indicates that a requested engine version requires a newer launcher version. +/** Indicates that a requested engine version requires a newer launcher version. * * This error can be recovered by * [[org.enso.launcher.upgrade.LauncherUpgrader.recoverUpgradeRequiredErrors]] @@ -51,8 +46,7 @@ case class LauncherUpgradeRequiredError( s"$expectedLauncherVersion" ) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = s"This launcher version is ${CurrentVersion.version}, but " + @@ -60,14 +54,12 @@ case class LauncherUpgradeRequiredError( s"to use it, upgrade the launcher with `enso upgrade`." } -/** - * Indicates a component is not recognized. +/** Indicates a component is not recognized. */ case class UnrecognizedComponentError(message: String, cause: Throwable = null) extends ComponentsException(message, cause) -/** - * Indicates that the component is installed, but its installation is +/** Indicates that the component is installed, but its installation is * corrupted. * * Most common reason for this exception is that some critical files are @@ -76,8 +68,7 @@ case class UnrecognizedComponentError(message: String, cause: Throwable = null) case class CorruptedComponentError(message: String, cause: Throwable = null) extends ComponentsException(message, cause) -/** - * Indicates the requested component is not installed. +/** Indicates the requested component is not installed. */ case class ComponentMissingError(message: String, cause: Throwable = null) extends ComponentsException(message, cause) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsManager.scala index 4f0e7e408a..cb36b74e35 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/ComponentsManager.scala @@ -26,8 +26,7 @@ import org.enso.launcher.{FileSystem, InfoLogger} import scala.util.control.NonFatal import scala.util.{Failure, Success, Try, Using} -/** - * Manages runtime and engine components. +/** Manages runtime and engine components. * * Allows to find, list, install and uninstall components. * @@ -49,16 +48,14 @@ class ComponentsManager( private val showProgress = !cliOptions.hideProgress private val logger = Logger[ComponentsManager] - /** - * Tries to find runtime for the provided engine. + /** Tries to find runtime for the provided engine. * * Returns None if the runtime is missing. */ def findRuntime(engine: Engine): Option[Runtime] = findRuntime(engine.manifest.runtimeVersion) - /** - * Finds an installed runtime with the given `version`. + /** Finds an installed runtime with the given `version`. * * Returns None if that version is not installed. */ @@ -70,25 +67,23 @@ class ComponentsManager( // corrupted, in #1052 offer to repair the broken installation loadGraalRuntime(path) .map(Some(_)) - .recoverWith { - case e: Exception => - Failure( - UnrecognizedComponentError( - s"The runtime $version is already installed, but cannot be " + - s"loaded due to $e. Until the launcher gets an auto-repair " + - s"feature, please try reinstalling the runtime by " + - s"uninstalling all engines that use it and installing them " + - s"again, or manually removing `$path`.", - e - ) + .recoverWith { case e: Exception => + Failure( + UnrecognizedComponentError( + s"The runtime $version is already installed, but cannot be " + + s"loaded due to $e. Until the launcher gets an auto-repair " + + s"feature, please try reinstalling the runtime by " + + s"uninstalling all engines that use it and installing them " + + s"again, or manually removing `$path`.", + e ) + ) } .get } else None } - /** - * Executes the provided action with a requested engine version. + /** Executes the provided action with a requested engine version. * * The engine is locked with a shared lock, so it is guaranteed that it will * not be uninstalled while the action is being executed. @@ -119,8 +114,7 @@ class ComponentsManager( } } - /** - * Executes the provided action with a requested engine version and its + /** Executes the provided action with a requested engine version and its * corresponding runtime. * * The components are locked with a shared lock, so it is guaranteed that @@ -167,8 +161,7 @@ class ComponentsManager( } } - /** - * Returns the runtime needed for the given engine, trying to install it if + /** Returns the runtime needed for the given engine, trying to install it if * it is missing. * * @param engine the engine for which the runtime is requested @@ -209,8 +202,7 @@ class ComponentsManager( } } - /** - * Finds an installed engine with the given `version` and reports any errors. + /** Finds an installed engine with the given `version` and reports any errors. */ private def getEngine(version: SemVer): Try[Engine] = { val name = engineNameForVersion(version) @@ -222,8 +214,7 @@ class ComponentsManager( } else Failure(ComponentMissingError(s"Engine $version is not installed.")) } - /** - * Finds an engine with the given `version` or returns None if it is not + /** Finds an engine with the given `version` or returns None if it is not * installed. * * Any other errors regarding loading the engine are thrown. @@ -257,8 +248,7 @@ class ComponentsManager( } .get - /** - * Returns the engine needed with the given version, trying to install it if + /** Returns the engine needed with the given version, trying to install it if * it is missing. * * @param version the requested engine version @@ -300,14 +290,12 @@ class ComponentsManager( } } - /** - * Finds installed engines that use the given `runtime`. + /** Finds installed engines that use the given `runtime`. */ def findEnginesUsingRuntime(runtime: Runtime): Seq[Engine] = listInstalledEngines().filter(_.manifest.runtimeVersion == runtime.version) - /** - * Lists all installed runtimes. + /** Lists all installed runtimes. */ def listInstalledRuntimes(): Seq[Runtime] = FileSystem @@ -315,8 +303,7 @@ class ComponentsManager( .map(path => (path, loadGraalRuntime(path))) .flatMap(handleErrorsAsWarnings[Runtime]("A runtime")) - /** - * Lists all installed engines. + /** Lists all installed engines. * @return */ def listInstalledEngines(): Seq[Engine] = { @@ -326,8 +313,7 @@ class ComponentsManager( .flatMap(handleErrorsAsWarnings[Engine]("An engine")) } - /** - * A helper function that is used when listing components. + /** A helper function that is used when listing components. * * A component error is non-fatal in context of listing, so it is issued as a * warning and the component is treated as non-existent in the list. @@ -345,15 +331,13 @@ class ComponentsManager( case (_, Success(value)) => Seq(value) } - /** - * Finds the latest released version of the engine, by asking the + /** Finds the latest released version of the engine, by asking the * [[engineReleaseProvider]]. */ def fetchLatestEngineVersion(): SemVer = engineReleaseProvider.findLatestVersion().get - /** - * Uninstalls the engine with the provided `version` (if it was installed). + /** Uninstalls the engine with the provided `version` (if it was installed). */ def uninstallEngine(version: SemVer): Unit = resourceManager.withResources( @@ -370,8 +354,7 @@ class ComponentsManager( cleanupRuntimes() } - /** - * Installs the engine with the provided version. + /** Installs the engine with the provided version. * * Used internally by [[findOrInstallEngine]]. Does not check if the engine * is already installed. @@ -490,8 +473,7 @@ class ComponentsManager( ) } - /** - * Finalizes the installation. + /** Finalizes the installation. * * Has to be called with an acquired lock for the runtime. If * `wasJustInstalled` is true, the lock must be exclusive and it the @@ -525,8 +507,7 @@ class ComponentsManager( val runtimeVersion = temporaryEngine.graalRuntimeVersion - /** - * Tries to finalize the installation assuming that the runtime was + /** Tries to finalize the installation assuming that the runtime was * installed and without acquiring an unnecessary exclusive lock. */ def getEngineIfRuntimeIsInstalled: Option[Engine] = @@ -539,8 +520,7 @@ class ComponentsManager( } } - /** - * Finalizes the installation, installing the runtime if necessary. + /** Finalizes the installation, installing the runtime if necessary. * This variant acquires an exclusive lock on the runtime (but it * should generally be called only if the runtime was not installed). */ @@ -565,20 +545,17 @@ class ComponentsManager( } } - /** - * Returns name of the directory containing the engine of that version. + /** Returns name of the directory containing the engine of that version. */ private def engineNameForVersion(version: SemVer): String = version.toString - /** - * Returns name of the directory containing the runtime of that version. + /** Returns name of the directory containing the runtime of that version. */ private def runtimeNameForVersion(version: RuntimeVersion): String = s"graalvm-ce-java${version.java}-${version.graal}" - /** - * Loads the GraalVM runtime definition. + /** Loads the GraalVM runtime definition. */ private def loadGraalRuntime(path: Path): Try[Runtime] = { val name = path.getFileName.toString @@ -593,8 +570,7 @@ class ComponentsManager( } yield runtime } - /** - * Gets the runtime version from its name. + /** Gets the runtime version from its name. */ private def parseGraalRuntimeVersionString( name: String @@ -619,8 +595,7 @@ class ComponentsManager( } } - /** - * Loads the engine definition. + /** Loads the engine definition. */ private def loadEngine(path: Path): Try[Engine] = for { @@ -630,8 +605,7 @@ class ComponentsManager( _ <- engine.ensureValid() } yield engine - /** - * Gets the engine version from its path. + /** Gets the engine version from its path. */ private def parseEngineVersion(path: Path): Try[SemVer] = { val name = path.getFileName.toString @@ -644,8 +618,7 @@ class ComponentsManager( .toTry } - /** - * Loads the engine manifest, checking if that release is compatible with the + /** Loads the engine manifest, checking if that release is compatible with the * currently running launcher. */ private def loadAndCheckEngineManifest(path: Path): Try[Manifest] = { @@ -661,8 +634,7 @@ class ComponentsManager( } } - /** - * Installs the runtime with the provided version. + /** Installs the runtime with the provided version. * * Does not check if the runtime is already installed. * @@ -740,8 +712,7 @@ class ComponentsManager( private def graalDirectoryForVersion(version: RuntimeVersion): Path = Path.of(s"graalvm-ce-java${version.java}-${version.graal}") - /** - * Removes runtimes that are not used by any installed engines. + /** Removes runtimes that are not used by any installed engines. * * The caller must hold [[Resource.AddOrRemoveComponents]] exclusively. */ @@ -757,8 +728,7 @@ class ComponentsManager( } } - /** - * Tries to remove a component in a safe way. + /** Tries to remove a component in a safe way. * * The component is moved (hopefully atomically) to temporary directory next * to the actual components directories and only then it is removed from @@ -843,8 +813,7 @@ class ComponentsManager( object ComponentsManager { - /** - * Creates a [[ComponentsManager]] using the default [[DistributionManager]] + /** Creates a [[ComponentsManager]] using the default [[DistributionManager]] * and release providers. * * @param globalCLIOptions options from the CLI setting verbosity of the diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/Engine.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/Engine.scala index 82a09b3be8..cc40c2f3e2 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/Engine.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/Engine.scala @@ -7,8 +7,7 @@ import org.enso.launcher.FileSystem.PathSyntax import scala.util.{Failure, Success, Try} -/** - * Represents an engine component. +/** Represents an engine component. * * @param version version of the component * @param path path to the component @@ -16,37 +15,31 @@ import scala.util.{Failure, Success, Try} */ case class Engine(version: SemVer, path: Path, manifest: Manifest) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = { val broken = if (isMarkedBroken) " (marked as broken)" else "" s"Enso Engine $version$broken" } - /** - * The runtime version that is associated with this engine and should be used + /** The runtime version that is associated with this engine and should be used * for running it. */ def graalRuntimeVersion: RuntimeVersion = manifest.runtimeVersion - /** - * A set of JVM options that should be added when running this engine. + /** A set of JVM options that should be added when running this engine. */ def defaultJVMOptions: Seq[Manifest.JVMOption] = manifest.jvmOptions - /** - * Path to the runner JAR. + /** Path to the runner JAR. */ def runnerPath: Path = path / "component" / "runner.jar" - /** - * Path to the runtime JAR. + /** Path to the runtime JAR. */ def runtimePath: Path = path / "component" / "runtime.jar" - /** - * Checks if the installation is not corrupted and reports any issues as + /** Checks if the installation is not corrupted and reports any issues as * failures. */ def ensureValid(): Try[Unit] = @@ -66,8 +59,7 @@ case class Engine(version: SemVer, path: Path, manifest: Manifest) { ) else Success(()) - /** - * Returns if the engine release was marked as broken when it was being + /** Returns if the engine release was marked as broken when it was being * installed. * * Releases marked as broken are not considered when looking for the latest diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/Manifest.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/Manifest.scala index 90a8a64d1b..dfd5f7fa34 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/Manifest.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/Manifest.scala @@ -12,8 +12,7 @@ import org.enso.pkg.SemVerJson._ import scala.util.{Failure, Try, Using} -/** - * Contains release metadata read from the manifest file that is attached to +/** Contains release metadata read from the manifest file that is attached to * each release. * * @param minimumLauncherVersion The minimum required version of the launcher @@ -35,8 +34,7 @@ case class Manifest( brokenMark: Boolean ) { - /** - * Returns a [[RuntimeVersion]] which encapsulates all version information + /** Returns a [[RuntimeVersion]] which encapsulates all version information * needed to find the runtime required for this release. */ def runtimeVersion: RuntimeVersion = @@ -48,13 +46,11 @@ case class Manifest( object Manifest { - /** - * Defines the name under which the manifest is included in the releases. + /** Defines the name under which the manifest is included in the releases. */ val DEFAULT_MANIFEST_NAME = "manifest.yaml" - /** - * Context used to substitute context-dependent variables in an JVM option. + /** Context used to substitute context-dependent variables in an JVM option. * * The context depends on what engine is being run on the JVM. * @@ -63,8 +59,7 @@ object Manifest { */ case class JVMOptionsContext(enginePackagePath: Path) - /** - * Represents an option that is added to the JVM running an engine. + /** Represents an option that is added to the JVM running an engine. * * @param value option value, possibly containing variables that will be * substituted @@ -73,15 +68,13 @@ object Manifest { */ case class JVMOption(value: String, osRestriction: Option[OS]) { - /** - * Checks if the option applies on the operating system that is currently + /** Checks if the option applies on the operating system that is currently * running. */ def isRelevant: Boolean = osRestriction.isEmpty || osRestriction.contains(OS.operatingSystem) - /** - * Substitutes any variables based on the provided `context`. + /** Substitutes any variables based on the provided `context`. */ def substitute(context: JVMOptionsContext): String = value.replace( @@ -96,8 +89,7 @@ object Manifest { val value = "value" } - /** - * [[Decoder]] instance that allows to parse the [[JVMOption]] from the + /** [[Decoder]] instance that allows to parse the [[JVMOption]] from the * YAML manifest. */ implicit val decoder: Decoder[JVMOption] = { json => @@ -113,8 +105,7 @@ object Manifest { } } - /** - * Tries to load the manifest at the given path. + /** Tries to load the manifest at the given path. * * Returns None if the manifest could not be opened or could not be parsed. */ @@ -128,8 +119,7 @@ object Manifest { Failure(ManifestLoadingError.fromThrowable(error)) } - /** - * Parses the manifest from a string containing a YAML definition. + /** Parses the manifest from a string containing a YAML definition. * * Returns None if the definition cannot be parsed. */ @@ -143,22 +133,19 @@ object Manifest { } } - /** - * Indicates an error that prevented loading the engine manifest. + /** Indicates an error that prevented loading the engine manifest. */ case class ManifestLoadingError(message: String, cause: Throwable) extends RuntimeException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = message } object ManifestLoadingError { - /** - * Creates a [[ManifestLoadingError]] by wrapping another [[Throwable]]. + /** Creates a [[ManifestLoadingError]] by wrapping another [[Throwable]]. * * Special logic is used for [[io.circe.Error]] to display the error * summary in a human-readable way. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/Runtime.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/Runtime.scala index 5f6e3291e3..b0ca16188d 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/Runtime.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/Runtime.scala @@ -7,22 +7,19 @@ import org.enso.launcher.OS import scala.util.{Failure, Success, Try} -/** - * Represents a runtime component. +/** Represents a runtime component. * * @param version version of the component * @param path path to the component */ case class Runtime(version: RuntimeVersion, path: Path) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = s"GraalVM ${version.graal}-java${version.java}" - /** - * The path to the JAVA_HOME directory associated with this runtime. + /** The path to the JAVA_HOME directory associated with this runtime. */ def javaHome: Path = OS.operatingSystem match { @@ -31,16 +28,14 @@ case class Runtime(version: RuntimeVersion, path: Path) { case OS.Windows => path } - /** - * The path to the `java` executable associated with this runtime. + /** The path to the `java` executable associated with this runtime. */ def javaExecutable: Path = { val executableName = if (OS.isWindows) "java.exe" else "java" javaHome / "bin" / executableName } - /** - * Checks if the installation is not corrupted and reports any issues as + /** Checks if the installation is not corrupted and reports any issues as * failures. */ def ensureValid(): Try[Unit] = diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/RuntimeVersion.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/RuntimeVersion.scala index e400533012..c30dffc83a 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/RuntimeVersion.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/RuntimeVersion.scala @@ -2,8 +2,7 @@ package org.enso.launcher.components import nl.gn0s1s.bump.SemVer -/** - * Version information identifying the runtime that can be used with an engine +/** Version information identifying the runtime that can be used with an engine * release. * * @param graal version of the GraalVM @@ -11,8 +10,7 @@ import nl.gn0s1s.bump.SemVer */ case class RuntimeVersion(graal: SemVer, java: String) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = s"GraalVM $graal Java $java" } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Command.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Command.scala index 9241c7d227..0ab59e703d 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Command.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Command.scala @@ -5,8 +5,7 @@ import com.typesafe.scalalogging.Logger import scala.sys.process.Process import scala.util.{Failure, Try} -/** - * Represents information required to run a system command. +/** Represents information required to run a system command. * * @param command the command and its arguments that should be executed * @param extraEnv environment variables that should be overridden @@ -14,8 +13,7 @@ import scala.util.{Failure, Try} case class Command(command: Seq[String], extraEnv: Seq[(String, String)]) { private val logger = Logger[Command] - /** - * Runs the command and returns its exit code. + /** Runs the command and returns its exit code. * * May return an exception if it is impossible to run the command (for * example due to insufficient permissions or nonexistent executable). @@ -32,8 +30,7 @@ case class Command(command: Seq[String], extraEnv: Seq[(String, String)]) { process.waitFor() } - /** - * Runs the command and returns its standard output as [[String]]. + /** Runs the command and returns its standard output as [[String]]. * * The standard error is printed to the console. * @@ -47,8 +44,7 @@ case class Command(command: Seq[String], extraEnv: Seq[(String, String)]) { processBuilder.!! } - /** - * Runs the provided action and wraps any errors into a [[Failure]] + /** Runs the provided action and wraps any errors into a [[Failure]] * containing a [[RunnerError]]. */ private def wrapError[R](action: => R): Try[R] = @@ -61,8 +57,7 @@ case class Command(command: Seq[String], extraEnv: Seq[(String, String)]) { ) ) - /** - * A textual representation of the command in a format that can be copied in + /** A textual representation of the command in a format that can be copied in * to a terminal and executed. */ override def toString: String = { diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/JVMSettings.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/JVMSettings.scala index 781f87b3a1..59e2583d2f 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/JVMSettings.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/JVMSettings.scala @@ -1,7 +1,6 @@ package org.enso.launcher.components.runner -/** - * Represents settings that are used to launch the runtime JVM. +/** Represents settings that are used to launch the runtime JVM. * * @param useSystemJVM if set, the system configured JVM is used instead of * the one managed by the launcher diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/LanguageServerOptions.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/LanguageServerOptions.scala index cbc5fde935..4687354ebb 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/LanguageServerOptions.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/LanguageServerOptions.scala @@ -3,8 +3,7 @@ package org.enso.launcher.components.runner import java.nio.file.Path import java.util.UUID -/** - * Options that are passed to the language server. +/** Options that are passed to the language server. * * @param rootId an id of content root * @param path a path to the content root diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunSettings.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunSettings.scala index d0050e106c..81ebcc0683 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunSettings.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunSettings.scala @@ -2,8 +2,7 @@ package org.enso.launcher.components.runner import nl.gn0s1s.bump.SemVer -/** - * Represents settings that are used to launch the runner JAR. +/** Represents settings that are used to launch the runner JAR. * * @param version Enso engine version to use * @param runnerArguments arguments that should be passed to the runner diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Runner.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Runner.scala index 6c6b6cca80..8259b9abad 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Runner.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/Runner.scala @@ -20,8 +20,7 @@ import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, Future, TimeoutException} import scala.util.Try -/** - * A helper class that prepares settings for running Enso components and +/** A helper class that prepares settings for running Enso components and * converts these settings to actual commands that launch the component inside * of a JVM. */ @@ -33,8 +32,7 @@ class Runner( loggerConnection: Future[Option[Uri]] ) { - /** - * The current working directory that is a starting point when checking if + /** The current working directory that is a starting point when checking if * the command is launched inside of a project. * * Can be overridden in tests. @@ -64,8 +62,7 @@ class Runner( RunSettings(version, arguments, connectLoggerIfAvailable = false) } - /** - * Creates [[RunSettings]] for launching the REPL. + /** Creates [[RunSettings]] for launching the REPL. * * See [[org.enso.launcher.Launcher.runRepl]] for more details. */ @@ -105,8 +102,7 @@ class Runner( ) } - /** - * Creates [[RunSettings]] for running Enso projects or scripts. + /** Creates [[RunSettings]] for running Enso projects or scripts. * * See [[org.enso.launcher.Launcher.runRun]] for more details. */ @@ -166,8 +162,7 @@ class Runner( ) } - /** - * Creates [[RunSettings]] for launching the Language Server. + /** Creates [[RunSettings]] for launching the Language Server. * * See [[org.enso.launcher.Launcher.runLanguageServer]] for more details. */ @@ -204,8 +199,7 @@ class Runner( ) } - /** - * Creates [[RunSettings]] for querying the currently selected engine + /** Creates [[RunSettings]] for querying the currently selected engine * version. * * If the current working directory is inside of a project, the engine @@ -242,8 +236,7 @@ class Runner( final private val JVM_OPTIONS_ENV_VAR = "ENSO_JVM_OPTS" - /** - * Runs an action giving it a command that can be used to launch the + /** Runs an action giving it a command that can be used to launch the * component. * * While the action is executed, it is guaranteed that the component @@ -312,8 +305,7 @@ class Runner( } } - /** - * Represents a way of launching the JVM. + /** Represents a way of launching the JVM. * * Stores the name of the `java` executable to run and a possible JAVA_HOME * environment variable override. @@ -323,13 +315,11 @@ class Runner( javaHomeOverride: Option[String] ) - /** - * The [[JavaCommand]] representing the system-configured JVM. + /** The [[JavaCommand]] representing the system-configured JVM. */ private def systemJavaCommand: JavaCommand = JavaCommand("java", None) - /** - * The [[JavaCommand]] representing a managed [[Runtime]]. + /** The [[JavaCommand]] representing a managed [[Runtime]]. */ private def javaCommandForRuntime(runtime: Runtime): JavaCommand = JavaCommand( @@ -338,8 +328,7 @@ class Runner( Some(runtime.javaHome.toAbsolutePath.normalize.toString) ) - /** - * Returns arguments that should be added to a launched component to connect + /** Returns arguments that should be added to a launched component to connect * it to launcher's logging service. * * It waits until the logging service has been set up and should be called as diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunnerError.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunnerError.scala index cbc3d64d4b..c3994b5779 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunnerError.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/RunnerError.scala @@ -1,13 +1,11 @@ package org.enso.launcher.components.runner -/** - * Represents an error encountered when running the component. +/** Represents an error encountered when running the component. */ case class RunnerError(message: String, cause: Throwable = null) extends RuntimeException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = message } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/WhichEngine.scala b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/WhichEngine.scala index 2ede36fd27..19a2376a35 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/components/runner/WhichEngine.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/components/runner/WhichEngine.scala @@ -1,7 +1,6 @@ package org.enso.launcher.components.runner -/** - * Returned by [[Runner.version]], specifies if the engine that is queried for +/** Returned by [[Runner.version]], specifies if the engine that is queried for * version is from a project or the default one. */ sealed trait WhichEngine diff --git a/engine/launcher/src/main/scala/org/enso/launcher/config/DefaultVersion.scala b/engine/launcher/src/main/scala/org/enso/launcher/config/DefaultVersion.scala index ec40f54f43..855bdd40e2 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/config/DefaultVersion.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/config/DefaultVersion.scala @@ -7,38 +7,32 @@ import org.enso.cli.arguments.Argument import org.enso.launcher.cli.Arguments._ import org.enso.pkg.SemVerJson._ -/** - * Default version that is used when launching Enso outside of projects and +/** Default version that is used when launching Enso outside of projects and * when creating new projects. */ sealed trait DefaultVersion object DefaultVersion { - /** - * Defaults to the latest installed version, or if no versions are installed, + /** Defaults to the latest installed version, or if no versions are installed, * to the latest available release. */ case object LatestInstalled extends DefaultVersion { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = "latest-installed" } - /** - * Defaults to a specified version. + /** Defaults to a specified version. */ case class Exact(version: SemVer) extends DefaultVersion { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = version.toString } - /** - * [[Encoder]] instance for [[DefaultVersion]]. + /** [[Encoder]] instance for [[DefaultVersion]]. */ implicit val encoder: Encoder[DefaultVersion] = { case LatestInstalled => @@ -47,8 +41,7 @@ object DefaultVersion { version.asJson } - /** - * [[Decoder]] instance for [[DefaultVersion]]. + /** [[Decoder]] instance for [[DefaultVersion]]. */ implicit val decoder: Decoder[DefaultVersion] = { json => if (json.value.isNull) Right(LatestInstalled) @@ -58,8 +51,7 @@ object DefaultVersion { } yield Exact(version) } - /** - * [[Argument]] instance for [[DefaultVersion]]. + /** [[Argument]] instance for [[DefaultVersion]]. */ implicit val argument: Argument[DefaultVersion] = { string => if (string == LatestInstalled.toString) Right(LatestInstalled) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfig.scala b/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfig.scala index c7cda5a5a3..e42dc6bfc2 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfig.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfig.scala @@ -4,8 +4,7 @@ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Json, JsonObject} import org.enso.pkg.Contact -/** - * Global user configuration. +/** Global user configuration. * * Specifies default values for new projects and possibly other properties. Can * handle unknown keys which can be used for configuration of plugins. @@ -25,8 +24,7 @@ case class GlobalConfig( original: JsonObject ) { - /** - * Returns a [[Contact]] for the default author if at least one of the name + /** Returns a [[Contact]] for the default author if at least one of the name * and email is set. * * If both name and email are not set, returns None. @@ -38,8 +36,7 @@ case class GlobalConfig( object GlobalConfig { - /** - * The default configuration used when the configuration file does not exist. + /** The default configuration used when the configuration file does not exist. */ val Default: GlobalConfig = GlobalConfig( @@ -49,8 +46,7 @@ object GlobalConfig { original = JsonObject() ) - /** - * Field names used when serializing the configuration. + /** Field names used when serializing the configuration. */ object Fields { val DefaultVersion = "default.enso-version" @@ -58,8 +54,7 @@ object GlobalConfig { val AuthorEmail = "author.email" } - /** - * [[Decoder]] instance for [[GlobalConfig]]. + /** [[Decoder]] instance for [[GlobalConfig]]. */ implicit val decoder: Decoder[GlobalConfig] = { json => for { @@ -77,8 +72,7 @@ object GlobalConfig { ) } - /** - * [[Encoder]] instance for [[GlobalConfig]]. + /** [[Encoder]] instance for [[GlobalConfig]]. */ implicit val encoder: Encoder[GlobalConfig] = { config => val base = config.original.asJson diff --git a/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfigurationManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfigurationManager.scala index 70b95fa241..1b2fed4e0f 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfigurationManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/config/GlobalConfigurationManager.scala @@ -13,8 +13,7 @@ import org.enso.launcher.installation.DistributionManager import scala.util.{Failure, Success, Try, Using} -/** - * Manages the global configuration of the distribution which includes the +/** Manages the global configuration of the distribution which includes the * default engine version and default project metadata used for new projects. */ class GlobalConfigurationManager( @@ -24,8 +23,7 @@ class GlobalConfigurationManager( private val logger = Logger[GlobalConfigurationManager] - /** - * Returns the default Enso version that should be used when running Enso + /** Returns the default Enso version that should be used when running Enso * outside a project and when creating a new project. * * The default can be set by `enso default `. If the default is not @@ -53,15 +51,13 @@ class GlobalConfigurationManager( } } - /** - * Location of the global configuration file. + /** Location of the global configuration file. * @return */ def configLocation: Path = distributionManager.paths.config / GlobalConfigurationManager.globalConfigName - /** - * Loads the current global configuration. + /** Loads the current global configuration. * * If the configuration file does not exist, the default config is returned. * If it exists but cannot be loaded, an exception is thrown. @@ -69,26 +65,23 @@ class GlobalConfigurationManager( def getConfig: GlobalConfig = GlobalConfigurationManager .readConfig(configLocation) - .recoverWith { - case _: NoSuchFileException => - logger.debug( - s"Global config (at ${configLocation.toAbsolutePath} not found, " + - s"falling back to defaults." - ) - Success(GlobalConfig.Default) + .recoverWith { case _: NoSuchFileException => + logger.debug( + s"Global config (at ${configLocation.toAbsolutePath} not found, " + + s"falling back to defaults." + ) + Success(GlobalConfig.Default) } .get - /** - * Applies `update` to the current config and saves the returned value. + /** Applies `update` to the current config and saves the returned value. */ def updateConfig(update: GlobalConfig => GlobalConfig): Unit = { val updated = update(getConfig) GlobalConfigurationManager.writeConfig(configLocation, updated).get } - /** - * Sets `key` to the raw JSON `value` in the config. + /** Sets `key` to the raw JSON `value` in the config. * * If changing that setting would result in the config becoming unreadable * (because an invalid value has been set for a known field), the config is @@ -98,20 +91,18 @@ class GlobalConfigurationManager( val updated = GlobalConfig.encoder(getConfig).asObject.get.add(key, value) GlobalConfigurationManager .writeConfigRaw(configLocation, updated.asJson) - .recoverWith { - case e: InvalidConfigError => - Failure( - InvalidConfigError( - s"Invalid value for key `$key`. Config changes were not saved.", - e - ) + .recoverWith { case e: InvalidConfigError => + Failure( + InvalidConfigError( + s"Invalid value for key `$key`. Config changes were not saved.", + e ) + ) } .get } - /** - * Removes the `key` from the config. + /** Removes the `key` from the config. * * If removing that setting would result in the config becoming unreadable, * the config is not saved and an exception is thrown. @@ -124,13 +115,11 @@ class GlobalConfigurationManager( object GlobalConfigurationManager { - /** - * Name of the main global configuration file. + /** Name of the main global configuration file. */ val globalConfigName: String = "global-config.yaml" - /** - * Tries to read the global config from the given `path`. + /** Tries to read the global config from the given `path`. */ def readConfig(path: Path): Try[GlobalConfig] = Using(Files.newBufferedReader(path)) { reader => @@ -140,14 +129,12 @@ object GlobalConfigurationManager { } yield config }.flatMap(_.toTry) - /** - * Tries to write the provided `config` to the given `path`. + /** Tries to write the provided `config` to the given `path`. */ def writeConfig(path: Path, config: GlobalConfig): Try[Unit] = writeConfigRaw(path, GlobalConfig.encoder(config)) - /** - * Tries to write the config from a raw JSON value to the given `path`. + /** Tries to write the config from a raw JSON value to the given `path`. * * The config will not be saved if it is invalid, instead an exception is * thrown. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/config/InvalidConfigError.scala b/engine/launcher/src/main/scala/org/enso/launcher/config/InvalidConfigError.scala index c5794c0e3c..9e5935ccd3 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/config/InvalidConfigError.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/config/InvalidConfigError.scala @@ -1,13 +1,11 @@ package org.enso.launcher.config -/** - * Indicates that the config is invalid. +/** Indicates that the config is invalid. */ case class InvalidConfigError(message: String, cause: Throwable) extends RuntimeException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = message } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPDownload.scala b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPDownload.scala index 4fa250bb9c..62b746a5da 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPDownload.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPDownload.scala @@ -15,13 +15,11 @@ import org.enso.cli.{TaskProgress, TaskProgressImplementation} import scala.concurrent.Future -/** - * Represents a HTTP header. +/** Represents a HTTP header. */ case class Header(name: String, value: String) { - /** - * Checks if this header instance corresponds to a `headerName`. + /** Checks if this header instance corresponds to a `headerName`. * * The check is case-insensitive. */ @@ -29,8 +27,7 @@ case class Header(name: String, value: String) { name.toLowerCase == headerName.toLowerCase } -/** - * Contains the response contents as a string alongside with the headers +/** Contains the response contents as a string alongside with the headers * included in the response. * * @param content the response decoded as a string @@ -38,19 +35,16 @@ case class Header(name: String, value: String) { */ case class APIResponse(content: String, headers: Seq[Header]) -/** - * Contains utility functions for fetching data using the HTTP(S) protocol. +/** Contains utility functions for fetching data using the HTTP(S) protocol. */ object HTTPDownload { private val logger = Logger[HTTPDownload.type] - /** - * Determines how many redirects are taken until an error is thrown. + /** Determines how many redirects are taken until an error is thrown. */ val maximumRedirects: Int = 20 - /** - * Fetches the `request` and tries to decode is as a [[String]]. + /** Fetches the `request` and tries to decode is as a [[String]]. * * The request is executed in a separate thread. A [[TaskProgress]] instance * is returned immediately which can be used to track progress of the @@ -88,8 +82,7 @@ object HTTPDownload { ) } - /** - * Downloads the `request` and saves the response in the file pointed by the + /** Downloads the `request` and saves the response in the file pointed by the * `destination`. * * The request is executed in a separate thread. A [[TaskProgress]] instance @@ -133,8 +126,7 @@ object HTTPDownload { ) } - /** - * Starts the request and returns a [[TaskProgress]] that can be used to + /** Starts the request and returns a [[TaskProgress]] that can be used to * track download progress and get the result. * * @tparam A type of the result returned by `sink` diff --git a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPException.scala b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPException.scala index 05152bde9f..4369bb3be3 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPException.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPException.scala @@ -1,6 +1,5 @@ package org.enso.launcher.http -/** - * Indicates an error when processing a HTTP request. +/** Indicates an error when processing a HTTP request. */ case class HTTPException(message: String) extends RuntimeException(message) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequest.scala b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequest.scala index 0efd77b395..b0fe183137 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequest.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequest.scala @@ -2,8 +2,7 @@ package org.enso.launcher.http import akka.http.scaladsl.model.HttpRequest -/** - * Wraps an underlying HTTP request implementation to make the outside API +/** Wraps an underlying HTTP request implementation to make the outside API * independent of the internal implementation. */ case class HTTPRequest(requestImpl: HttpRequest) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequestBuilder.scala b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequestBuilder.scala index c200d9d0c2..b7d801bff0 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequestBuilder.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/http/HTTPRequestBuilder.scala @@ -3,8 +3,7 @@ package org.enso.launcher.http import akka.http.scaladsl.model.HttpHeader.ParsingResult import akka.http.scaladsl.model._ -/** - * A simple immutable builder for HTTP requests. +/** A simple immutable builder for HTTP requests. * * It contains very limited functionality that is needed by the APIs used in * the launcher. It can be easily extended if necessary. @@ -14,13 +13,11 @@ case class HTTPRequestBuilder private ( headers: Vector[(String, String)] ) { - /** - * Builds a GET request with the specified settings. + /** Builds a GET request with the specified settings. */ def GET: HTTPRequest = build(HttpMethods.GET) - /** - * Adds an additional header that will be included in the request. + /** Adds an additional header that will be included in the request. * * @param name name of the header * @param value the header value @@ -31,17 +28,16 @@ case class HTTPRequestBuilder private ( private def build( method: HttpMethod ): HTTPRequest = { - val httpHeaders = headers.map { - case (name, value) => - HttpHeader.parse(name, value) match { - case ParsingResult.Ok(header, errors) if errors.isEmpty => - header - case havingErrors => - throw new IllegalStateException( - s"Internal error: " + - s"Invalid value for header $name: ${havingErrors.errors}." - ) - } + val httpHeaders = headers.map { case (name, value) => + HttpHeader.parse(name, value) match { + case ParsingResult.Ok(header, errors) if errors.isEmpty => + header + case havingErrors => + throw new IllegalStateException( + s"Internal error: " + + s"Invalid value for header $name: ${havingErrors.errors}." + ) + } } HTTPRequest(HttpRequest(method = method, uri = uri, headers = httpHeaders)) } @@ -49,14 +45,12 @@ case class HTTPRequestBuilder private ( object HTTPRequestBuilder { - /** - * Creates a request builder that will send the request for the given URI. + /** Creates a request builder that will send the request for the given URI. */ def fromURI(uri: Uri): HTTPRequestBuilder = new HTTPRequestBuilder(uri, Vector.empty) - /** - * Tries to parse the URI provided as a [[String]] and returns a request + /** Tries to parse the URI provided as a [[String]] and returns a request * builder that will send the request to the given `uri`. */ def fromURIString(uri: String): HTTPRequestBuilder = diff --git a/engine/launcher/src/main/scala/org/enso/launcher/http/URIBuilder.scala b/engine/launcher/src/main/scala/org/enso/launcher/http/URIBuilder.scala index a632a5c9d6..de4ff15943 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/http/URIBuilder.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/http/URIBuilder.scala @@ -2,8 +2,7 @@ package org.enso.launcher.http import akka.http.scaladsl.model.Uri -/** - * A simple immutable builder for URIs based on URLs. +/** A simple immutable builder for URIs based on URLs. * * It contains very limited functionality that is needed by the APIs used in * the launcher. It can be easily extended if necessary. @@ -13,8 +12,7 @@ import akka.http.scaladsl.model.Uri */ case class URIBuilder private (uri: Uri) { - /** - * Resolve a segment over the path in the URI. + /** Resolve a segment over the path in the URI. * * For example adding `bar` to `http://example.com/foo` will result in * `http://example.com/foo/bar`. @@ -24,24 +22,21 @@ case class URIBuilder private (uri: Uri) { copy(uri.withPath(uri.path + part)) } - /** - * Add a query parameter to the URI. + /** Add a query parameter to the URI. * * The query is appended at the end. */ def addQuery(key: String, value: String): URIBuilder = copy(uri.withQuery(uri.query().+:((key, value)))) - /** - * Build the URI represented by this builder. + /** Build the URI represented by this builder. */ def build(): Uri = uri } object URIBuilder { - /** - * Create a builder basing from a hostname. + /** Create a builder basing from a hostname. * * A builder created by `fromHost("example.com")` represents * `https://example.com/`. @@ -49,19 +44,16 @@ object URIBuilder { def fromHost(host: String): URIBuilder = new URIBuilder(Uri.from(scheme = "https", host = host)) - /** - * A simple DSL for the URIBuilder. + /** A simple DSL for the URIBuilder. */ implicit class URIBuilderSyntax(builder: URIBuilder) { - /** - * Extends the URI with an additional path segment. + /** Extends the URI with an additional path segment. */ def /(part: String): URIBuilder = builder.addPathSegment(part) - /** - * Adds a query to the URI. + /** Adds a query to the URI. */ def ?(query: (String, String)): URIBuilder = builder.addQuery(query._1, query._2) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionInstaller.scala b/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionInstaller.scala index 072f992e8b..10c3c49744 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionInstaller.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionInstaller.scala @@ -17,8 +17,7 @@ import org.enso.launcher.{FileSystem, InfoLogger, OS} import scala.util.control.NonFatal -/** - * Allows to locally [[install]] a portable distribution. +/** Allows to locally [[install]] a portable distribution. * * @param manager a distribution manager instance which defines locations for * the source portable distribution and the installation @@ -43,8 +42,7 @@ class DistributionInstaller( final private val installed = manager.LocallyInstalledDirectories private val env = manager.env - /** - * Names of additional files that are not essential to running the + /** Names of additional files that are not essential to running the * distribution, but should be copied over to the data root if possible. * * These files are assumed to be located at the data root. @@ -57,8 +55,7 @@ class DistributionInstaller( private val runtimesDirectory = installed.dataDirectory / manager.RUNTIMES_DIRECTORY - /** - * Installs the distribution under configured location. + /** Installs the distribution under configured location. * * Unless [[autoConfirm]] is true, asks the user to confirm the action after * printing where it plans to install itself. @@ -98,8 +95,7 @@ class DistributionInstaller( private val currentLauncherPath = env.getPathToRunningExecutable private val installedLauncherPath = installed.binaryExecutable - /** - * Prepares for the installation. + /** Prepares for the installation. * * Finds and reports possible conflicts, and asks the user if they want to * proceed (unless [[autoConfirm]] is set, in which case it only reports @@ -195,8 +191,7 @@ class DistributionInstaller( InstallationSettings(bundleAction, removeInstaller) } - /** - * Checks if system PATH includes the directory that the binary will be + /** Checks if system PATH includes the directory that the binary will be * installed into. */ private def isBinOnSystemPath: Boolean = { @@ -204,8 +199,7 @@ class DistributionInstaller( paths.contains(installed.binDirectory) } - /** - * Copies the binary into the destination directory and ensures that it is + /** Copies the binary into the destination directory and ensures that it is * executable. */ private def installBinary(): Unit = { @@ -218,8 +212,7 @@ class DistributionInstaller( logger.debug("Binary installed.") } - /** - * Creates the basic directory structure and copies documentation files if + /** Creates the basic directory structure and copies documentation files if * present. */ private def createDirectoryStructure(): Unit = { @@ -241,8 +234,7 @@ class DistributionInstaller( } } - /** - * Copies non-essential files like README etc. + /** Copies non-essential files like README etc. * * Failure to find/copy one of these is reported as a warning, but does not * stop the installation. @@ -280,8 +272,7 @@ class DistributionInstaller( } } - /** - * Finds bundles included in the portable package. + /** Finds bundles included in the portable package. * * @return a tuple containing sequences of runtime and engine bundles */ @@ -298,8 +289,7 @@ class DistributionInstaller( (runtimes, engines) } - /** - * Checks if any bundles are available and depending on selected settings, + /** Checks if any bundles are available and depending on selected settings, * decides how to proceed with the bundles. * * May ask the user interactively, unless this is prohibited. @@ -335,8 +325,7 @@ class DistributionInstaller( IgnoreBundles } - /** - * Copies (and possibly removes the originals) bundled engine and runtime + /** Copies (and possibly removes the originals) bundled engine and runtime * components. */ private def installBundles(bundleAction: BundleAction): Unit = { @@ -380,8 +369,7 @@ class DistributionInstaller( } } - /** - * Decides if the installer should be removed if the installation succeeds. + /** Decides if the installer should be removed if the installation succeeds. */ private def decideIfInstallerShouldBeRemoved(): Boolean = { def askForRemoval(): Boolean = @@ -398,8 +386,7 @@ class DistributionInstaller( } else false } - /** - * If the user wants to, removes the installer. + /** If the user wants to, removes the installer. */ private def removeInstaller(): Nothing = { if (OS.isWindows) { @@ -416,8 +403,7 @@ class DistributionInstaller( object DistributionInstaller { - /** - * Creates a [[DistributionInstaller]] using the default managers. + /** Creates a [[DistributionInstaller]] using the default managers. */ def default( globalCLIOptions: GlobalCLIOptions, @@ -432,101 +418,83 @@ object DistributionInstaller { bundleActionOption = bundleActionOption ) - /** - * Defines the set of possible actions to take when installing the bundled + /** Defines the set of possible actions to take when installing the bundled * components. */ trait BundleAction extends CLIOutput.Answer { - /** - * Specifies whether this action requires copying the bundles to the + /** Specifies whether this action requires copying the bundles to the * installed location. */ def copy: Boolean - /** - * Specifies whether this action requires to remove the original bundle + /** Specifies whether this action requires to remove the original bundle * files afterwards. */ def delete: Boolean } - /** - * The bundle action that will copy the bundles and keep the ones in the + /** The bundle action that will copy the bundles and keep the ones in the * original location too. */ case object CopyBundles extends BundleAction { - /** - * @inheritdoc + /** @inheritdoc */ override def key: String = "c" - /** - * @inheritdoc + /** @inheritdoc */ override def description: String = "copy bundles" - /** - * @inheritdoc + /** @inheritdoc */ def copy: Boolean = true - /** - * @inheritdoc + /** @inheritdoc */ def delete: Boolean = false } - /** - * The bundle action that will copy the bundles and remove the ones at the + /** The bundle action that will copy the bundles and remove the ones at the * original location on success. */ case object MoveBundles extends BundleAction { - /** - * @inheritdoc + /** @inheritdoc */ override def key: String = "m" - /** - * @inheritdoc + /** @inheritdoc */ override def description: String = "move bundles" - /** - * @inheritdoc + /** @inheritdoc */ def copy: Boolean = true - /** - * @inheritdoc + /** @inheritdoc */ def delete: Boolean = true } - /** - * The bundle action that ignores the bundles. + /** The bundle action that ignores the bundles. */ case object IgnoreBundles extends BundleAction { - /** - * @inheritdoc + /** @inheritdoc */ override def key: String = "i" - /** - * @inheritdoc + /** @inheritdoc */ override def description: String = "ignore bundles" - /** - * @inheritdoc + /** @inheritdoc */ def copy: Boolean = false - /** - * @inheritdoc + /** @inheritdoc */ def delete: Boolean = false } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionManager.scala index d84928de5d..94ead819bf 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionManager.scala @@ -10,8 +10,7 @@ import org.enso.launcher.{Environment, FileSystem, InfoLogger, OS} import scala.util.Try import scala.util.control.NonFatal -/** - * Gathers filesystem paths used by the launcher. +/** Gathers filesystem paths used by the launcher. * * @param dataRoot the root of the data directory; for a portable distribution * this is the root of the distribution, for a locally @@ -45,8 +44,7 @@ case class DistributionPaths( resourceManager: ResourceManager ) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = s"""DistributionPaths( @@ -64,8 +62,7 @@ case class DistributionPaths( } } -/** - * A helper class that detects if a portable or installed distribution is run +/** A helper class that detects if a portable or installed distribution is run * and encapsulates management of paths to components of the distribution. */ class DistributionManager( @@ -74,8 +71,7 @@ class DistributionManager( ) { private val logger = Logger[DistributionManager] - /** - * Specifies whether the launcher has been run as a portable distribution or + /** Specifies whether the launcher has been run as a portable distribution or * it is a locally installed distribution. */ lazy val isRunningPortable: Boolean = { @@ -107,8 +103,7 @@ class DistributionManager( portable } - /** - * Determines paths that should be used by the launcher. + /** Determines paths that should be used by the launcher. */ lazy val paths: DistributionPaths = { val paths = detectPaths() @@ -161,8 +156,7 @@ class DistributionManager( ) } - /** - * Tries to clean the temporary files directory. + /** Tries to clean the temporary files directory. * * It should be run at startup whenever the program wants to run clean-up. * Currently it is run when installation-related operations are taking place. @@ -186,8 +180,7 @@ class DistributionManager( } } - /** - * Removes unused lockfiles. + /** Removes unused lockfiles. */ def tryCleaningUnusedLockfiles(): Unit = { val lockfiles = FileSystem.listDirectory(paths.locks) @@ -201,8 +194,7 @@ class DistributionManager( } } - /** - * A helper for managing directories of the non-portable installation. + /** A helper for managing directories of the non-portable installation. * * It returns paths of the non-portable installation even if the launcher is * running in portable mode, so that this helper can be used by the installer @@ -225,8 +217,7 @@ class DistributionManager( private val MACOS_ENSO_DIRECTORY = "org.enso" private val WINDOWS_ENSO_DIRECTORY = "enso" - /** - * Data directory for an installed distribution. + /** Data directory for an installed distribution. */ def dataDirectory: Path = env @@ -248,8 +239,7 @@ class DistributionManager( } .toAbsolutePath - /** - * Returns names of directories that may be located inside of the data + /** Returns names of directories that may be located inside of the data * directory. */ def possibleDirectoriesInsideDataDirectory: Seq[String] = @@ -261,8 +251,7 @@ class DistributionManager( "components-licences" ) - /** - * Config directory for an installed distribution. + /** Config directory for an installed distribution. */ def configDirectory: Path = env @@ -284,8 +273,7 @@ class DistributionManager( } .toAbsolutePath - /** - * The directory where the launcher binary will be placed for an installed + /** The directory where the launcher binary will be placed for an installed * distribution. */ def binDirectory: Path = @@ -307,8 +295,7 @@ class DistributionManager( } .toAbsolutePath - /** - * The directory where runtime-synchronization files are stored. + /** The directory where runtime-synchronization files are stored. */ def runtimeDirectory: Path = env @@ -324,8 +311,7 @@ class DistributionManager( } } - /** - * The directory for storing logs. + /** The directory for storing logs. */ def logDirectory: Path = env @@ -347,16 +333,14 @@ class DistributionManager( private def executableName: String = OS.executableName("enso") - /** - * The path where the binary executable of the installed distribution + /** The path where the binary executable of the installed distribution * should be placed by default. */ def binaryExecutable: Path = { binDirectory / executableName } - /** - * The safe version of [[dataDirectory]] which returns None if the + /** The safe version of [[dataDirectory]] which returns None if the * directory cannot be determined. * * Should be used in places where not being able to determine the data @@ -365,8 +349,7 @@ class DistributionManager( def safeDataDirectory: Option[Path] = Try(dataDirectory).toOption - /** - * Determines whether a locally installed distribution exists on the + /** Determines whether a locally installed distribution exists on the * system. */ def installedDistributionExists: Boolean = @@ -374,8 +357,7 @@ class DistributionManager( } } -/** - * A default DistributionManager using the default environment. +/** A default DistributionManager using the default environment. */ object DistributionManager extends DistributionManager(Environment, DefaultResourceManager) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionUninstaller.scala b/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionUninstaller.scala index c766566842..c8605461b2 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionUninstaller.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/installation/DistributionUninstaller.scala @@ -18,8 +18,7 @@ import org.enso.launcher.{FileSystem, InfoLogger, OS} import scala.util.control.NonFatal -/** - * Allows to [[uninstall]] an installed distribution. +/** Allows to [[uninstall]] an installed distribution. * * @param manager a distribution manager instance which defines locations for * the distribution that will be uninstalled @@ -32,8 +31,7 @@ class DistributionUninstaller( private val autoConfirm = globalCLIOptions.autoConfirm private val logger = Logger[DistributionUninstaller] - /** - * Uninstalls a locally installed (non-portable) distribution. + /** Uninstalls a locally installed (non-portable) distribution. * * Removes the launcher executable and the ENSO_DATA_DIRECTORY and * ENSO_CONFIG_DIRECTORY directories (unless they contain unexpected files). @@ -56,8 +54,7 @@ class DistributionUninstaller( else uninstallUNIX() } - /** - * Uninstall strategy for OSes that can remove running executables. + /** Uninstall strategy for OSes that can remove running executables. * * Simply removes each component, starting with the ones that can potentially * be nested (as config and the binary can be inside of the data directory @@ -70,8 +67,7 @@ class DistributionUninstaller( InfoLogger.info("Successfully uninstalled the distribution.") } - /** - * Uninstall strategy for Windows, where it is not possible to remove a + /** Uninstall strategy for Windows, where it is not possible to remove a * running executable. * * The executable has to be removed last as the program must terminate to do @@ -95,8 +91,7 @@ class DistributionUninstaller( ) } - /** - * Checks if the launcher is running in portable mode and terminates + /** Checks if the launcher is running in portable mode and terminates * execution if it does. * * It prints an explanation that uninstall can only be used with non-portable @@ -117,8 +112,7 @@ class DistributionUninstaller( } } - /** - * Prints an explanation of what will be uninstalled and which directories + /** Prints an explanation of what will be uninstalled and which directories * will be removed and asks the user if they want to proceed. */ private def askConfirmation(): Unit = { @@ -142,8 +136,7 @@ class DistributionUninstaller( } } - /** - * True if the currently running executable is inside of the data root. + /** True if the currently running executable is inside of the data root. * * This is checked, because on Windows this will make removing data root more * complicated. @@ -155,8 +148,7 @@ class DistributionUninstaller( binaryPath.startsWith(dataPath) } - /** - * Removes the configuration file and the ENSO_CONFIG_DIRECTORY if it does + /** Removes the configuration file and the ENSO_CONFIG_DIRECTORY if it does * not contain any other files (or if the user agreed to remove them too). */ private def uninstallConfig(): Unit = { @@ -173,13 +165,11 @@ class DistributionUninstaller( FileSystem.removeDirectoryIfEmpty(manager.paths.config) } - /** - * Files that are expected to be inside of the data root. + /** Files that are expected to be inside of the data root. */ private val knownDataFiles = Seq("README.md", "NOTICE") - /** - * Directories that are expected to be inside of the data root, except for + /** Directories that are expected to be inside of the data root, except for * the locks directory which is handled separately. */ private val knownDataDirectories = @@ -187,8 +177,7 @@ class DistributionUninstaller( manager.LocallyInstalledDirectories.possibleDirectoriesInsideDataDirectory ) - manager.LOCK_DIRECTORY - /** - * Removes all files contained in the ENSO_DATA_DIRECTORY and possibly the + /** Removes all files contained in the ENSO_DATA_DIRECTORY and possibly the * directory itself. * * If `deferDataRootRemoval` is set, the directory itself is not removed @@ -244,9 +233,9 @@ class DistributionUninstaller( val ignoredFiles = if (deferDataRootRemoval) Set("bin") else Set() val remainingFiles = FileSystem - .listDirectory(dataRoot) - .map(_.getFileName.toString) - .toSet -- ignoredFiles + .listDirectory(dataRoot) + .map(_.getFileName.toString) + .toSet -- ignoredFiles if (remainingFiles.nonEmpty) { handleRemainingFiles( manager.LocallyInstalledDirectories.ENSO_DATA_DIRECTORY, @@ -260,8 +249,7 @@ class DistributionUninstaller( } } - /** - * Common logic for handling unexpected files in ENSO_DATA_DIRECTORY and + /** Common logic for handling unexpected files in ENSO_DATA_DIRECTORY and * ENSO_CONFIG_DIRECTORY. * * It asks the user if they want to remove these files unless `auto-confirm` @@ -302,8 +290,7 @@ class DistributionUninstaller( } } - /** - * Uninstalls the executable on platforms that allow for removing running + /** Uninstalls the executable on platforms that allow for removing running * files. * * Simply removes the file. @@ -312,8 +299,7 @@ class DistributionUninstaller( FileSystem.removeFileIfExists(manager.env.getPathToRunningExecutable) } - /** - * Moves the current launcher executable, so other processes cannot start it + /** Moves the current launcher executable, so other processes cannot start it * while uninstallation is in progress. * * It will be removed at the last stage of the uninstallation. @@ -328,8 +314,7 @@ class DistributionUninstaller( newPath } - /** - * Uninstalls the executable on Windows where it is impossible to remove an + /** Uninstalls the executable on Windows where it is impossible to remove an * executable that is running. * * Uses a workaround implemented in [[InternalOpts]]. Has to be run at the @@ -355,8 +340,7 @@ class DistributionUninstaller( object DistributionUninstaller { - /** - * Creates a default [[DistributionUninstaller]] using the default managers + /** Creates a default [[DistributionUninstaller]] using the default managers * and the provided CLI options. */ def default(globalCLIOptions: GlobalCLIOptions): DistributionUninstaller = diff --git a/engine/launcher/src/main/scala/org/enso/launcher/installation/InstallationError.scala b/engine/launcher/src/main/scala/org/enso/launcher/installation/InstallationError.scala index dbbb795049..ca539d624e 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/installation/InstallationError.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/installation/InstallationError.scala @@ -1,7 +1,6 @@ package org.enso.launcher.installation -/** - * Indicates an installation failure. +/** Indicates an installation failure. * * Possibly installation being manually cancelled. */ diff --git a/engine/launcher/src/main/scala/org/enso/launcher/internal/ProgressInputStream.scala b/engine/launcher/src/main/scala/org/enso/launcher/internal/ProgressInputStream.scala index 0d8ff6f92f..801b3a4372 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/internal/ProgressInputStream.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/internal/ProgressInputStream.scala @@ -2,27 +2,23 @@ package org.enso.launcher.internal import java.io.InputStream -/** - * Represents a *mutable* progress status. +/** Represents a *mutable* progress status. */ trait ReadProgress { - /** - * Specifies how many units have already been read. + /** Specifies how many units have already been read. * * Querying this property over time may give different results as the task * progresses. */ def alreadyRead(): Long - /** - * Specifies how many units in total are expected, if known. + /** Specifies how many units in total are expected, if known. */ def total(): Option[Long] } -/** - * A wrapper for an [[InputStream]] that tracks the read progresss. +/** A wrapper for an [[InputStream]] that tracks the read progresss. * * @param in the base stream to wrap * @param totalSize total amount of bytes that are expected to be available in @@ -41,20 +37,17 @@ class ProgressInputStream( override def total(): Option[Long] = totalSize } - /** - * Returns the [[ReadProgress]] instance that can be queried to check how + /** Returns the [[ReadProgress]] instance that can be queried to check how * many bytes have been read already. */ def progress: ReadProgress = readProgress - /** - * @inheritdoc + /** @inheritdoc */ override def available: Int = in.available() - /** - * @inheritdoc + /** @inheritdoc */ override def read: Int = { bytesRead += 1 @@ -62,8 +55,7 @@ class ProgressInputStream( in.read() } - /** - * @inheritdoc + /** @inheritdoc */ override def read(b: Array[Byte]): Int = { val bytes = in.read(b) @@ -72,8 +64,7 @@ class ProgressInputStream( bytes } - /** - * @inheritdoc + /** @inheritdoc */ override def read(b: Array[Byte], off: Int, len: Int): Int = { val bytes = in.read(b, off, len) @@ -82,8 +73,7 @@ class ProgressInputStream( bytes } - /** - * @inheritdoc + /** @inheritdoc */ override def skip(n: Long): Long = { val skipped = in.skip(n) @@ -92,8 +82,7 @@ class ProgressInputStream( skipped } - /** - * @inheritdoc + /** @inheritdoc */ override def close(): Unit = in.close() diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultFileLockManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultFileLockManager.scala index 0ece863015..adc1bafbf6 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultFileLockManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultFileLockManager.scala @@ -3,14 +3,12 @@ import java.nio.file.Path import org.enso.launcher.installation.DistributionManager -/** - * Default [[FileLockManager]] storing lock files in a directory defined by the +/** Default [[FileLockManager]] storing lock files in a directory defined by the * [[DistributionManager]]. */ object DefaultFileLockManager extends FileLockManager { - /** - * @inheritdoc + /** @inheritdoc */ override def locksRoot: Path = DistributionManager.paths.locks } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultResourceManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultResourceManager.scala index 88e54b30c0..e6b9645425 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultResourceManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/DefaultResourceManager.scala @@ -1,6 +1,5 @@ package org.enso.launcher.locking -/** - * Default [[ResourceManager]] using the [[DefaultFileLockManager]]. +/** Default [[ResourceManager]] using the [[DefaultFileLockManager]]. */ object DefaultResourceManager extends ResourceManager(DefaultFileLockManager) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/FileLockManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/FileLockManager.scala index 3eb350d2e5..ef272c1c75 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/FileLockManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/FileLockManager.scala @@ -7,8 +7,7 @@ import com.typesafe.scalalogging.Logger import scala.util.control.NonFatal -/** - * [[LockManager]] using file-based locks. +/** [[LockManager]] using file-based locks. * * This is the [[LockManager]] that should be used in production as it is able * to synchronize locks between different processes. @@ -24,13 +23,11 @@ import scala.util.control.NonFatal */ abstract class FileLockManager extends LockManager { - /** - * Specifies the directory in which lockfiles should be created. + /** Specifies the directory in which lockfiles should be created. */ def locksRoot: Path - /** - * @inheritdoc + /** @inheritdoc */ override def acquireLock(resourceName: String, lockType: LockType): Lock = { val channel = openChannel(resourceName) @@ -43,8 +40,7 @@ abstract class FileLockManager extends LockManager { } } - /** - * @inheritdoc + /** @inheritdoc */ override def tryAcquireLock( resourceName: String, diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/Lock.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/Lock.scala index e96820648b..f3019204d9 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/Lock.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/Lock.scala @@ -2,13 +2,11 @@ package org.enso.launcher.locking import scala.util.Using.Releasable -/** - * A lock synchronizing access to some resource. +/** A lock synchronizing access to some resource. */ trait Lock { - /** - * Releases the lock and any resources (file channels etc.) that are + /** Releases the lock and any resources (file channels etc.) that are * associated with it. */ def release(): Unit @@ -16,8 +14,7 @@ trait Lock { object Lock { - /** - * [[Releasable]] instance for [[Lock]] making it usable with the `Using` + /** [[Releasable]] instance for [[Lock]] making it usable with the `Using` * construct. */ implicit val releasable: Releasable[Lock] = (resource: Lock) => diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/LockManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/LockManager.scala index 5213a44760..6ad27a618a 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/LockManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/LockManager.scala @@ -1,29 +1,25 @@ package org.enso.launcher.locking -/** - * Manages locks that can be used to synchronize different launcher processes +/** Manages locks that can be used to synchronize different launcher processes * running in parallel to avoid components corruption caused by simultaneous * modification of components. */ trait LockManager { - /** - * Acquires the lock with the given name and type. + /** Acquires the lock with the given name and type. * * Will wait if the lock cannot be acquired immediately. */ def acquireLock(resourceName: String, lockType: LockType): Lock - /** - * Tries to immediately acquire the lock. + /** Tries to immediately acquire the lock. * * Returns immediately with None if the lock cannot be acquired without * waiting. */ def tryAcquireLock(resourceName: String, lockType: LockType): Option[Lock] - /** - * Acquires the lock with the given name and type. + /** Acquires the lock with the given name and type. * * If the lock cannot be acquired immediately, it will execute the * `waitingAction` and start waiting to acquire the lock. The waiting action diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/LockType.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/LockType.scala index bf838f45bc..2a14c87422 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/LockType.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/LockType.scala @@ -1,18 +1,15 @@ package org.enso.launcher.locking -/** - * Defines the lock type. +/** Defines the lock type. */ sealed trait LockType object LockType { - /** - * An exclusive lock can be held by only one user at a time. + /** An exclusive lock can be held by only one user at a time. */ case object Exclusive extends LockType - /** - * A shared lock may be held by multiple users in a given moment. + /** A shared lock may be held by multiple users in a given moment. */ case object Shared extends LockType } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/Resource.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/Resource.scala index 02b0a19793..abd69506dd 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/Resource.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/Resource.scala @@ -3,28 +3,24 @@ package org.enso.launcher.locking import nl.gn0s1s.bump.SemVer import org.enso.launcher.components.RuntimeVersion -/** - * Represents a resource that can be locked. +/** Represents a resource that can be locked. */ trait Resource { - /** - * Name of the resource. + /** Name of the resource. * * Must be a valid filename part. */ def name: String - /** - * A message that is displayed by default if the lock on that resource cannot + /** A message that is displayed by default if the lock on that resource cannot * be acquired immediately. */ def waitMessage: String } object Resource { - /** - * Synchronizes launcher upgrades. + /** Synchronizes launcher upgrades. */ case object LauncherExecutable extends Resource { override def name: String = "launcher-executable" @@ -33,8 +29,7 @@ object Resource { "the current process must wait until it is completed." } - /** - * This resource is held when adding or removing any components. + /** This resource is held when adding or removing any components. */ case object AddOrRemoveComponents extends Resource { override def name: String = "add-remove-components" @@ -43,8 +38,7 @@ object Resource { "the current process must wait until it finishes." } - /** - * This resource should be held (shared) by any process that is using the + /** This resource should be held (shared) by any process that is using the * engine to ensure that it will stay available for the duration of the * action. * @@ -57,8 +51,7 @@ object Resource { "the current process must wait until other processes complete." } - /** - * This resource should be held (shared) by any process that is using the + /** This resource should be held (shared) by any process that is using the * runtime to ensure that it will stay available for the duration of the * action. * diff --git a/engine/launcher/src/main/scala/org/enso/launcher/locking/ResourceManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/locking/ResourceManager.scala index d131ea9461..0fc3877dfd 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/locking/ResourceManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/locking/ResourceManager.scala @@ -4,15 +4,13 @@ import com.typesafe.scalalogging.Logger import scala.util.Using -/** - * Uses a [[LockManager]] implementation to synchronize access to [[Resource]]. +/** Uses a [[LockManager]] implementation to synchronize access to [[Resource]]. */ class ResourceManager(lockManager: LockManager) { private val logger = Logger[ResourceManager] - /** - * Runs the `action` while holding a lock (of `lockType`) for the `resource`. + /** Runs the `action` while holding a lock (of `lockType`) for the `resource`. * * If the lock cannot be acquired immediately, the `waitingAction` is * executed. It can be used to notify the user. @@ -35,8 +33,7 @@ class ResourceManager(lockManager: LockManager) { ) } { _ => action }.get - /** - * Runs the `action` while holding multiple locks for a sequence of + /** Runs the `action` while holding multiple locks for a sequence of * resources. */ def withResources[R](resources: (Resource, LockType)*)(action: => R): R = @@ -49,8 +46,7 @@ class ResourceManager(lockManager: LockManager) { var mainLock: Option[Lock] = None - /** - * Initializes the [[MainLock]]. + /** Initializes the [[MainLock]]. */ def initializeMainLock(): Unit = { val lock = @@ -62,8 +58,7 @@ class ResourceManager(lockManager: LockManager) { mainLock = Some(lock) } - /** - * Exception that is thrown when the main lock is held exclusively. + /** Exception that is thrown when the main lock is held exclusively. * * This situation means that the current distribution is being installed or * uninstalled, so it should not be used in the meantime and the application @@ -72,8 +67,7 @@ class ResourceManager(lockManager: LockManager) { case class DistributionIsModifiedError(message: String) extends RuntimeException(message) - /** - * Acquires an exclusive main lock (first releasing the shared lock), + /** Acquires an exclusive main lock (first releasing the shared lock), * ensuring that no other processes using this distribution can be running in * parallel. * @@ -96,8 +90,7 @@ class ResourceManager(lockManager: LockManager) { mainLock = Some(lock) } - /** - * Releases the main lock. + /** Releases the main lock. * * Should be called just before the program terminates. It is not an error to * skip it, as the operating system should unlock all resources after the @@ -113,8 +106,7 @@ class ResourceManager(lockManager: LockManager) { case None => } - /** - * Runs the provided `action` if an exclusive lock can be immediately + /** Runs the provided `action` if an exclusive lock can be immediately * acquired for the temporary directory, i.e. the directory is not used by * anyone. * @@ -135,8 +127,7 @@ class ResourceManager(lockManager: LockManager) { private var temporaryDirectoryLock: Option[Lock] = None - /** - * Marks the temporary directory as in use. + /** Marks the temporary directory as in use. * * This lock does not have to be released as it will be automatically * released when the program terminates. @@ -150,8 +141,7 @@ class ResourceManager(lockManager: LockManager) { temporaryDirectoryLock = Some(lock) } - /** - * Releases the lock for the temporary directory. + /** Releases the lock for the temporary directory. * * Used by the uninstaller as part of releasing all locks to ensure that the * locks directory can be removed. @@ -164,8 +154,7 @@ class ResourceManager(lockManager: LockManager) { case None => } - /** - * This resource is acquired whenever the temporary directory is first + /** This resource is acquired whenever the temporary directory is first * accessed. * * It ensures that installations running in parallel will not remove each @@ -180,8 +169,7 @@ class ResourceManager(lockManager: LockManager) { "conflicts. It should not take a long time." } - /** - * The main lock that is held by all launcher processes. + /** The main lock that is held by all launcher processes. * * It is used to ensure that no other processes are running when the * distribution is being installed or uninstalled. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/project/Project.scala b/engine/launcher/src/main/scala/org/enso/launcher/project/Project.scala index 7fe5daa7a0..d5c9a2a5ce 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/project/Project.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/project/Project.scala @@ -7,8 +7,7 @@ import nl.gn0s1s.bump.SemVer import org.enso.launcher.config.GlobalConfigurationManager import org.enso.pkg.{Config, DefaultEnsoVersion, Package, SemVerEnsoVersion} -/** - * Represents an Enso project. +/** Represents an Enso project. * * @param pkg the package associated with the project * @param globalConfigurationManager the configuration manager that is @@ -20,8 +19,7 @@ class Project( globalConfigurationManager: GlobalConfigurationManager ) { - /** - * The Enso engine version associated with the project. + /** The Enso engine version associated with the project. * * If the version in the configuration is set to `default`, the locally * default Enso version is used. @@ -33,18 +31,15 @@ class Project( case SemVerEnsoVersion(version) => version } - /** - * The package name of the project. + /** The package name of the project. */ def name: String = pkg.name - /** - * The path to the content root of the project. + /** The path to the content root of the project. */ def path: Path = pkg.root.toPath - /** - * Project configuration. + /** Project configuration. */ def config: Config = pkg.config } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectLoadingError.scala b/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectLoadingError.scala index 85f891fdd8..235a53deec 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectLoadingError.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectLoadingError.scala @@ -2,8 +2,7 @@ package org.enso.launcher.project import java.nio.file.Path -/** - * Indicates that it was impossible to load the project at a specified path. +/** Indicates that it was impossible to load the project at a specified path. */ case class ProjectLoadingError(path: Path, cause: Throwable) extends RuntimeException( @@ -11,8 +10,7 @@ case class ProjectLoadingError(path: Path, cause: Throwable) cause ) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = getMessage } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectManager.scala b/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectManager.scala index 996024f0ce..5867774be4 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectManager.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/project/ProjectManager.scala @@ -7,8 +7,7 @@ import org.enso.pkg.PackageManager import scala.util.{Failure, Try} -/** - * A helper class for project management. +/** A helper class for project management. * * It allows to create new project, open existing ones or traverse the * directory tree to find a project based on a path inside it. @@ -17,8 +16,7 @@ class ProjectManager(globalConfigurationManager: GlobalConfigurationManager) { private val packageManager = PackageManager.Default - /** - * Tries to load the project at the provided `path`. + /** Tries to load the project at the provided `path`. */ def loadProject(path: Path): Try[Project] = packageManager @@ -26,8 +24,7 @@ class ProjectManager(globalConfigurationManager: GlobalConfigurationManager) { .map(new Project(_, globalConfigurationManager)) .recoverWith(error => Failure(ProjectLoadingError(path, error))) - /** - * Traverses the directory tree looking for a project in one of the ancestors + /** Traverses the directory tree looking for a project in one of the ancestors * of the provided `path`. * * If a package file is missing in a directory, its ancestors are searched diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/Asset.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/Asset.scala index c354d99e65..3d0b1e8eec 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/Asset.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/Asset.scala @@ -4,18 +4,15 @@ import java.nio.file.Path import org.enso.cli.TaskProgress -/** - * Represents a downloadable release asset. +/** Represents a downloadable release asset. */ trait Asset { - /** - * Asset's filename. + /** Asset's filename. */ def fileName: String - /** - * Downloads the asset to the provided path. + /** Downloads the asset to the provided path. * * The path should include a filename for the asset (not just a parent * directory). @@ -25,8 +22,7 @@ trait Asset { */ def downloadTo(path: Path): TaskProgress[Unit] - /** - * Fetches the asset treating it as text data. + /** Fetches the asset treating it as text data. * * Returns a [[TaskProgress]] instance that will contain a [[String]] * containing the fetched text. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoReleaseProvider.scala index 973bfbb3e8..f8efdf6ad0 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoReleaseProvider.scala @@ -4,8 +4,7 @@ import org.enso.launcher.OS import scala.util.{Failure, Success, Try} -/** - * A helper class that implements the shared logic of engine and launcher +/** A helper class that implements the shared logic of engine and launcher * releases which handles listing releases excluding broken ones. * * @param simpleReleaseProvider a base release provided that provides the raw @@ -18,8 +17,7 @@ abstract class EnsoReleaseProvider[ReleaseType]( ) extends ReleaseProvider[ReleaseType] { protected val tagPrefix = "enso-" - /** - * @inheritdoc + /** @inheritdoc */ override def findLatestVersion(): Try[SemVer] = fetchAllValidVersions().flatMap { versions => @@ -28,8 +26,7 @@ abstract class EnsoReleaseProvider[ReleaseType]( } } - /** - * @inheritdoc + /** @inheritdoc */ override def fetchAllValidVersions(): Try[Seq[SemVer]] = simpleReleaseProvider.listReleases().map { releases => @@ -42,8 +39,7 @@ abstract class EnsoReleaseProvider[ReleaseType]( object EnsoReleaseProvider { - /** - * Returns a full system-dependent package name for a component with a given + /** Returns a full system-dependent package name for a component with a given * name and version. * * The package name can depend on the current OS and its architecture. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoRepository.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoRepository.scala index 343c065209..651239f202 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoRepository.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/EnsoRepository.scala @@ -14,8 +14,7 @@ import org.enso.launcher.releases.launcher.{ } import org.enso.launcher.releases.testing.FakeReleaseProvider -/** - * Represents the default Enso repository providing releases for the engine and +/** Represents the default Enso repository providing releases for the engine and * the launcher. * * In test mode, the default GitHub repository can be overridden with a local @@ -29,8 +28,7 @@ object EnsoRepository { "enso-staging" ) - /** - * Defines the URL of the fallback mechanism. + /** Defines the URL of the fallback mechanism. * * That URL must *never* be changed to ensure that all older launcher * versions can be upgraded. @@ -38,8 +36,7 @@ object EnsoRepository { private val launcherFallbackProviderHostname = "launcherfallback.release.enso.org" - /** - * Defines a part of the URL scheme of the fallback mechanism - the name of + /** Defines a part of the URL scheme of the fallback mechanism - the name of * the directory that holds the releases. * * That must *never* be changed to ensure that all older launcher versions @@ -52,20 +49,17 @@ object EnsoRepository { launcherFallbackReleaseDirectory ) - /** - * Default provider of engine releases. + /** Default provider of engine releases. */ def defaultEngineReleaseProvider: ReleaseProvider[EngineRelease] = new EngineReleaseProvider(defaultEngineRepository) - /** - * Default provider of launcher releases. + /** Default provider of launcher releases. */ def defaultLauncherReleaseProvider: ReleaseProvider[LauncherRelease] = new LauncherReleaseProvider(launcherRepository) - /** - * Overrides the default repository with a local filesystem based fake + /** Overrides the default repository with a local filesystem based fake * repository. * * Currently only the launcher repository is overridden. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/Release.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/Release.scala index a7afbf0278..458cd9826d 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/Release.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/Release.scala @@ -1,23 +1,19 @@ package org.enso.launcher.releases -/** - * Wraps a generic release identified by a tag and containing a sequence of +/** Wraps a generic release identified by a tag and containing a sequence of * assets. */ trait Release { - /** - * The tag identifying this release. + /** The tag identifying this release. */ def tag: String - /** - * The sequence of assets available in this release. + /** The sequence of assets available in this release. */ def assets: Seq[Asset] - /** - * Checks if the given release is marked as broken. + /** Checks if the given release is marked as broken. */ def isMarkedBroken: Boolean = assets.exists(_.fileName == "broken") } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProvider.scala index 4e3eed9c2f..f6dbee043b 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProvider.scala @@ -4,30 +4,26 @@ import nl.gn0s1s.bump.SemVer import scala.util.Try -/** - * A high-level release provider that includes release metadata. +/** A high-level release provider that includes release metadata. * @tparam ReleaseType type of a specific component's release, containing any * necessary metadata */ trait ReleaseProvider[ReleaseType] { - /** - * Returns the version of the most recent release. + /** Returns the version of the most recent release. * * It ignores releases marked as broken, so the latest non-broken release is * returned. */ def findLatestVersion(): Try[SemVer] - /** - * Returns sequence of available non-broken versions. + /** Returns sequence of available non-broken versions. * * The sequence does not have to be sorted. */ def fetchAllValidVersions(): Try[Seq[SemVer]] - /** - * Fetch release metadata for the given version. + /** Fetch release metadata for the given version. */ def fetchRelease(version: SemVer): Try[ReleaseType] } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProviderException.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProviderException.scala index a37c5ad008..5a96f2f2fd 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProviderException.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/ReleaseProviderException.scala @@ -1,13 +1,11 @@ package org.enso.launcher.releases -/** - * Indicates a release provider failure. +/** Indicates a release provider failure. */ case class ReleaseProviderException(message: String, cause: Throwable = null) extends RuntimeException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = s"A problem occurred when trying to find the release: $message" diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/SimpleReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/SimpleReleaseProvider.scala index 07bfe035df..7a3b2f0761 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/SimpleReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/SimpleReleaseProvider.scala @@ -2,18 +2,15 @@ package org.enso.launcher.releases import scala.util.Try -/** - * A generic release provider that allows to list and download releases. +/** A generic release provider that allows to list and download releases. */ trait SimpleReleaseProvider { - /** - * Finds a release for the given tag. + /** Finds a release for the given tag. */ def releaseForTag(tag: String): Try[Release] - /** - * Fetches a list of all releases. + /** Fetches a list of all releases. */ def listReleases(): Try[Seq[Release]] } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineRelease.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineRelease.scala index 409c88b2be..da1bebff9d 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineRelease.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineRelease.scala @@ -6,39 +6,33 @@ import nl.gn0s1s.bump.SemVer import org.enso.cli.TaskProgress import org.enso.launcher.components.Manifest -/** - * Represents an engine release. +/** Represents an engine release. */ trait EngineRelease { - /** - * Engine version. + /** Engine version. */ def version: SemVer - /** - * Manifest associated with the release. + /** Manifest associated with the release. * * @return */ def manifest: Manifest - /** - * Specifies whether this release is marked as broken. + /** Specifies whether this release is marked as broken. * @return */ def isBroken: Boolean - /** - * Determines the filename of the package that should be downloaded from this + /** Determines the filename of the package that should be downloaded from this * release. * * That filename may be platform specific. */ def packageFileName: String - /** - * Downloads the package associated with the release into `destination`. + /** Downloads the package associated with the release into `destination`. * * @param destination name of the file that will be created to contain the * downloaded package diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineReleaseProvider.scala index d8efd65811..b67e1901f5 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/engine/EngineReleaseProvider.scala @@ -14,14 +14,12 @@ import org.enso.launcher.releases.{ import scala.util.{Failure, Try} -/** - * Wraps a generic [[SimpleReleaseProvider]] to provide engine releases. +/** Wraps a generic [[SimpleReleaseProvider]] to provide engine releases. */ class EngineReleaseProvider(releaseProvider: SimpleReleaseProvider) extends EnsoReleaseProvider[EngineRelease](releaseProvider) { - /** - * @inheritdoc + /** @inheritdoc */ def fetchRelease(version: SemVer): Try[EngineRelease] = { val tag = tagPrefix + version.toString diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/FallbackReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/FallbackReleaseProvider.scala index 46fc2abf8f..b6bcbf9eea 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/FallbackReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/FallbackReleaseProvider.scala @@ -2,8 +2,7 @@ package org.enso.launcher.releases.fallback import org.enso.launcher.releases.SimpleReleaseProvider -/** - * A fallback [[SimpleReleaseProvider]]. +/** A fallback [[SimpleReleaseProvider]]. * * It should implement all the functionality of the [[SimpleReleaseProvider]], * but it is extended with a notion of availability. This provider should only @@ -11,8 +10,7 @@ import org.enso.launcher.releases.SimpleReleaseProvider */ trait FallbackReleaseProvider extends SimpleReleaseProvider { - /** - * Specifies if the fallback release provider is enabled and can be used. + /** Specifies if the fallback release provider is enabled and can be used. */ def isEnabled: Boolean } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/SimpleReleaseProviderWithFallback.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/SimpleReleaseProviderWithFallback.scala index a7cb569984..4132d1cc26 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/SimpleReleaseProviderWithFallback.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/SimpleReleaseProviderWithFallback.scala @@ -4,8 +4,7 @@ import org.enso.launcher.releases.{Release, SimpleReleaseProvider} import scala.util.{Failure, Try} -/** - * Extends a base release provider with a fallback method. +/** Extends a base release provider with a fallback method. * * If the `baseProvider` fails, the fallback method is checked for availability * and if it is available, it tries to recover. If the fallback method is @@ -16,8 +15,7 @@ class SimpleReleaseProviderWithFallback( fallbackProvider: FallbackReleaseProvider ) extends SimpleReleaseProvider { - /** - * @inheritdoc + /** @inheritdoc */ override def releaseForTag(tag: String): Try[Release] = baseProvider.releaseForTag(tag).recoverWith { error => @@ -26,8 +24,7 @@ class SimpleReleaseProviderWithFallback( else Failure(error) } - /** - * @inheritdoc + /** @inheritdoc */ override def listReleases(): Try[Seq[Release]] = baseProvider.listReleases().recoverWith { error => diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackAsset.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackAsset.scala index 4f767c9b0d..cb57a84171 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackAsset.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackAsset.scala @@ -5,8 +5,7 @@ import java.nio.file.Path import org.enso.cli.TaskProgress import org.enso.launcher.releases.Asset -/** - * An [[Asset]] provided by [[FallbackRelease]]. +/** An [[Asset]] provided by [[FallbackRelease]]. * * @param fileName filename of the asset * @param storage reference to the [[FileStorage]] associated with the @@ -21,14 +20,12 @@ case class FallbackAsset( releaseRoot: Seq[String] ) extends Asset { - /** - * @inheritdoc + /** @inheritdoc */ override def downloadTo(path: Path): TaskProgress[Unit] = storage.download(storagePath, destination = path) - /** - * @inheritdoc + /** @inheritdoc */ override def fetchAsText(): TaskProgress[String] = storage.fetchString(storagePath) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackManifest.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackManifest.scala index 011d0dfed3..151c36ebcf 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackManifest.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackManifest.scala @@ -4,8 +4,7 @@ import io.circe.Decoder import scala.util.Try -/** - * Manifest of the fallback mechanism. +/** Manifest of the fallback mechanism. * * Specifies whether the mechanism is enabled and should be considered * available. @@ -14,8 +13,7 @@ case class FallbackManifest(enabled: Boolean) object FallbackManifest { - /** - * Defines a part of the URL scheme of the fallback mechanism - the name of + /** Defines a part of the URL scheme of the fallback mechanism - the name of * manifest file. * * That must *never* be changed to ensure that all older launcher versions @@ -27,8 +25,7 @@ object FallbackManifest { val enabled = "enabled" } - /** - * [[Decoder]] instance for [[FallbackManifest]]. + /** [[Decoder]] instance for [[FallbackManifest]]. * * It should always remain backwards compatible, since the fallback mechanism * must work for all released launcher versions. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackRelease.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackRelease.scala index b99d20caf6..ef2c4632ba 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackRelease.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FallbackRelease.scala @@ -2,8 +2,7 @@ package org.enso.launcher.releases.fallback.staticwebsite import org.enso.launcher.releases.{Asset, Release} -/** - * A [[Release]] provided by the [[FileStorageFallbackReleaseProvider]]. +/** A [[Release]] provided by the [[FileStorageFallbackReleaseProvider]]. * * @param tag tag identifying the release * @param assetNames filenames of assets included in the release @@ -18,8 +17,7 @@ case class FallbackRelease( root: Seq[String] ) extends Release { - /** - * @inheritdoc + /** @inheritdoc */ override def assets: Seq[Asset] = assetNames.map(name => FallbackAsset(name, storage, root)) @@ -27,8 +25,7 @@ case class FallbackRelease( object FallbackRelease { - /** - * Creates a [[FallbackRelease]] from a [[ReleaseDescription]], a + /** Creates a [[FallbackRelease]] from a [[ReleaseDescription]], a * [[FileStorage]] and a path representing the root of the releases * directory in that storage. */ diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorage.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorage.scala index eab9afa4c9..93ea0267ed 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorage.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorage.scala @@ -4,8 +4,7 @@ import java.nio.file.Path import org.enso.cli.TaskProgress -/** - * A generic file storage that allows to download files or read them as +/** A generic file storage that allows to download files or read them as * [[String]]. * * Can be backed by a local filesystem or a web service. @@ -14,14 +13,12 @@ import org.enso.cli.TaskProgress */ trait FileStorage { - /** - * Downloads the file from storage `path` and saves it into `destination` on + /** Downloads the file from storage `path` and saves it into `destination` on * the local filesystem. */ def download(path: Seq[String], destination: Path): TaskProgress[Unit] - /** - * Fetches the file from storage `path` as a [[String]]. + /** Fetches the file from storage `path` as a [[String]]. */ def fetchString(path: Seq[String]): TaskProgress[String] } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorageFallbackReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorageFallbackReleaseProvider.scala index e2d25f1060..b2ea3d36e6 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorageFallbackReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/FileStorageFallbackReleaseProvider.scala @@ -6,8 +6,7 @@ import org.enso.launcher.releases.{Release, ReleaseProviderException} import scala.util.control.NonFatal import scala.util.{Failure, Success, Try} -/** - * Implements a fallback release provider which queries a simple file +/** Implements a fallback release provider which queries a simple file * [[storage]]. * * It has the following requirements: @@ -28,13 +27,11 @@ class FileStorageFallbackReleaseProvider( releasesDirectory: String ) extends FallbackReleaseProvider { - /** - * @inheritdoc + /** @inheritdoc */ override def isEnabled: Boolean = isEnabledCached - /** - * @inheritdoc + /** @inheritdoc */ override def releaseForTag(tag: String): Try[Release] = if (!isEnabled) { @@ -53,8 +50,7 @@ class FileStorageFallbackReleaseProvider( ) } - /** - * @inheritdoc + /** @inheritdoc */ override def listReleases(): Try[Seq[Release]] = if (!isEnabled) { diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/ReleaseList.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/ReleaseList.scala index c210c1c67c..0892833020 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/ReleaseList.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/ReleaseList.scala @@ -4,24 +4,21 @@ import io.circe.Decoder import scala.util.Try -/** - * Describes a release available in a [[FileStorageFallbackReleaseProvider]]. +/** Describes a release available in a [[FileStorageFallbackReleaseProvider]]. * * That release description can be used to create a concrete * [[FallbackRelease]] by adding the release provider specific information. */ case class ReleaseDescription(tag: String, assetNames: Seq[String]) -/** - * Contains the list of releases available in a +/** Contains the list of releases available in a * [[FileStorageFallbackReleaseProvider]]. */ case class ReleaseList(releases: Seq[ReleaseDescription]) object ReleaseList { - /** - * Defines a part of the URL scheme of the fallback mechanism - the name of + /** Defines a part of the URL scheme of the fallback mechanism - the name of * the file describing the contents of all available releases. * * That must *never* be changed to ensure that all older launcher versions @@ -35,8 +32,7 @@ object ReleaseList { val assets = "assets" } - /** - * [[Decoder]] instance for [[ReleaseDescription]]. + /** [[Decoder]] instance for [[ReleaseDescription]]. * * It should always remain backwards compatible, since the fallback mechanism * must work for all released launcher versions. @@ -48,8 +44,7 @@ object ReleaseList { } yield ReleaseDescription(tag, assets) } - /** - * [[Decoder]] instance for [[ReleaseList]]. + /** [[Decoder]] instance for [[ReleaseList]]. * * It should always remain backwards compatible, since the fallback mechanism * must work for all released launcher versions. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsite.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsite.scala index b810d66de6..58921868e0 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsite.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsite.scala @@ -5,15 +5,13 @@ import java.nio.file.Path import org.enso.cli.TaskProgress import org.enso.launcher.http.{HTTPDownload, HTTPRequestBuilder, URIBuilder} -/** - * Provides [[FileStorage]] backed by a static HTTPS website. +/** Provides [[FileStorage]] backed by a static HTTPS website. * * @param root [[URIBuilder]] for the website's storage root */ case class StaticWebsite(root: URIBuilder) extends FileStorage { - /** - * @inheritdoc + /** @inheritdoc */ override def download( path: Seq[String], @@ -21,8 +19,7 @@ case class StaticWebsite(root: URIBuilder) extends FileStorage { ): TaskProgress[Unit] = HTTPDownload.download(makeGETRequest(path), destination).map(_ => ()) - /** - * @inheritdoc + /** @inheritdoc */ override def fetchString(path: Seq[String]): TaskProgress[String] = HTTPDownload.fetchString(makeGETRequest(path)).map(_.content) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsiteFallbackReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsiteFallbackReleaseProvider.scala index 8348e52004..a321eb4565 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsiteFallbackReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/fallback/staticwebsite/StaticWebsiteFallbackReleaseProvider.scala @@ -6,8 +6,7 @@ import org.enso.launcher.releases.fallback.FallbackReleaseProvider import scala.util.Try -/** - * Implements a fallback release provider which queries a simple static web +/** Implements a fallback release provider which queries a simple static web * storage. * * This provider can use for example AWS S3 as its backend. @@ -35,19 +34,16 @@ class StaticWebsiteFallbackReleaseProvider( private val provider = new FileStorageFallbackReleaseProvider(storage, releasesDirectory) - /** - * @inheritdoc + /** @inheritdoc */ override def isEnabled: Boolean = provider.isEnabled - /** - * @inheritdoc + /** @inheritdoc */ override def releaseForTag(tag: String): Try[Release] = provider.releaseForTag(tag) - /** - * @inheritdoc + /** @inheritdoc */ override def listReleases(): Try[Seq[Release]] = provider.listReleases() } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAPI.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAPI.scala index 83692e7b80..e15fa11449 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAPI.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAPI.scala @@ -16,29 +16,25 @@ import org.enso.launcher.releases.ReleaseProviderException import scala.util.{Success, Try} -/** - * Contains functions used to query the GitHubAPI endpoints. +/** Contains functions used to query the GitHubAPI endpoints. */ object GithubAPI { - /** - * Represents a GitHub repository. + /** Represents a GitHub repository. * * @param owner owner of the repository * @param name name of the repository */ case class Repository(owner: String, name: String) - /** - * Represents a GitHub release. + /** Represents a GitHub release. * * @param tag tag associated with the release * @param assets sequence of assets present in this release */ case class Release(tag: String, assets: Seq[Asset]) - /** - * Represents an asset available in a [[Release]] + /** Represents an asset available in a [[Release]] * * @param name filename of that asset * @param url URL that can be used to download this asset @@ -46,8 +42,7 @@ object GithubAPI { */ case class Asset(name: String, url: String, size: Long) - /** - * Returns a list of all releases in the repository. + /** Returns a list of all releases in the repository. * * It fetches all available pages of releases, to make sure all releases are * included. This is necessary, because the GitHub API does not guarantee @@ -98,8 +93,7 @@ object GithubAPI { listAllPages(1) } - /** - * Fetches release metadata for the release associated with the given tag. + /** Fetches release metadata for the release associated with the given tag. */ def getRelease(repo: Repository, tag: String): TaskProgress[Release] = { val uri = projectURI(repo) / "releases" / "tags" / tag @@ -120,8 +114,7 @@ object GithubAPI { ) } - /** - * A helper function that detecte a rate-limit error and tries to make a more + /** A helper function that detecte a rate-limit error and tries to make a more * friendly user message. * * If the rate-limit is hit, an error message is returned by the API which is @@ -146,8 +139,7 @@ object GithubAPI { } } - /** - * Fetches an asset as text. + /** Fetches an asset as text. * * Returns a [[TaskProgress]] that will return the asset contents as a * [[String]] on success. @@ -161,8 +153,7 @@ object GithubAPI { HTTPDownload.fetchString(request, Some(asset.size)).map(_.content) } - /** - * Downloads the asset to the provided `destination`. + /** Downloads the asset to the provided `destination`. * * The returned [[TaskProgress]] succeeds iff the download was successful. */ diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAsset.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAsset.scala index 96a38e6978..748078289b 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAsset.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubAsset.scala @@ -7,19 +7,16 @@ import org.enso.launcher.releases.Asset case class GithubAsset(asset: GithubAPI.Asset) extends Asset { - /** - * @inheritdoc + /** @inheritdoc */ override def fileName: String = asset.name - /** - * @inheritdoc + /** @inheritdoc */ override def downloadTo(path: Path): TaskProgress[Unit] = GithubAPI.downloadAsset(asset, path) - /** - * @inheritdoc + /** @inheritdoc */ override def fetchAsText(): TaskProgress[String] = GithubAPI.fetchTextAsset(asset) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubRelease.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubRelease.scala index b32093d94d..77388bf4e2 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubRelease.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubRelease.scala @@ -4,13 +4,11 @@ import org.enso.launcher.releases.{Asset, Release} case class GithubRelease(release: GithubAPI.Release) extends Release { - /** - * @inheritdoc + /** @inheritdoc */ override def tag: String = release.tag - /** - * @inheritdoc + /** @inheritdoc */ override def assets: Seq[Asset] = release.assets.map(GithubAsset) } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubReleaseProvider.scala index 0d476f2601..c2917cf8ee 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/github/GithubReleaseProvider.scala @@ -4,8 +4,7 @@ import org.enso.launcher.releases.{Release, SimpleReleaseProvider} import scala.util.Try -/** - * Implements [[SimpleReleaseProvider]] providing releases from a specified GitHub +/** Implements [[SimpleReleaseProvider]] providing releases from a specified GitHub * repository using the GitHub Release API. * * @param owner owner of the repository @@ -17,14 +16,12 @@ class GithubReleaseProvider( ) extends SimpleReleaseProvider { private val repo = GithubAPI.Repository(owner, repositoryName) - /** - * @inheritdoc + /** @inheritdoc */ override def releaseForTag(tag: String): Try[Release] = GithubAPI.getRelease(repo, tag).waitForResult().map(GithubRelease) - /** - * @inheritdoc + /** @inheritdoc */ override def listReleases(): Try[Seq[Release]] = GithubAPI.listReleases(repo).map(_.map(GithubRelease)) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherManifest.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherManifest.scala index ebda43e6a4..f281b8e6d7 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherManifest.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherManifest.scala @@ -7,8 +7,7 @@ import org.enso.pkg.SemVerJson._ import scala.util.{Failure, Try} -/** - * Contains release metadata associated with a launcher release. +/** Contains release metadata associated with a launcher release. * * @param minimumVersionForUpgrade minimum version of the current launcher that * is required to upgrade to this version; if @@ -28,8 +27,7 @@ case class LauncherManifest( object LauncherManifest { - /** - * Default name of the asset containing the launcher manifest. + /** Default name of the asset containing the launcher manifest. */ val assetName: String = "launcher-manifest.yaml" @@ -39,8 +37,7 @@ object LauncherManifest { val directoriesToCopy = "directories-to-copy" } - /** - * [[Decoder]] instance for [[LauncherManifest]]. + /** [[Decoder]] instance for [[LauncherManifest]]. */ implicit val decoder: Decoder[LauncherManifest] = { json => for { @@ -56,8 +53,7 @@ object LauncherManifest { ) } - /** - * Tries to parse the [[LauncherManifest]] from a [[String]]. + /** Tries to parse the [[LauncherManifest]] from a [[String]]. */ def fromYAML(string: String): Try[LauncherManifest] = yaml.parser diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherRelease.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherRelease.scala index 9114ca67fa..6bc97e00ac 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherRelease.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherRelease.scala @@ -6,47 +6,39 @@ import nl.gn0s1s.bump.SemVer import org.enso.cli.TaskProgress import org.enso.launcher.CurrentVersion -/** - * Represents a launcher release. +/** Represents a launcher release. */ trait LauncherRelease { - /** - * Version of the release. + /** Version of the release. */ def version: SemVer - /** - * Minimum version of the launcher that is required to upgrade to this + /** Minimum version of the launcher that is required to upgrade to this * release. */ def minimumVersionToPerformUpgrade: SemVer = manifest.minimumVersionForUpgrade - /** - * Manifest associated with the release. + /** Manifest associated with the release. */ def manifest: LauncherManifest - /** - * Specifies if the release is marked as broken and should not generally be + /** Specifies if the release is marked as broken and should not generally be * used unless explicitly asked to. */ def isMarkedBroken: Boolean - /** - * Name of the asset containing the launcher package for the current platform + /** Name of the asset containing the launcher package for the current platform * inside of this release. */ def packageFileName: String - /** - * Downloads the launcher package to the specified destination. + /** Downloads the launcher package to the specified destination. */ def downloadPackage(path: Path): TaskProgress[Unit] - /** - * Checks if the current launcher version is allowed to upgrade directly to + /** Checks if the current launcher version is allowed to upgrade directly to * this release. * * If false, a multi-step upgrade must be performed. diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherReleaseProvider.scala index 0a3242aec6..80bf5a60bd 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/launcher/LauncherReleaseProvider.scala @@ -13,14 +13,12 @@ import org.enso.launcher.releases.{ import scala.util.Try -/** - * Wraps a generic [[SimpleReleaseProvider]] to provide launcher releases. +/** Wraps a generic [[SimpleReleaseProvider]] to provide launcher releases. */ class LauncherReleaseProvider(releaseProvider: SimpleReleaseProvider) extends EnsoReleaseProvider[LauncherRelease](releaseProvider) { - /** - * @inheritdoc + /** @inheritdoc */ override def fetchRelease(version: SemVer): Try[LauncherRelease] = { val tag = tagPrefix + version.toString diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/GraalCEReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/GraalCEReleaseProvider.scala index feb10f798f..e6707f3e43 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/GraalCEReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/GraalCEReleaseProvider.scala @@ -13,15 +13,13 @@ import org.enso.launcher.releases.{ import scala.util.{Failure, Success} -/** - * [[RuntimeReleaseProvider]] implementation providing Graal Community Edition +/** [[RuntimeReleaseProvider]] implementation providing Graal Community Edition * releases from the given [[SimpleReleaseProvider]]. */ class GraalCEReleaseProvider(releaseProvider: SimpleReleaseProvider) extends RuntimeReleaseProvider { - /** - * @inheritdoc + /** @inheritdoc */ override def packageFileName(version: RuntimeVersion): String = { val os = OS.operatingSystem match { @@ -38,8 +36,7 @@ class GraalCEReleaseProvider(releaseProvider: SimpleReleaseProvider) s"graalvm-ce-java${version.java}-$os-$arch-${version.graal}$extension" } - /** - * @inheritdoc + /** @inheritdoc */ override def downloadPackage( version: RuntimeVersion, @@ -66,8 +63,7 @@ class GraalCEReleaseProvider(releaseProvider: SimpleReleaseProvider) } } -/** - * Default [[RuntimeReleaseProvider]] that provides Graal CE releases using the +/** Default [[RuntimeReleaseProvider]] that provides Graal CE releases using the * GitHub Release API. */ object GraalCEReleaseProvider diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/RuntimeReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/RuntimeReleaseProvider.scala index a362bc75b9..203cf12617 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/RuntimeReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/runtime/RuntimeReleaseProvider.scala @@ -5,13 +5,11 @@ import java.nio.file.Path import org.enso.cli.TaskProgress import org.enso.launcher.components.RuntimeVersion -/** - * Interface for a service providing runtime releases. +/** Interface for a service providing runtime releases. */ trait RuntimeReleaseProvider { - /** - * Determines filename of the package that should be downloaded from the + /** Determines filename of the package that should be downloaded from the * release for a given version. * * The result of this function may be system specific (the package name may @@ -19,8 +17,7 @@ trait RuntimeReleaseProvider { */ def packageFileName(version: RuntimeVersion): String - /** - * Downloads a package for the given version to the provided location. + /** Downloads a package for the given version to the provided location. * @param version runtime version to download * @param destination name of the file that will be created to contain the * downloaded package diff --git a/engine/launcher/src/main/scala/org/enso/launcher/releases/testing/FakeReleaseProvider.scala b/engine/launcher/src/main/scala/org/enso/launcher/releases/testing/FakeReleaseProvider.scala index 04e75a0ec1..d52ac982ed 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/releases/testing/FakeReleaseProvider.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/releases/testing/FakeReleaseProvider.scala @@ -16,8 +16,7 @@ import scala.io.Source import scala.sys.process._ import scala.util.{Success, Try, Using} -/** - * A release provider that creates fake releases from the specified files. +/** A release provider that creates fake releases from the specified files. * * @param releasesRoot path to the directory containing subdirectories for each * release @@ -34,8 +33,7 @@ case class FakeReleaseProvider( .listDirectory(releasesRoot) .map(FakeRelease(_, copyIntoArchiveRoot, shouldWaitForAssets)) - /** - * @inheritdoc + /** @inheritdoc */ override def releaseForTag(tag: String): Try[Release] = releases @@ -43,14 +41,12 @@ case class FakeReleaseProvider( .toRight(ReleaseProviderException(s"Release $tag does not exist.")) .toTry - /** - * @inheritdoc + /** @inheritdoc */ override def listReleases(): Try[Seq[Release]] = Success(releases) } -/** - * The release created by [[FakeReleaseProvider]]. +/** The release created by [[FakeReleaseProvider]]. * * @param path path to the release root, each file or directory inside of it * represents a [[FakeAsset]] @@ -62,13 +58,11 @@ case class FakeRelease( shouldWaitForAssets: Boolean ) extends Release { - /** - * @inheritdoc + /** @inheritdoc */ override def tag: String = path.getFileName.toString - /** - * @inheritdoc + /** @inheritdoc */ override def assets: Seq[Asset] = { val pathsToCopy = copyIntoArchiveRoot.map(path.resolve) @@ -78,8 +72,7 @@ case class FakeRelease( } } -/** - * Represents an asset of the [[FakeRelease]]. +/** Represents an asset of the [[FakeRelease]]. * * If it is a file, 'downloading' it just copies it to the destination. * Fetching it reads it as text. @@ -96,13 +89,11 @@ case class FakeAsset( shouldWaitForAssets: Boolean ) extends Asset { - /** - * @inheritdoc + /** @inheritdoc */ override def fileName: String = source.getFileName.toString - /** - * @inheritdoc + /** @inheritdoc */ override def downloadTo(path: Path): TaskProgress[Unit] = { maybeWaitForAsset() @@ -116,8 +107,7 @@ case class FakeAsset( } } - /** - * If [[shouldWaitForAssets]] is set, acquires a shared lock on the asset. + /** If [[shouldWaitForAssets]] is set, acquires a shared lock on the asset. * * The test runner may grab an exclusive lock on an asset as a way to * synchronize actions (this download will wait until such exclusive lock is @@ -182,8 +172,7 @@ case class FakeAsset( private def copyNormalFile(destination: Path): Unit = FileSystem.copyFile(source, destination) - /** - * @inheritdoc + /** @inheritdoc */ override def fetchAsText(): TaskProgress[String] = if (Files.isDirectory(source)) diff --git a/engine/launcher/src/main/scala/org/enso/launcher/upgrade/AnotherUpgradeInProgressError.scala b/engine/launcher/src/main/scala/org/enso/launcher/upgrade/AnotherUpgradeInProgressError.scala index 8bc07f67d0..74173a0a11 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/upgrade/AnotherUpgradeInProgressError.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/upgrade/AnotherUpgradeInProgressError.scala @@ -1,7 +1,6 @@ package org.enso.launcher.upgrade -/** - * Error thrown when trying to upgrade, but another upgrade is in progress and +/** Error thrown when trying to upgrade, but another upgrade is in progress and * this one cannot continue. */ case class AnotherUpgradeInProgressError() @@ -9,8 +8,7 @@ case class AnotherUpgradeInProgressError() "Another upgrade is in progress. Please wait for it to finish." ) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = getMessage } diff --git a/engine/launcher/src/main/scala/org/enso/launcher/upgrade/LauncherUpgrader.scala b/engine/launcher/src/main/scala/org/enso/launcher/upgrade/LauncherUpgrader.scala index 9156284408..2ba13d7077 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/upgrade/LauncherUpgrader.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/upgrade/LauncherUpgrader.scala @@ -34,16 +34,14 @@ class LauncherUpgrader( private val logger = Logger[LauncherUpgrader] - /** - * Queries the release provider for the latest available valid launcher + /** Queries the release provider for the latest available valid launcher * version. */ def latestVersion(): Try[SemVer] = { releaseProvider.findLatestVersion() } - /** - * Performs an upgrade to the `targetVersion`. + /** Performs an upgrade to the `targetVersion`. * * The upgrade may first temporarily install versions older than the target * if the upgrade cannot be performed directly from the current version. @@ -93,8 +91,7 @@ class LauncherUpgrader( } } - /** - * Cleans up temporary and old launcher executables. + /** Cleans up temporary and old launcher executables. * * Some executables may fail to be cleaned the first time, if other launcher * instances are still running. To ensure that old executables are cleaned, @@ -121,8 +118,7 @@ class LauncherUpgrader( } } - /** - * Continues a multi-step upgrade. + /** Continues a multi-step upgrade. * * Called by [[InternalOpts]] when the upgrade continuation is requested by * [[runNextUpgradeStep]]. @@ -135,8 +131,7 @@ class LauncherUpgrader( performStepByStepUpgrade(release) } - /** - * Run the next step of the upgrade using the newly extracted newer launcher + /** Run the next step of the upgrade using the newly extracted newer launcher * version. * * @param temporaryExecutable path to the new, temporary launcher executable @@ -160,16 +155,14 @@ class LauncherUpgrader( private def showProgress = !globalCLIOptions.hideProgress - /** - * Path to the original launcher executable. + /** Path to the original launcher executable. */ private val originalExecutable = originalExecutablePath.getOrElse( distributionManager.env.getPathToRunningExecutable ) - /** - * Performs a step-by-step recursive upgrade. + /** Performs a step-by-step recursive upgrade. * * Finds a next version that can be directly upgraded to and is newer enough * to allow to upgrade to new versions, extracts it and runs it telling it to @@ -235,8 +228,7 @@ class LauncherUpgrader( else nextVersionToUpgradeTo(nextRelease, availableVersions) } - /** - * Extracts just the launcher executable from the archive. + /** Extracts just the launcher executable from the archive. * * @param archivePath path to the archive * @param executablePath path where to put the extracted executable @@ -336,8 +328,7 @@ class LauncherUpgrader( } } - /** - * Replaces the current launcher executable with a new one. + /** Replaces the current launcher executable with a new one. * * On UNIX systems, it just removes the old one and moves the new one in its * place. @@ -365,8 +356,7 @@ class LauncherUpgrader( object LauncherUpgrader { - /** - * Creates a [[LauncherUpgrader]] using the default [[DistributionManager]] + /** Creates a [[LauncherUpgrader]] using the default [[DistributionManager]] * and release providers. * * Should be run late enough so that the testing repository override can be @@ -390,8 +380,7 @@ object LauncherUpgrader { originalExecutablePath ) - /** - * Wraps an action and intercepts the [[LauncherUpgradeRequiredError]] + /** Wraps an action and intercepts the [[LauncherUpgradeRequiredError]] * offering to upgrade the launcher and re-run the command with the newer * version. * diff --git a/engine/launcher/src/main/scala/org/enso/launcher/upgrade/UpgradeError.scala b/engine/launcher/src/main/scala/org/enso/launcher/upgrade/UpgradeError.scala index 26cae5e002..7853ea7422 100644 --- a/engine/launcher/src/main/scala/org/enso/launcher/upgrade/UpgradeError.scala +++ b/engine/launcher/src/main/scala/org/enso/launcher/upgrade/UpgradeError.scala @@ -1,13 +1,11 @@ package org.enso.launcher.upgrade -/** - * Indicates an error during an upgrade. +/** Indicates an error during an upgrade. */ case class UpgradeError(message: String, cause: Throwable = null) extends RuntimeException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = message } diff --git a/engine/launcher/src/test/scala/org/enso/launcher/FakeEnvironment.scala b/engine/launcher/src/test/scala/org/enso/launcher/FakeEnvironment.scala index f6d4b54c87..5a018c6ad8 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/FakeEnvironment.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/FakeEnvironment.scala @@ -3,15 +3,13 @@ package org.enso.launcher import java.nio.file.{Files, Path} import org.enso.launcher.FileSystem.PathSyntax -/** - * A test-suite mixin that adds helper functions that create a fake environment +/** A test-suite mixin that adds helper functions that create a fake environment * which points to an Enso installation inside the temporary directory * generated for the test. */ trait FakeEnvironment { self: WithTemporaryDirectory => - /** - * Returns a fake path to the Enso executable that is inside the temporary + /** Returns a fake path to the Enso executable that is inside the temporary * directory for the test. * * @param portable specifies whether the distribution should be marked as @@ -26,8 +24,7 @@ trait FakeEnvironment { self: WithTemporaryDirectory => fakeBin / "enso" } - /** - * Returns an [[Environment]] instance that overrides the `ENSO_*` + /** Returns an [[Environment]] instance that overrides the `ENSO_*` * directories to be inside the temporary directory for the test. * * Additionall environment overrides may be passed that will also be added to diff --git a/engine/launcher/src/test/scala/org/enso/launcher/NativeTest.scala b/engine/launcher/src/test/scala/org/enso/launcher/NativeTest.scala index af3311b427..7f60ed03c4 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/NativeTest.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/NativeTest.scala @@ -17,8 +17,7 @@ import scala.concurrent.TimeoutException import scala.jdk.CollectionConverters._ import scala.jdk.StreamConverters._ -/** - * Contains helper methods for creating tests that need to run the native +/** Contains helper methods for creating tests that need to run the native * launcher binary. */ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { @@ -26,8 +25,7 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { override val timeLimit: Span = 60.seconds override val defaultTestSignaler: Signaler = _.interrupt() - /** - * A result of running the native launcher binary. + /** A result of running the native launcher binary. * * @param exitCode the returned exit code * @param stdout contents of the standard output stream @@ -46,20 +44,17 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { ) } - /** - * A scalatest Matcher that allows to write expressions like + /** A scalatest Matcher that allows to write expressions like * `run should returnSuccess`. */ def returnSuccess: RunSuccessMatcher.type = RunSuccessMatcher - /** - * Specifies if the current OS is Windows. + /** Specifies if the current OS is Windows. */ val isWindows: Boolean = System.getProperty("os.name").toLowerCase().contains("windows") - /** - * Runs the native launcher binary with the specified arguments and captures + /** Runs the native launcher binary with the specified arguments and captures * its output. * * @param args arguments to forward to the launcher @@ -82,8 +77,7 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { ) } - /** - * Runs the native launcher binary located at `pathToLauncher` with the + /** Runs the native launcher binary located at `pathToLauncher` with the * specified arguments and captures its output. * * @param pathToLauncher path to the launcher executable to run @@ -105,16 +99,14 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { run(Seq(pathToLauncher.toAbsolutePath.toString) ++ args, extraEnv.toSeq) } - /** - * Returns the expected location of the launcher binary compiled by the + /** Returns the expected location of the launcher binary compiled by the * Native Image. This binary can be copied into various places to test its * functionality. */ def baseLauncherLocation: Path = Path.of(".").resolve(OS.executableName("enso")) - /** - * Creates a copy of the tested launcher binary at the specified location. + /** Creates a copy of the tested launcher binary at the specified location. * * It waits a 100ms delay after creating the copy to ensure that the copy can * be called right away after calling this function. It is not absolutely @@ -132,8 +124,7 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { Thread.sleep(100) } - /** - * Runs the native launcher binary with the specified arguments and captures + /** Runs the native launcher binary with the specified arguments and captures * its output. * * @param args arguments to forward to the launcher @@ -151,8 +142,7 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { ) } - /** - * Starts the provided `command`. + /** Starts the provided `command`. * * `extraEnv` may be provided to extend the environment. Care must be taken * on Windows where environment variables are (mostly) case-insensitive. @@ -244,8 +234,7 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { outThread.start() errThread.start() - /** - * Waits for a message on the stderr to appear. + /** Waits for a message on the stderr to appear. */ def waitForMessageOnErrorStream( message: String, @@ -270,8 +259,7 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { } } - /** - * Starts printing the stdout and stderr of the started process to the + /** Starts printing the stdout and stderr of the started process to the * stdout with prefixes to indicate that these messages come from another * process. * @@ -298,15 +286,13 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { ) } - /** - * Tries to kill the process immediately. + /** Tries to kill the process immediately. */ def kill(): Unit = { process.destroyForcibly() } - /** - * Waits for the process to finish and returns its [[RunResult]]. + /** Waits for the process to finish and returns its [[RunResult]]. * * If `waitForDescendants` is set, tries to wait for descendants of the * launched process to finish too. Especially important on Windows where @@ -357,8 +343,7 @@ trait NativeTest extends AnyWordSpec with Matchers with TimeLimitedTests { } } - /** - * Runs the provided `command`. + /** Runs the provided `command`. * * `extraEnv` may be provided to extend the environment. Care must be taken * on Windows where environment variables are (mostly) case-insensitive. diff --git a/engine/launcher/src/test/scala/org/enso/launcher/TestHelpers.scala b/engine/launcher/src/test/scala/org/enso/launcher/TestHelpers.scala index bfe307bf9b..4b164e3c87 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/TestHelpers.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/TestHelpers.scala @@ -5,13 +5,11 @@ import java.nio.file.Path import scala.io.Source import scala.util.Using -/** - * Gathers helper functions for the test suite. +/** Gathers helper functions for the test suite. */ object TestHelpers { - /** - * Reads file contents into a [[String]]. + /** Reads file contents into a [[String]]. */ def readFileContent(path: Path): String = { Using(Source.fromFile(path.toFile)) { source => diff --git a/engine/launcher/src/test/scala/org/enso/launcher/WithTemporaryDirectory.scala b/engine/launcher/src/test/scala/org/enso/launcher/WithTemporaryDirectory.scala index e4685dd90e..0ca6b25cb0 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/WithTemporaryDirectory.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/WithTemporaryDirectory.scala @@ -6,35 +6,30 @@ import java.io.{File, IOException} import org.apache.commons.io.FileUtils import org.scalatest.{BeforeAndAfterEach, Suite} -/** - * Creates a separate temporary directory for each test. +/** Creates a separate temporary directory for each test. */ trait WithTemporaryDirectory extends Suite with BeforeAndAfterEach { private var testDirectory: Path = _ - /** - * @inheritdoc + /** @inheritdoc */ override def beforeEach(): Unit = { super.beforeEach() prepareTemporaryDirectory() } - /** - * @inheritdoc + /** @inheritdoc */ override def afterEach(): Unit = { super.afterEach() robustDeleteDirectory(testDirectory.toFile) } - /** - * Returns the temporary directory for this test. + /** Returns the temporary directory for this test. */ def getTestDirectory: Path = testDirectory.toAbsolutePath.normalize - /** - * Tries to remove the directory, retrying every 100ms for 3 seconds. + /** Tries to remove the directory, retrying every 100ms for 3 seconds. * * This is used because there may be some lag between the test finalizing and * the filesystem allowing to remove the files (especially on Windows, @@ -63,8 +58,7 @@ trait WithTemporaryDirectory extends Suite with BeforeAndAfterEach { testDirectory = Files.createTempDirectory("enso-test") } - /** - * Overrides the temporary directory with a fresh one so that the test can be + /** Overrides the temporary directory with a fresh one so that the test can be * safely retried. * * Without this, retried tests re-use the directory which may cause problems. diff --git a/engine/launcher/src/test/scala/org/enso/launcher/components/ComponentsManagerTest.scala b/engine/launcher/src/test/scala/org/enso/launcher/components/ComponentsManagerTest.scala index f4578ba0a5..e84d7420a9 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/components/ComponentsManagerTest.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/components/ComponentsManagerTest.scala @@ -28,8 +28,7 @@ class ComponentsManagerTest with FakeEnvironment with DropLogs { - /** - * Creates the [[DistributionManager]], [[ComponentsManager]] and an + /** Creates the [[DistributionManager]], [[ComponentsManager]] and an * [[Environment]] for use in the tests. * * Should be called separately for each test case, as the components use @@ -75,15 +74,13 @@ class ComponentsManagerTest (distributionManager, componentsManager, env) } - /** - * Returns just the [[ComponentsManager]]. + /** Returns just the [[ComponentsManager]]. * * See [[makeManagers]] for details. */ def makeComponentsManager(): ComponentsManager = makeManagers()._2 - /** - * Creates a new project using the default package manager. + /** Creates a new project using the default package manager. */ def newProject(name: String, path: Path, version: SemVer): Unit = { PackageManager.Default.create( diff --git a/engine/launcher/src/test/scala/org/enso/launcher/components/runner/RunnerSpec.scala b/engine/launcher/src/test/scala/org/enso/launcher/components/runner/RunnerSpec.scala index ea25db8f3b..b98681042f 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/components/runner/RunnerSpec.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/components/runner/RunnerSpec.scala @@ -148,7 +148,7 @@ class RunnerSpec extends ComponentsManagerTest { runSettings.version shouldEqual defaultEngineVersion runSettings.runnerArguments should (contain("arg") and contain("--flag")) runSettings.runnerArguments.mkString(" ") should - (include("--repl") and not include (s"--in-project")) + (include("--repl") and not include s"--in-project") } "run repl in project context" in { diff --git a/engine/launcher/src/test/scala/org/enso/launcher/installation/InstallerSpec.scala b/engine/launcher/src/test/scala/org/enso/launcher/installation/InstallerSpec.scala index 91221b9bba..ffb0f5ffca 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/installation/InstallerSpec.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/installation/InstallerSpec.scala @@ -40,8 +40,7 @@ class InstallerSpec extends NativeTest with WithTemporaryDirectory { FileSystem.writeTextFile(runtimeBundle / "jvm.txt", "") } - /** - * Checks if the file does not exist, retrying `retry` times with a 200ms + /** Checks if the file does not exist, retrying `retry` times with a 200ms * delay between retries. * * Useful to check if the file was removed, but the removal action is not diff --git a/engine/launcher/src/test/scala/org/enso/launcher/installation/UninstallerSpec.scala b/engine/launcher/src/test/scala/org/enso/launcher/installation/UninstallerSpec.scala index 9e295ebd0f..f2b033af03 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/installation/UninstallerSpec.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/installation/UninstallerSpec.scala @@ -8,8 +8,7 @@ import org.enso.launcher.{FileSystem, NativeTest, OS, WithTemporaryDirectory} class UninstallerSpec extends NativeTest with WithTemporaryDirectory { def installedRoot: Path = getTestDirectory / "installed" - /** - * Prepares an installed distribution for the purposes of testing + /** Prepares an installed distribution for the purposes of testing * uninstallation. * * @param everythingInsideData if true, config and binary directory are put diff --git a/engine/launcher/src/test/scala/org/enso/launcher/locking/ConcurrencyTest.scala b/engine/launcher/src/test/scala/org/enso/launcher/locking/ConcurrencyTest.scala index 1397f6e7f2..6aaa4b415c 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/locking/ConcurrencyTest.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/locking/ConcurrencyTest.scala @@ -57,22 +57,19 @@ class ConcurrencyTest testLocalLockManager = Some(new TestLocalLockManager) } - /** - * A separate [[LockManager]] for each test case. + /** A separate [[LockManager]] for each test case. * @return */ def lockManager: LockManager = testLocalLockManager.get - /** - * Each call creates a distinct [[ResourceManager]], but all resource + /** Each call creates a distinct [[ResourceManager]], but all resource * managers created within one test case share the same [[lockManager]], so * that they see each other's locks. */ def makeNewResourceManager(): ResourceManager = new ResourceManager(lockManager) - /** - * Creates a [[DistributionManager]] and [[ComponentsManager]] that can be + /** Creates a [[DistributionManager]] and [[ComponentsManager]] that can be * used in a test. * * @param releaseCallback called when a release asset is fetched @@ -145,8 +142,7 @@ class ConcurrencyTest (distributionManager, componentsManager) } - /** - * Helper function, acts as [[makeManagers]] but returns only the + /** Helper function, acts as [[makeManagers]] but returns only the * [[ComponentsManager]]. */ def makeComponentsManager( @@ -161,8 +157,7 @@ class ConcurrencyTest "locks" should { "synchronize parallel installations with the same runtime" in { - /** - * Two threads start installing different engines in parallel, but these + /** Two threads start installing different engines in parallel, but these * engines use the same runtime. The second thread is stalled on * downloading its engine package, so that the first one can start * downloading the runtime. When it starts downloading, it is suspended @@ -238,8 +233,7 @@ class ConcurrencyTest "synchronize installation and usage" in { - /** - * The first thread starts installing the engine, but is suspended when + /** The first thread starts installing the engine, but is suspended when * downloading the package. The second thread then tries to use it, but * it should wait until the installation is finished. */ @@ -297,8 +291,7 @@ class ConcurrencyTest "synchronize uninstallation and usage" in { - /** - * The first thread starts using the engine, while in the meantime + /** The first thread starts using the engine, while in the meantime * another thread starts uninstalling it. The second thread has to wait * with uninstalling until the first one finishes using it. */ @@ -353,8 +346,7 @@ class ConcurrencyTest "synchronize main lock" in { - /** - * First two threads start and acquire the shared lock, than the third + /** First two threads start and acquire the shared lock, than the third * thread tries to acquire an exclusive lock (in practice that will be our * (un)installer), it should wait for the other threads to finish. When * the threads see that it started waiting (the waiting notification is diff --git a/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalLockManager.scala b/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalLockManager.scala index 6bb42b82cf..e3d19ed228 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalLockManager.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalLockManager.scala @@ -7,8 +7,7 @@ import java.util.concurrent.locks.{ Lock => JLock } -/** - * A [[LockManager]] that creates process-local locks. +/** A [[LockManager]] that creates process-local locks. * * The locks are not visible by other processes, so this manager is not useful * for synchronizing multiple processes. It can be used to test concurrency @@ -20,8 +19,7 @@ import java.util.concurrent.locks.{ */ class TestLocalLockManager extends LockManager { - /** - * @inheritdoc + /** @inheritdoc */ override def acquireLock(resourceName: String, lockType: LockType): Lock = { val lock = getLock(resourceName, lockType) @@ -34,8 +32,7 @@ class TestLocalLockManager extends LockManager { WrapLock(lock) } - /** - * @inheritdoc + /** @inheritdoc */ override def tryAcquireLock( resourceName: String, diff --git a/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalResourceManager.scala b/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalResourceManager.scala index df8ebc268b..bc0e908c04 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalResourceManager.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/locking/TestLocalResourceManager.scala @@ -2,8 +2,7 @@ package org.enso.launcher.locking object TestLocalResourceManager { - /** - * Creates a [[ResourceManager]] that manages resource access between threads + /** Creates a [[ResourceManager]] that manages resource access between threads * of a single process. * * The resource locks are not visible by other processes, so this manager is diff --git a/engine/launcher/src/test/scala/org/enso/launcher/locking/TestSynchronizer.scala b/engine/launcher/src/test/scala/org/enso/launcher/locking/TestSynchronizer.scala index 7c6d207bb2..50b406bcbb 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/locking/TestSynchronizer.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/locking/TestSynchronizer.scala @@ -5,8 +5,7 @@ import java.util.concurrent.{Semaphore, TimeUnit} import org.scalatest.exceptions.TestFailedException import scala.jdk.CollectionConverters._ -/** - * A helper class that can be used to synchronize actions between multiple +/** A helper class that can be used to synchronize actions between multiple * threads to create interleaving scenarios useful in testing concurrent * interaction. * @@ -15,16 +14,14 @@ import scala.jdk.CollectionConverters._ */ class TestSynchronizer { - /** - * If enabled, prints additional debug messages describing when events are + /** If enabled, prints additional debug messages describing when events are * signalled or waited for. * * Can be enabled to aid with debugging, but should be disabled by default. */ val enableDebugOutput: Boolean = false - /** - * Executes the `action` in a separate thread with the given `name` + /** Executes the `action` in a separate thread with the given `name` */ def startThread(name: String)(action: => Unit): Unit = { val thread = new Thread(() => action, name) @@ -33,8 +30,7 @@ class TestSynchronizer { thread.start() } - /** - * Waits for a signal indicating that an event with the specified name has + /** Waits for a signal indicating that an event with the specified name has * happened. * * Will return immediately if the event has happened prior to calling that @@ -59,8 +55,7 @@ class TestSynchronizer { } } - /** - * Signals that an event has happened. + /** Signals that an event has happened. * * Will wake up the thread waiting for it. Only one waiting thread is woken * up, so if multiple threads wait for the same event, it must be signalled @@ -75,13 +70,11 @@ class TestSynchronizer { getSemaphore(event).release() } - /** - * Timeout used by [[waitFor]]. + /** Timeout used by [[waitFor]]. */ val timeOutSeconds: Long = 20 - /** - * Reports that the event has happened now. + /** Reports that the event has happened now. * * Can be used to test for order of events. Independent of [[waitFor]] and * [[signal]]. @@ -94,8 +87,7 @@ class TestSynchronizer { reports.add(event) } - /** - * Returns names of events reported using [[report]] in the order that they + /** Returns names of events reported using [[report]] in the order that they * were reported. * * Should only be called *after* [[join]]. @@ -113,8 +105,7 @@ class TestSynchronizer { hadException = true } - /** - * Waits for all threads started with [[startThread]] to finish execution. + /** Waits for all threads started with [[startThread]] to finish execution. * * Reports any exceptions thrown inside of the threads or if any of the * threads has timed out. diff --git a/engine/launcher/src/test/scala/org/enso/launcher/releases/fallback/FileStorageFallbackReleaseProviderSpec.scala b/engine/launcher/src/test/scala/org/enso/launcher/releases/fallback/FileStorageFallbackReleaseProviderSpec.scala index 19304b5b08..e29cb9448a 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/releases/fallback/FileStorageFallbackReleaseProviderSpec.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/releases/fallback/FileStorageFallbackReleaseProviderSpec.scala @@ -47,16 +47,14 @@ class FileStorageFallbackReleaseProviderSpec "fail with IllegalStateException if it is queried but unavailable" in { val provider = makeProvider(Provider.Unavailable) - inside(provider.listReleases()) { - case Failure(exception) => - exception shouldBe an[IllegalStateException] - exception.getMessage should include("provider is unavailable") + inside(provider.listReleases()) { case Failure(exception) => + exception shouldBe an[IllegalStateException] + exception.getMessage should include("provider is unavailable") } - inside(provider.releaseForTag("tag")) { - case Failure(exception) => - exception shouldBe an[IllegalStateException] - exception.getMessage should include("provider is unavailable") + inside(provider.releaseForTag("tag")) { case Failure(exception) => + exception shouldBe an[IllegalStateException] + exception.getMessage should include("provider is unavailable") } } diff --git a/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala b/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala index ddb239c370..c5458b298d 100644 --- a/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala +++ b/engine/launcher/src/test/scala/org/enso/launcher/upgrade/UpgradeSpec.scala @@ -18,37 +18,32 @@ class UpgradeSpec with BeforeAndAfterAll with OptionValues { - /** - * Location of the fake releases root. + /** Location of the fake releases root. */ private val fakeReleaseRoot = Path - .of( - getClass - .getResource("/org/enso/launcher/components/fake-releases") - .toURI - ) / "launcher" + .of( + getClass + .getResource("/org/enso/launcher/components/fake-releases") + .toURI + ) / "launcher" - /** - * Location of built Rust artifacts. + /** Location of built Rust artifacts. */ private val rustBuildRoot = Path.of("./target/rust/debug/") - /** - * Location of the actual launcher executable that is wrapped by the shims. + /** Location of the actual launcher executable that is wrapped by the shims. */ private val realLauncherLocation = Path.of(".").resolve(OS.executableName("enso")).toAbsolutePath.normalize - /** - * Path to a launcher shim that pretends to be `version`. + /** Path to a launcher shim that pretends to be `version`. */ private def builtLauncherBinary(version: SemVer): Path = { val simplifiedVersion = version.toString.replaceAll("[.-]", "") rustBuildRoot / OS.executableName(s"launcher_$simplifiedVersion") } - /** - * Copies a launcher shim into the fake release directory. + /** Copies a launcher shim into the fake release directory. */ private def prepareLauncherBinary(version: SemVer): Unit = { val os = OS.operatingSystem.configName @@ -74,8 +69,7 @@ class UpgradeSpec prepareLauncherBinary(SemVer(0, 0, 4)) } - /** - * Prepares a launcher distribution in the temporary test location. + /** Prepares a launcher distribution in the temporary test location. * * If `launcherVersion` is not provided, the default one is used. * @@ -104,14 +98,12 @@ class UpgradeSpec Thread.sleep(100) } - /** - * Path to the launcher executable in the temporary distribution. + /** Path to the launcher executable in the temporary distribution. */ private def launcherPath = getTestDirectory / "enso" / "bin" / OS.executableName("enso") - /** - * Runs `enso version` to inspect the version reported by the launcher. + /** Runs `enso version` to inspect the version reported by the launcher. * @return the reported version */ private def checkVersion(): SemVer = { @@ -129,8 +121,7 @@ class UpgradeSpec SemVer(version.asObject.value.apply("version").value.asString.value).value } - /** - * Runs the launcher in the temporary distribution. + /** Runs the launcher in the temporary distribution. * * @param args arguments for the launcher * @param extraEnv environment variable overrides @@ -141,8 +132,7 @@ class UpgradeSpec extraEnv: Map[String, String] = Map.empty ): RunResult = startLauncher(args, extraEnv).join(timeoutSeconds = 20) - /** - * Starts the launcher in the temporary distribution. + /** Starts the launcher in the temporary distribution. * * @param args arguments for the launcher * @param extraEnv environment variable overrides diff --git a/engine/polyglot-api/src/main/java/org/enso/polyglot/RuntimeServerInfo.java b/engine/polyglot-api/src/main/java/org/enso/polyglot/RuntimeServerInfo.java index 38e70bef4a..7adaa761bb 100644 --- a/engine/polyglot-api/src/main/java/org/enso/polyglot/RuntimeServerInfo.java +++ b/engine/polyglot-api/src/main/java/org/enso/polyglot/RuntimeServerInfo.java @@ -12,5 +12,5 @@ public class RuntimeServerInfo { public static final String JOB_PARALLELISM_OPTION = INSTRUMENT_NAME + ".jobParallelism"; public static final OptionKey JOB_PARALLELISM_KEY = new OptionKey<>(1); public static final OptionDescriptor JOB_PARALLELISM_DESCRIPTOR = - OptionDescriptor.newBuilder(JOB_PARALLELISM_KEY, JOB_PARALLELISM_OPTION).build(); + OptionDescriptor.newBuilder(JOB_PARALLELISM_KEY, JOB_PARALLELISM_OPTION).build(); } diff --git a/engine/polyglot-api/src/main/java/org/enso/polyglot/debugger/DebugServerInfo.java b/engine/polyglot-api/src/main/java/org/enso/polyglot/debugger/DebugServerInfo.java index e590d11da8..9665c7a795 100644 --- a/engine/polyglot-api/src/main/java/org/enso/polyglot/debugger/DebugServerInfo.java +++ b/engine/polyglot-api/src/main/java/org/enso/polyglot/debugger/DebugServerInfo.java @@ -1,8 +1,6 @@ package org.enso.polyglot.debugger; -/** - * Container for Runtime Server related constants. - */ +/** Container for Runtime Server related constants. */ public class DebugServerInfo { public static final String URI = "enso://debug-server"; public static final String INSTRUMENT_NAME = "enso-debug-server"; diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Function.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Function.scala index ebba24b9d7..744e4aa5ba 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Function.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Function.scala @@ -2,23 +2,20 @@ package org.enso.polyglot import org.graalvm.polyglot.Value -/** - * Represents an Enso function. +/** Represents an Enso function. * * @param value the polyglot value of this function */ class Function(val value: Value) { - /** - * Executes the function with given parameters. + /** Executes the function with given parameters. * * @param args the execution arguments * @return the result of execution */ def execute(args: AnyRef*): Value = value.execute(args: _*) - /** - * Checks function equality by checking the identity of the underlying + /** Checks function equality by checking the identity of the underlying * objects. * * @param obj the other comparison operand diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala index 81d1730e71..37a08edfb0 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala @@ -2,30 +2,26 @@ package org.enso.polyglot import org.graalvm.polyglot.Value -/** - * Represents an Enso Module. +/** Represents an Enso Module. * * @param value the polyglot value of this scope */ class Module(private val value: Value) { import MethodNames.Module._ - /** - * @return the associated type of this module + /** @return the associated type of this module */ def getAssociatedConstructor: Value = value.invokeMember(GET_ASSOCIATED_CONSTRUCTOR) - /** - * Gets a constructor definition by name + /** Gets a constructor definition by name * @param name the constructor name * @return the polyglot representation of the constructor. */ def getConstructor(name: String): Value = value.invokeMember(GET_CONSTRUCTOR, name) - /** - * Gets a method by the type it's defined on and name. + /** Gets a method by the type it's defined on and name. * * @param constructor the constructor the method is defined on * @param name the name of the method @@ -34,8 +30,7 @@ class Module(private val value: Value) { def getMethod(constructor: Value, name: String): Function = new Function(value.invokeMember(GET_METHOD, constructor, name)) - /** - * Evaluates an arbitrary expression as if it were placed in a function + /** Evaluates an arbitrary expression as if it were placed in a function * body inside this module. * @param code the expression to evaluate * @return the return value of the expression @@ -43,8 +38,7 @@ class Module(private val value: Value) { def evalExpression(code: String): Value = value.invokeMember(EVAL_EXPRESSION, code) - /** - * Triggers reparsing of module sources. Used to notify the module that + /** Triggers reparsing of module sources. Used to notify the module that * sources have changed. */ def reparse(): Unit = { diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/PolyglotContext.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/PolyglotContext.scala index b660f3822d..32c03297c6 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/PolyglotContext.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/PolyglotContext.scala @@ -3,14 +3,12 @@ import java.io.File import org.graalvm.polyglot.{Context, Source} -/** - * Exposes language specific aliases for generic polyglot context operations. +/** Exposes language specific aliases for generic polyglot context operations. * @param context the Graal polyglot context to use. */ class PolyglotContext(val context: Context) { - /** - * Evaluates provided code string as a new module. + /** Evaluates provided code string as a new module. * * @param code the code to evaluate. * @param moduleName the name for the newly parsed module. @@ -23,8 +21,7 @@ class PolyglotContext(val context: Context) { new Module(context.eval(source)) } - /** - * Evaluates provided code file as a new module. + /** Evaluates provided code file as a new module. * * @param codeFile the code to evaluate. * @return the module representing evaluated code. @@ -34,8 +31,7 @@ class PolyglotContext(val context: Context) { new Module(context.eval(source)) } - /** - * @return the top scope of Enso execution context + /** @return the top scope of Enso execution context */ def getTopScope: TopScope = { new TopScope(context.getBindings(LanguageInfo.ID)) diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Suggestion.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Suggestion.scala index d50ef67a30..4b57a1c085 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Suggestion.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Suggestion.scala @@ -29,8 +29,8 @@ import com.fasterxml.jackson.annotation.{JsonSubTypes, JsonTypeInfo} sealed trait Suggestion { def externalId: Option[Suggestion.ExternalId] - def module: String - def name: String + def module: String + def name: String def returnType: String } diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/TopScope.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/TopScope.scala index 085eeb110a..291ff70b31 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/TopScope.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/TopScope.scala @@ -2,8 +2,7 @@ package org.enso.polyglot import org.graalvm.polyglot.Value -/** - * Represents the top scope of Enso execution context +/** Represents the top scope of Enso execution context * * @param value the polyglot value of this scope */ @@ -18,8 +17,7 @@ class TopScope(private val value: Value) { def getModule(name: String): Module = new Module(value.invokeMember(GET_MODULE, name)) - /** - * Creates a new, unregistered module. + /** Creates a new, unregistered module. * * The returned module is not accessible through [[getModule()]]. * diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Debugger.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Debugger.scala index 79fbaeb927..9d83a520da 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Debugger.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Debugger.scala @@ -18,8 +18,7 @@ import org.enso.polyglot.debugger.protocol.{ object Debugger { - /** - * Deserializes a byte buffer into a Request message. + /** Deserializes a byte buffer into a Request message. * * @param bytes the buffer to deserialize * @return the deserialized message, if the byte buffer can be deserialized. @@ -53,8 +52,7 @@ object Debugger { ) } - /** - * Deserializes a byte buffer into a Response message. + /** Deserializes a byte buffer into a Response message. * * @param bytes the buffer to deserialize * @return the deserialized message, if the byte buffer can be deserialized. @@ -101,8 +99,7 @@ object Debugger { ) } - /** - * Creates an EvaluationRequest message in the form of a ByteBuffer that can + /** Creates an EvaluationRequest message in the form of a ByteBuffer that can * be sent to the debugger. * * @param expression expression to evaluate @@ -120,8 +117,7 @@ object Debugger { builder.dataBuffer() } - /** - * Creates a ListBindingsRequest message in the form of a ByteBuffer that can + /** Creates a ListBindingsRequest message in the form of a ByteBuffer that can * be sent to the debugger. * * @return the serialized message @@ -138,8 +134,7 @@ object Debugger { builder.dataBuffer() } - /** - * Creates a ExitRequest message in the form of a ByteBuffer that can be sent + /** Creates a ExitRequest message in the form of a ByteBuffer that can be sent * to the debugger. * * @return the serialized message @@ -156,8 +151,7 @@ object Debugger { builder.dataBuffer() } - /** - * Creates an EvaluationSuccess message in the form of a ByteBuffer that can + /** Creates an EvaluationSuccess message in the form of a ByteBuffer that can * be sent from the debugger. * * @param result evaluation result @@ -175,8 +169,7 @@ object Debugger { builder.dataBuffer() } - /** - * Creates an EvaluationFailure message in the form of a ByteBuffer that can + /** Creates an EvaluationFailure message in the form of a ByteBuffer that can * be sent from the debugger. * * @param exception the exception that caused the failure @@ -194,8 +187,7 @@ object Debugger { builder.dataBuffer() } - /** - * Creates a ListBindingsResult message in the form of a ByteBuffer that can + /** Creates a ListBindingsResult message in the form of a ByteBuffer that can * be sent from the debugger. * * @param bindings mapping from names to bound values @@ -213,8 +205,7 @@ object Debugger { builder.dataBuffer() } - /** - * Creates a ListBindingsResult message in the form of a ByteBuffer that can + /** Creates a ListBindingsResult message in the form of a ByteBuffer that can * be sent from the debugger. * Alternative version that is more friendly to Java code. * @@ -226,8 +217,7 @@ object Debugger { ): ByteBuffer = createListBindingsResult(bindings.asScala.toMap) - /** - * Creates an SessionStartNotification message in the form of a ByteBuffer + /** Creates an SessionStartNotification message in the form of a ByteBuffer * that can be sent from the debugger. * * @return the serialized message @@ -255,8 +245,7 @@ object Debugger { ) } - /** - * Creates an instance of java.lang.Exception based on the + /** Creates an instance of java.lang.Exception based on the * ExceptionRepresentation. * * The created Exception has the same stack trace as the original. The diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/DebuggerSessionManagerEndpoint.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/DebuggerSessionManagerEndpoint.scala index 0c044248d7..5ea040c370 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/DebuggerSessionManagerEndpoint.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/DebuggerSessionManagerEndpoint.scala @@ -4,8 +4,7 @@ import java.nio.ByteBuffer import org.graalvm.polyglot.io.MessageEndpoint -/** - * Class that can be returned by serverTransport to establish communication +/** Class that can be returned by serverTransport to establish communication * with the ReplDebuggerInstrument. */ class DebuggerSessionManagerEndpoint( diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/ObjectRepresentation.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/ObjectRepresentation.scala index 78c39a1e1a..3985250c6a 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/ObjectRepresentation.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/ObjectRepresentation.scala @@ -1,7 +1,6 @@ package org.enso.polyglot.debugger -/** - * A user-friendly wrapper for the internal object representation used in the +/** A user-friendly wrapper for the internal object representation used in the * binary protocol */ class ObjectRepresentation(val representation: protocol.ObjectRepresentation) diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Request.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Request.scala index e9d610b96e..bfdc9741b0 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Request.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Request.scala @@ -1,26 +1,22 @@ package org.enso.polyglot.debugger -/** - * Represents a deserialized request that is received at the debugger. +/** Represents a deserialized request that is received at the debugger. * * It is a separate class from BinaryRequest to encapsulate Flatbuffers union * handling logic in a type-safe way. */ sealed trait Request -/** - * Represents an evaluation request. +/** Represents an evaluation request. * * @param expression expression to evaluate */ case class EvaluationRequest(expression: String) extends Request -/** - * Represents a list bindings request. +/** Represents a list bindings request. */ object ListBindingsRequest extends Request -/** - * Represents a request to end debugger session. +/** Represents a request to end debugger session. */ object SessionExitRequest extends Request diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Response.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Response.scala index 4d6c901242..0454902c1f 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Response.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/Response.scala @@ -5,23 +5,20 @@ import org.enso.polyglot.debugger.protocol.{ ObjectRepresentation } -/** - * Represents a deserialized response returned from the debugger. +/** Represents a deserialized response returned from the debugger. * * It is a separate class from BinaryResponse to encapsulate Flatbuffers union * handling logic in a type-safe way. */ sealed trait Response -/** - * Represents an evaluation success. +/** Represents an evaluation success. * * @param result over-the-wire representation of evaluation result */ case class EvaluationSuccess(result: ObjectRepresentation) extends Response -/** - * Represents an evaluation failure. +/** Represents an evaluation failure. * * @param exception over-the-wire representation of the exception that caused * the failure @@ -29,16 +26,14 @@ case class EvaluationSuccess(result: ObjectRepresentation) extends Response case class EvaluationFailure(exception: ExceptionRepresentation) extends Response -/** - * Represents the returned list of bindings. +/** Represents the returned list of bindings. * * @param bindings mapping from names to bound values */ case class ListBindingsResult(bindings: Map[String, ObjectRepresentation]) extends Response -/** - * Notification that is sent from the debugger that a REPL session should be +/** Notification that is sent from the debugger that a REPL session should be * started. */ object SessionStartNotification extends Response diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/SessionManager.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/SessionManager.scala index 4406a00e0b..ff21fe6501 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/SessionManager.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/SessionManager.scala @@ -1,15 +1,13 @@ package org.enso.polyglot.debugger -/** - * Interface for executing Repl commands inside of a Repl session. +/** Interface for executing Repl commands inside of a Repl session. * * A single instance is valid only during the current session, it is provided * to the SessionManager on start of each session. */ trait ReplExecutor { - /** - * Evaluates an arbitrary expression in the current execution context. + /** Evaluates an arbitrary expression in the current execution context. * * @param expression the expression to evaluate * @return the result of evaluating the expression or error @@ -18,16 +16,14 @@ trait ReplExecutor { expression: String ): Either[Exception, ObjectRepresentation] - /** - * Lists all the bindings available in the current execution scope. + /** Lists all the bindings available in the current execution scope. * * @return a map, where keys are variable names and values are current * values of variables. */ def listBindings(): Map[String, ObjectRepresentation] - /** - * Terminates this REPL session. + /** Terminates this REPL session. * * The last result of [[evaluate]] (or `Unit` if [[evaluate]] was not called * before) will be returned from the instrumented node. @@ -41,14 +37,12 @@ trait ReplExecutor { def exit(): Nothing } -/** - * Trait that should be implemented by Repl users to define how to handle Repl +/** Trait that should be implemented by Repl users to define how to handle Repl * sessions. */ trait SessionManager { - /** - * Method that is run when starting each Repl session. The whole session + /** Method that is run when starting each Repl session. The whole session * lives inside this method. It should always be finished by running * `executor.exit()`. * diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ExceptionRepresentationFactory.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ExceptionRepresentationFactory.scala index 1846a73821..4adf66f65b 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ExceptionRepresentationFactory.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ExceptionRepresentationFactory.scala @@ -9,8 +9,7 @@ import java.lang.{StackTraceElement => JStackTraceElement} object ExceptionRepresentationFactory { - /** - * Creates ExceptionRepresentation inside a [[FlatBufferBuilder]]. + /** Creates ExceptionRepresentation inside a [[FlatBufferBuilder]]. * * @param ex an exception (any Throwable) to serialize * @param builder a class that helps build a FlatBuffer representation of diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ObjectRepresentationFactory.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ObjectRepresentationFactory.scala index 5b7c8c962c..87e5ad8d0a 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ObjectRepresentationFactory.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ObjectRepresentationFactory.scala @@ -5,8 +5,7 @@ import org.enso.polyglot.debugger.protocol.ObjectRepresentation object ObjectRepresentationFactory { - /** - * Creates ObjectRepresentation inside a [[FlatBufferBuilder]]. + /** Creates ObjectRepresentation inside a [[FlatBufferBuilder]]. * * @param obj an object to serialize * @param builder a class that helps build a FlatBuffer representation of diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/RequestFactory.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/RequestFactory.scala index 447fb23ed1..b72b78245a 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/RequestFactory.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/RequestFactory.scala @@ -9,8 +9,7 @@ import org.enso.polyglot.debugger.protocol.{ object RequestFactory { - /** - * Creates EvaluationRequest inside a [[FlatBufferBuilder]]. + /** Creates EvaluationRequest inside a [[FlatBufferBuilder]]. * * @param expression expression to evaluate * @param builder a class that helps build a FlatBuffer representation of @@ -25,8 +24,7 @@ object RequestFactory { EvaluationRequest.createEvaluationRequest(builder, exprOffset) } - /** - * Creates ListBindingsRequest inside a [[FlatBufferBuilder]]. + /** Creates ListBindingsRequest inside a [[FlatBufferBuilder]]. * * @param builder a class that helps build a FlatBuffer representation of * complex objects @@ -38,8 +36,7 @@ object RequestFactory { ListBindingsRequest.endListBindingsRequest(builder) } - /** - * Creates SessionExitRequest inside a [[FlatBufferBuilder]]. + /** Creates SessionExitRequest inside a [[FlatBufferBuilder]]. * * @param builder a class that helps build a FlatBuffer representation of * complex objects diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ResponseFactory.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ResponseFactory.scala index c5604e8ea9..87057254b9 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ResponseFactory.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/debugger/protocol/factory/ResponseFactory.scala @@ -11,8 +11,7 @@ import org.enso.polyglot.debugger.protocol.{ object ResponseFactory { - /** - * Creates EvaluationSuccess inside a [[FlatBufferBuilder]]. + /** Creates EvaluationSuccess inside a [[FlatBufferBuilder]]. * * @param result result of evaluation * @param builder a class that helps build a FlatBuffer representation of @@ -27,8 +26,7 @@ object ResponseFactory { EvaluationSuccess.createEvaluationSuccess(builder, resultOffset) } - /** - * Creates EvaluationFailure inside a [[FlatBufferBuilder]]. + /** Creates EvaluationFailure inside a [[FlatBufferBuilder]]. * * @param exception exception that caused evaluation failure * @param builder a class that helps build a FlatBuffer representation of @@ -43,8 +41,7 @@ object ResponseFactory { EvaluationFailure.createEvaluationFailure(builder, excpetionOffset) } - /** - * Creates ListBindingsResult inside a [[FlatBufferBuilder]]. + /** Creates ListBindingsResult inside a [[FlatBufferBuilder]]. * * @param bindings mapping of names to bound values * @param builder a class that helps build a FlatBuffer representation of @@ -61,23 +58,22 @@ object ResponseFactory { ListBindingsResult.createListBindingsResult(builder, bindingsOffset) } - /** - * Creates SessionStartNotification inside a [[FlatBufferBuilder]]. + /** Creates SessionStartNotification inside a [[FlatBufferBuilder]]. * * @param builder a class that helps build a FlatBuffer representation of * complex objects * @return an offset pointing to the FlatBuffer representation of the * created object */ - def createSessionStartNotification()( - implicit builder: FlatBufferBuilder + def createSessionStartNotification()(implicit + builder: FlatBufferBuilder ): Int = { SessionStartNotification.startSessionStartNotification(builder) SessionStartNotification.endSessionStartNotification(builder) } - private def createBinding(name: String, value: Object)( - implicit builder: FlatBufferBuilder + private def createBinding(name: String, value: Object)(implicit + builder: FlatBufferBuilder ): Int = { val nameOffset = builder.createString(name) val valueOffset = ObjectRepresentationFactory.create(value) diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/runtime/Runtime.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/runtime/Runtime.scala index eb67b219ca..628af5e5ae 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/runtime/Runtime.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/runtime/Runtime.scala @@ -18,8 +18,7 @@ import scala.util.Try object Runtime { - /** - * A common supertype for all Runtime API methods. + /** A common supertype for all Runtime API methods. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes( @@ -194,13 +193,11 @@ object Runtime { type RequestId = UUID type VisualisationId = UUID - /** - * Indicates error response. + /** Indicates error response. */ sealed trait Error extends ApiResponse - /** - * A representation of a pointer to a method definition. + /** A representation of a pointer to a method definition. */ case class MethodPointer( module: String, @@ -208,8 +205,7 @@ object Runtime { name: String ) - /** - * A representation of an executable position in code. + /** A representation of an executable position in code. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes( @@ -228,8 +224,7 @@ object Runtime { object StackItem { - /** - * A call performed at the top of the stack, to initialize the context. + /** A call performed at the top of the stack, to initialize the context. */ case class ExplicitCall( methodPointer: MethodPointer, @@ -237,14 +232,12 @@ object Runtime { positionalArgumentsExpressions: Vector[String] ) extends StackItem - /** - * A call corresponding to "entering a function call". + /** A call corresponding to "entering a function call". */ case class LocalCall(expressionId: ExpressionId) extends StackItem } - /** - * An update containing information about expression. + /** An update containing information about expression. * * @param expressionId expression id. * @param expressionType the type of expression. @@ -256,8 +249,7 @@ object Runtime { methodCall: Option[MethodPointer] ) - /** - * An object representing invalidated expressions selector. + /** An object representing invalidated expressions selector. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes( @@ -276,13 +268,11 @@ object Runtime { object InvalidatedExpressions { - /** - * An object representing invalidation of all expressions. + /** An object representing invalidation of all expressions. */ case class All() extends InvalidatedExpressions - /** - * An object representing invalidation of a list of expressions. + /** An object representing invalidation of a list of expressions. * * @param value a list of expressions to invalidate. */ @@ -290,8 +280,7 @@ object Runtime { extends InvalidatedExpressions } - /** - * A notification about updated expressions of the context. + /** A notification about updated expressions of the context. * * @param contextId the context's id. * @param updates a list of updates. @@ -301,8 +290,7 @@ object Runtime { updates: Vector[ExpressionValueUpdate] ) extends ApiNotification - /** - * Represents a visualisation context. + /** Represents a visualisation context. * * @param visualisationId a visualisation identifier * @param contextId a context identifier @@ -314,8 +302,7 @@ object Runtime { expressionId: ExpressionId ) - /** - * A configuration object for properties of the visualisation. + /** A configuration object for properties of the visualisation. * * @param executionContextId an execution context of the visualisation * @param visualisationModule a qualified name of the module containing @@ -349,23 +336,20 @@ object Runtime { sealed trait SuggestionsDatabaseUpdate object SuggestionsDatabaseUpdate { - /** - * Create or replace the database entry. + /** Create or replace the database entry. * * @param suggestion the new suggestion */ case class Add(suggestion: Suggestion) extends SuggestionsDatabaseUpdate - /** - * Remove the database entry. + /** Remove the database entry. * * @param suggestion the suggestion to remove */ case class Remove(suggestion: Suggestion) extends SuggestionsDatabaseUpdate - /** - * Remove all module entries from the database. + /** Remove all module entries from the database. * * @param module the module name */ @@ -392,8 +376,7 @@ object Runtime { case class Warning() extends DiagnosticType } - /** - * The element in the stack trace. + /** The element in the stack trace. * * @param functionName the function containing the stack call * @param file the location of a file @@ -421,8 +404,7 @@ object Runtime { sealed trait ExecutionResult object ExecutionResult { - /** - * A diagnostic object produced as a compilation outcome, like error or + /** A diagnostic object produced as a compilation outcome, like error or * warning. * * @param kind the diagnostic type @@ -441,8 +423,7 @@ object Runtime { case object Diagnostic { - /** - * Create an error diagnostic message. + /** Create an error diagnostic message. * * @param message the diagnostic message * @param file the location of a file @@ -458,8 +439,7 @@ object Runtime { ): Diagnostic = new Diagnostic(DiagnosticType.Error(), message, file, location, stack) - /** - * Create a warning diagnostic message. + /** Create a warning diagnostic message. * * @param message the diagnostic message * @param file the location of a file @@ -482,8 +462,7 @@ object Runtime { ) } - /** - * A critical failure when attempting to execute a context. + /** A critical failure when attempting to execute a context. * * @param message the error message * @param file the location of a file producing the error @@ -493,8 +472,7 @@ object Runtime { } - /** - * The notification about the execution status. + /** The notification about the execution status. * * @param contextId the context's id * @param diagnostics the list of diagnostic messages @@ -504,8 +482,7 @@ object Runtime { diagnostics: Seq[ExecutionResult.Diagnostic] ) extends ApiNotification - /** - * Signals about the critical failure during the context execution. + /** Signals about the critical failure during the context execution. * * @param contextId the context's id * @param failure the error description @@ -515,8 +492,7 @@ object Runtime { failure: ExecutionResult.Failure ) extends ApiNotification - /** - * An event signaling a visualisation update. + /** An event signaling a visualisation update. * * @param visualisationContext a visualisation context * @param data a visualisation data @@ -526,8 +502,7 @@ object Runtime { data: Array[Byte] ) extends ApiNotification - /** - * Envelope for an Api request. + /** Envelope for an Api request. * * @param requestId the request identifier. * @param payload the request payload. @@ -536,8 +511,7 @@ object Runtime { object Request { - /** - * A smart constructor for [[Request]]. + /** A smart constructor for [[Request]]. * * @param requestId the reqest identifier. * @param payload the request payload. @@ -546,8 +520,7 @@ object Runtime { def apply(requestId: RequestId, payload: ApiRequest): Request = Request(Some(requestId), payload) - /** - * A smart constructor for [[Request]]. + /** A smart constructor for [[Request]]. * * @param payload the request payload. * @return a request object without request id and specified payload. @@ -556,8 +529,7 @@ object Runtime { Request(None, payload) } - /** - * Envelope for an Api response. + /** Envelope for an Api response. * * @param correlationId request that initiated the response * @param payload response @@ -566,8 +538,7 @@ object Runtime { object Response { - /** - * A smart constructor for [[Response]]. + /** A smart constructor for [[Response]]. * * @param correlationId the request id triggering this response. * @param payload the response payload. @@ -576,8 +547,7 @@ object Runtime { def apply(correlationId: RequestId, payload: ApiResponse): Response = Response(Some(correlationId), payload) - /** - * A smart constructor for [[Response]] that was not triggered by + /** A smart constructor for [[Response]] that was not triggered by * any request (i.e. a notification). * * @param payload the data carried by the response. @@ -586,39 +556,34 @@ object Runtime { def apply(payload: ApiResponse): Response = Response(None, payload) } - /** - * A Request sent from the client to the runtime server, to create a new + /** A Request sent from the client to the runtime server, to create a new * execution context with a given id. * * @param contextId the newly created context's id. */ case class CreateContextRequest(contextId: ContextId) extends ApiRequest - /** - * A response sent from the server upon handling the [[CreateContextRequest]] + /** A response sent from the server upon handling the [[CreateContextRequest]] * * @param contextId the newly created context's id. */ case class CreateContextResponse(contextId: ContextId) extends ApiResponse - /** - * A Request sent from the client to the runtime server, to destroy an + /** A Request sent from the client to the runtime server, to destroy an * execution context with a given id. * * @param contextId the destroyed context's id. */ case class DestroyContextRequest(contextId: ContextId) extends ApiRequest - /** - * A success response sent from the server upon handling the + /** A success response sent from the server upon handling the * [[DestroyContextRequest]] * * @param contextId the destroyed context's id */ case class DestroyContextResponse(contextId: ContextId) extends ApiResponse - /** - * A Request sent from the client to the runtime server, to move + /** A Request sent from the client to the runtime server, to move * the execution context to a new location deeper down the stack. * * @param contextId the context's id. @@ -627,30 +592,26 @@ object Runtime { case class PushContextRequest(contextId: ContextId, stackItem: StackItem) extends ApiRequest - /** - * A response sent from the server upon handling the [[PushContextRequest]] + /** A response sent from the server upon handling the [[PushContextRequest]] * * @param contextId the context's id. */ case class PushContextResponse(contextId: ContextId) extends ApiResponse - /** - * A Request sent from the client to the runtime server, to move + /** A Request sent from the client to the runtime server, to move * the execution context up the stack. * * @param contextId the context's id. */ case class PopContextRequest(contextId: ContextId) extends ApiRequest - /** - * A response sent from the server upon handling the [[PopContextRequest]] + /** A response sent from the server upon handling the [[PopContextRequest]] * * @param contextId the context's id. */ case class PopContextResponse(contextId: ContextId) extends ApiResponse - /** - * A Request sent from the client to the runtime server, to recompute + /** A Request sent from the client to the runtime server, to recompute * the execution context. * * @param contextId the context's id. @@ -662,8 +623,7 @@ object Runtime { expressions: Option[InvalidatedExpressions] ) extends ApiRequest - /** - * A response sent from the server upon handling the + /** A response sent from the server upon handling the * [[RecomputeContextRequest]] * * @param contextId the context's id. @@ -671,37 +631,32 @@ object Runtime { case class RecomputeContextResponse(contextId: ContextId) extends ApiResponse - /** - * An error response signifying a non-existent context. + /** An error response signifying a non-existent context. * * @param contextId the context's id */ case class ContextNotExistError(contextId: ContextId) extends Error - /** - * Signals that a module cannot be found. + /** Signals that a module cannot be found. * * @param moduleName the module name */ case class ModuleNotFound(moduleName: String) extends Error - /** - * Signals that execution of a context completed. + /** Signals that execution of a context completed. * * @param contextId the context's id */ case class ExecutionComplete(contextId: ContextId) extends ApiNotification - /** - * Signals that an expression specified in a [[AttachVisualisation]] or + /** Signals that an expression specified in a [[AttachVisualisation]] or * a [[ModifyVisualisation]] cannot be evaluated. * * @param message the reason of the failure */ case class VisualisationExpressionFailed(message: String) extends Error - /** - * Signals that an evaluation of a code responsible for generating + /** Signals that an evaluation of a code responsible for generating * visualisation data failed. * * @param contextId the context's id. @@ -712,27 +667,23 @@ object Runtime { message: String ) extends ApiNotification - /** - * Signals that visualisation cannot be found. + /** Signals that visualisation cannot be found. */ case class VisualisationNotFound() extends Error - /** - * An error response signifying that stack is empty. + /** An error response signifying that stack is empty. * * @param contextId the context's id */ case class EmptyStackError(contextId: ContextId) extends Error - /** - * An error response signifying that stack item is invalid. + /** An error response signifying that stack item is invalid. * * @param contextId the context's id */ case class InvalidStackItemError(contextId: ContextId) extends Error - /** - * A notification sent to the server about switching a file to literal + /** A notification sent to the server about switching a file to literal * contents. * * @param path the file being moved to memory. @@ -745,8 +696,7 @@ object Runtime { isIndexed: Boolean ) extends ApiRequest - /** - * A notification sent to the server about in-memory file contents being + /** A notification sent to the server about in-memory file contents being * edited. * * @param path the file being edited. @@ -755,23 +705,20 @@ object Runtime { case class EditFileNotification(path: File, edits: Seq[TextEdit]) extends ApiRequest - /** - * A notification sent to the server about dropping the file from memory + /** A notification sent to the server about dropping the file from memory * back to on-disk version. * * @param path the file being closed. */ case class CloseFileNotification(path: File) extends ApiRequest - /** - * Notification sent from the server to the client upon successful + /** Notification sent from the server to the client upon successful * initialization. Any messages sent to the server before receiving this * message will be dropped. */ case class InitializedNotification() extends ApiResponse - /** - * A request sent from the client to the runtime server, to create a new + /** A request sent from the client to the runtime server, to create a new * visualisation for an expression identified by `expressionId`. * * @param visualisationId an identifier of a visualisation @@ -785,13 +732,11 @@ object Runtime { visualisationConfig: VisualisationConfiguration ) extends ApiRequest - /** - * Signals that attaching a visualisation has succeeded. + /** Signals that attaching a visualisation has succeeded. */ case class VisualisationAttached() extends ApiResponse - /** - * A request sent from the client to the runtime server, to detach a + /** A request sent from the client to the runtime server, to detach a * visualisation from an expression identified by `expressionId`. * * @param contextId an execution context identifier @@ -804,13 +749,11 @@ object Runtime { expressionId: ExpressionId ) extends ApiRequest - /** - * Signals that detaching a visualisation has succeeded. + /** Signals that detaching a visualisation has succeeded. */ case class VisualisationDetached() extends ApiResponse - /** - * A request sent from the client to the runtime server, to modify a + /** A request sent from the client to the runtime server, to modify a * visualisation identified by `visualisationId`. * * @param visualisationId an identifier of a visualisation @@ -822,23 +765,19 @@ object Runtime { visualisationConfig: VisualisationConfiguration ) extends ApiRequest - /** - * Signals that a visualisation modification has succeeded. + /** Signals that a visualisation modification has succeeded. */ case class VisualisationModified() extends ApiResponse - /** - * A request to shut down the runtime server. + /** A request to shut down the runtime server. */ case class ShutDownRuntimeServer() extends ApiRequest - /** - * Signals that the runtime server has been shut down. + /** Signals that the runtime server has been shut down. */ case class RuntimeServerShutDown() extends ApiResponse - /** - * A request for project renaming. + /** A request for project renaming. * * @param oldName the old project name * @param newName the new project name @@ -846,15 +785,13 @@ object Runtime { case class RenameProject(oldName: String, newName: String) extends ApiRequest - /** - * Signals that project has been renamed. + /** Signals that project has been renamed. * * @param newName the new project name */ case class ProjectRenamed(newName: String) extends ApiResponse - /** - * A notification about the changes in the suggestions database. + /** A notification about the changes in the suggestions database. * * @param file the module file path * @param contents the module source @@ -878,8 +815,7 @@ object Runtime { mapper.registerModule(DefaultScalaModule) } - /** - * Serializes a Request into a byte buffer. + /** Serializes a Request into a byte buffer. * * @param message the message to serialize. * @return the serialized version of the message. @@ -887,8 +823,7 @@ object Runtime { def serialize(message: Request): ByteBuffer = ByteBuffer.wrap(mapper.writeValueAsBytes(message)) - /** - * Serializes a Response into a byte buffer. + /** Serializes a Response into a byte buffer. * * @param message the message to serialize. * @return the serialized version of the message. @@ -896,8 +831,7 @@ object Runtime { def serialize(message: Response): ByteBuffer = ByteBuffer.wrap(mapper.writeValueAsBytes(message)) - /** - * Deserializes a byte buffer into a Request message. + /** Deserializes a byte buffer into a Request message. * * @param bytes the buffer to deserialize * @return the deserialized message, if the byte buffer can be deserialized. @@ -905,8 +839,7 @@ object Runtime { def deserializeRequest(bytes: ByteBuffer): Option[Request] = Try(mapper.readValue(bytes.array(), classOf[Request])).toOption - /** - * Deserializes a byte buffer into a Response message. + /** Deserializes a byte buffer into a Response message. * * @param bytes the buffer to deserialize * @return the deserialized message, if the byte buffer can be deserialized. diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala index 5b4b751215..5f59643ee0 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala @@ -99,9 +99,12 @@ class ModuleManagementTest extends AnyFlatSpec with Matchers { |main = Foo.foo + 1 |""".stripMargin) - ctx.writeFile("Foo.enso", """ - |foo = 10 - |""".stripMargin) + ctx.writeFile( + "Foo.enso", + """ + |foo = 10 + |""".stripMargin + ) val topScope = ctx.executionContext.getTopScope topScope.registerModule("MyLib.Foo", ctx.mkFile("Foo.enso").getAbsolutePath) @@ -120,9 +123,12 @@ class ModuleManagementTest extends AnyFlatSpec with Matchers { |main = Foo.foo + 1 |""".stripMargin) - ctx.writeFile("Foo.enso", """ - |foo = 10 - |""".stripMargin) + ctx.writeFile( + "Foo.enso", + """ + |foo = 10 + |""".stripMargin + ) val topScope = ctx.executionContext.getTopScope val fooModule = topScope.registerModule( diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/EitherValue.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/EitherValue.scala index 1bdd84b81c..1eb2a4a128 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/EitherValue.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/EitherValue.scala @@ -16,9 +16,13 @@ trait EitherValue { def rightValue: B = either match { case Right(value) => value case Left(_) => - throw new TestFailedException({ _: StackDepthException => - Some(s"Either right value was expected, but it was $either") - }, None, pos) + throw new TestFailedException( + { _: StackDepthException => + Some(s"Either right value was expected, but it was $either") + }, + None, + pos + ) } } } diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/SerializationTest.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/SerializationTest.scala index ed3f9e964e..f506abbfb1 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/SerializationTest.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/debugger/SerializationTest.scala @@ -139,9 +139,8 @@ class SerializationTest extends AnyWordSpec with Matchers with EitherValue { bindingsRepr.size shouldEqual bindings.size assert( - bindings forall { - case (name: String, value: Object) => - objectRepresentationIsConsistent(value, bindingsRepr(name)) + bindings forall { case (name: String, value: Object) => + objectRepresentationIsConsistent(value, bindingsRepr(name)) }, "bindings representations should be consistent" ) diff --git a/engine/runner/src/main/scala/org/enso/runner/ContextFactory.scala b/engine/runner/src/main/scala/org/enso/runner/ContextFactory.scala index c9182c6ec2..668fd3405d 100644 --- a/engine/runner/src/main/scala/org/enso/runner/ContextFactory.scala +++ b/engine/runner/src/main/scala/org/enso/runner/ContextFactory.scala @@ -11,13 +11,11 @@ import org.enso.polyglot.debugger.{ import org.enso.polyglot.{LanguageInfo, PolyglotContext, RuntimeOptions} import org.graalvm.polyglot.Context -/** - * Utility class for creating Graal polyglot contexts. +/** Utility class for creating Graal polyglot contexts. */ class ContextFactory { - /** - * Creates a new Graal polyglot context. + /** Creates a new Graal polyglot context. * * @param packagesPath Enso packages path * @param in the input stream for standard in diff --git a/engine/runner/src/main/scala/org/enso/runner/LanguageServerApp.scala b/engine/runner/src/main/scala/org/enso/runner/LanguageServerApp.scala index e86bad7450..4ef76d43f9 100644 --- a/engine/runner/src/main/scala/org/enso/runner/LanguageServerApp.scala +++ b/engine/runner/src/main/scala/org/enso/runner/LanguageServerApp.scala @@ -9,13 +9,11 @@ import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn -/** - * Language server runner. +/** Language server runner. */ object LanguageServerApp { - /** - * Runs a Language Server + /** Runs a Language Server * * @param config a config */ diff --git a/engine/runner/src/main/scala/org/enso/runner/Main.scala b/engine/runner/src/main/scala/org/enso/runner/Main.scala index eb0ede2019..461181368f 100644 --- a/engine/runner/src/main/scala/org/enso/runner/Main.scala +++ b/engine/runner/src/main/scala/org/enso/runner/Main.scala @@ -40,8 +40,7 @@ object Main { private val LOG_LEVEL = "log-level" private val LOGGER_CONNECT = "logger-connect" - /** - * Builds the [[Options]] object representing the CLI syntax. + /** Builds the [[Options]] object representing the CLI syntax. * * @return an [[Options]] object representing the CLI syntax */ @@ -197,8 +196,7 @@ object Main { options } - /** - * Prints the help message to the standard output. + /** Prints the help message to the standard output. * * @param options object representing the CLI syntax */ @@ -217,8 +215,7 @@ object Main { sys.exit(exitCode) } - /** - * Handles the `--new` CLI option. + /** Handles the `--new` CLI option. * * Creates a project at the provided path. If the nameOption is provided it * specifies the project name, otherwise the name is generated automatically. @@ -256,8 +253,7 @@ object Main { exitSuccess() } - /** - * Handles the `--run` CLI option. + /** Handles the `--run` CLI option. * * If `path` is a directory, so a project is run, a conflicting (pointing to * another project) `projectPath` should not be provided. @@ -399,8 +395,7 @@ object Main { } } - /** - * Handles the `--repl` CLI option + /** Handles the `--repl` CLI option * * @param projectPath if specified, the REPL is run in context of a project * at the given path @@ -431,8 +426,7 @@ object Main { exitSuccess() } - /** - * Handles `--server` CLI option + /** Handles `--server` CLI option * * @param line a CLI line * @param logLevel log level to set for the engine runtime @@ -492,8 +486,7 @@ object Main { println(versionDescription.asString(useJson)) } - /** - * Parses the log level option. + /** Parses the log level option. */ def parseLogLevel(levelOption: String): LogLevel = { val name = levelOption.toLowerCase @@ -505,8 +498,7 @@ object Main { } } - /** - * Parses an URI that specifies the logging service connection. + /** Parses an URI that specifies the logging service connection. */ def parseUri(string: String): Uri = try { @@ -517,13 +509,11 @@ object Main { exitFail() } - /** - * Default log level to use if the LOG_LEVEL option is not provided. + /** Default log level to use if the LOG_LEVEL option is not provided. */ val defaultLogLevel: LogLevel = LogLevel.Info - /** - * Main entry point for the CLI program. + /** Main entry point for the CLI program. * * @param args the command line arguments */ diff --git a/engine/runner/src/main/scala/org/enso/runner/Repl.scala b/engine/runner/src/main/scala/org/enso/runner/Repl.scala index f4ab30a629..ec47a5fcc0 100644 --- a/engine/runner/src/main/scala/org/enso/runner/Repl.scala +++ b/engine/runner/src/main/scala/org/enso/runner/Repl.scala @@ -10,42 +10,35 @@ import org.jline.terminal.{Terminal, TerminalBuilder} import scala.util.Try -/** - * Represents user console input. +/** Represents user console input. */ sealed trait UserInput -/** - * End of user input. +/** End of user input. */ case object EndOfInput extends UserInput -/** - * A normal line of user input. +/** A normal line of user input. * @param line the contents of the input line */ case class Line(line: String) extends UserInput -/** - * Abstract representation of Repl IO operations +/** Abstract representation of Repl IO operations */ trait ReplIO { - /** - * Ask user for a line of input, using given prompt + /** Ask user for a line of input, using given prompt * @param prompt the prompt to display to the user * @return the user-provided input */ def readLine(prompt: String): UserInput - /** - * Print a line to the REPL. + /** Print a line to the REPL. * @param contents contents of the line to print */ def println(contents: String): Unit - /** - * Print a stack trace to the REPL. + /** Print a stack trace to the REPL. * @param exception which stack trace is to be printed */ def printStackTrace(exception: Exception): Unit = { @@ -67,8 +60,7 @@ trait ReplIO { } } -/** - * A barebones implementation of [[ReplIO]] based on standard input / output operations. +/** A barebones implementation of [[ReplIO]] based on standard input / output operations. * @param in input stream to use * @param out output stream to use */ @@ -76,8 +68,7 @@ case class SimpleReplIO(in: InputStream, out: OutputStream) extends ReplIO { private val scanner: Scanner = new Scanner(in) private val printer: PrintStream = new PrintStream(out) - /** - * Ask user for a line of input, using given prompt + /** Ask user for a line of input, using given prompt * @param prompt the prompt to display to the user * @return the user-provided input */ @@ -86,15 +77,13 @@ case class SimpleReplIO(in: InputStream, out: OutputStream) extends ReplIO { Try(scanner.nextLine()).map(Line).getOrElse(EndOfInput) } - /** - * Print a line to the REPL. + /** Print a line to the REPL. * @param contents contents of the line to print */ override def println(contents: String): Unit = printer.println(contents) } -/** - * An implementation of [[ReplIO]] using system terminal capabilities. +/** An implementation of [[ReplIO]] using system terminal capabilities. */ case class TerminalIO() extends ReplIO { private val terminal: Terminal = @@ -104,31 +93,27 @@ case class TerminalIO() extends ReplIO { private val lineReader: LineReader = LineReaderBuilder.builder().parser(parser).terminal(terminal).build() - /** - * Ask user for a line of input, using given prompt + /** Ask user for a line of input, using given prompt * @param prompt the prompt to display to the user * @return the user-provided input */ override def readLine(prompt: String): UserInput = Try(lineReader.readLine(prompt)).map(Line).getOrElse(EndOfInput) - /** - * Print a line to the REPL. + /** Print a line to the REPL. * @param contents contents of the line to print */ override def println(contents: String): Unit = terminal.writer().println(contents) } -/** - * The Repl logic to inject into runtime instrumentation framework. +/** The Repl logic to inject into runtime instrumentation framework. * * @param replIO the IO implementation to use with this Repl */ case class Repl(replIO: ReplIO) extends SessionManager { - /** - * Runs the Repl session by asking for user input and performing + /** Runs the Repl session by asking for user input and performing * the requested action with the execution node. * * End of input causes exit from the Repl. @@ -147,9 +132,8 @@ case class Repl(replIO: ReplIO) extends SessionManager { case Line(line) => if (line == ":list" || line == ":l") { val bindings = executor.listBindings() - bindings.foreach { - case (varName, value) => - replIO.println(s"$varName = $value") + bindings.foreach { case (varName, value) => + replIO.println(s"$varName = $value") } } else if (line == ":quit" || line == ":q") { continueRunning = false diff --git a/engine/runner/src/main/scala/org/enso/runner/RunnerLogging.scala b/engine/runner/src/main/scala/org/enso/runner/RunnerLogging.scala index c1294dc05e..a8e23af37b 100644 --- a/engine/runner/src/main/scala/org/enso/runner/RunnerLogging.scala +++ b/engine/runner/src/main/scala/org/enso/runner/RunnerLogging.scala @@ -8,13 +8,11 @@ import org.enso.loggingservice.{LogLevel, LoggerMode, LoggingServiceManager} import scala.concurrent.Future import scala.util.{Failure, Success} -/** - * Manages setting up the logging service within the runner. +/** Manages setting up the logging service within the runner. */ object RunnerLogging { - /** - * Sets up the runner's logging service. + /** Sets up the runner's logging service. * * If `connectionUri` is provided it tries to connect to a logging service * server and pass logs to it. If it is not provided, or the connection could @@ -64,8 +62,7 @@ object RunnerLogging { private val logger = Logger[RunnerLogging.type] - /** - * Shuts down the logging service gracefully. + /** Shuts down the logging service gracefully. */ def tearDown(): Unit = LoggingServiceManager.tearDown() diff --git a/engine/runtime/src/bench/java/org/enso/interpreter/bench/BenchmarksRunner.java b/engine/runtime/src/bench/java/org/enso/interpreter/bench/BenchmarksRunner.java index a076a26f8d..11c33ef492 100644 --- a/engine/runtime/src/bench/java/org/enso/interpreter/bench/BenchmarksRunner.java +++ b/engine/runtime/src/bench/java/org/enso/interpreter/bench/BenchmarksRunner.java @@ -33,10 +33,7 @@ public class BenchmarksRunner { */ public BenchmarkItem run(String label) throws RunnerException, JAXBException { Options benchmarkOptions = - new OptionsBuilder() - .jvmArgsAppend("-Xss16M") - .include("^" + label + "$") - .build(); + new OptionsBuilder().jvmArgsAppend("-Xss16M").include("^" + label + "$").build(); RunResult benchmarksResult = new Runner(benchmarkOptions).runSingle(); Report report; diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index 436a062a01..505b538b39 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -13,8 +13,8 @@ class AtomFixtures extends DefaultInterpreterRunner { .getModule(Builtins.MODULE_NAME) val nil = builtins.getConstructor("Nil") val cons = builtins.getConstructor("Cons") - 1L.to(length).foldLeft(nil.newInstance()) { - case (tail, el) => cons.newInstance(el.asInstanceOf[Object], tail) + 1L.to(length).foldLeft(nil.newInstance()) { case (tail, el) => + cons.newInstance(el.asInstanceOf[Object], tail) } } val millionElementList = buildInputList(million) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/instrument/RuntimeServerInstrument.java b/engine/runtime/src/main/java/org/enso/interpreter/instrument/RuntimeServerInstrument.java index 1ca9c5f4d5..4f0fc686a5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/instrument/RuntimeServerInstrument.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/instrument/RuntimeServerInstrument.java @@ -121,7 +121,6 @@ public class RuntimeServerInstrument extends TruffleInstrument { Arrays.asList( OptionDescriptor.newBuilder(new OptionKey<>(""), RuntimeServerInfo.ENABLE_OPTION) .build(), - RuntimeServerInfo.JOB_PARALLELISM_DESCRIPTOR - )); + RuntimeServerInfo.JOB_PARALLELISM_DESCRIPTOR)); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/ClosureRootNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/ClosureRootNode.java index 5bb28cbded..c09162b728 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/ClosureRootNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/ClosureRootNode.java @@ -52,8 +52,7 @@ public class ClosureRootNode extends EnsoRootNode { ExpressionNode body, SourceSection section, String name) { - return new ClosureRootNode( - language, localScope, moduleScope, body, section, name); + return new ClosureRootNode(language, localScope, moduleScope, body, section, name); } /** diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/IndirectCurryNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/IndirectCurryNode.java index 355bcbebf5..8b67d834c0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/IndirectCurryNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/dispatch/IndirectCurryNode.java @@ -74,14 +74,7 @@ public abstract class IndirectCurryNode extends Node { if (appliesFully) { if (!postApplicationSchema.hasOversaturatedArgs()) { Stateful result = - doCall( - function, - callerInfo, - state, - arguments, - isTail, - directCall, - loopingCall); + doCall(function, callerInfo, state, arguments, isTail, directCall, loopingCall); if (defaultsExecutionMode.isExecute() && TypesGen.isFunction(result.getValue())) { return oversaturatedCallableNode.execute( result.getValue(), diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/thunk/ForceNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/thunk/ForceNode.java index 90bff0d363..cb4772a7e7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/thunk/ForceNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/thunk/ForceNode.java @@ -29,9 +29,7 @@ public abstract class ForceNode extends ExpressionNode { @Specialization Object passToExecutorNode( - VirtualFrame frame, - Object thunk, - @Cached("build()") ThunkExecutorNode thunkExecutorNode) { + VirtualFrame frame, Object thunk, @Cached("build()") ThunkExecutorNode thunkExecutorNode) { Object state = FrameUtil.getObjectSafe(frame, getStateFrameSlot()); Stateful result = thunkExecutorNode.executeThunk(thunk, state, getTailStatus()); frame.setObject(getStateFrameSlot(), result.getState()); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/ToTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/ToTextNode.java index 2945ec8262..e9ef41cdd5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/ToTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/ToTextNode.java @@ -8,6 +8,7 @@ import org.enso.interpreter.runtime.data.text.Text; public class ToTextNode extends Node { Text t = Text.create("True"); Text f = Text.create("False"); + Text execute(boolean _this) { return _this ? t : f; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java index cd16654f7e..bf982f6ed8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/GetCwdNode.java @@ -15,8 +15,7 @@ import org.enso.interpreter.runtime.data.text.Text; @BuiltinMethod( type = "Prim_Io", name = "get_cwd", - description = - "A file corresponding to the current working directory.") + description = "A file corresponding to the current working directory.") public abstract class GetCwdNode extends Node { static GetCwdNode build() { return GetCwdNodeGen.create(); @@ -25,9 +24,7 @@ public abstract class GetCwdNode extends Node { abstract Object execute(Object _this); @Specialization - Object doExecute( - Object _this, - @CachedContext(Language.class) Context ctx) { + Object doExecute(Object _this, @CachedContext(Language.class) Context ctx) { TruffleFile file = ctx.getEnvironment().getCurrentWorkingDirectory(); EnsoFile ensoFile = new EnsoFile(file); return ctx.getEnvironment().asGuestValue(ensoFile); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java index a785d6b98c..d6700f0997 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java @@ -35,12 +35,12 @@ public abstract class PrintErrNode extends Node { @Specialization Stateful doPrintText( - VirtualFrame frame, - Object state, - Object self, - Text message, - @CachedContext(Language.class) Context ctx, - @Cached("build()") ToJavaStringNode toJavaStringNode) { + VirtualFrame frame, + Object state, + Object self, + Text message, + @CachedContext(Language.class) Context ctx, + @Cached("build()") ToJavaStringNode toJavaStringNode) { print(ctx.getErr(), toJavaStringNode.execute(message)); return new Stateful(state, ctx.getUnit().newInstance()); } @@ -71,9 +71,9 @@ public abstract class PrintErrNode extends Node { InvokeCallableNode buildInvokeCallableNode() { return InvokeCallableNode.build( - new CallArgumentInfo[] {new CallArgumentInfo()}, - InvokeCallableNode.DefaultsExecutionMode.EXECUTE, - InvokeCallableNode.ArgumentsExecutionMode.PRE_EXECUTED); + new CallArgumentInfo[] {new CallArgumentInfo()}, + InvokeCallableNode.DefaultsExecutionMode.EXECUTE, + InvokeCallableNode.ArgumentsExecutionMode.PRE_EXECUTED); } UnresolvedSymbol buildSymbol(Context ctx) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java index 4d9f1025cb..4fb3c6c660 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java @@ -4,10 +4,7 @@ import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.type.TypesGen; -@BuiltinMethod( - type = "Meta", - name = "is_atom", - description = "Checks if the argument is an atom") +@BuiltinMethod(type = "Meta", name = "is_atom", description = "Checks if the argument is an atom") public class IsAtomNode extends Node { boolean execute(Object _this, Object value) { return TypesGen.isAtom(value); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsPolyglotNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsPolyglotNode.java index 90d96b908c..847f89bbd0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsPolyglotNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsPolyglotNode.java @@ -8,7 +8,10 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.type.TypesGen; -@BuiltinMethod(type = "Meta", name = "is_polyglot", description = "Checks if the argument is a polyglot value.") +@BuiltinMethod( + type = "Meta", + name = "is_polyglot", + description = "Checks if the argument is a polyglot value.") public abstract class IsPolyglotNode extends Node { static IsPolyglotNode build() { return IsPolyglotNodeGen.create(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java index fe5538ada2..5df4f5c27f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java @@ -34,7 +34,6 @@ public abstract class GreaterNode extends Node { @Fallback boolean doOther(double _this, Object that) { - throw new TypeError("Unexpected type provided for argument `that` in Decimal.>", this); - + throw new TypeError("Unexpected type provided for argument `that` in Decimal.>", this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java index b85528ecfd..652fba144a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java @@ -17,7 +17,9 @@ public abstract class MultiplyNode extends Node { } @Specialization - double doDouble(double _this, double that) { return _this * that;} + double doDouble(double _this, double that) { + return _this * that; + } @Specialization double doLong(double _this, long that) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ToDecimalNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ToDecimalNode.java index bf7a2ef6be..0a76c8f010 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ToDecimalNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ToDecimalNode.java @@ -5,10 +5,7 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; import org.enso.interpreter.runtime.number.EnsoBigInteger; -@BuiltinMethod( - type = "Decimal", - name = "to_decimal", - description = "Identity on decimals") +@BuiltinMethod(type = "Decimal", name = "to_decimal", description = "Identity on decimals") public class ToDecimalNode extends Node { double execute(double _this) { return _this; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java index 61edab865d..3f2b5f3ffe 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java @@ -4,7 +4,7 @@ import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; -@BuiltinMethod(type="Runtime", name="gc", description = "Forces garbage collection") +@BuiltinMethod(type = "Runtime", name = "gc", description = "Forces garbage collection") public class GCNode extends Node { @CompilerDirectives.TruffleBoundary Object execute(Object _this) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/OsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/OsNode.java index dc7f66cfd0..45dab88266 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/OsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/OsNode.java @@ -5,10 +5,7 @@ import org.apache.commons.lang3.SystemUtils; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.data.text.Text; -@BuiltinMethod( - type = "System", - name = "os", - description = "Get the type of operating system.") +@BuiltinMethod(type = "System", name = "os", description = "Get the type of operating system.") public final class OsNode extends Node { private final Text LINUX = Text.create("linux"); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/thread/WithInterruptHandlerNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/thread/WithInterruptHandlerNode.java index 07966ef6d4..5040f68c64 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/thread/WithInterruptHandlerNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/thread/WithInterruptHandlerNode.java @@ -19,7 +19,10 @@ public class WithInterruptHandlerNode extends Node { private @Child ThunkExecutorNode handlerExecutorNode = ThunkExecutorNode.build(); Stateful execute( - @MonadicState Object state, Object _this, @Suspend Object action, @Suspend Object interrupt_handler) { + @MonadicState Object state, + Object _this, + @Suspend Object action, + @Suspend Object interrupt_handler) { try { return actExecutorNode.executeThunk(action, state, BaseNode.TailStatus.NOT_TAIL); } catch (ThreadInterruptedException e) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java index 0b415e4cd6..cdc21f6d42 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/ConstructorNode.java @@ -46,6 +46,5 @@ public abstract class ConstructorNode extends ExpressionNode { return constructor.newInstance(); } return constructor; - } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java index b679380933..a9542d5618 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/constant/EnsoProjectNode.java @@ -27,8 +27,7 @@ public class EnsoProjectNode extends RootNode { result = context.getBuiltins().getEnsoProject().newInstance(rootPath); } else { result = - new RuntimeError( - context.getBuiltins().error().moduleNotInPackageError().newInstance()); + new RuntimeError(context.getBuiltins().error().moduleNotInPackageError().newInstance()); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java index 130d807e3c..820709b12d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Meta.java @@ -18,7 +18,6 @@ public class Meta { AtomConstructor meta = new AtomConstructor("Meta", scope).initializeFields(); scope.registerConstructor(meta); - scope.registerMethod( meta, "is_unresolved_symbol", IsUnresolvedSymbolMethodGen.makeFunction(language)); scope.registerMethod( @@ -39,7 +38,6 @@ public class Meta { meta, "get_constructor_fields", GetConstructorFieldNamesMethodGen.makeFunction(language)); scope.registerMethod(meta, "new_atom", NewAtomInstanceMethodGen.makeFunction(language)); - scope.registerMethod(meta, "is_atom", IsAtomMethodGen.makeFunction(language)); scope.registerMethod(meta, "get_atom_fields", GetAtomFieldsMethodGen.makeFunction(language)); scope.registerMethod( @@ -48,7 +46,8 @@ public class Meta { scope.registerMethod(meta, "is_error", IsErrorMethodGen.makeFunction(language)); scope.registerMethod(meta, "is_polyglot", IsPolyglotMethodGen.makeFunction(language)); - scope.registerMethod(meta, "get_polyglot_language", GetPolyglotLanguageMethodGen.makeFunction(language)); + scope.registerMethod( + meta, "get_polyglot_language", GetPolyglotLanguageMethodGen.makeFunction(language)); scope.registerMethod(meta, "is_same_object", IsSameObjectMethodGen.makeFunction(language)); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java index a37694e211..8029112f33 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java @@ -45,13 +45,13 @@ public class Number { scope.registerMethod( smallInteger, "-", - org.enso.interpreter.node.expression.builtin.number.smallInteger.SubtractMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.SubtractMethodGen + .makeFunction(language)); scope.registerMethod( smallInteger, "*", - org.enso.interpreter.node.expression.builtin.number.smallInteger.MultiplyMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.MultiplyMethodGen + .makeFunction(language)); scope.registerMethod( smallInteger, "^", @@ -60,8 +60,8 @@ public class Number { scope.registerMethod( smallInteger, "/", - org.enso.interpreter.node.expression.builtin.number.smallInteger.DivideMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.DivideMethodGen + .makeFunction(language)); scope.registerMethod( smallInteger, "div", @@ -75,8 +75,8 @@ public class Number { scope.registerMethod( smallInteger, "negate", - org.enso.interpreter.node.expression.builtin.number.smallInteger.NegateMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.NegateMethodGen + .makeFunction(language)); scope.registerMethod( smallInteger, "abs", @@ -85,13 +85,13 @@ public class Number { scope.registerMethod( smallInteger, "==", - org.enso.interpreter.node.expression.builtin.number.smallInteger.EqualsMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.EqualsMethodGen + .makeFunction(language)); scope.registerMethod( smallInteger, ">", - org.enso.interpreter.node.expression.builtin.number.smallInteger.GreaterMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.GreaterMethodGen + .makeFunction(language)); scope.registerMethod( smallInteger, ">=", @@ -105,13 +105,13 @@ public class Number { scope.registerMethod( smallInteger, "<=", - org.enso.interpreter.node.expression.builtin.number.smallInteger.LessOrEqualMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.LessOrEqualMethodGen + .makeFunction(language)); scope.registerMethod( smallInteger, "to_decimal", - org.enso.interpreter.node.expression.builtin.number.smallInteger.ToDecimalMethodGen.makeFunction( - language)); + org.enso.interpreter.node.expression.builtin.number.smallInteger.ToDecimalMethodGen + .makeFunction(language)); } private void registerBigIntegerMethods(Language language, ModuleScope scope) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/argument/CallArgumentInfo.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/argument/CallArgumentInfo.java index ca2360146e..7b5bb47457 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/argument/CallArgumentInfo.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/argument/CallArgumentInfo.java @@ -220,10 +220,7 @@ public class CallArgumentInfo { newOversaturatedArgInfo.length); return new FunctionSchema( - originalSchema.getCallerFrameAccess(), - definitions, - argumentUsed, - oversaturatedArgInfo); + originalSchema.getCallerFrameAccess(), definitions, argumentUsed, oversaturatedArgInfo); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/FunctionSchema.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/FunctionSchema.java index e9c6c8e96a..770e467470 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/FunctionSchema.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/FunctionSchema.java @@ -75,9 +75,7 @@ public class FunctionSchema { * @param callerFrameAccess the declaration of need to access the caller frame from the function * @param argumentInfos Definition site arguments information */ - public FunctionSchema( - CallerFrameAccess callerFrameAccess, - ArgumentDefinition... argumentInfos) { + public FunctionSchema(CallerFrameAccess callerFrameAccess, ArgumentDefinition... argumentInfos) { this( callerFrameAccess, argumentInfos, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/RedefinedMethodException.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/RedefinedMethodException.java index 174c46b955..63bc6524f0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/RedefinedMethodException.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/RedefinedMethodException.java @@ -16,7 +16,8 @@ public class RedefinedMethodException extends RuntimeException implements Truffl super("Methods cannot be overloaded, but you have tried to overload " + atom + "." + method); } - /** Gets the location where the exception occurred. + /** + * Gets the location where the exception occurred. * * @return the location where the exception occurred */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java index 0c3f257cea..0d116de2c0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java @@ -239,8 +239,7 @@ public class ExecutionService { * @param edits the edits to apply. * @return an object for computing the changed IR nodes. */ - public ChangesetBuilder modifyModuleSources( - File path, List edits) { + public ChangesetBuilder modifyModuleSources(File path, List edits) { Optional moduleMay = context.getModuleForFile(path); if (moduleMay.isEmpty()) { throw new ModuleNotFoundForFileException(path); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/error/ModuleNotFoundForFileException.java b/engine/runtime/src/main/java/org/enso/interpreter/service/error/ModuleNotFoundForFileException.java index 5041737d56..edbdafb9f3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/error/ModuleNotFoundForFileException.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/error/ModuleNotFoundForFileException.java @@ -13,5 +13,4 @@ public class ModuleNotFoundForFileException extends ModuleNotFoundException { public ModuleNotFoundForFileException(File path) { super("Module not found for file " + path + "."); } - } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala index 2dedc2440f..51ec6b0767 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -40,8 +40,7 @@ class Compiler(val context: Context) { private val stubsGenerator: RuntimeStubsGenerator = new RuntimeStubsGenerator() - /** - * Processes the provided language sources, registering any bindings in the + /** Processes the provided language sources, registering any bindings in the * given scope. * * @param module the scope into which new bindings are registered @@ -113,8 +112,7 @@ class Compiler(val context: Context) { module.unsafeSetCompilationStage(Module.CompilationStage.AFTER_PARSING) } - /** - * Gets a module definition by name. + /** Gets a module definition by name. * * @param name the name of module to look up * @return the module corresponding to the provided name, if exists @@ -123,8 +121,7 @@ class Compiler(val context: Context) { context.getTopScope.getModule(name).toScala } - /** - * Ensures the passed module is in at least the parsed compilation stage. + /** Ensures the passed module is in at least the parsed compilation stage. * * @param module the module to ensure is parsed. */ @@ -138,8 +135,7 @@ class Compiler(val context: Context) { } } - /** - * Processes the language source, interpreting it as an expression. + /** Processes the language source, interpreting it as an expression. * Processes the source in the context of given local and module scopes. * * @param srcString string representing the expression to process @@ -168,8 +164,7 @@ class Compiler(val context: Context) { } } - /** - * Finds and processes a language source by its qualified name. + /** Finds and processes a language source by its qualified name. * * The results of this operation are cached internally so we do not need to * process the same source file multiple times. @@ -194,8 +189,7 @@ class Compiler(val context: Context) { module.getScope } - /** - * Parses the provided language sources. + /** Parses the provided language sources. * * @param source the code to parse * @return an AST representation of `source` @@ -203,8 +197,7 @@ class Compiler(val context: Context) { def parse(source: Source): AST = Parser().runWithIds(source.getCharacters.toString) - /** - * Parses the metadata of the provided language sources. + /** Parses the metadata of the provided language sources. * * @param source the code to parse * @return the source metadata @@ -212,8 +205,7 @@ class Compiler(val context: Context) { def parseMeta(source: CharSequence): IDMap = Parser().splitMeta(source.toString)._2 - /** - * Lowers the input AST to the compiler's high-level intermediate + /** Lowers the input AST to the compiler's high-level intermediate * representation. * * @param sourceAST the parser AST input @@ -233,8 +225,7 @@ class Compiler(val context: Context) { ) } - /** - * Lowers the input AST to the compiler's high-level intermediate + /** Lowers the input AST to the compiler's high-level intermediate * representation. * * @param sourceAST the parser AST representing the program source @@ -269,8 +260,7 @@ class Compiler(val context: Context) { passManager.runPassesInline(ir, inlineContext) } - /** - * Runs the strict error handling mechanism (if enabled in the language + /** Runs the strict error handling mechanism (if enabled in the language * context) for the inline compiler flow. * * @param ir the IR after compilation passes. @@ -295,8 +285,7 @@ class Compiler(val context: Context) { } } - /** - * Runs the strict error handling mechanism (if enabled in the language + /** Runs the strict error handling mechanism (if enabled in the language * context) for the module-level compiler flow. * * @param modules the modules to check against errors @@ -346,8 +335,7 @@ class Compiler(val context: Context) { } } - /** - * Reports diagnostics from multiple modules. + /** Reports diagnostics from multiple modules. * * @param diagnostics the mapping between modules and existing diagnostics. * @return whether any errors were encountered. @@ -355,20 +343,18 @@ class Compiler(val context: Context) { def reportDiagnostics( diagnostics: List[(Module, List[IR.Diagnostic])] ): Boolean = { - val results = diagnostics.map { - case (mod, diags) => - if (diags.nonEmpty) { - context.getOut.println(s"In module ${mod.getName}:") - reportDiagnostics(diags, mod.getSource) - } else { - false - } + val results = diagnostics.map { case (mod, diags) => + if (diags.nonEmpty) { + context.getOut.println(s"In module ${mod.getName}:") + reportDiagnostics(diags, mod.getSource) + } else { + false + } } results.exists(r => r) } - /** - * Reports compilation diagnostics to the standard output and throws an + /** Reports compilation diagnostics to the standard output and throws an * exception breaking the execution flow if there are errors. * * @param diagnostics all the diagnostics found in the program IR. diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala index a6912dd9c2..8667b09627 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala @@ -22,8 +22,7 @@ import org.enso.syntax.text.ast.text.Escape.Unicode import scala.annotation.tailrec import scala.util.control.Breaks.{break, breakable} -/** - * This file contains the functionality that translates from the parser's +/** This file contains the functionality that translates from the parser's * [[AST]] type to the internal representation used by the compiler. * * The current internal representation is [[IR]]. @@ -108,8 +107,8 @@ object AstToIr { ) } - val exports = presentBlocks.collect { - case AST.Export.any(export) => translateExport(export) + val exports = presentBlocks.collect { case AST.Export.any(export) => + translateExport(export) } val nonImportBlocks = presentBlocks.filter { @@ -167,8 +166,8 @@ object AstToIr { } val methodRef = if (targetPath.nonEmpty) { - val pathSegments = targetPath.collect { - case AST.Ident.Cons.any(c) => c + val pathSegments = targetPath.collect { case AST.Ident.Cons.any(c) => + c } val pathNames = pathSegments.map(buildName) @@ -592,8 +591,7 @@ object AstToIr { err.map(Left(_)).getOrElse(Right(bldr.toString)) } - /** - * Translates a sequence literal into its [[IR]] counterpart. + /** Translates a sequence literal into its [[IR]] counterpart. * @param literal the literal to translate * @return the [[IR]] representation of `literal` */ diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala index 3ff53dcbcc..18e21a4e62 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala @@ -660,9 +660,9 @@ object AstView { val consPath = segments.dropRight(1) val maybeVar = segments.last - val isValid = consPath.collect { - case a @ AST.Ident.Cons(_) => a - }.length == consPath.length + val isValid = consPath.collect { case a @ AST.Ident.Cons(_) => + a + }.length == consPath.length if (isValid) { maybeVar match { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index bdb7db16e8..7af66c45be 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -179,37 +179,36 @@ class IrToTruffle( atomConstructors .zip(atomDefs) - .foreach { - case (atomCons, atomDefn) => - val scopeInfo = atomDefn - .unsafeGetMetadata( - AliasAnalysis, - "No root scope on an atom definition." - ) - .unsafeAs[AliasAnalysis.Info.Scope.Root] - - val dataflowInfo = atomDefn.unsafeGetMetadata( - DataflowAnalysis, - "No dataflow information associated with an atom." + .foreach { case (atomCons, atomDefn) => + val scopeInfo = atomDefn + .unsafeGetMetadata( + AliasAnalysis, + "No root scope on an atom definition." ) + .unsafeAs[AliasAnalysis.Info.Scope.Root] - val argFactory = - new DefinitionArgumentProcessor( - scope = new LocalScope( - None, - scopeInfo.graph, - scopeInfo.graph.rootScope, - dataflowInfo - ) + val dataflowInfo = atomDefn.unsafeGetMetadata( + DataflowAnalysis, + "No dataflow information associated with an atom." + ) + + val argFactory = + new DefinitionArgumentProcessor( + scope = new LocalScope( + None, + scopeInfo.graph, + scopeInfo.graph.rootScope, + dataflowInfo ) - val argDefs = - new Array[ArgumentDefinition](atomDefn.arguments.size) + ) + val argDefs = + new Array[ArgumentDefinition](atomDefn.arguments.size) - for (idx <- atomDefn.arguments.indices) { - argDefs(idx) = argFactory.run(atomDefn.arguments(idx), idx) - } + for (idx <- atomDefn.arguments.indices) { + argDefs(idx) = argFactory.run(atomDefn.arguments(idx), idx) + } - atomCons.initializeFields(argDefs: _*) + atomCons.initializeFields(argDefs: _*) } // Register the method definitions in scope @@ -228,58 +227,56 @@ class IrToTruffle( val consOpt = methodDef.methodReference.typePointer .getMetadata(MethodDefinitions) - .map { - res => - res.target match { - case BindingsMap.ResolvedModule(module) => - module.getScope.getAssociatedType - case BindingsMap.ResolvedConstructor(definitionModule, cons) => - definitionModule.getScope.getConstructors.get(cons.name) - case BindingsMap.ResolvedPolyglotSymbol(_, _) => - throw new CompilerError( - "Impossible polyglot symbol, should be caught by MethodDefinitions pass." - ) - case _: BindingsMap.ResolvedMethod => - throw new CompilerError( - "Impossible here, should be caught by MethodDefinitions pass." - ) - } + .map { res => + res.target match { + case BindingsMap.ResolvedModule(module) => + module.getScope.getAssociatedType + case BindingsMap.ResolvedConstructor(definitionModule, cons) => + definitionModule.getScope.getConstructors.get(cons.name) + case BindingsMap.ResolvedPolyglotSymbol(_, _) => + throw new CompilerError( + "Impossible polyglot symbol, should be caught by MethodDefinitions pass." + ) + case _: BindingsMap.ResolvedMethod => + throw new CompilerError( + "Impossible here, should be caught by MethodDefinitions pass." + ) + } } - consOpt.foreach { - cons => - val expressionProcessor = new ExpressionProcessor( - cons.getName ++ Constants.SCOPE_SEPARATOR ++ methodDef.methodName.name, - scopeInfo.graph, - scopeInfo.graph.rootScope, - dataflowInfo - ) + consOpt.foreach { cons => + val expressionProcessor = new ExpressionProcessor( + cons.getName ++ Constants.SCOPE_SEPARATOR ++ methodDef.methodName.name, + scopeInfo.graph, + scopeInfo.graph.rootScope, + dataflowInfo + ) - val function = methodDef.body match { - case fn: IR.Function => - val (body, arguments) = - expressionProcessor.buildFunctionBody(fn.arguments, fn.body) - val rootNode = MethodRootNode.build( - language, - expressionProcessor.scope, - moduleScope, - body, - makeSection(methodDef.location), - cons, - methodDef.methodName.name - ) - val callTarget = Truffle.getRuntime.createCallTarget(rootNode) - new RuntimeFunction( - callTarget, - null, - new FunctionSchema(arguments: _*) - ) - case _ => - throw new CompilerError( - "Method bodies must be functions at the point of codegen." - ) - } - moduleScope.registerMethod(cons, methodDef.methodName.name, function) + val function = methodDef.body match { + case fn: IR.Function => + val (body, arguments) = + expressionProcessor.buildFunctionBody(fn.arguments, fn.body) + val rootNode = MethodRootNode.build( + language, + expressionProcessor.scope, + moduleScope, + body, + makeSection(methodDef.location), + cons, + methodDef.methodName.name + ) + val callTarget = Truffle.getRuntime.createCallTarget(rootNode) + new RuntimeFunction( + callTarget, + null, + new FunctionSchema(arguments: _*) + ) + case _ => + throw new CompilerError( + "Method bodies must be functions at the point of codegen." + ) + } + moduleScope.registerMethod(cons, methodDef.methodName.name, function) } }) @@ -380,40 +377,39 @@ class IrToTruffle( BindingAnalysis, "No binding analysis at the point of codegen." ) - bindingsMap.exportedSymbols.foreach { - case (name, List(resolution)) => - if (resolution.module != moduleScope.getModule) { - resolution match { - case BindingsMap.ResolvedConstructor(definitionModule, cons) => - val runtimeCons = - definitionModule.getScope.getConstructors.get(cons.name) - val fun = mkConsGetter(runtimeCons) - moduleScope.registerMethod( - moduleScope.getAssociatedType, - name, - fun - ) - case BindingsMap.ResolvedModule(module) => - val runtimeCons = - module.getScope.getAssociatedType - val fun = mkConsGetter(runtimeCons) - moduleScope.registerMethod( - moduleScope.getAssociatedType, - name, - fun - ) - case BindingsMap.ResolvedMethod(module, method) => - val fun = module.getScope.getMethods - .get(module.getScope.getAssociatedType) - .get(method.name) - moduleScope.registerMethod( - moduleScope.getAssociatedType, - name, - fun - ) - case BindingsMap.ResolvedPolyglotSymbol(_, _) => - } + bindingsMap.exportedSymbols.foreach { case (name, List(resolution)) => + if (resolution.module != moduleScope.getModule) { + resolution match { + case BindingsMap.ResolvedConstructor(definitionModule, cons) => + val runtimeCons = + definitionModule.getScope.getConstructors.get(cons.name) + val fun = mkConsGetter(runtimeCons) + moduleScope.registerMethod( + moduleScope.getAssociatedType, + name, + fun + ) + case BindingsMap.ResolvedModule(module) => + val runtimeCons = + module.getScope.getAssociatedType + val fun = mkConsGetter(runtimeCons) + moduleScope.registerMethod( + moduleScope.getAssociatedType, + name, + fun + ) + case BindingsMap.ResolvedMethod(module, method) => + val fun = module.getScope.getMethods + .get(module.getScope.getAssociatedType) + .get(method.name) + moduleScope.registerMethod( + moduleScope.getAssociatedType, + name, + fun + ) + case BindingsMap.ResolvedPolyglotSymbol(_, _) => } + } } } @@ -590,8 +586,8 @@ class IrToTruffle( if (allCasesValid) { val cases = maybeCases - .collect { - case Right(x) => x + .collect { case Right(x) => + x } .toArray[BranchNode] @@ -602,8 +598,8 @@ class IrToTruffle( ) setLocation(matchExpr, location) } else { - val invalidBranches = maybeCases.collect { - case Left(x) => x + val invalidBranches = maybeCases.collect { case Left(x) => + x } val message = invalidBranches.map(_.message).mkString(", ") @@ -912,8 +908,7 @@ class IrToTruffle( setLocation(TextLiteralNode.build(text), location) } - /** - * Generates a runtime implementation for compile error nodes. + /** Generates a runtime implementation for compile error nodes. * * @param error the IR representing a compile error. * @return a runtime node representing the error. @@ -965,8 +960,7 @@ class IrToTruffle( setLocation(ErrorNode.build(payload), error.location) } - /** - * Processes function arguments, generates arguments reads and creates + /** Processes function arguments, generates arguments reads and creates * a node to represent the whole method body. * * @param arguments the argument definitions @@ -1178,8 +1172,8 @@ class IrToTruffle( .unsafeAs[AliasAnalysis.Info.Scope.Child] val shouldSuspend = value match { - case _: IR.Name => false - case _: IR.Literal.Text => false + case _: IR.Name => false + case _: IR.Literal.Text => false case _: IR.Literal.Number => false case _ => shouldBeSuspended.getOrElse( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala index ad19560d67..aba0139475 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/RuntimeStubsGenerator.scala @@ -4,15 +4,13 @@ import org.enso.compiler.pass.analyse.BindingAnalysis import org.enso.interpreter.runtime.Module import org.enso.interpreter.runtime.callable.atom.AtomConstructor -/** - * Generates stubs of runtime representations of atom constructors, to allow +/** Generates stubs of runtime representations of atom constructors, to allow * [[IrToTruffle the code generator]] to refer to constructors that are not * fully generated yet. */ class RuntimeStubsGenerator() { - /** - * Runs the stage on the given module. + /** Runs the stage on the given module. * * @param module the module to generate stubs in. */ diff --git a/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala b/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala index 8ba5cf585c..31543827d9 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/context/SuggestionBuilder.scala @@ -60,14 +60,14 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { typePtr.getMetadata(MethodDefinitions).flatMap(buildSelfType) selfTypeOpt.foreach { selfType => acc += buildMethod( - body.getExternalId, - module, - methodName, - selfType, - args, - doc, - typeSignature - ) + body.getExternalId, + module, + methodName, + selfType, + args, + doc, + typeSignature + ) } scopes += Scope(body.children, body.location.map(_.location)) go(scope, scopes, acc) @@ -80,34 +80,34 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { ) if name.location.isDefined => val typeSignature = ir.getMetadata(TypeSignatures) acc += buildFunction( - body.getExternalId, - module, - name, - args, - scope.location.get, - typeSignature - ) + body.getExternalId, + module, + name, + args, + scope.location.get, + typeSignature + ) scopes += Scope(body.children, body.location.map(_.location)) go(scope, scopes, acc) case IR.Expression.Binding(name, expr, _, _, _) if name.location.isDefined => val typeSignature = ir.getMetadata(TypeSignatures) acc += buildLocal( - expr.getExternalId, - module, - name.name, - scope.location.get, - typeSignature - ) + expr.getExternalId, + module, + name.name, + scope.location.get, + typeSignature + ) scopes += Scope(expr.children, expr.location.map(_.location)) go(scope, scopes, acc) case IR.Module.Scope.Definition.Atom(name, arguments, _, _, _) => acc += buildAtom( - module, - name.name, - arguments, - doc - ) + module, + name.name, + arguments, + doc + ) go(scope, scopes, acc) case _ => go(scope, scopes, acc) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala b/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala index 62b90cf471..aac8cb04e6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/core/IR.scala @@ -154,33 +154,28 @@ object IR { /** The type of external identifiers */ type ExternalId = AST.ID - /** - * Couples a location with a possible source identifier. + /** Couples a location with a possible source identifier. * * @param location the code location. * @param id the identifier for the location. */ case class IdentifiedLocation(location: Location, id: Option[AST.ID]) { - /** - * @return the character index of the start of this source location. + /** @return the character index of the start of this source location. */ def start: Int = location.start - /** - * @return the character index of the end of this source location. + /** @return the character index of the end of this source location. */ def end: Int = location.end - /** - * @return the length in characters of this location. + /** @return the length in characters of this location. */ def length: Int = location.length } object IdentifiedLocation { - /** - * Utility constructor, building a location without an ID. + /** Utility constructor, building a location without an ID. * * @param location the code location. * @return an [[IdentifiedLocation]] corresponding to the input location. @@ -520,16 +515,14 @@ object IR { } } - /** - * Gets the name of the module visible in the importing scope, + /** Gets the name of the module visible in the importing scope, * either the original name or the rename. * * @return the name of this export visible in code */ def getSimpleName: IR.Name = rename.getOrElse(name.parts.last) - /** - * Checks whether the export statement allows use of the given + /** Checks whether the export statement allows use of the given * exported name. * * Note that it does not verify if the name is actually exported @@ -682,16 +675,14 @@ object IR { } } - /** - * Gets the name of the module visible in this scope, either the + /** Gets the name of the module visible in this scope, either the * original name or the rename. * * @return the name of this import visible in code */ def getSimpleName: IR.Name = rename.getOrElse(name.parts.last) - /** - * Checks whether the import statement allows use of the given + /** Checks whether the import statement allows use of the given * exported name. * * Note that it does not verify if the name is actually exported @@ -1610,8 +1601,7 @@ object IR { override def showCode(indent: Int): String = value - /** - * Checks whether the literal represents a fractional value. + /** Checks whether the literal represents a fractional value. * * @return `true` if the value is fractional, `false` otherwise. */ @@ -4907,8 +4897,7 @@ object IR { } } - /** - * A dummy pattern used for storing documentation comments between branches + /** A dummy pattern used for storing documentation comments between branches * in a pattern match. * * To store a documentation comment next to a branch, a dummy branch is @@ -5179,8 +5168,7 @@ object IR { /** A representation of various kinds of diagnostic in the IR. */ sealed trait Diagnostic { - /** - * @return a human-readable description of this error condition. + /** @return a human-readable description of this error condition. */ def message: String @@ -5272,8 +5260,7 @@ object IR { } } - /** - * A warning about a `@Tail_Call` annotation placed in a non-tail + /** A warning about a `@Tail_Call` annotation placed in a non-tail * position. * @param location the location of the annotated application */ @@ -5417,8 +5404,7 @@ object IR { object Resolution { - /** - * A representation of a symbol resolution error. + /** A representation of a symbol resolution error. */ sealed trait Reason { def explain(originalName: IR.Name): String @@ -5430,16 +5416,14 @@ object IR { " importing the default definition from the Base.Vector module." } - /** - * An error coming from an unknown annotation name. + /** An error coming from an unknown annotation name. */ case object UnknownAnnotation extends Reason { override def explain(originalName: Name): String = s"The annotation ${originalName.name} is not defined." } - /** - * An error coming from a tail call annotation placed in a syntactically + /** An error coming from a tail call annotation placed in a syntactically * incorrect position. */ case object UnexpectedTailCallAnnotation extends Reason { @@ -5448,8 +5432,7 @@ object IR { s"used with function applications." } - /** - * An error coming from an unexpected occurence of a polyglot symbol. + /** An error coming from an unexpected occurence of a polyglot symbol. * * @param context the description of a context in which the error * happened. @@ -5460,8 +5443,7 @@ object IR { s"but polyglot symbols are not allowed in $context." } - /** - * An error coming from an unexpected occurence of a static method. + /** An error coming from an unexpected occurence of a static method. * * @param context the description of a context in which the error * happened. @@ -5472,16 +5454,14 @@ object IR { s"but methods are not allowed in $context." } - /** - * An error coming from name resolver. + /** An error coming from name resolver. * * @param err the original error. */ case class ResolverError(err: BindingsMap.ResolutionError) extends Reason { - /** - * Provides a human-readable explanation of the error. + /** Provides a human-readable explanation of the error. * @param originalName the original unresolved name. * @return a human-readable message. */ @@ -5584,20 +5564,17 @@ object IR { object Pattern { - /** - * A representation of the reason the pattern is erroneous. + /** A representation of the reason the pattern is erroneous. */ sealed trait Reason { - /** - * Provides a human-readable explanation of the error. + /** Provides a human-readable explanation of the error. * @return */ def explain: String } - /** - * A reason for pattern failing due to wrong arity. + /** A reason for pattern failing due to wrong arity. * * @param consName the constructor name. * @param expected expected field count. @@ -5692,13 +5669,11 @@ object IR { } object Syntax { - /** - * A common type for all syntax errors expected by the language. + /** A common type for all syntax errors expected by the language. */ sealed trait Reason { - /** - * @return a human-readable description of the error. + /** @return a human-readable description of the error. */ def explanation: String } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala index 8e903d5ce7..f82485195c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala @@ -5,8 +5,7 @@ import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.BindingAnalysis import org.enso.interpreter.runtime.Module -/** - * A utility structure for resolving symbols in a given module. +/** A utility structure for resolving symbols in a given module. * * @param types the types defined in the current module * @param polyglotSymbols the polyglot symbols imported into the scope @@ -25,8 +24,7 @@ case class BindingsMap( override def duplicate(): Option[IRPass.Metadata] = Some(this) - /** - * Other modules, imported by [[currentModule]]. + /** Other modules, imported by [[currentModule]]. */ var resolvedImports: List[ResolvedImport] = List() @@ -108,8 +106,7 @@ case class BindingsMap( ) } - /** - * Resolves a name in the context of current module. + /** Resolves a name in the context of current module. * * @param name the name to resolve. * @return a resolution for [[name]] or an error, if the name could not be @@ -129,8 +126,7 @@ case class BindingsMap( handleAmbiguity(findExportedCandidatesInImports(name)) } - /** - * Resolves a qualified name to a symbol in the context of this module. + /** Resolves a qualified name to a symbol in the context of this module. * * @param name the name to resolve * @return a resolution for `name` @@ -159,8 +155,7 @@ case class BindingsMap( exportedSymbols.getOrElse(name.toLowerCase, List()) } - /** - * Resolves a name exported by this module. + /** Resolves a name exported by this module. * * @param name the name to resolve * @return the resolution for `name` @@ -171,66 +166,62 @@ case class BindingsMap( handleAmbiguity(findExportedSymbolsFor(name)) } - /** - * Dumps the export statements from this module into a structure ready for + /** Dumps the export statements from this module into a structure ready for * further analysis. * * @return a list of triples of the exported module, the name it is exported * as and any further symbol restrictions. */ def getDirectlyExportedModules: List[ExportedModule] = - resolvedImports.collect { - case ResolvedImport(_, Some(exp), mod) => - val hidingEnsoProject = - SymbolRestriction.Hiding(Set(Generated.ensoProjectMethodName)) - val restriction = if (exp.isAll) { - val definedRestriction = if (exp.onlyNames.isDefined) { - SymbolRestriction.Only( - exp.onlyNames.get - .map(name => - SymbolRestriction - .AllowedResolution(name.name.toLowerCase, None) - ) - .toSet - ) - } else if (exp.hiddenNames.isDefined) { - SymbolRestriction.Hiding( - exp.hiddenNames.get.map(_.name.toLowerCase).toSet - ) - } else { - SymbolRestriction.All - } - SymbolRestriction.Intersect( - List(hidingEnsoProject, definedRestriction) - ) - } else { + resolvedImports.collect { case ResolvedImport(_, Some(exp), mod) => + val hidingEnsoProject = + SymbolRestriction.Hiding(Set(Generated.ensoProjectMethodName)) + val restriction = if (exp.isAll) { + val definedRestriction = if (exp.onlyNames.isDefined) { SymbolRestriction.Only( - Set( - SymbolRestriction.AllowedResolution( - exp.getSimpleName.name.toLowerCase, - Some(ResolvedModule(mod)) + exp.onlyNames.get + .map(name => + SymbolRestriction + .AllowedResolution(name.name.toLowerCase, None) ) + .toSet + ) + } else if (exp.hiddenNames.isDefined) { + SymbolRestriction.Hiding( + exp.hiddenNames.get.map(_.name.toLowerCase).toSet + ) + } else { + SymbolRestriction.All + } + SymbolRestriction.Intersect( + List(hidingEnsoProject, definedRestriction) + ) + } else { + SymbolRestriction.Only( + Set( + SymbolRestriction.AllowedResolution( + exp.getSimpleName.name.toLowerCase, + Some(ResolvedModule(mod)) ) ) - } - val rename = if (!exp.isAll) { - Some(exp.getSimpleName.name) - } else { - None - } - ExportedModule(mod, rename, restriction) + ) + } + val rename = if (!exp.isAll) { + Some(exp.getSimpleName.name) + } else { + None + } + ExportedModule(mod, rename, restriction) } } object BindingsMap { - /** - * Utilities for methods automatically generated by the compiler. + /** Utilities for methods automatically generated by the compiler. */ object Generated { - /** - * The name of the builtin `enso_project` method. + /** The name of the builtin `enso_project` method. */ val ensoProjectMethodName: String = "enso_project" } @@ -238,8 +229,7 @@ object BindingsMap { /** Represents a symbol restriction on symbols exported from a module. */ sealed trait SymbolRestriction { - /** - * Whether the export statement allows accessing the given name. + /** Whether the export statement allows accessing the given name. * * @param symbol the name to check * @param resolution the particular resolution of `symbol` @@ -247,8 +237,7 @@ object BindingsMap { */ def canAccess(symbol: String, resolution: ResolvedName): Boolean - /** - * Performs static optimizations on the restriction, simplifying + /** Performs static optimizations on the restriction, simplifying * common patterns. * * @return a possibly simpler version of the restriction, describing @@ -259,8 +248,7 @@ object BindingsMap { case object SymbolRestriction { - /** - * A representation of allowed symbol. An allowed symbol consists of + /** A representation of allowed symbol. An allowed symbol consists of * a name and an optional resolution refinement. * * @param symbol the symbol name @@ -271,8 +259,7 @@ object BindingsMap { resolution: Option[ResolvedName] ) { - /** - * Checks if the `symbol` is visible under this restriction, with + /** Checks if the `symbol` is visible under this restriction, with * a given resolution. * @param symbol the symbol * @param resolution `symbol`'s resolution @@ -286,8 +273,7 @@ object BindingsMap { } } - /** - * A restriction representing a set of allowed symbols. + /** A restriction representing a set of allowed symbols. * * @param symbols the allowed symbols. */ @@ -300,8 +286,7 @@ object BindingsMap { override def optimize: SymbolRestriction = this } - /** - * A restriction representing a set of excluded symbols. + /** A restriction representing a set of excluded symbols. * * @param symbols the excluded symbols. */ @@ -315,8 +300,7 @@ object BindingsMap { override def optimize: SymbolRestriction = this } - /** - * A restriction meaning there's no restriction at all. + /** A restriction meaning there's no restriction at all. */ case object All extends SymbolRestriction { override def canAccess( @@ -326,8 +310,7 @@ object BindingsMap { override def optimize: SymbolRestriction = this } - /** - * A complete restriction – no symbols are permitted + /** A complete restriction – no symbols are permitted */ case object Empty extends SymbolRestriction { override def canAccess( @@ -337,8 +320,7 @@ object BindingsMap { override def optimize: SymbolRestriction = this } - /** - * An intersection of restrictions – a symbol is allowed if all components + /** An intersection of restrictions – a symbol is allowed if all components * allow it. * * @param restrictions the intersected restrictions. @@ -357,8 +339,8 @@ object BindingsMap { val (intersects, otherTerms) = optimizedTerms.partition(_.isInstanceOf[Intersect]) val allTerms = intersects.flatMap( - _.asInstanceOf[Intersect].restrictions - ) ++ otherTerms + _.asInstanceOf[Intersect].restrictions + ) ++ otherTerms if (allTerms.contains(Empty)) { return Empty } @@ -384,8 +366,7 @@ object BindingsMap { } } - /** - * A union of restrictions – a symbol is allowed if any component allows + /** A union of restrictions – a symbol is allowed if any component allows * it. * * @param restrictions the component restricitons. @@ -403,8 +384,8 @@ object BindingsMap { val (unions, otherTerms) = optimizedTerms.partition(_.isInstanceOf[Union]) val allTerms = unions.flatMap( - _.asInstanceOf[Union].restrictions - ) ++ otherTerms + _.asInstanceOf[Union].restrictions + ) ++ otherTerms if (allTerms.contains(All)) { return All } @@ -432,8 +413,7 @@ object BindingsMap { } } - /** - * A representation of a resolved export statement. + /** A representation of a resolved export statement. * * @param module the module being exported. * @param exportedAs the name it is exported as. @@ -445,8 +425,7 @@ object BindingsMap { symbols: SymbolRestriction ) - /** - * A representation of a resolved import statement. + /** A representation of a resolved import statement. * * @param importDef the definition of the import * @param exports the exports associated with the import @@ -458,37 +437,32 @@ object BindingsMap { module: Module ) - /** - * A representation of a constructor. + /** A representation of a constructor. * * @param name the name of the constructor. * @param arity the number of fields in the constructor. */ case class Cons(name: String, arity: Int) - /** - * A representation of an imported polyglot symbol. + /** A representation of an imported polyglot symbol. * * @param name the name of the symbol. */ case class PolyglotSymbol(name: String) - /** - * A representation of a method defined on the current module. + /** A representation of a method defined on the current module. * * @param name the name of the method. */ case class ModuleMethod(name: String) - /** - * A result of successful name resolution. + /** A result of successful name resolution. */ sealed trait ResolvedName { def module: Module } - /** - * A representation of a name being resolved to a constructor. + /** A representation of a name being resolved to a constructor. * * @param module the module the constructor is defined in. * @param cons a representation of the constructor. @@ -496,44 +470,38 @@ object BindingsMap { case class ResolvedConstructor(module: Module, cons: Cons) extends ResolvedName - /** - * A representation of a name being resolved to a module. + /** A representation of a name being resolved to a module. * * @param module the module the name resolved to. */ case class ResolvedModule(module: Module) extends ResolvedName - /** - * A representation of a name being resolved to a method call. + /** A representation of a name being resolved to a method call. * @param module the module defining the method. * @param method the method representation. */ case class ResolvedMethod(module: Module, method: ModuleMethod) extends ResolvedName - /** - * A representation of a name being resolved to a polyglot symbol. + /** A representation of a name being resolved to a polyglot symbol. * * @param symbol the imported symbol name. */ case class ResolvedPolyglotSymbol(module: Module, symbol: PolyglotSymbol) extends ResolvedName - /** - * A representation of an error during name resolution. + /** A representation of an error during name resolution. */ sealed trait ResolutionError - /** - * A representation of a resolution error due to symbol ambiguity. + /** A representation of a resolution error due to symbol ambiguity. * * @param candidates all the possible resolutions for the name. */ case class ResolutionAmbiguous(candidates: List[ResolvedName]) extends ResolutionError - /** - * A resolution error due to the symbol not being found. + /** A resolution error due to the symbol not being found. */ case object ResolutionNotFound extends ResolutionError diff --git a/engine/runtime/src/main/scala/org/enso/compiler/exception/CompilationAbortedException.scala b/engine/runtime/src/main/scala/org/enso/compiler/exception/CompilationAbortedException.scala index 74bc6ed470..55e10d3ba8 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/exception/CompilationAbortedException.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/exception/CompilationAbortedException.scala @@ -3,8 +3,7 @@ package org.enso.compiler.exception import com.oracle.truffle.api.TruffleException import com.oracle.truffle.api.nodes.Node -/** - * An exception thrown to break out of the compilation flow after reporting +/** An exception thrown to break out of the compilation flow after reporting * all the encountered errors. */ class CompilationAbortedException extends Exception with TruffleException { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/exception/UnhandledEntity.scala b/engine/runtime/src/main/scala/org/enso/compiler/exception/UnhandledEntity.scala index 5c4e7c5a03..58e23068b0 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/exception/UnhandledEntity.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/exception/UnhandledEntity.scala @@ -1,7 +1,6 @@ package org.enso.compiler.exception -/** - * This exception is thrown when compiler internal processing encounters an +/** This exception is thrown when compiler internal processing encounters an * entity that it doesn't know how to deal with. * * @param entity the undhandled entity diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/Pass.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/Pass.scala index e49d601011..ff97b5227f 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/Pass.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/Pass.scala @@ -1,7 +1,6 @@ package org.enso.compiler.pass -/** - * A pass is a transformation from source type to sink type. +/** A pass is a transformation from source type to sink type. * * Passes may take in additional information when run (e.g. analysis output), * and may also output additional information. @@ -11,8 +10,7 @@ package org.enso.compiler.pass */ trait Pass[In, Out] { - /** - * A class representing the output of a pass. + /** A class representing the output of a pass. * * @param result the result of running the pass * @param metadata any metadata produced by the pass @@ -20,8 +18,7 @@ trait Pass[In, Out] { */ sealed case class Output[TOut](result: Out, metadata: TOut) - /** - * Executes the pass on the source, with optional input metadata. + /** Executes the pass on the source, with optional input metadata. * * @param input the source to transform or analyse * @param data metadata necessary foe the pass to execute correctly diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala index 0fbafdf2c4..c895cb3c66 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala @@ -409,16 +409,15 @@ case object AliasAnalysis extends IRPass { graph: AliasAnalysis.Graph, parentScope: AliasAnalysis.Graph.Scope ): List[IR.CallArgument] = { - args.map { - case arg @ IR.CallArgument.Specified(_, expr, _, _, _, _) => - val currentScope = expr match { - case _: IR.Literal => parentScope - case _ => parentScope.addChild() - } + args.map { case arg @ IR.CallArgument.Specified(_, expr, _, _, _, _) => + val currentScope = expr match { + case _: IR.Literal => parentScope + case _ => parentScope.addChild() + } - arg - .copy(value = analyseExpression(expr, graph, currentScope)) - .updateMetadata(this -->> Info.Scope.Child(graph, currentScope)) + arg + .copy(value = analyseExpression(expr, graph, currentScope)) + .updateMetadata(this -->> Info.Scope.Child(graph, currentScope)) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala index 4609588d88..aae90ab4e4 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala @@ -12,8 +12,7 @@ import org.enso.compiler.pass.desugar.{ } import org.enso.compiler.pass.resolve.{MethodDefinitions, Patterns} -/** - * Recognizes all defined bindings in the current module and constructs +/** Recognizes all defined bindings in the current module and constructs * a mapping data structure that can later be used for symbol resolution. */ case object BindingAnalysis extends IRPass { @@ -53,24 +52,23 @@ case object BindingAnalysis extends IRPass { BindingsMap.PolyglotSymbol(poly.getVisibleName) } val moduleMethods = ir.bindings - .collect { - case method: IR.Module.Scope.Definition.Method.Explicit => - val ref = method.methodReference - ref.typePointer match { - case IR.Name.Qualified(List(), _, _, _) => Some(ref.methodName.name) - case IR.Name.Qualified(List(n), _, _, _) => - val shadowed = definedConstructors.exists(_.name == n.name) - if (!shadowed && n.name == moduleContext.module.getName.item) - Some(ref.methodName.name) - else None - case IR.Name.Here(_, _, _) => Some(ref.methodName.name) - case IR.Name.Literal(n, _, _, _, _) => - val shadowed = definedConstructors.exists(_.name == n) - if (!shadowed && n == moduleContext.module.getName.item) - Some(ref.methodName.name) - else None - case _ => None - } + .collect { case method: IR.Module.Scope.Definition.Method.Explicit => + val ref = method.methodReference + ref.typePointer match { + case IR.Name.Qualified(List(), _, _, _) => Some(ref.methodName.name) + case IR.Name.Qualified(List(n), _, _, _) => + val shadowed = definedConstructors.exists(_.name == n.name) + if (!shadowed && n.name == moduleContext.module.getName.item) + Some(ref.methodName.name) + else None + case IR.Name.Here(_, _, _) => Some(ref.methodName.name) + case IR.Name.Literal(n, _, _, _, _) => + val shadowed = definedConstructors.exists(_.name == n) + if (!shadowed && n == moduleContext.module.getName.item) + Some(ref.methodName.name) + else None + case _ => None + } } .flatten .map(BindingsMap.ModuleMethod) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala index 99c037dcde..baf1581d93 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/ComplexType.scala @@ -102,11 +102,11 @@ case object ComplexType extends IRPass { def desugarComplexType( typ: IR.Module.Scope.Definition.Type ): List[IR.Module.Scope.Definition] = { - val atomDefs = typ.body.collect { - case d: IR.Module.Scope.Definition.Atom => d + val atomDefs = typ.body.collect { case d: IR.Module.Scope.Definition.Atom => + d } - val atomIncludes = typ.body.collect { - case n: IR.Name => n + val atomIncludes = typ.body.collect { case n: IR.Name => + n } val namesToDefineMethodsOn = atomIncludes ++ atomDefs.map(_.name) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/LambdaShorthandToLambda.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/LambdaShorthandToLambda.scala index 422e95bcdf..f7f9d47090 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/LambdaShorthandToLambda.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/LambdaShorthandToLambda.scala @@ -164,17 +164,16 @@ case object LambdaShorthandToLambda extends IRPass { args .zip(argIsUnderscore) .map(updateShorthandArg(_, freshNameSupply)) - .map { - case s @ IR.CallArgument.Specified(_, value, _, _, _, _) => - s.copy(value = desugarExpression(value, freshNameSupply)) + .map { case s @ IR.CallArgument.Specified(_, value, _, _, _, _) => + s.copy(value = desugarExpression(value, freshNameSupply)) } // Generate a definition arg instance for each shorthand arg val defArgs = updatedArgs.zip(argIsUnderscore).map { case (arg, isShorthand) => generateDefinitionArg(arg, isShorthand) } - val actualDefArgs = defArgs.collect { - case Some(defArg) => defArg + val actualDefArgs = defArgs.collect { case Some(defArg) => + defArg } // Determine whether or not the function itself is shorthand @@ -264,12 +263,11 @@ case object LambdaShorthandToLambda extends IRPass { * position is lambda shorthand, otherwise `false` */ def determineLambdaShorthand(args: List[IR.CallArgument]): List[Boolean] = { - args.map { - case IR.CallArgument.Specified(_, value, _, _, _, _) => - value match { - case _: IR.Name.Blank => true - case _ => false - } + args.map { case IR.CallArgument.Specified(_, value, _, _, _, _) => + value match { + case _: IR.Name.Blank => true + case _ => false + } } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/MainImportAndExport.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/MainImportAndExport.scala index c0ba7fdd33..8ecf6d5200 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/MainImportAndExport.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/MainImportAndExport.scala @@ -4,8 +4,7 @@ import org.enso.compiler.context.{InlineContext, ModuleContext} import org.enso.compiler.core.IR import org.enso.compiler.pass.IRPass -/** - * Desugars imports and exports mentioning only the project name to refer +/** Desugars imports and exports mentioning only the project name to refer * to the `Main` module of the mentioned project instead. */ case object MainImportAndExport extends IRPass { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/NestedPatternMatch.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/NestedPatternMatch.scala index 7480cb49a6..44eb00b9a6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/NestedPatternMatch.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/NestedPatternMatch.scala @@ -139,8 +139,8 @@ case object NestedPatternMatch extends IRPass { ) ) - ir.transformExpressions { - case x => desugarExpression(x, freshNameSupply) + ir.transformExpressions { case x => + desugarExpression(x, freshNameSupply) } } @@ -156,8 +156,8 @@ case object NestedPatternMatch extends IRPass { expr: IR.Expression, freshNameSupply: FreshNameSupply ): IR.Expression = { - expr.transformExpressions { - case cse: IR.Case => desugarCase(cse, freshNameSupply) + expr.transformExpressions { case cse: IR.Case => + desugarCase(cse, freshNameSupply) } } @@ -180,17 +180,16 @@ case object NestedPatternMatch extends IRPass { val caseExprScrutinee = scrutineeBindingName.duplicate() - val processedBranches = branches.zipWithIndex.map { - case (branch, ix) => - val remainingBranches = branches.drop(ix + 1).toList + val processedBranches = branches.zipWithIndex.map { case (branch, ix) => + val remainingBranches = branches.drop(ix + 1).toList - desugarCaseBranch( - branch, - caseExprScrutinee, - branch.location, - remainingBranches, - freshNameSupply - ) + desugarCaseBranch( + branch, + caseExprScrutinee, + branch.location, + remainingBranches, + freshNameSupply + ) } val desugaredCaseExpr = expr.copy( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/SectionsToBinOp.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/SectionsToBinOp.scala index 563dfb76d1..04c7cbc06b 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/SectionsToBinOp.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/SectionsToBinOp.scala @@ -72,9 +72,8 @@ case object SectionsToBinOp extends IRPass { ) ) - ir.transformExpressions { - case sec: IR.Application.Operator.Section => - desugarSections(sec, freshNameSupply) + ir.transformExpressions { case sec: IR.Application.Operator.Section => + desugarSections(sec, freshNameSupply) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ShadowedPatternFields.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ShadowedPatternFields.scala index eb245b5d93..389cf4304c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ShadowedPatternFields.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ShadowedPatternFields.scala @@ -71,8 +71,8 @@ case object ShadowedPatternFields extends IRPass { ir: IR.Expression, @unused inlineContext: InlineContext ): IR.Expression = { - ir.transformExpressions { - case x => lintExpression(x) + ir.transformExpressions { case x => + lintExpression(x) } } @@ -86,8 +86,8 @@ case object ShadowedPatternFields extends IRPass { def lintExpression( expression: IR.Expression ): IR.Expression = { - expression.transformExpressions { - case cse: IR.Case => lintCase(cse) + expression.transformExpressions { case cse: IR.Case => + lintCase(cse) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/LambdaConsolidate.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/LambdaConsolidate.scala index d910a91c36..0607037bf2 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/LambdaConsolidate.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/LambdaConsolidate.scala @@ -103,9 +103,8 @@ case object LambdaConsolidate extends IRPass { "A fresh name supply is required for lambda consolidation." ) ) - ir.transformExpressions { - case fn: IR.Function => - collapseFunction(fn, inlineContext, freshNameSupply) + ir.transformExpressions { case fn: IR.Function => + collapseFunction(fn, inlineContext, freshNameSupply) } } @@ -200,30 +199,29 @@ case object LambdaConsolidate extends IRPass { val argsWithIndex = argsWithShadowed.zipWithIndex.map(t => (t._1._1, t._1._2, t._2)) - argsWithIndex.map { - case (arg, isShadowed, ix) => - if (isShadowed) { - val restArgs = args.drop(ix + 1) - arg match { - case spec @ DefinitionArgument.Specified(argName, _, _, _, _, _) => - val mShadower = restArgs.collectFirst { - case s @ IR.DefinitionArgument.Specified(sName, _, _, _, _, _) - if sName.name == argName.name => - s - } + argsWithIndex.map { case (arg, isShadowed, ix) => + if (isShadowed) { + val restArgs = args.drop(ix + 1) + arg match { + case spec @ DefinitionArgument.Specified(argName, _, _, _, _, _) => + val mShadower = restArgs.collectFirst { + case s @ IR.DefinitionArgument.Specified(sName, _, _, _, _, _) + if sName.name == argName.name => + s + } - val shadower: IR = mShadower.getOrElse(IR.Empty(spec.location)) + val shadower: IR = mShadower.getOrElse(IR.Empty(spec.location)) - spec.diagnostics.add( - IR.Warning.Shadowed - .FunctionParam(argName.name, shadower, spec.location) - ) + spec.diagnostics.add( + IR.Warning.Shadowed + .FunctionParam(argName.name, shadower, spec.location) + ) - (spec, isShadowed) - } - } else { - (arg, isShadowed) + (spec, isShadowed) } + } else { + (arg, isShadowed) + } } } @@ -285,9 +283,8 @@ case object LambdaConsolidate extends IRPass { argument: IR.DefinitionArgument, toReplaceExpressionIds: Set[IR.Identifier] ): IR.Expression = { - expr.transformExpressions { - case name: IR.Name => - replaceInName(name, argument, toReplaceExpressionIds) + expr.transformExpressions { case name: IR.Name => + replaceInName(name, argument, toReplaceExpressionIds) } } @@ -335,19 +332,18 @@ case object LambdaConsolidate extends IRPass { args: List[IR.DefinitionArgument] ): Set[AliasAnalysis.Graph.Id] = { args - .map { - case spec: IR.DefinitionArgument.Specified => - val aliasInfo = - spec - .unsafeGetMetadata( - AliasAnalysis, - "Missing aliasing information for an argument definition." - ) - .unsafeAs[AliasAnalysis.Info.Occurrence] - aliasInfo.graph - .getOccurrence(aliasInfo.id) - .flatMap(occ => Some(aliasInfo.graph.knownShadowedDefinitions(occ))) - .getOrElse(Set()) + .map { case spec: IR.DefinitionArgument.Specified => + val aliasInfo = + spec + .unsafeGetMetadata( + AliasAnalysis, + "Missing aliasing information for an argument definition." + ) + .unsafeAs[AliasAnalysis.Info.Occurrence] + aliasInfo.graph + .getOccurrence(aliasInfo.id) + .flatMap(occ => Some(aliasInfo.graph.knownShadowedDefinitions(occ))) + .getOrElse(Set()) } .foldLeft(Set[AliasAnalysis.Graph.Occurrence]())(_ ++ _) .map(_.id) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/UnreachableMatchBranches.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/UnreachableMatchBranches.scala index 21b851c562..da848d91e4 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/UnreachableMatchBranches.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/optimise/UnreachableMatchBranches.scala @@ -84,8 +84,8 @@ case object UnreachableMatchBranches extends IRPass { ir: IR.Expression, @unused inlineContext: InlineContext ): IR.Expression = { - ir.transformExpressions { - case x => optimizeExpression(x) + ir.transformExpressions { case x => + optimizeExpression(x) } } @@ -98,8 +98,8 @@ case object UnreachableMatchBranches extends IRPass { * @return `expression` with unreachable case branches removed */ def optimizeExpression(expression: IR.Expression): IR.Expression = { - expression.transformExpressions { - case cse: IR.Case => optimizeCase(cse) + expression.transformExpressions { case cse: IR.Case => + optimizeCase(cse) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/IgnoredBindings.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/IgnoredBindings.scala index ad99abe6d4..a28c8a549c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/IgnoredBindings.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/IgnoredBindings.scala @@ -156,8 +156,8 @@ case object IgnoredBindings extends IRPass { function match { case lam @ IR.Function.Lambda(args, body, _, _, _, _) => val argIsIgnore = args.map(isIgnoreArg) - val newArgs = args.zip(argIsIgnore).map { - case (arg, isIgnore) => genNewArg(arg, isIgnore, supply) + val newArgs = args.zip(argIsIgnore).map { case (arg, isIgnore) => + genNewArg(arg, isIgnore, supply) } lam.copy( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala index 55d58c017e..34541cede2 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala @@ -13,8 +13,7 @@ import org.enso.compiler.pass.desugar.{ GenerateMethodBodies } -/** - * Resolves the correct `this` argument type for methods definitions +/** Resolves the correct `this` argument type for methods definitions * and stores the resolution in the method's metadata. */ case object MethodDefinitions extends IRPass { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleThisToHere.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleThisToHere.scala index 3807cd5318..bae4f40228 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleThisToHere.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleThisToHere.scala @@ -7,8 +7,7 @@ import org.enso.compiler.data.BindingsMap.ResolvedModule import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.AliasAnalysis -/** - * Performs a substitution of `this` to `here` in methods defined on the +/** Performs a substitution of `this` to `here` in methods defined on the * current module. * * In module-level methods, both names are semantically equivalent, but `here` diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala index 014a0f7f95..d166b2d423 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala @@ -74,9 +74,8 @@ case object OverloadsResolution extends IRPass { .Method(method.typeName, method.methodName, method.location) } else { val currentMethods = seenMethods(method.typeName.name) - seenMethods = - seenMethods + (method.typeName.name -> - (currentMethods + method.methodName.name)) + seenMethods = seenMethods + (method.typeName.name -> + (currentMethods + method.methodName.name)) method } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala index 56da23aa9e..d8cc217de5 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala @@ -9,8 +9,7 @@ import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.{AliasAnalysis, BindingAnalysis} import org.enso.compiler.pass.desugar.{GenerateMethodBodies, NestedPatternMatch} -/** - * Resolves constructors in pattern matches and validates their arity. +/** Resolves constructors in pattern matches and validates their arity. */ object Patterns extends IRPass { @@ -65,91 +64,90 @@ object Patterns extends IRPass { expr: IR.Expression, bindings: BindingsMap ): IR.Expression = { - expr.transformExpressions { - case caseExpr: IR.Case.Expr => - val newBranches = caseExpr.branches.map { branch => - val resolvedPattern = branch.pattern match { - case consPat: IR.Pattern.Constructor => - val consName = consPat.constructor - val resolution = consName match { - case qual: IR.Name.Qualified => - val parts = qual.parts.map(_.name) - Some(bindings.resolveQualifiedName(parts)) - case lit: IR.Name.Literal => - Some(bindings.resolveUppercaseName(lit.name)) - case _ => None + expr.transformExpressions { case caseExpr: IR.Case.Expr => + val newBranches = caseExpr.branches.map { branch => + val resolvedPattern = branch.pattern match { + case consPat: IR.Pattern.Constructor => + val consName = consPat.constructor + val resolution = consName match { + case qual: IR.Name.Qualified => + val parts = qual.parts.map(_.name) + Some(bindings.resolveQualifiedName(parts)) + case lit: IR.Name.Literal => + Some(bindings.resolveUppercaseName(lit.name)) + case _ => None + } + val resolvedName = resolution + .map { + case Left(err) => + IR.Error.Resolution( + consPat.constructor, + IR.Error.Resolution.ResolverError(err) + ) + case Right(value: BindingsMap.ResolvedConstructor) => + consName.updateMetadata( + this -->> BindingsMap.Resolution(value) + ) + case Right(value: BindingsMap.ResolvedModule) => + consName.updateMetadata( + this -->> BindingsMap.Resolution(value) + ) + case Right(_: BindingsMap.ResolvedPolyglotSymbol) => + IR.Error.Resolution( + consName, + IR.Error.Resolution.UnexpectedPolyglot( + "a pattern match" + ) + ) + case Right(_: BindingsMap.ResolvedMethod) => + IR.Error.Resolution( + consName, + IR.Error.Resolution.UnexpectedMethod( + "a pattern match" + ) + ) } - val resolvedName = resolution - .map { - case Left(err) => - IR.Error.Resolution( - consPat.constructor, - IR.Error.Resolution.ResolverError(err) - ) - case Right(value: BindingsMap.ResolvedConstructor) => - consName.updateMetadata( - this -->> BindingsMap.Resolution(value) - ) - case Right(value: BindingsMap.ResolvedModule) => - consName.updateMetadata( - this -->> BindingsMap.Resolution(value) - ) - case Right(_: BindingsMap.ResolvedPolyglotSymbol) => - IR.Error.Resolution( - consName, - IR.Error.Resolution.UnexpectedPolyglot( - "a pattern match" - ) - ) - case Right(_: BindingsMap.ResolvedMethod) => - IR.Error.Resolution( - consName, - IR.Error.Resolution.UnexpectedMethod( - "a pattern match" - ) - ) - } - .getOrElse(consName) + .getOrElse(consName) - val actualResolution = resolvedName.getMetadata(this) - val expectedArity = actualResolution.map { res => - res.target match { - case BindingsMap.ResolvedConstructor(_, cons) => cons.arity - case BindingsMap.ResolvedModule(_) => 0 - case BindingsMap.ResolvedPolyglotSymbol(_, _) => - throw new CompilerError( - "Impossible, should be transformed into an error before." - ) - case BindingsMap.ResolvedMethod(_, _) => - throw new CompilerError( - "Impossible, should be transformed into an error before." + val actualResolution = resolvedName.getMetadata(this) + val expectedArity = actualResolution.map { res => + res.target match { + case BindingsMap.ResolvedConstructor(_, cons) => cons.arity + case BindingsMap.ResolvedModule(_) => 0 + case BindingsMap.ResolvedPolyglotSymbol(_, _) => + throw new CompilerError( + "Impossible, should be transformed into an error before." + ) + case BindingsMap.ResolvedMethod(_, _) => + throw new CompilerError( + "Impossible, should be transformed into an error before." + ) + } + } + expectedArity match { + case Some(arity) => + if (consPat.fields.length != arity) { + IR.Error.Pattern( + consPat, + IR.Error.Pattern.WrongArity( + consPat.constructor.name, + arity, + consPat.fields.length ) + ) + } else { + consPat.copy(constructor = resolvedName) } - } - expectedArity match { - case Some(arity) => - if (consPat.fields.length != arity) { - IR.Error.Pattern( - consPat, - IR.Error.Pattern.WrongArity( - consPat.constructor.name, - arity, - consPat.fields.length - ) - ) - } else { - consPat.copy(constructor = resolvedName) - } - case None => consPat.copy(constructor = resolvedName) - } - case other => other - } - branch.copy( - pattern = resolvedPattern, - expression = doExpression(branch.expression, bindings) - ) + case None => consPat.copy(constructor = resolvedName) + } + case other => other } - caseExpr.copy(branches = newBranches) + branch.copy( + pattern = resolvedPattern, + expression = doExpression(branch.expression, bindings) + ) + } + caseExpr.copy(branches = newBranches) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala index 5b6cc74523..7802f76d8a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala @@ -251,8 +251,8 @@ case object SuspendedArguments extends IRPass { args.zip(signatureSegments) } else if (args.length > signatureSegments.length) { val additionalSegments = signatureSegments ::: List.fill( - signatureSegments.length - args.length - )(IR.Empty(None)) + signatureSegments.length - args.length + )(IR.Empty(None)) args.zip(additionalSegments) } else { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala index d344232fdc..f1f3544aaf 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala @@ -69,8 +69,8 @@ case object TypeFunctions extends IRPass { ir: IR.Expression, @unused inlineContext: InlineContext ): IR.Expression = - ir.transformExpressions { - case a => resolveExpression(a) + ir.transformExpressions { case a => + resolveExpression(a) } // === Pass Internals ======================================================= @@ -94,13 +94,12 @@ case object TypeFunctions extends IRPass { * @return `expr`, with any typing functions resolved */ def resolveExpression(expr: IR.Expression): IR.Expression = { - expr.transformExpressions { - case app: IR.Application => - val result = resolveApplication(app) - app - .getMetadata(DocumentationComments) - .map(doc => result.updateMetadata(DocumentationComments -->> doc)) - .getOrElse(result) + expr.transformExpressions { case app: IR.Application => + val result = resolveApplication(app) + app + .getMetadata(DocumentationComments) + .map(doc => result.updateMetadata(DocumentationComments -->> doc)) + .getOrElse(result) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala index 643f19fc10..1cdf0d8957 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala @@ -74,62 +74,62 @@ case object TypeSignatures extends IRPass { var lastSignature: Option[IR.Type.Ascription] = None val newBindings: List[IR.Module.Scope.Definition] = mod.bindings.flatMap { - case sig: IR.Type.Ascription => - val res = lastSignature match { - case Some(oldSig) => Some(IR.Error.Unexpected.TypeSignature(oldSig)) - case None => None - } + case sig: IR.Type.Ascription => + val res = lastSignature match { + case Some(oldSig) => Some(IR.Error.Unexpected.TypeSignature(oldSig)) + case None => None + } - lastSignature = Some(sig) - res - case meth: IR.Module.Scope.Definition.Method => - val newMethod = meth.mapExpressions(resolveExpression) - val res = lastSignature match { - case Some(asc @ IR.Type.Ascription(typed, sig, _, _, _)) => - val methodRef = meth.methodReference - val newMethodWithDoc = asc - .getMetadata(DocumentationComments) - .map(doc => - newMethod.updateMetadata(DocumentationComments -->> doc) - ) - .getOrElse(newMethod) + lastSignature = Some(sig) + res + case meth: IR.Module.Scope.Definition.Method => + val newMethod = meth.mapExpressions(resolveExpression) + val res = lastSignature match { + case Some(asc @ IR.Type.Ascription(typed, sig, _, _, _)) => + val methodRef = meth.methodReference + val newMethodWithDoc = asc + .getMetadata(DocumentationComments) + .map(doc => + newMethod.updateMetadata(DocumentationComments -->> doc) + ) + .getOrElse(newMethod) - typed match { - case ref: IR.Name.MethodReference => - if (ref isSameReferenceAs methodRef) { - Some( - newMethodWithDoc.updateMetadata(this -->> Signature(sig)) - ) - } else { - List( - IR.Error.Unexpected.TypeSignature(asc), - newMethodWithDoc - ) - } - case _ => - List(IR.Error.Unexpected.TypeSignature(asc), newMethodWithDoc) - } - case None => Some(newMethod) - } + typed match { + case ref: IR.Name.MethodReference => + if (ref isSameReferenceAs methodRef) { + Some( + newMethodWithDoc.updateMetadata(this -->> Signature(sig)) + ) + } else { + List( + IR.Error.Unexpected.TypeSignature(asc), + newMethodWithDoc + ) + } + case _ => + List(IR.Error.Unexpected.TypeSignature(asc), newMethodWithDoc) + } + case None => Some(newMethod) + } - lastSignature = None - res - case atom: IR.Module.Scope.Definition.Atom => - Some(atom.mapExpressions(resolveExpression)) - case err: IR.Error => Some(err) - case _: IR.Module.Scope.Definition.Type => - throw new CompilerError( - "Complex type definitions should not be present during type " + - "signature resolution." - ) - case _: IR.Comment.Documentation => - throw new CompilerError( - "Documentation comments should not be present during type " + - "signature resolution." - ) - } ::: lastSignature - .map(asc => IR.Error.Unexpected.TypeSignature(asc)) - .toList + lastSignature = None + res + case atom: IR.Module.Scope.Definition.Atom => + Some(atom.mapExpressions(resolveExpression)) + case err: IR.Error => Some(err) + case _: IR.Module.Scope.Definition.Type => + throw new CompilerError( + "Complex type definitions should not be present during type " + + "signature resolution." + ) + case _: IR.Comment.Documentation => + throw new CompilerError( + "Documentation comments should not be present during type " + + "signature resolution." + ) + } ::: lastSignature + .map(asc => IR.Error.Unexpected.TypeSignature(asc)) + .toList mod.copy( bindings = newBindings @@ -170,51 +170,51 @@ case object TypeSignatures extends IRPass { block.expressions :+ block.returnValue val newExpressions = allBlockExpressions.flatMap { - case sig: IR.Type.Ascription => - val res = lastSignature match { - case Some(oldSig) => Some(IR.Error.Unexpected.TypeSignature(oldSig)) - case None => None - } + case sig: IR.Type.Ascription => + val res = lastSignature match { + case Some(oldSig) => Some(IR.Error.Unexpected.TypeSignature(oldSig)) + case None => None + } - lastSignature = Some(sig) - res - case binding: IR.Expression.Binding => - val newBinding = binding.mapExpressions(resolveExpression) - val res = lastSignature match { - case Some(asc @ IR.Type.Ascription(typed, sig, _, _, _)) => - val name = binding.name - val newBindingWithDoc = asc - .getMetadata(DocumentationComments) - .map(doc => - newBinding.updateMetadata(DocumentationComments -->> doc) - ) - .getOrElse(newBinding) + lastSignature = Some(sig) + res + case binding: IR.Expression.Binding => + val newBinding = binding.mapExpressions(resolveExpression) + val res = lastSignature match { + case Some(asc @ IR.Type.Ascription(typed, sig, _, _, _)) => + val name = binding.name + val newBindingWithDoc = asc + .getMetadata(DocumentationComments) + .map(doc => + newBinding.updateMetadata(DocumentationComments -->> doc) + ) + .getOrElse(newBinding) - typed match { - case typedName: IR.Name => - if (typedName.name == name.name) { - Some( - newBindingWithDoc.updateMetadata(this -->> Signature(sig)) - ) - } else { - List( - IR.Error.Unexpected.TypeSignature(asc), - newBindingWithDoc - ) - } - case _ => + typed match { + case typedName: IR.Name => + if (typedName.name == name.name) { + Some( + newBindingWithDoc.updateMetadata(this -->> Signature(sig)) + ) + } else { List( IR.Error.Unexpected.TypeSignature(asc), newBindingWithDoc ) - } - case None => Some(newBinding) - } + } + case _ => + List( + IR.Error.Unexpected.TypeSignature(asc), + newBindingWithDoc + ) + } + case None => Some(newBinding) + } - lastSignature = None - res - case a => Some(resolveExpression(a)) - } ::: lastSignature.map(IR.Error.Unexpected.TypeSignature(_)).toList + lastSignature = None + res + case a => Some(resolveExpression(a)) + } ::: lastSignature.map(IR.Error.Unexpected.TypeSignature(_)).toList block.copy( expressions = newExpressions.init, diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/UppercaseNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/UppercaseNames.scala index ae68cc72c0..55f3160781 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/UppercaseNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/UppercaseNames.scala @@ -14,8 +14,7 @@ import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.{AliasAnalysis, BindingAnalysis} import org.enso.interpreter.Constants -/** - * Resolves and desugars referent name occurences in non-pattern contexts. +/** Resolves and desugars referent name occurences in non-pattern contexts. * * 1. Attaches resolution metadata to encountered constructors, modules, * and polygot symbols. diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala index b40433b0d3..fce80aea1f 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala @@ -95,14 +95,13 @@ case object VectorLiterals extends IRPass { ir: IR.Expression, vec: IR.Expression ): IR.Expression = - ir.transformExpressions { - case seq: IR.Application.Literal.Sequence => - val trans = seq.mapExpressions(doExpression(_, vec)) - IR.Application.Prefix( - vec.duplicate(), - List(IR.CallArgument.Specified(None, trans, None, None)), - false, - None - ) + ir.transformExpressions { case seq: IR.Application.Literal.Sequence => + val trans = seq.mapExpressions(doExpression(_, vec)) + IR.Application.Prefix( + vec.duplicate(), + List(IR.CallArgument.Specified(None, trans, None, None)), + false, + None + ) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala index d4ead57e22..6d2b864ebc 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala @@ -14,8 +14,7 @@ import org.enso.interpreter.runtime.Module import scala.collection.mutable -/** - * An exception signaling a loop in the export statements. +/** An exception signaling a loop in the export statements. * @param modules the modules forming the cycle. */ case class ExportCycleException(modules: List[Module]) @@ -142,21 +141,19 @@ class ExportsResolution { val allExported = explicitlyExported ++ transitivelyExported val unified = allExported .groupBy(_.module) - .map { - case (mod, items) => - val name = items.collectFirst { - case ExportedModule(_, Some(n), _) => n - } - val itemsUnion = SymbolRestriction.Union(items.map(_.symbols)) - ExportedModule(mod, name, itemsUnion) + .map { case (mod, items) => + val name = items.collectFirst { case ExportedModule(_, Some(n), _) => + n + } + val itemsUnion = SymbolRestriction.Union(items.map(_.symbols)) + ExportedModule(mod, name, itemsUnion) } .toList exports(node.module) = unified } - exports.foreach { - case (module, exports) => - getBindings(module).resolvedExports = - exports.map(ex => ex.copy(symbols = ex.symbols.optimize)) + exports.foreach { case (module, exports) => + getBindings(module).resolvedExports = + exports.map(ex => ex.copy(symbols = ex.symbols.optimize)) } } @@ -191,14 +188,13 @@ class ExportsResolution { ownPolyglotBindings, exportedModules, reExportedSymbols - ).flatten.groupBy(_._1).map { - case (m, names) => (m, names.flatMap(_._2).distinct) + ).flatten.groupBy(_._1).map { case (m, names) => + (m, names.flatMap(_._2).distinct) } } } - /** - * Performs exports resolution on a selected set of modules. + /** Performs exports resolution on a selected set of modules. * * The exports graph is validated and stored in the individual modules, * allowing further use. diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/ImportResolver.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/ImportResolver.scala index 046e5f155a..6aca432474 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/ImportResolver.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/ImportResolver.scala @@ -8,8 +8,7 @@ import org.enso.interpreter.runtime.Module import scala.collection.mutable -/** - * Runs imports resolution. Starts from a given module and then recursively +/** Runs imports resolution. Starts from a given module and then recursively * collects all modules that are reachable from it. * * Each of the reachable modules will be parsed and will have imported modules @@ -21,8 +20,7 @@ import scala.collection.mutable */ class ImportResolver(compiler: Compiler) { - /** - * Runs the import mapping logic. + /** Runs the import mapping logic. * * @param module the entry-point module. * @return a list of all modules that need to be compiled in order to run diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala index cf534958b8..f0e0b0a468 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala @@ -9,15 +9,13 @@ import org.enso.compiler.pass.analyse.BindingAnalysis import scala.jdk.CollectionConverters._ -/** - * Builds an IR stub. This is useful for source-less modules (such as +/** Builds an IR stub. This is useful for source-less modules (such as * [[org.enso.interpreter.runtime.builtin.Builtins]]). Having a stub IR * guarantees that other modules can compile against it. */ object StubIrBuilder { - /** - * Build the stub IR for a given module. + /** Build the stub IR for a given module. * @param module the module to build IR for. * @return the built stub IR. */ @@ -27,9 +25,8 @@ object StubIrBuilder { val conses = scope.getConstructors.asScala val consNames = conses.keys.map(_.toLowerCase()).toSet val definedConstructors: List[BindingsMap.Cons] = - conses.toList.map { - case (name, cons) => - BindingsMap.Cons(name, cons.getArity) + conses.toList.map { case (name, cons) => + BindingsMap.Cons(name, cons.getArity) } val moduleMethods = Option(scope.getMethods.get(scope.getAssociatedType)) .map(methods => @@ -42,8 +39,8 @@ object StubIrBuilder { val polyglot = scope.getPolyglotSymbols.asScala.keys.toList .map(BindingsMap.PolyglotSymbol) val exportedBindings = definedConstructors.map(c => - (c.name.toLowerCase, List(ResolvedConstructor(module, c))) - ) ++ moduleMethods.map(m => (m.name, List(ResolvedMethod(module, m)))) + (c.name.toLowerCase, List(ResolvedConstructor(module, c))) + ) ++ moduleMethods.map(m => (m.name, List(ResolvedMethod(module, m)))) val meta = BindingsMap( definedConstructors, polyglot, diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/DebuggerMessageHandler.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/DebuggerMessageHandler.scala index c8b6ed4114..7b30614937 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/DebuggerMessageHandler.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/DebuggerMessageHandler.scala @@ -9,22 +9,19 @@ import org.graalvm.polyglot.io.MessageEndpoint import scala.jdk.CollectionConverters._ -/** - * Helper class that handles communication with Debugger client and delegates +/** Helper class that handles communication with Debugger client and delegates * request to the execution event node of the ReplDebuggerInstrument. */ class DebuggerMessageHandler extends MessageEndpoint { private var client: MessageEndpoint = _ - /** - * Sets the client end of the connection, after it has been established. + /** Sets the client end of the connection, after it has been established. * * @param ep the client endpoint. */ def setClient(ep: MessageEndpoint): Unit = client = ep - /** - * Checks if a client has been registered. + /** Checks if a client has been registered. * * @return a boolean value indicating whether a client is registered */ @@ -56,8 +53,7 @@ class DebuggerMessageHandler extends MessageEndpoint { private def currentExecutionNode: Option[ReplExecutionEventNode] = executionNodeStack.headOption - /** - * Starts a REPL session by sending a message to the client. + /** Starts a REPL session by sending a message to the client. * * @param executionNode execution node used for instrumenting the session */ @@ -66,8 +62,7 @@ class DebuggerMessageHandler extends MessageEndpoint { sendToClient(Debugger.createSessionStartNotification()) } - /** - * A helper function that cleans up the current session and terminates it. + /** A helper function that cleans up the current session and terminates it. * * @return never returns as control is passed to the interpreter */ @@ -113,8 +108,7 @@ class DebuggerMessageHandler extends MessageEndpoint { object DebuggerMessageHandler { - /** - * Converts the attached Truffle stack trace into StackTraceElements that are + /** Converts the attached Truffle stack trace into StackTraceElements that are * attached to the exception, so that they are preserved by serialization. * * The language stack trace is attached to the last exception in the diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextManager.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextManager.scala index d99cacf00c..265132215a 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextManager.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextManager.scala @@ -9,16 +9,14 @@ import org.enso.polyglot.runtime.Runtime.Api.{ import scala.collection.mutable.Stack -/** - * Storage for active execution contexts. +/** Storage for active execution contexts. */ class ExecutionContextManager { private var contexts: Map[ContextId, ExecutionContextState] = Map().withDefaultValue(ExecutionContextState.empty) - /** - * Creates a new context with a given id. + /** Creates a new context with a given id. * * @param id the context id. */ @@ -27,8 +25,7 @@ class ExecutionContextManager { contexts += id -> ExecutionContextState.empty } - /** - * Destroys a context with a given id. + /** Destroys a context with a given id. * @param id the context id. */ def destroy(id: ContextId): Unit = @@ -36,8 +33,7 @@ class ExecutionContextManager { contexts -= id } - /** - * Gets a context with a given id. + /** Gets a context with a given id. * * @param id the context id. * @return the context with the given id, if exists. @@ -49,8 +45,7 @@ class ExecutionContextManager { } yield id } - /** - * Gets a stack for a given context id. + /** Gets a stack for a given context id. * * @param id the context id. * @return the stack. @@ -60,8 +55,7 @@ class ExecutionContextManager { contexts(id).stack } - /** - * Gets all execution contexts. + /** Gets all execution contexts. * * @return all currently available execution contexsts. */ @@ -70,8 +64,7 @@ class ExecutionContextManager { contexts.view.mapValues(_.stack) } - /** - * If the context exists, push the item on the stack. + /** If the context exists, push the item on the stack. * * @param id the context id. * @param item stack item. @@ -84,8 +77,7 @@ class ExecutionContextManager { } yield state.stack.push(InstrumentFrame(item)) } - /** - * If the context exists and stack not empty, pop the item from the stack. + /** If the context exists and stack not empty, pop the item from the stack. * * @param id the context id. * @return stack frame or None if the stack is empty or not exists. @@ -98,8 +90,7 @@ class ExecutionContextManager { } yield state.stack.pop() } - /** - * Tests if a context specified by its id is stored by the manager. + /** Tests if a context specified by its id is stored by the manager. * * @param contextId the identifier of the execution context * @return true if the context is stored or false otherwise @@ -109,8 +100,7 @@ class ExecutionContextManager { contexts.contains(contextId) } - /** - * Upserts a visualisation for the specified context. + /** Upserts a visualisation for the specified context. * * @param contextId the identifier of the execution context * @param visualisation the visualisation to upsert @@ -124,8 +114,7 @@ class ExecutionContextManager { state.visualisations.upsert(visualisation) } - /** - * Returns a visualisation with the provided id. + /** Returns a visualisation with the provided id. * * @param contextId the identifier of the execution context * @param visualisationId the identifier of visualisation @@ -142,8 +131,7 @@ class ExecutionContextManager { } yield visualisation } - /** - * Finds all visualisations attached to an expression. + /** Finds all visualisations attached to an expression. * * @param contextId the identifier of the execution context * @param expressionId the unique identifier of the expression @@ -160,8 +148,7 @@ class ExecutionContextManager { } yield visualisation } - /** - * Removes a visualisation from the holder. + /** Removes a visualisation from the holder. * * @param contextId the identifier of the execution context * @param visualisationId the visualisation identifier diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextState.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextState.scala index a824f36746..e634c8b4d3 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextState.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/ExecutionContextState.scala @@ -4,8 +4,7 @@ import org.enso.polyglot.runtime.Runtime.Api.StackItem import scala.collection.mutable -/** - * Represents a state of an execution context. +/** Represents a state of an execution context. * * @param stack the current call stack for the execution context * @param visualisations the holder of all visualisations attached to the @@ -18,15 +17,13 @@ case class ExecutionContextState( object ExecutionContextState { - /** - * Returns empty state. + /** Returns empty state. */ def empty: ExecutionContextState = ExecutionContextState(mutable.Stack.empty, VisualisationHolder.empty) } -/** - * Stack frame of the context. +/** Stack frame of the context. * * @param item the stack item. * @param cache the cache of this stack frame. diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Handler.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Handler.scala index dc54cb3d13..e0edb3893e 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Handler.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Handler.scala @@ -12,23 +12,20 @@ import org.enso.interpreter.service.ExecutionService import org.enso.polyglot.runtime.Runtime.Api import org.graalvm.polyglot.io.MessageEndpoint -/** - * A message endpoint implementation used by the +/** A message endpoint implementation used by the * [[org.enso.interpreter.instrument.RuntimeServerInstrument]]. */ class Endpoint(handler: Handler) extends MessageEndpoint { var client: MessageEndpoint = _ - /** - * Sets the client end of the connection, after it has been established. + /** Sets the client end of the connection, after it has been established. * * @param ep the client endpoint. */ def setClient(ep: MessageEndpoint): Unit = client = ep - /** - * Sends a response to the connected client. + /** Sends a response to the connected client. * * @param msg the message to send. */ @@ -47,8 +44,7 @@ class Endpoint(handler: Handler) extends MessageEndpoint { override def sendClose(): Unit = {} } -/** - * A message handler, dispatching behaviors based on messages received +/** A message handler, dispatching behaviors based on messages received * from an instance of [[Endpoint]]. */ final class Handler { @@ -59,8 +55,7 @@ final class Handler { var truffleContext: TruffleContext = _ var commandProcessor: CommandProcessor = _ - /** - * Initializes the handler with relevant Truffle objects, allowing it to + /** Initializes the handler with relevant Truffle objects, allowing it to * perform code execution. * * @param service the language execution service instance. @@ -83,8 +78,7 @@ final class Handler { endpoint.sendToClient(Api.Response(Api.InitializedNotification())) } - /** - * Handles a message received from the client. + /** Handles a message received from the client. * * @param request the message to handle. */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/InterpreterContext.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/InterpreterContext.scala index 3af50c029e..dd933476f7 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/InterpreterContext.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/InterpreterContext.scala @@ -3,8 +3,7 @@ package org.enso.interpreter.instrument import com.oracle.truffle.api.TruffleContext import org.enso.interpreter.service.ExecutionService -/** - * Contains suppliers of services that provide interpreter specific +/** Contains suppliers of services that provide interpreter specific * functionality. * * @param executionService a service allowing externally-triggered code diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Visualisation.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Visualisation.scala index 3ea5f05f30..bce32bbbfa 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Visualisation.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/Visualisation.scala @@ -2,8 +2,7 @@ package org.enso.interpreter.instrument import org.enso.polyglot.runtime.Runtime.Api.{ExpressionId, VisualisationId} -/** - * An object containing visualisation data. +/** An object containing visualisation data. * * @param id the unique identifier of visualisation * @param expressionId the identifier of expression that the visualisation is diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/VisualisationHolder.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/VisualisationHolder.scala index 1031b97742..e3d81f69a1 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/VisualisationHolder.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/VisualisationHolder.scala @@ -2,16 +2,14 @@ package org.enso.interpreter.instrument import org.enso.polyglot.runtime.Runtime.Api.{ExpressionId, VisualisationId} -/** - * A mutable holder of all visualisations attached to an execution context. +/** A mutable holder of all visualisations attached to an execution context. */ class VisualisationHolder() { private var visualisationMap: Map[ExpressionId, List[Visualisation]] = Map.empty.withDefaultValue(List.empty) - /** - * Upserts a visualisation. + /** Upserts a visualisation. * * @param visualisation the visualisation to upsert */ @@ -21,8 +19,7 @@ class VisualisationHolder() { visualisationMap += (visualisation.expressionId -> (visualisation :: removed)) } - /** - * Removes a visualisation from the holder. + /** Removes a visualisation from the holder. * * @param visualisationId the visualisation identifier * @param expressionId the id of expression that the visualisation is @@ -37,8 +34,7 @@ class VisualisationHolder() { visualisationMap += (expressionId -> removed) } - /** - * Finds all visualisations attached to an expression. + /** Finds all visualisations attached to an expression. * * @param expressionId the unique identifier of the expression * @return a list of matching visualisation @@ -46,8 +42,7 @@ class VisualisationHolder() { def find(expressionId: ExpressionId): List[Visualisation] = visualisationMap(expressionId) - /** - * Returns a visualisation with the provided id. + /** Returns a visualisation with the provided id. * * @param visualisationId the identifier of visualisation * @return an option with visualisation @@ -59,8 +54,7 @@ class VisualisationHolder() { object VisualisationHolder { - /** - * Returns an empty holder. + /** Returns an empty holder. */ def empty = new VisualisationHolder() diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/AttachVisualisationCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/AttachVisualisationCmd.scala index 6164241cc9..9fabda2e79 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/AttachVisualisationCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/AttachVisualisationCmd.scala @@ -11,8 +11,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that attaches a visualisation to an expression. +/** A command that attaches a visualisation to an expression. * * @param maybeRequestId an option with request id * @param request a request for a service @@ -22,9 +21,9 @@ class AttachVisualisationCmd( request: Api.AttachVisualisation ) extends Command(maybeRequestId) { - /** @inheritdoc **/ - override def execute( - implicit ctx: RuntimeContext, + /** @inheritdoc */ + override def execute(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = { if (doesContextExist) { @@ -40,8 +39,8 @@ class AttachVisualisationCmd( ) } - private def attachVisualisation()( - implicit ctx: RuntimeContext, + private def attachVisualisation()(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = { val maybeFutureExecutable = @@ -69,8 +68,8 @@ class AttachVisualisationCmd( } } - private def replyWithContextNotExistError()( - implicit ctx: RuntimeContext, + private def replyWithContextNotExistError()(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = { Future { diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CloseFileCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CloseFileCmd.scala index a63dbc92c0..7d8b7ea628 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CloseFileCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CloseFileCmd.scala @@ -5,16 +5,15 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.{ExecutionContext, Future} -/** - * A command that closes a file. +/** A command that closes a file. * * @param request a request for a service */ class CloseFileCmd(request: Api.CloseFileNotification) extends Command(None) { - /** @inheritdoc **/ - override def execute( - implicit ctx: RuntimeContext, + /** @inheritdoc */ + override def execute(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = Future { diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/Command.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/Command.scala index cb3c43cca4..59604377d6 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/Command.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/Command.scala @@ -6,14 +6,12 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * Base command trait that encapsulates a function request. Uses +/** Base command trait that encapsulates a function request. Uses * [[RuntimeContext]] to perform a request. */ abstract class Command(maybeRequestId: Option[RequestId]) { - /** - * Executes a request. + /** Executes a request. * * @param ctx contains suppliers of services to perform a request */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CommandFactory.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CommandFactory.scala index cbd77d05d0..f8917a1513 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CommandFactory.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CommandFactory.scala @@ -2,13 +2,11 @@ package org.enso.interpreter.instrument.command import org.enso.polyglot.runtime.Runtime.Api -/** - * A factory that creates a command for an API request. +/** A factory that creates a command for an API request. */ object CommandFactory { - /** - * Creates a command that encapsulates a function request as an object. + /** Creates a command that encapsulates a function request as an object. * * @param request an API request * @return a command diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CreateContextCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CreateContextCmd.scala index 3de8b76392..4bc5d46542 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CreateContextCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/CreateContextCmd.scala @@ -6,8 +6,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that creates an execution context. +/** A command that creates an execution context. * * @param maybeRequestId an option with request id * @param request a request for a service @@ -17,9 +16,9 @@ class CreateContextCmd( request: Api.CreateContextRequest ) extends Command(maybeRequestId) { - /** @inheritdoc **/ - override def execute( - implicit ctx: RuntimeContext, + /** @inheritdoc */ + override def execute(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = Future { diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DestroyContextCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DestroyContextCmd.scala index 8ac2c9135a..91996110f2 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DestroyContextCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DestroyContextCmd.scala @@ -6,8 +6,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that destroys the specified execution context. +/** A command that destroys the specified execution context. * * @param maybeRequestId an option with request id * @param request a request for a service @@ -17,9 +16,9 @@ class DestroyContextCmd( request: Api.DestroyContextRequest ) extends Command(maybeRequestId) { - /** @inheritdoc **/ - override def execute( - implicit ctx: RuntimeContext, + /** @inheritdoc */ + override def execute(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = Future { diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala index 285cb24b4d..b55eec9069 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/DetachVisualisationCmd.scala @@ -6,8 +6,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that detaches a visualisation from the expression. +/** A command that detaches a visualisation from the expression. * * @param maybeRequestId an option with request id * @param request a request for a service @@ -17,9 +16,9 @@ class DetachVisualisationCmd( request: Api.DetachVisualisation ) extends Command(maybeRequestId) { - /** @inheritdoc **/ - override def execute( - implicit ctx: RuntimeContext, + /** @inheritdoc */ + override def execute(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = Future { diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/EditFileCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/EditFileCmd.scala index 903a96c33f..b1ecedbdb6 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/EditFileCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/EditFileCmd.scala @@ -6,15 +6,13 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.{ExecutionContext, Future} -/** - * A command that performs edition of a file. +/** A command that performs edition of a file. * * @param request a request for editing */ class EditFileCmd(request: Api.EditFileNotification) extends Command(None) { - /** - * Executes a request. + /** Executes a request. * * @param ctx contains suppliers of services to perform a request */ @@ -41,9 +39,8 @@ class EditFileCmd(request: Api.EditFileNotification) extends Command(None) { ctx.contextManager.getAll .filter(kv => kv._2.nonEmpty) .mapValues(_.toList) - .map { - case (contextId, stack) => - new ExecuteJob(contextId, stack, Seq(), sendMethodCallUpdates = false) + .map { case (contextId, stack) => + new ExecuteJob(contextId, stack, Seq(), sendMethodCallUpdates = false) } } diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/InvalidateModulesIndexCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/InvalidateModulesIndexCmd.scala index aee36fe84e..4549d749b3 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/InvalidateModulesIndexCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/InvalidateModulesIndexCmd.scala @@ -5,8 +5,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.{ExecutionContext, Future} -/** - * A command that invalidates the modules index. +/** A command that invalidates the modules index. * * @param maybeRequestId an option with request id * @param request a request for invalidation @@ -16,8 +15,7 @@ class InvalidateModulesIndexCmd( val request: Api.InvalidateModulesIndexRequest ) extends Command(maybeRequestId) { - /** - * Executes a request. + /** Executes a request. * * @param ctx contains suppliers of services to perform a request */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala index 614dc141d5..3a3986b232 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/ModifyVisualisationCmd.scala @@ -11,8 +11,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that modifies a visualisation. +/** A command that modifies a visualisation. * * @param maybeRequestId an option with request id * @param request a request for a service @@ -22,9 +21,9 @@ class ModifyVisualisationCmd( request: Api.ModifyVisualisation ) extends Command(maybeRequestId) { - /** @inheritdoc **/ - override def execute( - implicit ctx: RuntimeContext, + /** @inheritdoc */ + override def execute(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = { if (doesContextExist) { @@ -34,8 +33,8 @@ class ModifyVisualisationCmd( } } - private def modifyVisualisation()( - implicit ctx: RuntimeContext, + private def modifyVisualisation()(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = { val maybeVisualisation = ctx.contextManager.getVisualisationById( @@ -80,8 +79,8 @@ class ModifyVisualisationCmd( ) } - private def replyWithContextNotExistError()( - implicit ctx: RuntimeContext, + private def replyWithContextNotExistError()(implicit + ctx: RuntimeContext, ec: ExecutionContext ): Future[Unit] = { Future { diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/OpenFileCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/OpenFileCmd.scala index af245a3b09..c638730edd 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/OpenFileCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/OpenFileCmd.scala @@ -5,8 +5,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.concurrent.{ExecutionContext, Future} -/** - * A command that opens a file. +/** A command that opens a file. * * @param request a request for a service */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PopContextCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PopContextCmd.scala index 66163bf2bd..e4f29ef304 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PopContextCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PopContextCmd.scala @@ -7,8 +7,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that pops an item from a stack. +/** A command that pops an item from a stack. * * @param maybeRequestId an option with request id * @param request a request for a service diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PushContextCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PushContextCmd.scala index 8f007b31a5..0a2f58367e 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PushContextCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/PushContextCmd.scala @@ -11,8 +11,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that pushes an item onto a stack. +/** A command that pushes an item onto a stack. * * @param maybeRequestId an option with request id * @param request a request for a service diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RecomputeContextCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RecomputeContextCmd.scala index bd37fb1da1..0e6d37aa0f 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RecomputeContextCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RecomputeContextCmd.scala @@ -8,8 +8,7 @@ import org.enso.polyglot.runtime.Runtime.Api.RequestId import scala.concurrent.{ExecutionContext, Future} -/** - * A command that forces a recomputation of the current position. +/** A command that forces a recomputation of the current position. * * @param maybeRequestId an option with request id * @param request a request for a service diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RenameProjectCmd.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RenameProjectCmd.scala index 7fa660d5f1..476d75cbb8 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RenameProjectCmd.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/command/RenameProjectCmd.scala @@ -10,8 +10,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.collection.mutable import scala.concurrent.{ExecutionContext, Future} -/** - * A command that orchestrates renaming of a project name. +/** A command that orchestrates renaming of a project name. * * @param maybeRequestId an option with request id * @param request a request for a service @@ -45,8 +44,7 @@ class RenameProjectCmd( } } - /** - * Update module name of method pointers in the stack. + /** Update module name of method pointers in the stack. * * @param projectName the new project name * @param stack the exeution stack diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandExecutionEngine.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandExecutionEngine.scala index 9e5f33384d..5808eaf1f2 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandExecutionEngine.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandExecutionEngine.scala @@ -13,8 +13,7 @@ import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, Future} import scala.util.control.NonFatal import scala.util.{Failure, Success} -/** - * This component schedules the execution of commands. It keep a queue of +/** This component schedules the execution of commands. It keep a queue of * pending commands and activates command execution in FIFO order. * * @param interpreterContext suppliers of services that provide interpreter diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandProcessor.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandProcessor.scala index 6dd48cf4fa..599129e4ef 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandProcessor.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/CommandProcessor.scala @@ -4,21 +4,18 @@ import org.enso.interpreter.instrument.command.Command import scala.concurrent.Future -/** - * Defines a uniform interface to execute commands. +/** Defines a uniform interface to execute commands. */ trait CommandProcessor { - /** - * Invokes a command with the provided context. + /** Invokes a command with the provided context. * * @param cmd a command to execute * @return a future signaling the completion of computations */ def invoke(cmd: Command): Future[Completion] - /** - * Stops the command processor. + /** Stops the command processor. */ def stop(): Unit diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Completion.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Completion.scala index 67011d85c8..2c7471f295 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Completion.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Completion.scala @@ -1,19 +1,16 @@ package org.enso.interpreter.instrument.execution -/** - * Represents completion of computations. +/** Represents completion of computations. */ sealed trait Completion object Completion { - /** - * Signals completion of computations. + /** Signals completion of computations. */ case object Done extends Completion - /** - * Signals that computations were interrupted. + /** Signals that computations were interrupted. */ case object Interrupted extends Completion diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Executable.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Executable.scala index 4fc5c8958c..e339cec0f7 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Executable.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Executable.scala @@ -5,8 +5,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.collection.mutable -/** - * Represents executable piece of enso program. +/** Represents executable piece of enso program. * * @param contextId an identifier of a context to execute * @param stack a call stack that must be executed diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobControlPlane.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobControlPlane.scala index 915238e1ac..e64e0d5147 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobControlPlane.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobControlPlane.scala @@ -2,18 +2,15 @@ package org.enso.interpreter.instrument.execution import java.util.UUID -/** - * Controls running jobs. +/** Controls running jobs. */ trait JobControlPlane { - /** - * Aborts all interruptible jobs. + /** Aborts all interruptible jobs. */ def abortAllJobs(): Unit - /** - * Aborts all jobs that relates to the specified execution context. + /** Aborts all jobs that relates to the specified execution context. * * @param contextId an identifier of a context */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobExecutionEngine.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobExecutionEngine.scala index 9986d19093..503bd5db33 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobExecutionEngine.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobExecutionEngine.scala @@ -12,8 +12,7 @@ import org.enso.polyglot.RuntimeServerInfo import scala.concurrent.{Future, Promise} import scala.util.control.NonFatal -/** - * This component schedules the execution of jobs. It keep a queue of +/** This component schedules the execution of jobs. It keep a queue of * pending jobs and activates job execution in FIFO order. * * @param interpreterContext suppliers of services that provide interpreter diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobProcessor.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobProcessor.scala index 32c346d414..82c94fe130 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobProcessor.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/JobProcessor.scala @@ -4,21 +4,18 @@ import org.enso.interpreter.instrument.job.Job import scala.concurrent.Future -/** - * Defines a uniform interface to execute job. +/** Defines a uniform interface to execute job. */ trait JobProcessor { - /** - * Runs a job with the provided context. + /** Runs a job with the provided context. * * @param job a job to execute * @return the future result of an asynchronous computation */ def run[A](job: Job[A]): Future[A] - /** - * Stops the job processor. + /** Stops the job processor. */ def stop(): Unit diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Locking.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Locking.scala index 044bbf42e9..c4b1e5df7a 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Locking.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/Locking.scala @@ -3,68 +3,57 @@ package org.enso.interpreter.instrument.execution import java.io.File import java.util.UUID -/** - * Provides locking capabilities for the runtime server. +/** Provides locking capabilities for the runtime server. */ trait Locking { - /** - * Removes a lock for an execution context. + /** Removes a lock for an execution context. * * @param contextId the context id */ def removeContextLock(contextId: UUID): Unit - /** - * Removes a lock for a file that contains enso code. + /** Removes a lock for a file that contains enso code. * * @param file the file to lock */ def removeFileLock(file: File): Unit - /** - * Acquires a compilation write lock. + /** Acquires a compilation write lock. */ def acquireWriteCompilationLock(): Unit - /** - * Releases a compilation write lock. + /** Releases a compilation write lock. */ def releaseWriteCompilationLock(): Unit - /** - * Acquires a compilation read lock. + /** Acquires a compilation read lock. */ def acquireReadCompilationLock(): Unit - /** - * Releases a compilation read lock. + /** Releases a compilation read lock. */ def releaseReadCompilationLock(): Unit - /** - * Acquires a context lock. + /** Acquires a context lock. * * @param contextId a context to lock */ def acquireContextLock(contextId: UUID): Unit - /** - * Releases a context lock. + /** Releases a context lock. * * @param contextId a context to unlock */ def releaseContextLock(contextId: UUID): Unit - /** - * Acquires a file lock. + /** Acquires a file lock. * * @param file a file to lock */ def acquireFileLock(file: File): Unit - /** - * Releases a file lock. + /** Releases a file lock. * * @param file a file to unlock */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/ReentrantLocking.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/ReentrantLocking.scala index 620889f739..621da940a7 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/ReentrantLocking.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/ReentrantLocking.scala @@ -4,8 +4,7 @@ import java.io.File import java.util.UUID import java.util.concurrent.locks.{Lock, ReentrantLock, ReentrantReadWriteLock} -/** - * Provides locking capabilities for the runtime server. Ir uses reentrant +/** Provides locking capabilities for the runtime server. Ir uses reentrant * locks. */ class ReentrantLocking extends Locking { @@ -35,7 +34,7 @@ class ReentrantLocking extends Locking { } } - /** @inheritdoc **/ + /** @inheritdoc */ override def removeContextLock(contextId: UUID): Unit = { contextMapLock.lock() try { @@ -60,7 +59,7 @@ class ReentrantLocking extends Locking { } } - /** @inheritdoc **/ + /** @inheritdoc */ override def removeFileLock(file: File): Unit = { fileMapLock.lock() try { @@ -70,35 +69,35 @@ class ReentrantLocking extends Locking { } } - /** @inheritdoc **/ + /** @inheritdoc */ override def acquireWriteCompilationLock(): Unit = compilationLock.writeLock().lockInterruptibly() - /** @inheritdoc **/ + /** @inheritdoc */ override def releaseWriteCompilationLock(): Unit = compilationLock.writeLock().unlock() - /** @inheritdoc **/ + /** @inheritdoc */ override def acquireReadCompilationLock(): Unit = compilationLock.readLock().lockInterruptibly() - /** @inheritdoc **/ + /** @inheritdoc */ override def releaseReadCompilationLock(): Unit = compilationLock.readLock().unlock() - /** @inheritdoc **/ + /** @inheritdoc */ override def acquireContextLock(contextId: UUID): Unit = getContextLock(contextId).lockInterruptibly() - /** @inheritdoc **/ + /** @inheritdoc */ override def releaseContextLock(contextId: UUID): Unit = getContextLock(contextId).unlock() - /** @inheritdoc **/ + /** @inheritdoc */ override def acquireFileLock(file: File): Unit = getFileLock(file).lockInterruptibly() - /** @inheritdoc **/ + /** @inheritdoc */ override def releaseFileLock(file: File): Unit = getFileLock(file).unlock() } diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RunningJob.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RunningJob.scala index d227abb599..8369356dc9 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RunningJob.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RunningJob.scala @@ -5,8 +5,7 @@ import java.util.concurrent.Future import org.enso.interpreter.instrument.job.Job -/** - * Represents a running job. +/** Represents a running job. * * @param id a job id * @param job a job diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RuntimeContext.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RuntimeContext.scala index 7221a0f3bc..9ed598ac84 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RuntimeContext.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/RuntimeContext.scala @@ -4,8 +4,7 @@ import com.oracle.truffle.api.TruffleContext import org.enso.interpreter.instrument.{Endpoint, ExecutionContextManager} import org.enso.interpreter.service.ExecutionService -/** - * Contains suppliers of services that provide application specific +/** Contains suppliers of services that provide application specific * functionality. * * @param executionService a service allowing externally-triggered code diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/TruffleThreadFactory.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/TruffleThreadFactory.scala index dd9508093f..00a4969c49 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/TruffleThreadFactory.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/execution/TruffleThreadFactory.scala @@ -5,8 +5,7 @@ import java.util.concurrent.atomic.AtomicInteger import org.enso.interpreter.runtime.Context -/** - * A factory that creates new truffle threads on demand. +/** A factory that creates new truffle threads on demand. * * @param context the language context * @param prefix the prefix for names of created threads @@ -16,7 +15,7 @@ class TruffleThreadFactory(context: Context, prefix: String) private val counter = new AtomicInteger(0) - /** @inheritdoc **/ + /** @inheritdoc */ override def newThread(r: Runnable): Thread = { val thread = context.createThread(r) thread.setName(s"$prefix-${counter.incrementAndGet()}") diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledJob.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledJob.scala index 2adb39c4ce..84c14b6a14 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledJob.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledJob.scala @@ -20,8 +20,7 @@ import scala.collection.concurrent.TrieMap import scala.jdk.CollectionConverters._ import scala.jdk.OptionConverters._ -/** - * A job that ensures that specified files are compiled. +/** A job that ensures that specified files are compiled. * * @param files a files to compile */ @@ -45,8 +44,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) } } - /** - * Run the scheduled compilation and invalidation logic, and send the + /** Run the scheduled compilation and invalidation logic, and send the * suggestion updates. * * @param modules the list of modules to compile. @@ -68,8 +66,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) } } - /** - * Compile the imported modules and send the suggestion updates. + /** Compile the imported modules and send the suggestion updates. * * @param modules the list of modules to analyze. * @param ctx the runtime context @@ -91,8 +88,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) } } - /** - * Compile all modules in the scope and send the extracted suggestions. + /** Compile all modules in the scope and send the extracted suggestions. * * @param ctx the runtime context */ @@ -225,8 +221,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) } } - /** - * Extract compilation diagnostics from the module and send the diagnostic + /** Extract compilation diagnostics from the module and send the diagnostic * updates. * * @param module the module to analyze @@ -253,8 +248,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) getCompilationStatus(diagnostics) } - /** - * Create Api diagnostic message from the `IR` node. + /** Create Api diagnostic message from the `IR` node. * * @param kind the diagnostic type * @param module the module to analyze @@ -287,8 +281,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) ) } - /** - * Compile the module. + /** Compile the module. * * @param module the module to compile. * @param ctx the runtime context @@ -309,8 +302,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) compilationResult } - /** - * Apply pending edits to the file. + /** Apply pending edits to the file. * * @param file the file to apply edits to * @param ctx the runtime context @@ -332,8 +324,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) } } - /** - * Create cache invalidation commands after applying the edits. + /** Create cache invalidation commands after applying the edits. * * @param changeset the [[Changeset]] object capturing the previous * version of IR @@ -365,8 +356,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) ) } - /** - * Run the invalidation commands. + /** Run the invalidation commands. * * @param invalidationCommands the invalidation command to run * @param ctx the runtime context @@ -381,8 +371,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) } } - /** - * Send notification about module updates. + /** Send notification about module updates. * * @param payload the module update * @param ctx the runtime context @@ -394,8 +383,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) ctx.endpoint.sendToClient(Api.Response(payload)) } - /** - * Send notification about the compilation status. + /** Send notification about the compilation status. * * @param diagnostics the list of diagnostic messages returned by the * compiler @@ -412,8 +400,7 @@ class EnsureCompiledJob(protected val files: Iterable[File]) } } - /** - * Send notification about the compilation status. + /** Send notification about the compilation status. * * @param failure the execution failure * @param ctx the runtime context @@ -479,8 +466,7 @@ object EnsureCompiledJob { case None => Some(edits) } - /** - * Create a job ensuring that files are compiled. + /** Create a job ensuring that files are compiled. * * @param files the list of files to compile * @return a new job @@ -489,8 +475,7 @@ object EnsureCompiledJob { new EnsureCompiledJob(files) } - /** - * Create a job ensuring that files are compiled after applying the edits. + /** Create a job ensuring that files are compiled after applying the edits. * * @param file a file to compile * @param edits the list of edits to apply @@ -501,8 +486,7 @@ object EnsureCompiledJob { EnsureCompiledJob(List(file)) } - /** - * Create a job ensuring that modules are compiled. + /** Create a job ensuring that modules are compiled. * * @param modules a list of modules to compile * @return a new job diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledStackJob.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledStackJob.scala index f6dcd598da..9dbbf64df6 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledStackJob.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/EnsureCompiledStackJob.scala @@ -10,8 +10,7 @@ import org.enso.polyglot.runtime.Runtime.Api import scala.jdk.OptionConverters._ -/** - * Ensures that all files on the provided stack are compiled. +/** Ensures that all files on the provided stack are compiled. * * @param stack a call stack */ @@ -54,8 +53,7 @@ class EnsureCompiledStackJob(stack: Iterable[InstrumentFrame])(implicit object EnsureCompiledStackJob { - /** - * Extracts files to compile from a call stack. + /** Extracts files to compile from a call stack. * * @param stack a call stack * @return a list of files to compile diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ExecuteJob.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ExecuteJob.scala index 11f95cef6f..c233019a34 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ExecuteJob.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ExecuteJob.scala @@ -6,8 +6,7 @@ import org.enso.interpreter.instrument.InstrumentFrame import org.enso.interpreter.instrument.execution.{Executable, RuntimeContext} import org.enso.polyglot.runtime.Runtime.Api -/** - * A job responsible for executing a call stack for the provided context. +/** A job responsible for executing a call stack for the provided context. * * @param contextId an identifier of a context to execute * @param stack a call stack to execute diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/Job.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/Job.scala index c76312a287..69354fb1af 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/Job.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/Job.scala @@ -4,8 +4,7 @@ import java.util.UUID import org.enso.interpreter.instrument.execution.RuntimeContext -/** - * A fine-grained request for a runtime server service. Uses [[RuntimeContext]] +/** A fine-grained request for a runtime server service. Uses [[RuntimeContext]] * to perform a request. * * @param contextIds affected executions contexts' ids @@ -19,8 +18,7 @@ abstract class Job[+A]( val mayInterruptIfRunning: Boolean ) { - /** - * Executes a job. + /** Executes a job. * * @param ctx contains suppliers of services to perform a request */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala index 5e6039a9a3..f66137d18e 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala @@ -43,14 +43,12 @@ import org.enso.text.editing.model import scala.jdk.OptionConverters._ import scala.jdk.CollectionConverters._ -/** - * Provides support for executing Enso code. Adds convenient methods to +/** Provides support for executing Enso code. Adds convenient methods to * run Enso programs in a Truffle context. */ trait ProgramExecutionSupport { - /** - * Runs an Enso program. + /** Runs an Enso program. * * @param executionFrame an execution frame * @param callStack a call stack @@ -141,8 +139,7 @@ trait ProgramExecutionSupport { } } - /** - * Runs an Enso program. + /** Runs an Enso program. * * @param contextId an identifier of an execution context * @param stack a call stack @@ -248,8 +245,7 @@ trait ProgramExecutionSupport { ) } - /** - * Convert the runtime exception to the corresponding API error messages. + /** Convert the runtime exception to the corresponding API error messages. * * @param t the exception * @param ctx the runtime context @@ -300,8 +296,7 @@ trait ProgramExecutionSupport { } } - /** - * Create a stack trace of a guest language from a java exception. + /** Create a stack trace of a guest language from a java exception. * * @param throwable the exception * @param ctx the runtime context @@ -316,8 +311,7 @@ trait ProgramExecutionSupport { .map(toStackElement) .toVector - /** - * Convert from the truffle stack element to the runtime API representation. + /** Convert from the truffle stack element to the runtime API representation. * * @param element the trufle stack trace element * @param ctx the runtime context @@ -451,8 +445,7 @@ trait ProgramExecutionSupport { call.getFunctionName ) - /** - * Convert truffle source section to the range of text. + /** Convert truffle source section to the range of text. * * @param section the source section * @return the correponding range in the text file @@ -463,8 +456,7 @@ trait ProgramExecutionSupport { model.Position(section.getEndLine - 1, section.getEndColumn) ) - /** - * Find source file path by the module name. + /** Find source file path by the module name. * * @param module the module name * @param ctx the runtime context diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/UpsertVisualisationJob.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/UpsertVisualisationJob.scala index e7018b4773..6ce55de4f8 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/UpsertVisualisationJob.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/UpsertVisualisationJob.scala @@ -17,8 +17,7 @@ import org.enso.polyglot.runtime.Runtime.{Api, ApiResponse} import scala.util.control.NonFatal -/** - * A job that upserts a visualisation. +/** A job that upserts a visualisation. * * @param requestId maybe a request id * @param visualisationId an identifier of visualisation @@ -134,18 +133,15 @@ class UpsertVisualisationJob( object UpsertVisualisationJob { - /** - * Base trait for evaluation failures. + /** Base trait for evaluation failures. */ sealed trait EvalFailure - /** - * Signals that a module cannot be found. + /** Signals that a module cannot be found. */ case object ModuleNotFound extends EvalFailure - /** - * Signals that an evaluation of an expression failed. + /** Signals that an evaluation of an expression failed. * * @param msg the textual reason of a failure */ diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/runtime/builtin/LanguageEntitySerializer.scala b/engine/runtime/src/main/scala/org/enso/interpreter/runtime/builtin/LanguageEntitySerializer.scala index 9f002d015f..2e1ea41f98 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/runtime/builtin/LanguageEntitySerializer.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/runtime/builtin/LanguageEntitySerializer.scala @@ -4,14 +4,12 @@ import com.oracle.truffle.api.interop.InteropLibrary import io.circe.Json import org.enso.interpreter.runtime.callable.atom.{Atom, AtomConstructor} -/** - * Helper for JSON-serializing runtime entities of the language. +/** Helper for JSON-serializing runtime entities of the language. */ object LanguageEntitySerializer { private val interopLibrary: InteropLibrary = InteropLibrary.getUncached() - /** - * Serializes a language entity into a JSON string. Returns null JSON for + /** Serializes a language entity into a JSON string. Returns null JSON for * unexpected entities. * * @param obj any object representing an Enso language entity. @@ -21,7 +19,7 @@ object LanguageEntitySerializer { final def serialize(obj: Object): String = toJson(obj).noSpaces private def toJson(obj: Any): Json = obj match { - case l: Long => Json.fromLong(l) + case l: Long => Json.fromLong(l) case cons: AtomConstructor => Json.obj("type" -> Json.fromString(cons.getName), "fields" -> Json.arr()) case atom: Atom => diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/runtime/scope/LocalScope.scala b/engine/runtime/src/main/scala/org/enso/interpreter/runtime/scope/LocalScope.scala index 2260ca4ca3..f5da4629e5 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/runtime/scope/LocalScope.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/runtime/scope/LocalScope.scala @@ -123,9 +123,9 @@ class LocalScope( scope.occurrences.foreach { case x: Occurrence.Def => parentResult += x.symbol -> new FramePointer( - level, - frameSlots(x.id) - ) + level, + frameSlots(x.id) + ) case _ => } parentResult diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala index 44e1900b14..1801829c85 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala @@ -213,8 +213,7 @@ trait CompilerRunner { } } - /** - * Builds a module context with a mocked module for testing purposes. + /** Builds a module context with a mocked module for testing purposes. * * @param moduleName the name of the test module. * @param freshNameSupply the fresh name supply to use in tests. @@ -233,8 +232,7 @@ trait CompilerRunner { ) } - /** - * Builds an inline context with a mocked module for testing purposes. + /** Builds an inline context with a mocked module for testing purposes. * * @param localScope the local scope for variable resolution. * @param isInTailPosition whether the expression is being evaluated in diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala index f61211965d..00f60154e3 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala @@ -875,19 +875,17 @@ class AstToIrTest extends CompilerTest with Inside { inside(ir.bindings(1)) { case binding: IR.Module.Scope.Definition.Method.Binding => - inside(binding.body) { - case block: IR.Expression.Block => - inside(block.returnValue) { - case application: IR.Application.Prefix => - inside(application.arguments.head) { - case argument: IR.CallArgument.Specified => - inside(argument.value) { - case error: IR.Error.Syntax => - error.reason shouldBe - IR.Error.Syntax.AmbiguousExpression - } - } - } + inside(binding.body) { case block: IR.Expression.Block => + inside(block.returnValue) { + case application: IR.Application.Prefix => + inside(application.arguments.head) { + case argument: IR.CallArgument.Specified => + inside(argument.value) { case error: IR.Error.Syntax => + error.reason shouldBe + IR.Error.Syntax.AmbiguousExpression + } + } + } } } } @@ -902,9 +900,8 @@ class AstToIrTest extends CompilerTest with Inside { |""".stripMargin.toIrModule inside(ir.bindings.head) { case definition: IR.Module.Scope.Definition.Type => - inside(definition.body(2)) { - case error: IR.Error.Syntax => - error.reason shouldBe IR.Error.Syntax.UnexpectedDeclarationInType + inside(definition.body(2)) { case error: IR.Error.Syntax => + error.reason shouldBe IR.Error.Syntax.UnexpectedDeclarationInType } } } @@ -921,25 +918,21 @@ class AstToIrTest extends CompilerTest with Inside { |""".stripMargin.toIrModule inside(ir.bindings(1)) { case main: IR.Module.Scope.Definition.Method.Binding => - inside(main.body) { - case block: IR.Expression.Block => - inside(block.returnValue) { - case f: IR.Expression.Binding => - inside(f.expression) { - case app: IR.Application.Prefix => - inside(app.arguments(1)) { - case arg: IR.CallArgument.Specified => - inside(arg.value) { - case argBlock: IR.Expression.Block => - inside(argBlock.expressions.head) { - case error: IR.Error.Syntax => - error.reason shouldBe - IR.Error.Syntax.AmbiguousExpression - } - } + inside(main.body) { case block: IR.Expression.Block => + inside(block.returnValue) { case f: IR.Expression.Binding => + inside(f.expression) { case app: IR.Application.Prefix => + inside(app.arguments(1)) { + case arg: IR.CallArgument.Specified => + inside(arg.value) { case argBlock: IR.Expression.Block => + inside(argBlock.expressions.head) { + case error: IR.Error.Syntax => + error.reason shouldBe + IR.Error.Syntax.AmbiguousExpression } - } + } + } } + } } } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/MatchersTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/MatchersTest.scala index 2ab10aefbb..e0c367405a 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/MatchersTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/MatchersTest.scala @@ -18,8 +18,8 @@ class MatchersTest extends CompilerTest with Inside { def toSimpleAst: AST = { val ast = source.toAst - inside(ast) { - case Module(List1(line, _)) => line.elem.get + inside(ast) { case Module(List1(line, _)) => + line.elem.get } } } @@ -49,12 +49,10 @@ class MatchersTest extends CompilerTest with Inside { "peel-off exactly one paren" in { val twoParens = "((x))".toSimpleAst - inside(twoParens) { - case AstView.Parensed(oneParen) => - inside(oneParen) { - case AstView.Parensed(zeroParens) => - zeroParens should not be group - } + inside(twoParens) { case AstView.Parensed(oneParen) => + inside(oneParen) { case AstView.Parensed(zeroParens) => + zeroParens should not be group + } } } } @@ -70,13 +68,11 @@ class MatchersTest extends CompilerTest with Inside { "peel-off at-most one paren" in { val twoParens = "((x))".toSimpleAst - inside(twoParens) { - case AstView.MaybeParensed(oneParen) => - oneParen shouldBe group - inside(oneParen) { - case AstView.MaybeParensed(zeroParens) => - zeroParens should not be group - } + inside(twoParens) { case AstView.MaybeParensed(oneParen) => + oneParen shouldBe group + inside(oneParen) { case AstView.MaybeParensed(zeroParens) => + zeroParens should not be group + } } } } @@ -95,9 +91,8 @@ class MatchersTest extends CompilerTest with Inside { "peel-off all parens" in { val twoParens = "((x))".toSimpleAst - inside(twoParens) { - case AstView.ManyParensed(zeroParens) => - zeroParens should not be group + inside(twoParens) { case AstView.ManyParensed(zeroParens) => + zeroParens should not be group } } } @@ -113,9 +108,8 @@ class MatchersTest extends CompilerTest with Inside { "peel-off all parens" in { val twoParens = "((x))".toSimpleAst - inside(twoParens) { - case AstView.MaybeManyParensed(zeroParens) => - zeroParens.shape should not be group + inside(twoParens) { case AstView.MaybeManyParensed(zeroParens) => + zeroParens.shape should not be group } } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/core/CoreTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/core/CoreTest.scala index f1ee7d1e93..1e758b4d5b 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/core/CoreTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/core/CoreTest.scala @@ -200,7 +200,10 @@ class CoreTest extends CompilerTest { "be able to contain complex structures" in { val bindingRef = - Utility.ListOps.at(list, 0).getOrElse(fail()).unsafeAs[NodeShape.Binding] + Utility.ListOps + .at(list, 0) + .getOrElse(fail()) + .unsafeAs[NodeShape.Binding] bindingRef shouldEqual myBinding diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/core/SmartConstructorsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/core/SmartConstructorsTest.scala index 0f2b2f3a4b..7ad7de4005 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/core/SmartConstructorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/core/SmartConstructorsTest.scala @@ -1236,7 +1236,9 @@ class SmartConstructorsTest extends CompilerTest { Node.New.ForeignCodeLiteral("lambda x: x + 1", dummyLocation) val foreignDefinition = - Node.New.ForeignDefinition(language, code, dummyLocation).getOrElse(fail()) + Node.New + .ForeignDefinition(language, code, dummyLocation) + .getOrElse(fail()) "have valid fields" in { foreignDefinition.location shouldEqual dummyLocation diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/core/ir/DiagnosticStorageTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/core/ir/DiagnosticStorageTest.scala index 3c3f535f04..630003a240 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/core/ir/DiagnosticStorageTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/core/ir/DiagnosticStorageTest.scala @@ -92,8 +92,8 @@ class DiagnosticStorageTest extends CompilerTest { ) ) - diagnostics.collect { - case e: IR.Error.Syntax => e + diagnostics.collect { case e: IR.Error.Syntax => + e } shouldEqual Seq(err) } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/PassConfigurationTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/PassConfigurationTest.scala index c868c8c79f..aba6e13000 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/PassConfigurationTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/PassConfigurationTest.scala @@ -15,7 +15,7 @@ class PassConfigurationTest extends CompilerTest { override type Metadata = IRPass.Metadata.Empty override type Config = Configuration1 - override val precursorPasses: Seq[IRPass] = List() + override val precursorPasses: Seq[IRPass] = List() override val invalidatedPasses: Seq[IRPass] = List() override def runModule( @@ -37,7 +37,7 @@ class PassConfigurationTest extends CompilerTest { override type Metadata = IRPass.Metadata.Empty override type Config = Configuration2 - override val precursorPasses: Seq[IRPass] = List() + override val precursorPasses: Seq[IRPass] = List() override val invalidatedPasses: Seq[IRPass] = List() override def runModule( @@ -61,9 +61,9 @@ class PassConfigurationTest extends CompilerTest { "allow adding configuration pairs" in { val config = PassConfiguration() - val pass = TestPass1 + val pass = TestPass1 val passConfig = TestPass1.Configuration1() - val depPair = pass -->> passConfig + val depPair = pass -->> passConfig config.update(depPair) config.get(pass) shouldEqual Some(passConfig) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/FunctionBindingTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/FunctionBindingTest.scala index 11da39cf91..966d47c5b7 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/FunctionBindingTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/FunctionBindingTest.scala @@ -13,7 +13,7 @@ class FunctionBindingTest extends CompilerTest { val passes = new Passes - val precursorPasses: PassGroup = passes.getPrecursors(FunctionBinding).get + val precursorPasses: PassGroup = passes.getPrecursors(FunctionBinding).get val passConfig: PassConfiguration = PassConfiguration() implicit val passManager: PassManager = diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/lint/UnusedBindingsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/lint/UnusedBindingsTest.scala index ebbf159b0e..d376e93cd7 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/lint/UnusedBindingsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/lint/UnusedBindingsTest.scala @@ -116,15 +116,14 @@ class UnusedBindingsTest extends CompilerTest with Inside { inside(ir.bindings.head) { case definition: IR.Module.Scope.Definition.Method.Explicit => - inside(definition.body) { - case f: IR.Function.Lambda => - val lintMeta = f.arguments(1).diagnostics.collect { - case u: IR.Warning.Unused.FunctionArgument => u - } + inside(definition.body) { case f: IR.Function.Lambda => + val lintMeta = f.arguments(1).diagnostics.collect { + case u: IR.Warning.Unused.FunctionArgument => u + } - lintMeta should not be empty - lintMeta.head shouldBe an[IR.Warning.Unused.FunctionArgument] - lintMeta.head.name.name shouldEqual "x" + lintMeta should not be empty + lintMeta.head shouldBe an[IR.Warning.Unused.FunctionArgument] + lintMeta.head.name.name shouldEqual "x" } } } @@ -154,8 +153,8 @@ class UnusedBindingsTest extends CompilerTest with Inside { |""".stripMargin.preprocessExpression.get.lint .asInstanceOf[IR.Expression.Binding] - val lintMeta = ir.diagnostics.collect { - case u: IR.Warning.Unused => u + val lintMeta = ir.diagnostics.collect { case u: IR.Warning.Unused => + u } lintMeta should not be empty @@ -172,8 +171,8 @@ class UnusedBindingsTest extends CompilerTest with Inside { |""".stripMargin.preprocessExpression.get.lint .asInstanceOf[IR.Expression.Binding] - val lintMeta = ir.diagnostics.collect { - case u: IR.Warning.Unused => u + val lintMeta = ir.diagnostics.collect { case u: IR.Warning.Unused => + u } lintMeta shouldBe empty @@ -195,11 +194,11 @@ class UnusedBindingsTest extends CompilerTest with Inside { val field1 = pattern.fields.head.asInstanceOf[Pattern.Name] val field2 = pattern.fields(1).asInstanceOf[Pattern.Name] - val lintMeta1 = field1.diagnostics.collect { - case u: IR.Warning.Unused => u + val lintMeta1 = field1.diagnostics.collect { case u: IR.Warning.Unused => + u } - val lintMeta2 = field2.diagnostics.collect { - case u: IR.Warning.Unused => u + val lintMeta2 = field2.diagnostics.collect { case u: IR.Warning.Unused => + u } lintMeta1 should not be empty diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/LambdaConsolidateTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/LambdaConsolidateTest.scala index 0307df2668..4f37260222 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/LambdaConsolidateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/optimise/LambdaConsolidateTest.scala @@ -201,12 +201,16 @@ class LambdaConsolidateTest extends CompilerTest { "work properly with arguments defaulted to lambdas" in { implicit val inlineContext: InlineContext = mkContext val ir = """ - |x -> (y = x->y->z) -> y x - |""".stripMargin.preprocessExpression.get.optimise.asInstanceOf[IR.Function.Lambda] + |x -> (y = x->y->z) -> y x + |""".stripMargin.preprocessExpression.get.optimise + .asInstanceOf[IR.Function.Lambda] ir.arguments.length shouldEqual 2 val defaultExpr = ir.arguments(1).defaultValue.get defaultExpr shouldBe a[IR.Function.Lambda] - defaultExpr.asInstanceOf[IR.Function.Lambda].arguments.length shouldEqual 2 + defaultExpr + .asInstanceOf[IR.Function.Lambda] + .arguments + .length shouldEqual 2 } "collapse lambdas with multiple parameters" in { diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/AnnotationsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/AnnotationsTest.scala index 685fbb5d45..3a0ed3d2e9 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/AnnotationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/AnnotationsTest.scala @@ -86,15 +86,16 @@ class AnnotationsTest extends CompilerTest { .asInstanceOf[IR.Error.Resolution] .reason shouldEqual IR.Error.Resolution.UnexpectedTailCallAnnotation - val correct = items - .returnValue + val correct = items.returnValue .asInstanceOf[IR.Application.Prefix] .arguments(0) .value .asInstanceOf[IR.Application.Prefix] correct.function.asInstanceOf[IR.Name].name shouldEqual "bar" correct.arguments.length shouldEqual 1 - correct.getMetadata(Annotations) should contain(Annotations.TailCallAnnotated) + correct.getMetadata(Annotations) should contain( + Annotations.TailCallAnnotated + ) } } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala index 82814b5877..76982e06c4 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala @@ -65,8 +65,7 @@ class DocumentationCommentsTest extends CompilerTest with Inside { buildInlineContext() } - /** - * Gets documentation metadata from a node. + /** Gets documentation metadata from a node. * Throws an exception if missing. * * @param ir the ir to get the doc from. @@ -254,29 +253,24 @@ class DocumentationCommentsTest extends CompilerTest with Inside { inside(ir.bindings(1)) { case method: IR.Module.Scope.Definition.Method.Explicit => getDoc(method) shouldEqual " a method" - inside(method.body) { - case lambda: IR.Function.Lambda => - inside(lambda.body) { - case block: IR.Expression.Block => - getDoc(block.expressions(0)) shouldEqual " a statement" - getDoc(block.returnValue) shouldEqual " the return" - } + inside(method.body) { case lambda: IR.Function.Lambda => + inside(lambda.body) { case block: IR.Expression.Block => + getDoc(block.expressions(0)) shouldEqual " a statement" + getDoc(block.returnValue) shouldEqual " the return" + } } } inside(ir.bindings(2)) { case method: IR.Module.Scope.Definition.Method.Explicit => - inside(method.body) { - case lambda: IR.Function.Lambda => - inside(lambda.body) { - case block: IR.Expression.Block => - inside(block.returnValue) { - case caseExpr: IR.Case.Expr => - caseExpr.branches should have length 2 - getDoc(caseExpr.branches(0)) shouldEqual " case 1" - getDoc(caseExpr.branches(1)) shouldEqual " catchall" - } + inside(method.body) { case lambda: IR.Function.Lambda => + inside(lambda.body) { case block: IR.Expression.Block => + inside(block.returnValue) { case caseExpr: IR.Case.Expr => + caseExpr.branches should have length 2 + getDoc(caseExpr.branches(0)) shouldEqual " case 1" + getDoc(caseExpr.branches(1)) shouldEqual " catchall" } + } } } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/UppercaseNamesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/UppercaseNamesTest.scala index bacc86f963..6b99b9552b 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/UppercaseNamesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/UppercaseNamesTest.scala @@ -3,7 +3,12 @@ package org.enso.compiler.test.pass.resolve import org.enso.compiler.Passes import org.enso.compiler.context.{FreshNameSupply, ModuleContext} import org.enso.compiler.core.IR -import org.enso.compiler.data.BindingsMap.{Cons, Resolution, ResolvedConstructor, ResolvedModule} +import org.enso.compiler.data.BindingsMap.{ + Cons, + Resolution, + ResolvedConstructor, + ResolvedModule +} import org.enso.compiler.pass.resolve.UppercaseNames import org.enso.compiler.pass.{PassConfiguration, PassGroup, PassManager} import org.enso.compiler.phase.ExportsResolution @@ -21,7 +26,9 @@ class UppercaseNamesTest extends CompilerTest { val passes = new Passes val group1 = passes.moduleDiscoveryPasses - val group2 = new PassGroup(passes.functionBodyPasses.passes.takeWhile(_ != UppercaseNames)) + val group2 = new PassGroup( + passes.functionBodyPasses.passes.takeWhile(_ != UppercaseNames) + ) val passConfiguration: PassConfiguration = PassConfiguration() @@ -49,7 +56,7 @@ class UppercaseNamesTest extends CompilerTest { "Method definition resolution" should { implicit val ctx: ModuleContext = mkModuleContext - val code = """ + val code = """ |main = | x1 = My_Cons 1 2 3 | x2 = Constant @@ -65,12 +72,12 @@ class UppercaseNamesTest extends CompilerTest { |add_one x = x + 1 | |""".stripMargin - val parsed = code.toIrModule + val parsed = code.toIrModule val moduleMapped = passManager.runPassesOnModule(parsed, ctx, group1) ctx.module.unsafeSetIr(moduleMapped) new ExportsResolution().run(List(ctx.module)) val allPrecursors = passManager.runPassesOnModule(moduleMapped, ctx, group2) - val ir = allPrecursors.analyse + val ir = allPrecursors.analyse val bodyExprs = ir .bindings(0) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/Metadata.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/Metadata.scala index 6730dbd586..fb3c3db791 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/Metadata.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/Metadata.scala @@ -7,15 +7,13 @@ private case class Item(start: Int, len: Int, id: UUID) { s"""[{"index": {"value": $start}, "size": {"value": $len}}, "$id"]""" } -/** - * A helper class for decorating source code with expression IDs. +/** A helper class for decorating source code with expression IDs. */ class Metadata { private var items: List[Item] = List() - /** - * Adds another entry to this metadata container. + /** Adds another entry to this metadata container. * * @param start the start position of the entry. * @param len the length of the entry. @@ -30,8 +28,7 @@ class Metadata { private def toJsonString: String = "[" + items.map(_.toJsonString).mkString(",") + "]" - /** - * Appends a serialized version of this at the end of a source code string. + /** Appends a serialized version of this at the end of a source code string. * * @param code the code to append metadata to. * @return the code decorated with this metadata. diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala index 04b7fa258a..b8ce1814fe 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala @@ -9,7 +9,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers trait PackageTest extends AnyFlatSpec with Matchers with ValueEquality { - val output = new ByteArrayOutputStream() + val output = new ByteArrayOutputStream() def evalTestProject(name: String): Value = { val pkgPath = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala index ac25d7ac49..918b8709d2 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CaseTest.scala @@ -1,16 +1,16 @@ package org.enso.interpreter.test.semantic import org.enso.interpreter.test.{ - InterpreterTest, InterpreterContext, - InterpreterException + InterpreterException, + InterpreterTest } class CaseTest extends InterpreterTest { override def subject = "Case expressions" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "result in an error if the matched constructor isn't visible" in { val code = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala index 4d33bde9b7..04077023ee 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CodeLocationsTest.scala @@ -16,8 +16,8 @@ class CodeLocationsTest extends InterpreterTest { var off = 0 code.linesIterator.toList.foreach { line => val chars: List[Any] = line.toList.map { c => - s" ${if (c == ' ') '_' else c} " - } :+ '↵' + s" ${if (c == ' ') '_' else c} " + } :+ '↵' val ixes = off.until(off + chars.length).map { i => if (i.toString.length == 1) s" $i " else s"$i " } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CommentsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CommentsTest.scala index 3248e83492..6b60afe34e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CommentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CommentsTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class CommentsTest extends InterpreterTest { override def subject: String = "All Comments" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "be ignored in execution" in { val code = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala index 869d69db6e..5fbecac40e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CompileDiagnosticsTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class CompileDiagnosticsTest extends InterpreterTest { override def subject: String = "Compile Error Reporting" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "surface ast-processing errors in the language" in { val code = @@ -18,7 +18,9 @@ class CompileDiagnosticsTest extends InterpreterTest { | case err of | Syntax_Error msg -> "Oopsie, it's a syntax error: " + msg |""".stripMargin - eval(code) shouldEqual "Oopsie, it's a syntax error: Parentheses can't be empty." + eval( + code + ) shouldEqual "Oopsie, it's a syntax error: Parentheses can't be empty." } "surface parsing errors in the language" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala index e60f1f83c9..fda08cdeb9 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ComplexTypeDefinitionSugarTest.scala @@ -1,13 +1,13 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class ComplexTypeDefinitionSugarTest extends InterpreterTest { override def subject: String = "Complex type definitions" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "work properly with simple method definitions" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala index 228bd8ce81..91696b4239 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConstructorsTest.scala @@ -1,17 +1,17 @@ package org.enso.interpreter.test.semantic import org.enso.interpreter.test.{ - InterpreterTest, InterpreterContext, - InterpreterException + InterpreterException, + InterpreterTest } class ConstructorsTest extends InterpreterTest { override def subject: String = "Constructors & Pattern Matching" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "dispatch to the proper match branch" in { val patternMatchingCode = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala index 41d27b9bea..42ace8f775 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/CurryingTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class CurryingTest extends InterpreterTest { override def subject: String = "Functions" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "allow partial application" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala index af1d959a73..2b47dfcfec 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/EvalTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class EvalTest extends InterpreterTest { override def subject: String = "Debug.eval" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "evaluate a string expression" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala index fbff542063..ec5f76f13b 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ExpressionIdTest.scala @@ -1,16 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{ - InterpreterTest, - InterpreterContext, - Metadata -} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest, Metadata} class ExpressionIdTest extends InterpreterTest { override def subject: String = "Expression IDs" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "be correct in simple arithmetic expressions" in withIdsInstrumenter { instrumenter => diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala index 8f4b780361..7f8031fe47 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/FunctionSugarTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class FunctionSugarTest extends InterpreterTest { override def subject: String = "Function Definition Sugar" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "work for local functions" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala index 7a288f4a6a..8ded5a8775 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GlobalScopeTest.scala @@ -1,13 +1,13 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class GlobalScopeTest extends InterpreterTest { override def subject: String = "Functions" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "use values from the global scope in their bodies" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala index 46d62bb947..193d763ebf 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/GroupingTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class GroupingTest extends InterpreterTest { override def subject: String = "Parentheses" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "work with arbitrary lambdas" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala index 789fe10eb6..7f8f7769b6 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/JavaInteropTest.scala @@ -1,13 +1,13 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class JavaInteropTest extends InterpreterTest { override def subject: String = "Java Interop" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "allow importing classes and calling methods on them" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala index cdde6aea7f..6bba9bf2d1 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaChainingTest.scala @@ -1,13 +1,13 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class LambdaChainingTest extends InterpreterTest { override def subject: String = "Chains of Lambdas" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "evaluate as expected" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala index 2529bdd2c3..33c3ea7fe1 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaShorthandArgsTest.scala @@ -1,13 +1,13 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class LambdaShorthandArgsTest extends InterpreterTest { override def subject = "Lambda shorthand arguments" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "work for simple applications" in { val code = diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala index c49e3332d5..c7bac03540 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/LambdaTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class LambdaTest extends InterpreterTest { override def subject: String = "Lambdas" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "take arguments and use them in their bodies" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala index 304190cf1c..c56c74a67e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class MixfixFunctionsTest extends InterpreterTest { override def subject = "Mixfix Functions" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "be able to be defined as a method" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala index baca6421cb..ecd1f419c7 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/NamedArgumentsTest.scala @@ -1,16 +1,16 @@ package org.enso.interpreter.test.semantic import org.enso.interpreter.test.{ - InterpreterTest, InterpreterContext, - InterpreterException + InterpreterException, + InterpreterTest } class NamedArgumentsTest extends InterpreterTest { override def subject: String = "Named and Default Arguments" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "be used in function bodies" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OperatorSectionsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OperatorSectionsTest.scala index eb994fc6a7..5639f4581d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OperatorSectionsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OperatorSectionsTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class OperatorSectionsTest extends InterpreterTest { override def subject: String = "Operator Sections" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "work when left" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala index 65f4d18d61..74843179dc 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/OverloadsResolutionErrorTest.scala @@ -1,9 +1,9 @@ package org.enso.interpreter.test.semantic import org.enso.interpreter.test.{ - InterpreterTest, InterpreterContext, - InterpreterException + InterpreterException, + InterpreterTest } import org.enso.polyglot.RuntimeOptions import org.graalvm.polyglot.Context @@ -14,8 +14,8 @@ class OverloadsResolutionErrorTest extends InterpreterTest { override def contextModifiers: Context#Builder => Context#Builder = _.option(RuntimeOptions.STRICT_ERRORS, "true") - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "result in an error at runtime for methods" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala index ab17ee53c1..dbf638e9e3 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PatternMatchTest.scala @@ -1,17 +1,17 @@ package org.enso.interpreter.test.semantic import org.enso.interpreter.test.{ - InterpreterTest, InterpreterContext, - InterpreterException + InterpreterException, + InterpreterTest } class PatternMatchTest extends InterpreterTest { override def subject = "Pattern Matching" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "work for simple patterns" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala index bd202ff50f..5df4e34ad2 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/PolyglotTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class PolyglotTest extends InterpreterTest { override def subject: String = "Polyglot" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "allow calling methods on static objects" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala index d221891999..85914f1e9d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/RuntimeManagementTest.scala @@ -62,8 +62,7 @@ class RuntimeManagementTest extends InterpreterTest { runTest() } - /** - * Don't use this in production code, ever. + /** Don't use this in production code, ever. */ def forceGC(): Unit = { var obj = new Object diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SimpleArithmeticTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SimpleArithmeticTest.scala index 74c0803b55..942f9ed01f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SimpleArithmeticTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SimpleArithmeticTest.scala @@ -1,13 +1,13 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class SimpleArithmeticTest extends InterpreterTest { override def subject: String = "Arithmetic" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "1 = 1" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala index 480a407b22..2c646c10c8 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StateTest.scala @@ -1,12 +1,12 @@ package org.enso.interpreter.test.semantic -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class StateTest extends InterpreterTest { override def subject: String = "State" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "be accessible from functions" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StrictCompileDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StrictCompileDiagnosticsTest.scala index fc12fd6b4b..80ce3a696f 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StrictCompileDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/StrictCompileDiagnosticsTest.scala @@ -1,9 +1,9 @@ package org.enso.interpreter.test.semantic import org.enso.interpreter.test.{ - InterpreterTest, InterpreterContext, - InterpreterException + InterpreterException, + InterpreterTest } import org.enso.polyglot.RuntimeOptions import org.graalvm.polyglot.Context @@ -14,8 +14,8 @@ class StrictCompileDiagnosticsTest extends InterpreterTest { override def contextModifiers: Context#Builder => Context#Builder = _.option(RuntimeOptions.STRICT_ERRORS, "true") - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "be reported and abort execution" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala index 123926170e..2bc6d9f3c2 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/SuspendedArgumentsTest.scala @@ -5,8 +5,8 @@ import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class SuspendedArgumentsTest extends InterpreterTest { override def subject = "Suspended arguments" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "work in basic expressions" in { diff --git a/engine/runtime/src/test/scala/org/enso/std/test/JsonSerializationTest.scala b/engine/runtime/src/test/scala/org/enso/std/test/JsonSerializationTest.scala index 47ba965210..a416e494f0 100644 --- a/engine/runtime/src/test/scala/org/enso/std/test/JsonSerializationTest.scala +++ b/engine/runtime/src/test/scala/org/enso/std/test/JsonSerializationTest.scala @@ -1,13 +1,13 @@ package org.enso.std.test -import org.enso.interpreter.test.{InterpreterTest, InterpreterContext} +import org.enso.interpreter.test.{InterpreterContext, InterpreterTest} class JsonSerializationTest extends InterpreterTest { override def subject = "Automatic JSON serialization" - override def specify( - implicit interpreterContext: InterpreterContext + override def specify(implicit + interpreterContext: InterpreterContext ): Unit = { "support strings" in { @@ -34,7 +34,9 @@ class JsonSerializationTest extends InterpreterTest { | |main = X 123 "foo" Unit . json_serialize |""".stripMargin - eval(code) shouldEqual """{"type":"X","fields":[123,"foo",{"type":"Unit","fields":[]}]}""" + eval( + code + ) shouldEqual """{"type":"X","fields":[123,"foo",{"type":"Unit","fields":[]}]}""" } "support functions" in { diff --git a/lib/scala/akka-native/src/main/java/org/enso/nativeimage/workarounds/ReplacementStatics.java b/lib/scala/akka-native/src/main/java/org/enso/nativeimage/workarounds/ReplacementStatics.java index 3eff193d60..f5931604d0 100644 --- a/lib/scala/akka-native/src/main/java/org/enso/nativeimage/workarounds/ReplacementStatics.java +++ b/lib/scala/akka-native/src/main/java/org/enso/nativeimage/workarounds/ReplacementStatics.java @@ -14,12 +14,11 @@ final class ReplacementStatics { /** * Implements a "release fence" without using an unsupported {@link java.lang.invoke.MethodHandle} * like the original one. - *

- * Instead, uses {@link sun.misc.Unsafe#storeFence()} under the hood. + * + *

Instead, uses {@link sun.misc.Unsafe#storeFence()} under the hood. */ @Substitute public static void releaseFence() { Unsafe.unsafeInstance().storeFence(); } } - diff --git a/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/native-image.properties b/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/native-image.properties index 98d306764b..05864c2bff 100644 --- a/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/native-image.properties +++ b/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/native-image.properties @@ -1 +1 @@ -Args = -H:ReflectionConfigurationResources=${.}/reflect-config.json +Args=-H:ReflectionConfigurationResources=${.}/reflect-config.json diff --git a/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/reflect-config.json b/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/reflect-config.json index ac6fd61788..9f3f7f59d1 100644 --- a/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/reflect-config.json +++ b/lib/scala/akka-native/src/main/resources/META-INF/native-image/com.typesafe.akka/akka-actor/reflect-config.json @@ -1 +1,5 @@ -[{ "name": "[B" }] +[ + { + "name": "[B" + } +] diff --git a/lib/scala/akka-native/src/main/scala/org/enso/nativeimage/workarounds/Unsafe.scala b/lib/scala/akka-native/src/main/scala/org/enso/nativeimage/workarounds/Unsafe.scala index b1208cc3db..622d304095 100755 --- a/lib/scala/akka-native/src/main/scala/org/enso/nativeimage/workarounds/Unsafe.scala +++ b/lib/scala/akka-native/src/main/scala/org/enso/nativeimage/workarounds/Unsafe.scala @@ -1,7 +1,6 @@ package org.enso.nativeimage.workarounds -/** - * Gives access to an instance of [[sun.misc.Unsafe]] which contains low-level +/** Gives access to an instance of [[sun.misc.Unsafe]] which contains low-level * functions that are used to replace the ones that cause problems in the * Native Image build. * @@ -10,8 +9,7 @@ package org.enso.nativeimage.workarounds */ object Unsafe { - /** - * Instance of the [[sun.misc.Unsafe]] acquired using reflection that allows + /** Instance of the [[sun.misc.Unsafe]] acquired using reflection that allows * to run the unsafe functions needed by the workaround. */ val unsafeInstance: sun.misc.Unsafe = { diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/CLIOutput.scala b/lib/scala/cli/src/main/scala/org/enso/cli/CLIOutput.scala index c3b00149e6..418a55fad5 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/CLIOutput.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/CLIOutput.scala @@ -6,8 +6,7 @@ object CLIOutput { val terminalWidth: Int = 80 val minimumColumnWrapWidth: Int = 50 - /** - * Aligns tables and wraps all text to [[terminalWidth]] (with some + /** Aligns tables and wraps all text to [[terminalWidth]] (with some * exceptions). * * A table is a continuous sequence of lines containing the `\t` character. @@ -32,21 +31,20 @@ object CLIOutput { val lines = splitLinesPreservingTrailing(text) val entities = CLIOutputInternal.groupTables(lines) val wrapped: Seq[String] = entities flatMap { - case CLIOutputInternal.TextLine(line) => - CLIOutputInternal.wrapLine(line, terminalWidth).toList - case CLIOutputInternal.TextTable(rows) => - CLIOutputInternal.alignAndWrapTable( - rows, - terminalWidth, - minimumColumnWrapWidth, - minimumTableWidth = minTableWidth.getOrElse(2) - ) - } + case CLIOutputInternal.TextLine(line) => + CLIOutputInternal.wrapLine(line, terminalWidth).toList + case CLIOutputInternal.TextTable(rows) => + CLIOutputInternal.alignAndWrapTable( + rows, + terminalWidth, + minimumColumnWrapWidth, + minimumTableWidth = minTableWidth.getOrElse(2) + ) + } joinLines(wrapped) } - /** - * Prints the provided text to stdout, first aligning and wrapping it as + /** Prints the provided text to stdout, first aligning and wrapping it as * described in [[alignAndWrap]]. */ def println(text: String): Unit = { @@ -61,8 +59,7 @@ object CLIOutput { ) } - /** - * Prints out the given question and asks the user to confirm the action by + /** Prints out the given question and asks the user to confirm the action by * typing 'y' or 'n'. * * Also handles uppercase variants. An empty line defaults to the default @@ -90,26 +87,22 @@ object CLIOutput { } } - /** - * A type for [[askQuestion]] which specifies how to display the possible + /** A type for [[askQuestion]] which specifies how to display the possible * answers. */ trait Answer { - /** - * The key that is associated with this answer. Should be a single + /** The key that is associated with this answer. Should be a single * character. */ def key: String - /** - * A short description of this answer. + /** A short description of this answer. */ def description: String } - /** - * Asks the user to choose one of the possible answers. + /** Asks the user to choose one of the possible answers. * * The first answer in the provided sequence is treated as the default and it * is returned if the user inputs an empty line. If the user inputs a @@ -144,13 +137,11 @@ object CLIOutput { } } - /** - * Default indentation used for printing lists. + /** Default indentation used for printing lists. */ val indent: String = " " - /** - * Splits the text into lines, preserving trailing newlines by adding empty + /** Splits the text into lines, preserving trailing newlines by adding empty * lines. */ private def splitLinesPreservingTrailing(string: String): Seq[String] = { diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/ProgressBar.scala b/lib/scala/cli/src/main/scala/org/enso/cli/ProgressBar.scala index 5301ee8e28..bb3530c374 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/ProgressBar.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/ProgressBar.scala @@ -4,13 +4,11 @@ import java.util.concurrent.LinkedTransferQueue import scala.util.Try -/** - * Allows to display a progress bar in a terminal. +/** Allows to display a progress bar in a terminal. */ object ProgressBar { - /** - * Displays a progressbar tracking progress of the provided task and waits + /** Displays a progressbar tracking progress of the provided task and waits * for its completion. * * The progress bar is displayed as long as the task is in progress. The diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/Spelling.scala b/lib/scala/cli/src/main/scala/org/enso/cli/Spelling.scala index 670f3e9e20..6c4d3fa7d9 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/Spelling.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/Spelling.scala @@ -4,8 +4,7 @@ import org.enso.cli.internal.NeedlemanWunsch object Spelling { - /** - * Selects closest matches to a potentially mistyped name. + /** Selects closest matches to a potentially mistyped name. * * @param typo the unknown name that the user typed * @param possibleWords a sequence of words that were expected @@ -17,8 +16,7 @@ object Spelling { ): Seq[String] = selectClosestMatchesWithMetadata(typo, possibleWords.map((_, ()))).map(_._1) - /** - * Selects closest matches to a potentially mistyped name, returning not only + /** Selects closest matches to a potentially mistyped name, returning not only * the matches but any metadata that was passed with them. May be useful for * including additional text in the match suggestions. * @@ -48,14 +46,12 @@ object Spelling { top.map(_._2) } - /** - * A threshold for the Needleman-Wunsch similarity score. Any matches above + /** A threshold for the Needleman-Wunsch similarity score. Any matches above * that threshold are not considered. */ private val maxScoreThreshold: Double = 10.0 - /** - * The limit of how many suggestions should be displayed at most. + /** The limit of how many suggestions should be displayed at most. */ private val topSuggestionsLimit = 3 } diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/TaskProgress.scala b/lib/scala/cli/src/main/scala/org/enso/cli/TaskProgress.scala index 7caf50d3b6..5bbdb2d930 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/TaskProgress.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/TaskProgress.scala @@ -4,21 +4,18 @@ import java.util.concurrent.LinkedTransferQueue import scala.util.{Failure, Try} -/** - * Clients can implement this trait to get progress updates. +/** Clients can implement this trait to get progress updates. */ trait ProgressListener[A] { def progressUpdate(done: Long, total: Option[Long]): Unit def done(result: Try[A]): Unit } -/** - * Represents a long-running background task. +/** Represents a long-running background task. */ trait TaskProgress[A] { - /** - * Adds a progress listener to this task. + /** Adds a progress listener to this task. * * Even if the task is already finished, the [[ProgressListener.done]] * method should be fired with the result. This way, `done` is fired @@ -27,8 +24,7 @@ trait TaskProgress[A] { */ def addProgressListener(listener: ProgressListener[A]): Unit - /** - * Blocks and waits for the completion of the task. + /** Blocks and waits for the completion of the task. * * Optionally displays a progress bar in the terminal. Returns a [[Try]] * value that wraps the result. @@ -39,8 +35,7 @@ trait TaskProgress[A] { if (showProgress) ProgressBar.waitWithProgress(this) else TaskProgress.waitForTask(this) - /** - * Alters the task by transforming its result with a function `f` that may + /** Alters the task by transforming its result with a function `f` that may * fail. * * The progress of applying `f` is not monitored - it is meant for functions @@ -54,8 +49,7 @@ trait TaskProgress[A] { def flatMap[B](f: A => Try[B]): TaskProgress[B] = new MappedTask(this, f) - /** - * Alters the task by transforming its result with a function `f`. + /** Alters the task by transforming its result with a function `f`. * * The progress of applying `f` is not monitored - it is meant for functions * that do not take a very long time in comparison with the base task. @@ -73,8 +67,7 @@ trait TaskProgress[A] { object TaskProgress { - /** - * Creates a task that fails immediately. + /** Creates a task that fails immediately. * * Useful for reporting early errors (before a background thread has even * been started for the task). @@ -91,8 +84,7 @@ object TaskProgress { } } - /** - * Blocks and waits for the task to complete. + /** Blocks and waits for the task to complete. */ def waitForTask[A](task: TaskProgress[A]): Try[A] = { val queue = new LinkedTransferQueue[Try[A]]() @@ -106,8 +98,7 @@ object TaskProgress { } } -/** - * Transforms the result of the `source` task with `f`. +/** Transforms the result of the `source` task with `f`. * * Used internally by [[TaskProgress.flatMap]]. */ @@ -124,8 +115,7 @@ private class MappedTask[A, B](source: TaskProgress[A], f: A => Try[B]) }) } -/** - * A simple implementation of [[TaskProgress]] that can be used to report +/** A simple implementation of [[TaskProgress]] that can be used to report * progress updates and mark completion of a task. */ class TaskProgressImplementation[A] extends TaskProgress[A] { @@ -146,8 +136,7 @@ class TaskProgressImplementation[A] extends TaskProgress[A] { } } - /** - * Marks the completion of this task. + /** Marks the completion of this task. * * All registered listeners are immediately notified. Any listeners added * later will also be notified as soon as they are added. @@ -168,8 +157,7 @@ class TaskProgressImplementation[A] extends TaskProgress[A] { } } - /** - * Report a progress update to all registered listeners. + /** Report a progress update to all registered listeners. * * This operation is not synchronized, as it is not a problem if a just added * listener does not get the latest progress update. diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Application.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Application.scala index 0e5021564c..f6cedfa79a 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Application.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Application.scala @@ -4,8 +4,7 @@ import cats.data.NonEmptyList import org.enso.cli.internal.Parser import org.enso.cli.internal.opts.TopLevelCommandsOpt -/** - * Represents a CLI application with multiple commands. +/** Represents a CLI application with multiple commands. * * The top-level options can be used to parse global configuration that is * passed to all commands. It can also be used to override behavior (to execute @@ -58,15 +57,13 @@ class Application[Config]( helpHeader ) - /** - * A helper overload that accepts the array as provided to the main function. + /** A helper overload that accepts the array as provided to the main function. */ def run( args: Array[String] ): Either[List[String], Int] = run(args.toSeq) - /** - * Runs the application logic. Parses the top level options and depending on + /** Runs the application logic. Parses the top level options and depending on * its result, possibly runs a command or a plugin. * * If a plugin is run, this function does not return (the application exits @@ -109,8 +106,7 @@ class Application[Config]( finalResult.toErrorList } - /** - * Generates a help text summarizing the usage of the application and listing + /** Generates a help text summarizing the usage of the application and listing * available commands and top-level options. */ def renderHelp(): String = combinedOpts.topLevelHelp(Seq(commandName)) @@ -118,8 +114,7 @@ class Application[Config]( object Application { - /** - * Helper constructor for [[Application]]. + /** Helper constructor for [[Application]]. * * @param commandName default name of the application for use in commands * @param prettyName pretty name of the application for use in text @@ -150,8 +145,7 @@ object Application { Some(pluginManager) ) - /** - * Helper constructor for [[Application]]. + /** Helper constructor for [[Application]]. * * Creates an application without plugin support. * @@ -181,8 +175,7 @@ object Application { None ) - /** - * Helper constructor for [[Application]]. + /** Helper constructor for [[Application]]. * * Creates an application without any top-level options and without plugin * support. diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Argument.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Argument.scala index ffab6ea524..58b0221d22 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Argument.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Argument.scala @@ -5,13 +5,11 @@ import java.util.UUID import cats.implicits._ -/** - * A typeclass which defines logic of parsing a String into a value of type A. +/** A typeclass which defines logic of parsing a String into a value of type A. */ trait Argument[A] { - /** - * Tries to convert the given string into a value of type A. + /** Tries to convert the given string into a value of type A. */ def read(string: String): Either[OptsParseError, A] } @@ -19,14 +17,12 @@ trait Argument[A] { object Argument { def apply[A](implicit argument: Argument[A]): Argument[A] = argument - /** - * [[Argument]] instance that just returns the provided [[String]]. + /** [[Argument]] instance that just returns the provided [[String]]. */ implicit val argumentString: Argument[String] = (string: String) => string.asRight - /** - * [[Argument]] instance that tries to treat the String as an [[Int]]. + /** [[Argument]] instance that tries to treat the String as an [[Int]]. */ implicit val argumentInteger: Argument[Int] = (string: String) => @@ -37,8 +33,7 @@ object Argument { OptsParseError.left(s"Invalid number `$string`") } - /** - * [[Argument]] instance that tries to parse the String as a [[Path]]. + /** [[Argument]] instance that tries to parse the String as a [[Path]]. */ implicit val argumentPath: Argument[Path] = (string: String) => @@ -51,8 +46,7 @@ object Argument { ) } - /** - * [[Argument]] instance that tries to parse the String as a [[UUID]]. + /** [[Argument]] instance that tries to parse the String as a [[UUID]]. */ implicit val argumentUUID: Argument[UUID] = (string: String) => try { UUID.fromString(string).asRight } diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Command.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Command.scala index 63754e3a37..3b7bdfcfab 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Command.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Command.scala @@ -1,7 +1,6 @@ package org.enso.cli.arguments -/** - * Represents a top-level command in the CLI. +/** Represents a top-level command in the CLI. * * @param name name of the command * @param comment a help comment displayed in the commands help text @@ -17,8 +16,7 @@ case class Command[A]( related: Seq[String] ) { - /** - * Returns a top-level help entry for the application help text. It includes + /** Returns a top-level help entry for the application help text. It includes * a short description of the command. */ def topLevelHelp: CommandHelp = CommandHelp(name, comment) @@ -26,8 +24,7 @@ case class Command[A]( object Command { - /** - * Utility constructor for creating commands. + /** Utility constructor for creating commands. * * Allows for the following syntax * {{{ @@ -42,8 +39,7 @@ object Command { opts: Opts[A] ): Command[A] = new Command(name, comment, opts, related) - /** - * A helper function that creates a mapping of related command names from a + /** A helper function that creates a mapping of related command names from a * list of commands. The mapping maps related command names to the original * commands that they should point to. */ @@ -51,8 +47,7 @@ object Command { Map.from(commands.flatMap(cmd => cmd.related.map(_ -> cmd.name))) } - /** - * Creates a message that is displayed when a related command is executed. It + /** Creates a message that is displayed when a related command is executed. It * points the user to the original command instead and informs them on usage. * * @param name name of the entered, unkown command diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/CommandHelp.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/CommandHelp.scala index 640385e44b..39bbfec518 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/CommandHelp.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/CommandHelp.scala @@ -1,7 +1,6 @@ package org.enso.cli.arguments -/** - * A help entry used in the top-level help text. +/** A help entry used in the top-level help text. * * @param name name of a command * @param comment a short description of that command diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/IllegalOptsStructure.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/IllegalOptsStructure.scala index 19768ed963..45ce405bd9 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/IllegalOptsStructure.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/IllegalOptsStructure.scala @@ -1,7 +1,6 @@ package org.enso.cli.arguments -/** - * Exception that is reported when Opts are combined in an illegal way. +/** Exception that is reported when Opts are combined in an illegal way. */ case class IllegalOptsStructure(message: String, cause: Throwable = null) extends RuntimeException(message, cause) diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Opts.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Opts.scala index 584021ea6c..022dff43cd 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Opts.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/Opts.scala @@ -7,8 +7,7 @@ import org.enso.cli.CLIOutput import org.enso.cli.internal._ import org.enso.cli.internal.opts._ -/** - * Represents a set of options (flags, parameters, arguments) and the logic +/** Represents a set of options (flags, parameters, arguments) and the logic * that converts all of them into a value of type A. * * Opts instances are allowed to use internal mutable state for parsing. They @@ -16,29 +15,24 @@ import org.enso.cli.internal.opts._ */ trait Opts[+A] { - /** - * Maps flag names to callbacks that are run for that flag. + /** Maps flag names to callbacks that are run for that flag. */ private[cli] def flags: Map[String, () => Unit] - /** - * Maps parameter names to callbacks that are run for that parameter. + /** Maps parameter names to callbacks that are run for that parameter. */ private[cli] def parameters: Map[String, String => Unit] - /** - * Maps prefixes to callbacks that are run for a prefixed parameter with that + /** Maps prefixes to callbacks that are run for a prefixed parameter with that * prefix. */ private[cli] def prefixedParameters: Map[String, (String, String) => Unit] - /** - * Specifies if this set of options can take another argument. + /** Specifies if this set of options can take another argument. */ private[cli] def wantsArgument(): Boolean - /** - * A callback for arguments. + /** A callback for arguments. * * Should not be called if [[wantsArgument]] returns false. * @@ -54,20 +48,17 @@ trait Opts[+A] { suppressUnexpectedArgument: Boolean ): ParserContinuation - /** - * An optional callback for additional arguments. If it is provided, all + /** An optional callback for additional arguments. If it is provided, all * arguments following `--` are passed to it. */ private[cli] def additionalArguments: Option[Seq[String] => Unit] - /** - * A reset callback that should reset all internal state. Allows to reuse an + /** A reset callback that should reset all internal state. Allows to reuse an * Opts instance several times. */ private[cli] def reset(): Unit - /** - * Called at the end of parsing to obtain the result. + /** Called at the end of parsing to obtain the result. * * Any errors accumulated throughout parsing should be returned here. This is * the right moment to do final validation (for example, detecting missing @@ -75,62 +66,52 @@ trait Opts[+A] { */ private[cli] def result(commandPrefix: Seq[String]): Either[OptsParseError, A] - /** - * Lists options that should be printed in the usage [[commandLines]]. + /** Lists options that should be printed in the usage [[commandLines]]. */ private[cli] def usageOptions: Seq[String] - /** - * Names of required arguments, for printing in the usage [[commandLines]]. + /** Names of required arguments, for printing in the usage [[commandLines]]. */ private[cli] def requiredArguments: Seq[String] - /** - * Names of optional arguments, for printing in the usage [[commandLines]]. + /** Names of optional arguments, for printing in the usage [[commandLines]]. */ private[cli] def optionalArguments: Seq[String] - /** - * Name of a trailing arguments set, for printing in the usage + /** Name of a trailing arguments set, for printing in the usage * [[commandLines]]. */ private[cli] def trailingArguments: Option[String] - /** - * Lists all available options by their name and format. + /** Lists all available options by their name and format. * * Used for displaying suggestions when an unknown option is provided. Can * contain, for example `("setting", "--setting VALUE")`. */ private[cli] def gatherOptions: Seq[(String, String)] - /** - * Lists all available prefixed parameters by their name and format. + /** Lists all available prefixed parameters by their name and format. * * Used for displaying suggestions when an unknown prefix is provided. Can * contain, for example `("jvm", "--jvm.KEY VALUE")`. */ private[cli] def gatherPrefixedParameters: Seq[(String, String)] - /** - * Lists all available options with their help messages to be displayed in + /** Lists all available options with their help messages to be displayed in * the help. */ def availableOptionsHelp(): Seq[String] - /** - * Lists all available prefixed parameters with their help messages to be + /** Lists all available prefixed parameters with their help messages to be * displayed in the help. */ def availablePrefixedParametersHelp(): Seq[String] - /** - * Lists additional help messages that are displayed at the end of the help. + /** Lists additional help messages that are displayed at the end of the help. */ def additionalHelp(): Seq[String] - /** - * A helper function that displays an options command line based on the + /** A helper function that displays an options command line based on the * definition of [[usageOptions]]. * * It does not include any arguments, but only parameters and flags. @@ -151,8 +132,7 @@ trait Opts[+A] { otherOptions + usageOptions.map(" " + _).mkString } - /** - * A helper function that gathers all options and arguments definitions, to + /** A helper function that gathers all options and arguments definitions, to * display a command line for showing in the usage section of the help. * * @return a non-empty list of available usages of this option set. Multiple @@ -177,8 +157,7 @@ trait Opts[+A] { NonEmptyList.one(sb.toString().stripLeading()) } - /** - * Generates explanations of parameters to be included in the help message. + /** Generates explanations of parameters to be included in the help message. */ def helpExplanations(): String = { val options = @@ -198,8 +177,7 @@ trait Opts[+A] { optionsHelp + prefixedHelp + additionalText } - /** - * Generates a help text for the command, including usage, available options + /** Generates a help text for the command, including usage, available options * and any additional help lines. * * @param commandPrefix list of command names that should prefix the @@ -219,15 +197,13 @@ trait Opts[+A] { usage + helpExplanations().stripTrailing() } - /** - * Renders text explaining how to display the help. + /** Renders text explaining how to display the help. */ def shortHelp(commandPrefix: Seq[String]): String = s"See `${commandPrefix.mkString(" ")} --help` for usage explanation." } -/** - * The external Opts API is inspired by https://github.com/bkirwi/decline but +/** The external Opts API is inspired by https://github.com/bkirwi/decline but * it is simplified in some places and extended in others to allow for the * features that we need. The internal implementation differs a lot, as the * main priority of its design was providing the best possible error messages. @@ -259,8 +235,7 @@ trait Opts[+A] { object Opts { object implicits { - /** - * A [[Semigroupal]] instance for combining multiple options sets. + /** A [[Semigroupal]] instance for combining multiple options sets. * * The combined set of options parses options from both sets and returns a * tuple of results of both sets if both have succeeded. Unordered options @@ -278,8 +253,7 @@ object Opts { new OptsProduct(fa, fb) } - /** - * A [[Functor]] instance that allows to map over option sets to process + /** A [[Functor]] instance that allows to map over option sets to process * their values. * * The mapping is done eagerly, and it is possible that the result of @@ -295,8 +269,7 @@ object Opts { implicit class WithDefaultSyntax[A](val opts: Opts[Option[A]]) { - /** - * Adds a default value that is returned if the result was None, turning + /** Adds a default value that is returned if the result was None, turning * `Opts[Option[A]]` into `Opts[A]`. */ def withDefault(defaultValue: => A): Opts[A] = @@ -305,8 +278,7 @@ object Opts { implicit class HiddenSyntax[A](val opts: Opts[A]) { - /** - * Makes options from this Opts instance hidden in any help messages. Can + /** Makes options from this Opts instance hidden in any help messages. Can * be used for internal configuration. */ def hidden: Opts[A] = new HiddenOpts(opts) @@ -314,8 +286,7 @@ object Opts { implicit class MapWithErrorsSyntax[A](val opts: Opts[A]) { - /** - * Allows to map an Opts instance in a way that may result in an error. + /** Allows to map an Opts instance in a way that may result in an error. * * If `f` returns a [[Left]], a parse error is reported. Otherwise, * proceeds as `map` would with the result of `Right`. @@ -327,8 +298,7 @@ object Opts { import implicits._ - /** - * An option that accepts a single (required) positional argument and returns + /** An option that accepts a single (required) positional argument and returns * its value. * * Fails if an argument is not provided. @@ -345,8 +315,7 @@ object Opts { ): Opts[A] = new PositionalArgument[A](metavar, if (help.isEmpty) None else Some(help)) - /** - * An option that accepts a single optional positional argument and returns + /** An option that accepts a single optional positional argument and returns * an [[Option]] containing its value, if it was provided. * * @param metavar the name of the argument used in help @@ -364,8 +333,7 @@ object Opts { if (help.isEmpty) None else Some(help) ) - /** - * An option that accepts an arbitrary amount of arguments and returns a + /** An option that accepts an arbitrary amount of arguments and returns a * (possibly empty) list of parsed arguments. * * @param metavar the name of the argument used in help @@ -380,8 +348,7 @@ object Opts { ): Opts[Seq[A]] = new TrailingArguments[A](metavar, if (help.isEmpty) None else Some(help)) - /** - * A flag that returns a [[Boolean]] value indicating if it was provided in + /** A flag that returns a [[Boolean]] value indicating if it was provided in * the command line. * * Returns true if `--name` is included in the command line. @@ -394,8 +361,7 @@ object Opts { def flag(name: String, help: String, showInUsage: Boolean): Opts[Boolean] = new Flag(name, None, help, showInUsage) - /** - * A flag with a short alternative that returns a [[Boolean]] value + /** A flag with a short alternative that returns a [[Boolean]] value * indicating if it was provided in the command line. * * Returns true if `--name` or `-s` (where `s` is the short argument) is @@ -418,8 +384,7 @@ object Opts { ): Opts[Boolean] = new Flag(name, Some(short), help, showInUsage) - /** - * A (required) parameter that tries to parse its value as type A. + /** A (required) parameter that tries to parse its value as type A. * * If a required parameter is not provided, an error is reported. * @@ -438,8 +403,7 @@ object Opts { help: String ): Opts[A] = new Parameter[A](name, metavar, help) - /** - * An optional parameter that tries to parse its value as type A. It returns + /** An optional parameter that tries to parse its value as type A. It returns * an [[Option]] that is defined if the parameter was provided. * * @param name name of the parameter @@ -459,8 +423,7 @@ object Opts { ): Opts[Option[A]] = new OptionalParameter[A](name, metavar, help, showInUsage) - /** - * An optional parameter with multiple aliases. + /** An optional parameter with multiple aliases. * * Returns a value if it is present for exactly one of the aliases or none if * no alias is present. If values are present for mulitple aliases, raises a @@ -514,8 +477,7 @@ object Opts { } } - /** - * An option that accepts an arbitrary amount of parameters with a fixed + /** An option that accepts an arbitrary amount of parameters with a fixed * prefix and returns a sequence of tuples that contain a suffix and a * (string) value. * @@ -541,8 +503,7 @@ object Opts { if (help.isEmpty) None else Some(help) ) - /** - * An option that accepts an arbitrary amount of unspecified additional + /** An option that accepts an arbitrary amount of unspecified additional * arguments and options (flags or parameters included). Any values following * a `--` are passed this option. * @@ -554,8 +515,7 @@ object Opts { def additionalArguments(help: String = ""): Opts[Seq[String]] = new AdditionalArguments(help) - /** - * An option that allows to create subcommands. It accepts a single argument + /** An option that allows to create subcommands. It accepts a single argument * which should be the name of the command that is chosen. Any parameters * following that argument are parsed according to the logic defined for the * selected command. @@ -575,21 +535,18 @@ object Opts { new SubcommandOpt[A](nonEmptyCommands) } - /** - * A helper option that does no parsing and simply returns the provided + /** A helper option that does no parsing and simply returns the provided * value. */ def pure[A](a: A): Opts[A] = new OptsPure[A](a) - /** - * Turns a sequence of options into a single option that returns results of + /** Turns a sequence of options into a single option that returns results of * these options, if all of them parsed successfully. */ def sequence[A](opts: Seq[Opts[A]]): Opts[Seq[A]] = sequence(opts.toList).map(_.toSeq) - /** - * Turns a list of options into a single option that returns results of + /** Turns a list of options into a single option that returns results of * these options, if all of them parsed successfully. */ def sequence[A](opts: List[Opts[A]]): Opts[List[A]] = diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/OptsParseError.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/OptsParseError.scala index 1e6063ef4f..9b834500b7 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/OptsParseError.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/OptsParseError.scala @@ -4,8 +4,7 @@ import cats.data.NonEmptyList import cats.implicits._ import cats.kernel.Semigroup -/** - * Aggregates errors encountered when parsing [[Opts]] and allows to attach +/** Aggregates errors encountered when parsing [[Opts]] and allows to attach * help texts. * * @param errors list of parse errors @@ -20,20 +19,17 @@ case class OptsParseError( fullHelpAppended: Boolean = false ) { - /** - * Creates a copy with additional errors from the provided list. + /** Creates a copy with additional errors from the provided list. */ def withErrors(additionalErrors: List[String]): OptsParseError = copy(errors = errors ++ additionalErrors) - /** - * Creates a copy with additional errors. + /** Creates a copy with additional errors. */ def withErrors(additionalErrors: String*): OptsParseError = withErrors(additionalErrors.toList) - /** - * Specifies if short help should be appended. + /** Specifies if short help should be appended. * * Short help is appended if it was not already mentioned in any of the * errors and if the full help is not added (or requested to be added later). @@ -45,14 +41,12 @@ case class OptsParseError( !isHelpHandled } - /** - * Creates a copy with short help appended. + /** Creates a copy with short help appended. */ def withShortHelp(helpString: String): OptsParseError = withErrors(helpString) - /** - * Creates a copy with full help appended. + /** Creates a copy with full help appended. */ def withFullHelp(helpString: String): OptsParseError = withErrors(helpString).copy( @@ -63,26 +57,22 @@ case class OptsParseError( object OptsParseError { - /** - * Creates a parse error containing the provided errors. + /** Creates a parse error containing the provided errors. */ def apply(error: String, errors: String*): OptsParseError = OptsParseError(NonEmptyList.of(error, errors: _*)) - /** - * Creates a parse error containing the provided error and indicating that + /** Creates a parse error containing the provided error and indicating that * full help text should be appended to it. */ def requestingFullHelp(error: String): OptsParseError = OptsParseError(NonEmptyList.one(error), fullHelpRequested = true) - /** - * Helper method that creates a parse error and wraps it in a [[Left]]. + /** Helper method that creates a parse error and wraps it in a [[Left]]. */ def left[A](error: String): Either[OptsParseError, A] = Left(apply(error)) - /** - * [[Semigroup]] instance for [[OptsParseError]] that allows to merge + /** [[Semigroup]] instance for [[OptsParseError]] that allows to merge * multiple errors into one. */ implicit val semigroup: Semigroup[OptsParseError] = @@ -96,14 +86,12 @@ object OptsParseError { ) } - /** - * Syntax extensions that add helper functions to objects of type + /** Syntax extensions that add helper functions to objects of type * `Either[OptsParseError, A]` (parsing results). */ implicit class ParseErrorSyntax[A](val result: Either[OptsParseError, A]) { - /** - * Add errors from the specified list to the result. + /** Add errors from the specified list to the result. * * If the result was [[Left]], the errors are appended. If the result was * [[Right]] and the list is non-empty, the modified result is [[Left]] @@ -120,24 +108,21 @@ object OptsParseError { } } - /** - * Appends the provided short help if it should be added. + /** Appends the provided short help if it should be added. */ def appendShortHelp(help: => String): Either[OptsParseError, A] = result.left.map { value => if (value.shouldAppendShortHelp) value.withShortHelp(help) else value } - /** - * Appends the provided full help text if it was requested. + /** Appends the provided full help text if it was requested. */ def appendFullHelp(help: => String): Either[OptsParseError, A] = result.left.map { value => if (value.fullHelpRequested) value.withFullHelp(help) else value } - /** - * Converts to an [[Either]] containing just a list of errors on failure. + /** Converts to an [[Either]] containing just a list of errors on failure. * * Makes sure that all help requests have been handled. */ @@ -154,8 +139,7 @@ object OptsParseError { } } - /** - * Merges two parse results into one that returns the pair created from + /** Merges two parse results into one that returns the pair created from * arguments' results on success. * * If any of the arguments is failed, the result is also a failure. If both @@ -172,8 +156,7 @@ object OptsParseError { case (_, Left(b)) => Left(b) } - /** - * Combines two parse results ensuring that the old one was not set already. + /** Combines two parse results ensuring that the old one was not set already. * * If any of the results is failed, the final result is also a failure. If * both results are successful and the first one is empty, the second one is diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/PluginManager.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/PluginManager.scala index f6bc9baa58..41fd824623 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/PluginManager.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/PluginManager.scala @@ -1,12 +1,10 @@ package org.enso.cli.arguments -/** - * A plugin manager that handles finding and running plugins. +/** A plugin manager that handles finding and running plugins. */ trait PluginManager { - /** - * Tries to run a given plugin with provided arguments. + /** Tries to run a given plugin with provided arguments. * * It never returns - either it exits with the plugin's exit code or throws * an exception if it was not possible to run the plugin. @@ -17,18 +15,15 @@ trait PluginManager { */ def runPlugin(name: String, args: Seq[String]): Int - /** - * Returns whether the plugin of the given `name` is available in the system. + /** Returns whether the plugin of the given `name` is available in the system. */ def hasPlugin(name: String): Boolean - /** - * Lists names of plugins found in the system. + /** Lists names of plugins found in the system. */ def pluginsNames(): Seq[String] - /** - * Lists names and short descriptions of plugins found on the system. + /** Lists names and short descriptions of plugins found on the system. */ def pluginsHelp(): Seq[CommandHelp] } diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/TopLevelBehavior.scala b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/TopLevelBehavior.scala index a5ab1f804f..8bf70f781d 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/arguments/TopLevelBehavior.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/arguments/TopLevelBehavior.scala @@ -1,7 +1,6 @@ package org.enso.cli.arguments -/** - * Defines the behaviour of parsing top-level application options. +/** Defines the behaviour of parsing top-level application options. * * @tparam Config type of configuration that is passed to commands */ @@ -9,8 +8,7 @@ sealed trait TopLevelBehavior[+Config] object TopLevelBehavior { - /** - * If top-level options return a value of this class, the application should + /** If top-level options return a value of this class, the application should * continue execution. The provided value of `Config` should be passed to the * executed commands. * @@ -20,8 +18,7 @@ object TopLevelBehavior { case class Continue[Config](withConfig: Config) extends TopLevelBehavior[Config] - /** - * If top-level options return a value of this class, it means that the + /** If top-level options return a value of this class, it means that the * top-level options have handled the execution and commands should not be * parsed further. This can be useful to implement top-level options like * `--version`. diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/CLIOutputInternal.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/CLIOutputInternal.scala index 4e3afa7c37..53ea23f0ee 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/CLIOutputInternal.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/CLIOutputInternal.scala @@ -75,17 +75,16 @@ private[cli] object CLIOutputInternal { val commonSuffixLength = wrapLength - commmonPrefixLength val additionalLinesPadding = " " * commmonPrefixLength - rows.flatMap { - case (prefix, suffix) => - val prefixPadded = rightPad(prefix, commmonPrefixLength) - val wrappedSuffix = wrapLine(suffix, commonSuffixLength) - val firstLine = - if (prefix.length >= commmonPrefixLength) - Seq(prefix, additionalLinesPadding + wrappedSuffix.head) - else - Seq(prefixPadded + wrappedSuffix.head) - val restLines = wrappedSuffix.tail.map(additionalLinesPadding + _) - firstLine ++ restLines + rows.flatMap { case (prefix, suffix) => + val prefixPadded = rightPad(prefix, commmonPrefixLength) + val wrappedSuffix = wrapLine(suffix, commonSuffixLength) + val firstLine = + if (prefix.length >= commmonPrefixLength) + Seq(prefix, additionalLinesPadding + wrappedSuffix.head) + else + Seq(prefixPadded + wrappedSuffix.head) + val restLines = wrappedSuffix.tail.map(additionalLinesPadding + _) + firstLine ++ restLines } } diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/NeedlemanWunsch.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/NeedlemanWunsch.scala index 744e36f9f7..1dce07167f 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/NeedlemanWunsch.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/NeedlemanWunsch.scala @@ -2,8 +2,7 @@ package org.enso.cli.internal object NeedlemanWunsch { - /** - * Computes the similarity score between two words using the Needleman-Wunsch + /** Computes the similarity score between two words using the Needleman-Wunsch * algorithm, as described at * https://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm * @@ -62,12 +61,10 @@ object NeedlemanWunsch { def computePositions( rows: Seq[(Double, String)] ): Seq[(Char, (Double, Double))] = - rows.zipWithIndex flatMap { - case ((paddingLeft, chars), row) => - chars.zipWithIndex map { - case (char, col) => - char -> ((paddingLeft + col, 0.0 + row)) - } + rows.zipWithIndex flatMap { case ((paddingLeft, chars), row) => + chars.zipWithIndex map { case (char, col) => + char -> ((paddingLeft + col, 0.0 + row)) + } } val tuples: Seq[(Char, (Double, Double))] = @@ -76,8 +73,7 @@ object NeedlemanWunsch { Map.from(tuples) } - /** - * Approximates distance between two keys on a QWERTY keyboard. If a provided + /** Approximates distance between two keys on a QWERTY keyboard. If a provided * character is not contained in the set of basic keys, None is returned. */ def keyboardDistance(from: Char, to: Char): Option[Double] = diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/Parser.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/Parser.scala index f2c24f3c40..ada347b577 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/Parser.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/Parser.scala @@ -5,8 +5,7 @@ import org.enso.cli.{CLIOutput, Spelling} object Parser { - /** - * Parses an option set. + /** Parses an option set. * * @param opts the option set that defines the parsing logic * @param tokens the sequence of tokens to parse @@ -28,8 +27,7 @@ object Parser { parseErrors = error :: parseErrors } - /** - * Flag used to avoid issuing an 'unexpected argument' error if it was + /** Flag used to avoid issuing an 'unexpected argument' error if it was * preceded by a potential parameter. * * It is used because if we find an unknown parameter, we do not know if it @@ -207,8 +205,7 @@ object Parser { private val mistypedLongParam = """-([\w-.]+)""".r private val mistypedParamWithValue = """-([\w-.]+)=(.*)""".r - /** - * Converts a sequence of arguments into a sequence of tokens and additional + /** Converts a sequence of arguments into a sequence of tokens and additional * arguments. * * All arguments are converted into tokens until a `--` argument is @@ -232,8 +229,7 @@ object Parser { (localArgs.map(toToken), rest) } - /** - * The inverse of [[tokenize]]. Used when the tokens have to be parsed to an + /** The inverse of [[tokenize]]. Used when the tokens have to be parsed to an * external plugin. */ def untokenize(tokens: Seq[Token]): Seq[String] = diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/ParserContinuation.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/ParserContinuation.scala index 4006f413bd..092ca85d9e 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/ParserContinuation.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/ParserContinuation.scala @@ -1,21 +1,18 @@ package org.enso.cli.internal -/** - * Specifies parser behaviour after parsing a plain token. +/** Specifies parser behaviour after parsing a plain token. */ sealed trait ParserContinuation object ParserContinuation { - /** - * Specifies to continue parsing. + /** Specifies to continue parsing. * * This variant is returned most of the time in the usual parsing flow. */ case object ContinueNormally extends ParserContinuation - /** - * Specifies to stop parsing and return partial results. + /** Specifies to stop parsing and return partial results. * * This can be used to abstain from handling further errors. For example, if * a command name is misspelled, any further parameters would be reported as @@ -24,8 +21,7 @@ object ParserContinuation { */ case object Stop extends ParserContinuation - /** - * Specifies that the parser should stop parsing immediately, gather the + /** Specifies that the parser should stop parsing immediately, gather the * partial results and finish by returning a closure that will call the * provided `continuation`. * diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/ProgressBar.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/ProgressBar.scala index d7976b725b..325d55c20f 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/ProgressBar.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/ProgressBar.scala @@ -1,19 +1,16 @@ package org.enso.cli.internal -/** - * Allows to display a progress bar in a terminal. +/** Allows to display a progress bar in a terminal. */ class ProgressBar { - /** - * Begins drawing the progressbar. + /** Begins drawing the progressbar. */ def start(): Unit = { drawProgressBar(0, "") } - /** - * Updates the progressbar with a percentage. + /** Updates the progressbar with a percentage. */ def updateProgress(percentage: Float): Unit = { drawProgressBar( @@ -22,15 +19,13 @@ class ProgressBar { ) } - /** - * Clears the progressbar. + /** Clears the progressbar. */ def hide(): Unit = { print("\r" + " " * (paddingLength + 2) + "\r") } - /** - * Displays a next step of animation indicating progress of a task with an + /** Displays a next step of animation indicating progress of a task with an * unknown total. */ def showUnknownProgress(): Unit = { diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/Token.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/Token.scala index 3a29468315..735edd33ff 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/Token.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/Token.scala @@ -1,26 +1,22 @@ package org.enso.cli.internal -/** - * A token used in the parser. +/** A token used in the parser. */ sealed trait Token { - /** - * The original value that this token has been created from. + /** The original value that this token has been created from. * * Used to reverse the tokenization process. */ def originalValue: String } -/** - * Plain token, usually treated as an argument or value for a parameter that is +/** Plain token, usually treated as an argument or value for a parameter that is * preceding it. */ case class PlainToken(override val originalValue: String) extends Token -/** - * A token representing a parameter or a flag. +/** A token representing a parameter or a flag. * * It has form `--abc`. */ @@ -28,8 +24,7 @@ case class ParameterOrFlag(parameter: String)( override val originalValue: String ) extends Token -/** - * A token representing a mistyped parameter, i.e. `-abc`. +/** A token representing a mistyped parameter, i.e. `-abc`. * * Used for better error handling. */ @@ -37,8 +32,7 @@ case class MistypedParameter(parameter: String)( override val originalValue: String ) extends Token -/** - * A token representing a parameter with a value, i.e. `--key=value`. +/** A token representing a parameter with a value, i.e. `--key=value`. */ case class ParameterWithValue(parameter: String, value: String)( override val originalValue: String diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/TokenStream.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/TokenStream.scala index 8fd9e95c54..f300abbf2b 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/TokenStream.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/TokenStream.scala @@ -1,20 +1,17 @@ package org.enso.cli.internal -/** - * A mutable stream of tokens. +/** A mutable stream of tokens. * @param initialTokens initial sequence of tokens * @param errorReporter a function used for reporting errors */ class TokenStream(initialTokens: Seq[Token], errorReporter: String => Unit) { var tokens: List[Token] = initialTokens.toList - /** - * Returns true if there are more tokens available. + /** Returns true if there are more tokens available. */ def hasTokens: Boolean = tokens.nonEmpty - /** - * Returns the next token. Cannot be called if [[hasTokens]] is false. + /** Returns the next token. Cannot be called if [[hasTokens]] is false. */ def consumeToken(): Token = { val token = tokens.head @@ -22,14 +19,12 @@ class TokenStream(initialTokens: Seq[Token], errorReporter: String => Unit) { token } - /** - * Returns the next token, but does not remove it from the stream yet. Cannot + /** Returns the next token, but does not remove it from the stream yet. Cannot * be called if [[hasTokens]] is false. */ def peekToken(): Token = tokens.head - /** - * If the next available token is an argument, returns it. Otherwise returns + /** If the next available token is an argument, returns it. Otherwise returns * None and reports a specified error message. */ def tryConsumeArgument(errorMessage: String): Option[String] = { @@ -43,8 +38,7 @@ class TokenStream(initialTokens: Seq[Token], errorReporter: String => Unit) { } } - /** - * Returns a sequence of remaining tokens. + /** Returns a sequence of remaining tokens. */ def remaining(): Seq[Token] = tokens } diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/BaseSubcommandOpt.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/BaseSubcommandOpt.scala index 0dbd7228ab..b2a4ec092a 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/BaseSubcommandOpt.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/BaseSubcommandOpt.scala @@ -4,46 +4,39 @@ import cats.data.NonEmptyList import org.enso.cli.arguments.{Command, Opts} import org.enso.cli.internal.ParserContinuation -/** - * Implements common logic for options that can take a command and modify their +/** Implements common logic for options that can take a command and modify their * further parsing behavior based on that command. * @tparam A returned type * @tparam B type returned by the commands */ trait BaseSubcommandOpt[A, B] extends Opts[A] { - /** - * Lists all available commands. + /** Lists all available commands. */ def availableSubcommands: NonEmptyList[Command[B]] - /** - * Handles an unknown command. + /** Handles an unknown command. * * Executed when a command is given that does not match any of * [[availableSubcommands]]. */ def handleUnknownCommand(command: String): ParserContinuation - /** - * The command that has been selected, if any. + /** The command that has been selected, if any. * * If no command was selected, is set to None. */ var selectedCommand: Option[Command[B]] = None - /** - * List of errors reported when parsing this set of options. + /** List of errors reported when parsing this set of options. */ var errors: List[String] = Nil - /** - * Adds an error that will be reported when getting the result. + /** Adds an error that will be reported when getting the result. */ def addError(error: String): Unit = errors ::= error - /** - * Extends a command prefix from the call with the currently selected command + /** Extends a command prefix from the call with the currently selected command * (if a command is selected). */ def extendPrefix(commandPrefix: Seq[String]): Seq[String] = @@ -111,28 +104,24 @@ trait BaseSubcommandOpt[A, B] extends Opts[A] { errors = Nil } - /** - * @inheritdoc + /** @inheritdoc */ override def availableOptionsHelp(): Seq[String] = availableSubcommands.toList.flatMap(_.opts.availableOptionsHelp()).distinct - /** - * @inheritdoc + /** @inheritdoc */ override def availablePrefixedParametersHelp(): Seq[String] = availableSubcommands.toList .flatMap(_.opts.availablePrefixedParametersHelp()) .distinct - /** - * @inheritdoc + /** @inheritdoc */ override def additionalHelp(): Seq[String] = availableSubcommands.toList.flatMap(_.opts.additionalHelp()).distinct - /** - * @inheritdoc + /** @inheritdoc */ override def commandLines( alwaysIncludeOtherOptions: Boolean = false @@ -148,8 +137,7 @@ trait BaseSubcommandOpt[A, B] extends Opts[A] { availableSubcommands.flatMap(prefixedCommandLines) } - /** - * @inheritdoc + /** @inheritdoc */ override def shortHelp(commandPrefix: Seq[String]): String = super.shortHelp(extendPrefix(commandPrefix)) diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/OptsProduct.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/OptsProduct.scala index d9d65f53f9..d3683cb713 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/OptsProduct.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/OptsProduct.scala @@ -69,8 +69,7 @@ class OptsProduct[A, B](lhs: Opts[A], rhs: Opts[B]) extends Opts[(A, B)] { override def additionalHelp(): Seq[String] = lhs.additionalHelp() ++ rhs.additionalHelp() - /** - * A helper function that gathers all options and arguments definitions, to + /** A helper function that gathers all options and arguments definitions, to * display a command line for showing in the usage section of the help. * * This variant is special to ensure proper handling of subcommands. diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/SubcommandOpt.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/SubcommandOpt.scala index 585c596f70..a7b9935070 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/SubcommandOpt.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/SubcommandOpt.scala @@ -8,13 +8,11 @@ import org.enso.cli.{CLIOutput, Spelling} class SubcommandOpt[A](subcommands: NonEmptyList[Command[A]]) extends BaseSubcommandOpt[A, A] { - /** - * @inheritdoc + /** @inheritdoc */ override def availableSubcommands: NonEmptyList[Command[A]] = subcommands - /** - * A flag that can be set to indicate that a command was provided, but it was + /** A flag that can be set to indicate that a command was provided, but it was * invalid. * * It is used for error reporting to differentiate invalid commands from @@ -22,8 +20,7 @@ class SubcommandOpt[A](subcommands: NonEmptyList[Command[A]]) */ private var commandProvidedButInvalid: Boolean = false - /** - * @inheritdoc + /** @inheritdoc */ override def handleUnknownCommand(command: String): ParserContinuation = { val similar = diff --git a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/TopLevelCommandsOpt.scala b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/TopLevelCommandsOpt.scala index 25de51bdbd..fee67a34af 100644 --- a/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/TopLevelCommandsOpt.scala +++ b/lib/scala/cli/src/main/scala/org/enso/cli/internal/opts/TopLevelCommandsOpt.scala @@ -7,8 +7,7 @@ import org.enso.cli.arguments.Opts.implicits._ import org.enso.cli.arguments._ import org.enso.cli.internal.{Parser, ParserContinuation} -/** - * Implements the entry point of options parsing for an [[Application]]. +/** Implements the entry point of options parsing for an [[Application]]. * * @param toplevelOpts top-level options that define a global configuration * and can override commands @@ -29,19 +28,16 @@ class TopLevelCommandsOpt[A, B]( private def helpOpt: Opts[Boolean] = Opts.flag("help", 'h', "Print this help message.", showInUsage = true) - /** - * Top-level options extended with an option for requesting help. + /** Top-level options extended with an option for requesting help. */ private val toplevelWithHelp = implicitly[Semigroupal[Opts]].product(toplevelOpts, helpOpt) - /** - * @inheritdoc + /** @inheritdoc */ override def availableSubcommands: NonEmptyList[Command[B => Int]] = commands - /** - * Handles an unknown command. + /** Handles an unknown command. * * First tries to find a plugin with the given name and if it finds it, * parsing is stopped to invoke that plugin. Otherwise it just reports an @@ -86,8 +82,7 @@ class TopLevelCommandsOpt[A, B]( result.addErrors(errors.reverse) } - /** - * Renders the help text, depending on if a command has been selected or not. + /** Renders the help text, depending on if a command has been selected or not. * * If no commands were selected, renders the top-level help text. Otherwise, * renders the help text for the selected command. @@ -100,8 +95,7 @@ class TopLevelCommandsOpt[A, B]( topLevelHelp(commandPrefix) } - /** - * Generates a help text for an unknown command, including, if available, + /** Generates a help text for an unknown command, including, if available, * suggestions of similar commands. * * @param typo the unrecognized command name @@ -158,27 +152,23 @@ class TopLevelCommandsOpt[A, B]( toplevelWithHelp.reset() } - /** - * @inheritdoc + /** @inheritdoc */ override def availableOptionsHelp(): Seq[String] = super.availableOptionsHelp() ++ toplevelWithHelp.availableOptionsHelp() - /** - * @inheritdoc + /** @inheritdoc */ override def availablePrefixedParametersHelp(): Seq[String] = super.availablePrefixedParametersHelp() ++ toplevelWithHelp.availablePrefixedParametersHelp() - /** - * @inheritdoc + /** @inheritdoc */ override def additionalHelp(): Seq[String] = super.additionalHelp() ++ toplevelWithHelp.additionalHelp() - /** - * @inheritdoc + /** @inheritdoc */ override def commandLines( alwaysIncludeOtherOptions: Boolean = false @@ -188,8 +178,7 @@ class TopLevelCommandsOpt[A, B]( super.commandLines(alwaysIncludeOtherOptions = include) } - /** - * Renders help text for the specific command. + /** Renders help text for the specific command. */ def commandHelp(command: Command[_], commandPrefix: Seq[String]): String = { val applicationName = commandPrefix.head @@ -198,8 +187,7 @@ class TopLevelCommandsOpt[A, B]( command.comment + "\n" + mergedOpts.help(Seq(applicationName, command.name)) } - /** - * Renders the part of the top-level help text listing the available + /** Renders the part of the top-level help text listing the available * commands. */ def availableCommands(): String = { @@ -210,8 +198,7 @@ class TopLevelCommandsOpt[A, B]( "Available commands:\n" + commandDescriptions } - /** - * Renders top-level help. + /** Renders top-level help. */ def topLevelHelp(commandPrefix: Seq[String]): String = { val usageOptions = toplevelWithHelp diff --git a/lib/scala/core-definition/src/main/scala/org/enso/core/CoreGraph.scala b/lib/scala/core-definition/src/main/scala/org/enso/core/CoreGraph.scala index 618a9937ce..665a13f6fc 100644 --- a/lib/scala/core-definition/src/main/scala/org/enso/core/CoreGraph.scala +++ b/lib/scala/core-definition/src/main/scala/org/enso/core/CoreGraph.scala @@ -535,8 +535,8 @@ object CoreGraph { def addParent( node: Node[CoreGraph], link: Link[CoreGraph] - )( - implicit graph: PrimGraph.GraphData[CoreGraph], + )(implicit + graph: PrimGraph.GraphData[CoreGraph], map: ParentStorage ): Unit = { import Node.ParentLinks._ @@ -551,8 +551,8 @@ object CoreGraph { * @tparam V the shape to set the node to * @return a refined node reference */ - def addRefined[V <: Node.Shape]( - implicit graph: PrimGraph.GraphData[CoreGraph], + def addRefined[V <: Node.Shape](implicit + graph: PrimGraph.GraphData[CoreGraph], ev: VariantIndexed[Node.Shape, V] ): PrimGraph.Component.Refined[Node.Shape, V, Node[CoreGraph]] = { val node = graph.addNode() @@ -570,8 +570,8 @@ object CoreGraph { */ def setShape[NodeShape <: Node.Shape]( node: Node[CoreGraph] - )( - implicit ev: VariantIndexed[Node.Shape, NodeShape], + )(implicit + ev: VariantIndexed[Node.Shape, NodeShape], graph: PrimGraph.GraphData[CoreGraph] ): Unit = { graph.unsafeSetVariantCase[Nodes, Node.Shape, NodeShape](node) diff --git a/lib/scala/flexer/src/main/scala/org/enso/flexer/Reader.scala b/lib/scala/flexer/src/main/scala/org/enso/flexer/Reader.scala index 9dcb51e685..208730ec67 100644 --- a/lib/scala/flexer/src/main/scala/org/enso/flexer/Reader.scala +++ b/lib/scala/flexer/src/main/scala/org/enso/flexer/Reader.scala @@ -80,10 +80,10 @@ class Reader(input: InputStream) extends ReaderUTF(input) { lazy val rewindBy = Array(Array(0, -1), Array(0, -1)) // Describes the currently matched sequence of characters that corresponds // to the currently matched rule. - lazy val matched = new Rewinder(0) + lazy val matched = new Rewinder(0) // Used for the implementation of overlapping rules and also for manual // rewinding by the user. - lazy val rule = new Rewinder(1) + lazy val rule = new Rewinder(1) def maxRewindOffset = if (rewindBy(0)(1) == -1) length else rewindBy(0)(0) diff --git a/lib/scala/flexer/src/main/scala/org/enso/flexer/Spec.scala b/lib/scala/flexer/src/main/scala/org/enso/flexer/Spec.scala index 19f397cebd..9fd45a24cb 100644 --- a/lib/scala/flexer/src/main/scala/org/enso/flexer/Spec.scala +++ b/lib/scala/flexer/src/main/scala/org/enso/flexer/Spec.scala @@ -49,11 +49,10 @@ case class Spec[C <: Context](c: C, dfa: DFA) { } def genSwitch(branchs: Seq[Branch]): Seq[CaseDef] = { - branchs.map { - case Branch(range, body) => - val pattern = - Alternative(range.map(i => q"${Literal(Constant(i))}").toList) - cq"$pattern => $body" + branchs.map { case Branch(range, body) => + val pattern = + Alternative(range.map(i => q"${Literal(Constant(i))}").toList) + cq"$pattern => $body" } } @@ -72,19 +71,18 @@ case class Spec[C <: Context](c: C, dfa: DFA) { val state = dfa.endStatePriorityMap.get(stateIx) var trgState = dfa.links(stateIx)(0) var rStart = Int.MinValue - val branches = dfa.vocabulary.toVector.flatMap { - case (range, vocIx) => - val newTrgState = dfa.links(stateIx)(vocIx) - if (newTrgState != trgState) { - val rEnd = range.start - 1 - val xtrgState = trgState - val xrStart = rStart - trgState = newTrgState - rStart = range.start - Some( - Branch(xrStart to rEnd, genBranchBody(xtrgState, state, overlaps)) - ) - } else None + val branches = dfa.vocabulary.toVector.flatMap { case (range, vocIx) => + val newTrgState = dfa.links(stateIx)(vocIx) + if (newTrgState != trgState) { + val rEnd = range.start - 1 + val xtrgState = trgState + val xrStart = rStart + trgState = newTrgState + rStart = range.start + Some( + Branch(xrStart to rEnd, genBranchBody(xtrgState, state, overlaps)) + ) + } else None } val allBranches = branches :+ @@ -119,11 +117,14 @@ case class Spec[C <: Context](c: C, dfa: DFA) { dfa.links.indices.toList .map(st => (st, TermName(s"state${i}_${st}"))) - val stateMatch = Match(q"state", stateNames.map { - case (st, fun) => cq"$st => $fun" - }) - val stateBodies = stateNames.map { - case (st, fun) => q"def $fun = {${generateCaseBody(st)}}" + val stateMatch = Match( + q"state", + stateNames.map { case (st, fun) => + cq"$st => $fun" + } + ) + val stateBodies = stateNames.map { case (st, fun) => + q"def $fun = {${generateCaseBody(st)}}" } q""" stateDefs($i) = ${TermName(s"nextState$i")} diff --git a/lib/scala/flexer/src/main/scala/org/enso/flexer/State.scala b/lib/scala/flexer/src/main/scala/org/enso/flexer/State.scala index a3bc3842bc..78b53be7bc 100644 --- a/lib/scala/flexer/src/main/scala/org/enso/flexer/State.scala +++ b/lib/scala/flexer/src/main/scala/org/enso/flexer/State.scala @@ -33,8 +33,8 @@ class State(val label: String, val ix: Int, val finish: () => Unit) { private def buildAutomata(): NFA = { val nfa = new NFA val start = nfa.addState() - val endpoints = rules.zipWithIndex.map { - case (rule, ix) => buildRuleAutomata(nfa, start, ix, rule) + val endpoints = rules.zipWithIndex.map { case (rule, ix) => + buildRuleAutomata(nfa, start, ix, rule) } val end = nfa.addState() nfa.state(end).rule = Some("") @@ -88,10 +88,9 @@ class State(val label: String, val ix: Int, val finish: () => Unit) { val nfa = buildAutomata() val dfa = nfa.toDFA() val state = Spec[c.type](c, dfa).generate(ix) - val rs = rules.zipWithIndex.map { - case (rule, ruleIx) => - val tree = c.parse(rule.tree) - q"def ${TermName(ruleName(ruleIx))}() = $tree" + val rs = rules.zipWithIndex.map { case (rule, ruleIx) => + val tree = c.parse(rule.tree) + q"def ${TermName(ruleName(ruleIx))}() = $tree" } q"..$state; ..$rs" } diff --git a/lib/scala/graph/src/main/scala/org/enso/graph/Graph.scala b/lib/scala/graph/src/main/scala/org/enso/graph/Graph.scala index 7f92dc8e80..5526be572a 100644 --- a/lib/scala/graph/src/main/scala/org/enso/graph/Graph.scala +++ b/lib/scala/graph/src/main/scala/org/enso/graph/Graph.scala @@ -56,8 +56,8 @@ object HListSum { implicit val onNil: HListSum.Aux[HNil, _0] = new HListSum[HNil] { type Out = _0 } - implicit def onCons[H <: Nat, T <: HList, TS <: Nat]( - implicit @unused rest: HListSum.Aux[T, TS], + implicit def onCons[H <: Nat, T <: HList, TS <: Nat](implicit + @unused rest: HListSum.Aux[T, TS], all: nat.Sum[H, TS] ): HListSum.Aux[H :: T, all.Out] = new HListSum[H :: T] { type Out = all.Out } @@ -79,8 +79,7 @@ object HListOfNatToVec { implicit def onNil: HListOfNatToVec[HNil] = new HListOfNatToVec[HNil] { val out = Vector[Int]() } - implicit def onCons[Head <: Nat, Tail <: HList]( - implicit + implicit def onCons[Head <: Nat, Tail <: HList](implicit tail: HListOfNatToVec[Tail], head: nat.ToInt[Head] ): HListOfNatToVec[Head :: Tail] = new HListOfNatToVec[Head :: Tail] { @@ -116,8 +115,8 @@ trait HListTakeUntil[T, Items <: HList] { object HListTakeUntil extends HListTakeUntilDefaults { type Aux[T, Items <: HList, X] = HListTakeUntil[T, Items] { type Out = X } - def apply[T, Items <: HList]( - implicit ev: HListTakeUntil[T, Items] + def apply[T, Items <: HList](implicit + ev: HListTakeUntil[T, Items] ): Aux[T, Items, ev.Out] = ev implicit def onNil[T]: HListTakeUntil.Aux[T, HNil, HNil] = @@ -129,8 +128,8 @@ object HListTakeUntil extends HListTakeUntilDefaults { } trait HListTakeUntilDefaults { - implicit def onConsNotFound[T, Head, Tail <: HList, Tail2 <: HList]( - implicit @unused ev1: HListTakeUntil.Aux[T, Tail, Tail2] + implicit def onConsNotFound[T, Head, Tail <: HList, Tail2 <: HList](implicit + @unused ev1: HListTakeUntil.Aux[T, Tail, Tail2] ): HListTakeUntil.Aux[T, Head :: Tail, Head :: Tail2] = new HListTakeUntil[T, Head :: Tail] { type Out = Head :: Tail2 } } @@ -161,8 +160,7 @@ object Sized { ListOfItems <: HList, ListOfSizes <: HList, TotalSize <: Nat - ]( - implicit + ](implicit @unused ev1: MapSized.Aux[ListOfItems, ListOfSizes], @unused ev2: HListSum.Aux[ListOfSizes, TotalSize] ): Sized.Aux[ListOfItems, TotalSize] = @@ -174,8 +172,7 @@ trait KnownSize[T] extends Sized[T] { val asInt: Int } object KnownSize { - implicit def instance[T, Size <: Nat]( - implicit + implicit def instance[T, Size <: Nat](implicit @unused ev: Sized.Aux[T, Size], sizeEv: nat.ToInt[Size] ): KnownSize[T] = new KnownSize[T] { val asInt: Int = sizeEv() } @@ -201,8 +198,8 @@ object MapSized { implicit val onNil: MapSized.Aux[HNil, HNil] = new MapSized[HNil] { type Out = HNil } - implicit def onCons[H, T <: HList, TS <: HList, HSize <: Nat]( - implicit @unused rest: MapSized.Aux[T, TS], + implicit def onCons[H, T <: HList, TS <: HList, HSize <: Nat](implicit + @unused rest: MapSized.Aux[T, TS], @unused headSize: Sized.Aux[H, HSize] ): MapSized.Aux[H :: T, HSize :: TS] = new MapSized[H :: T] { type Out = HSize :: TS } @@ -227,8 +224,8 @@ trait SizeUntil[Elem, Items <: HList] { object SizeUntil { type Aux[Elem, Items <: HList, X] = SizeUntil[Elem, Items] { type Out = X } - def apply[Elem, Items <: HList]( - implicit ev: SizeUntil[Elem, Items] + def apply[Elem, Items <: HList](implicit + ev: SizeUntil[Elem, Items] ): Aux[Elem, Items, ev.Out] = ev implicit def instance[ @@ -237,8 +234,7 @@ object SizeUntil { PriorElems <: HList, PriorFieldSizes <: HList, PriorFieldsSize <: Nat - ]( - implicit + ](implicit @unused ev1: HListTakeUntil.Aux[Elem, Items, PriorElems], @unused ev2: MapSized.Aux[PriorElems, PriorFieldSizes], @unused ev3: HListSum.Aux[PriorFieldSizes, PriorFieldsSize], @@ -265,8 +261,8 @@ trait MapsOf[Items <: HList] { object MapsOf { type Aux[Items <: HList, X] = MapsOf[Items] { type Out = X } - def apply[Items <: HList]( - implicit ev: MapsOf[Items] + def apply[Items <: HList](implicit + ev: MapsOf[Items] ): MapsOf.Aux[Items, ev.Out] = ev implicit def onNil: MapsOf.Aux[HNil, HNil] = @@ -275,8 +271,8 @@ object MapsOf { val instance = HNil } - implicit def onCons[Head, Tail <: HList]( - implicit ev: MapsOf[Tail], + implicit def onCons[Head, Tail <: HList](implicit + ev: MapsOf[Tail], @unused distinct: IsDistinctConstraint[Head :: Tail] ): MapsOf.Aux[Head :: Tail, mutable.Map[Int, Head] :: ev.Out] = new MapsOf[Head :: Tail] { @@ -286,8 +282,8 @@ object MapsOf { def getOpaqueData[T, Opaques <: HList]( list: Opaques - )( - implicit ev: Selector[Opaques, mutable.Map[Int, T]] + )(implicit + ev: Selector[Opaques, mutable.Map[Int, T]] ): mutable.Map[Int, T] = { list.select[mutable.Map[Int, T]] } @@ -467,12 +463,17 @@ object Graph { case class VariantMatcher[T <: Component.Field, V](ix: Int) { def unapply[G <: Graph, C <: Component]( arg: Component.Ref[G, C] - )( - implicit graph: GraphData[G], + )(implicit + graph: GraphData[G], ev: HasComponentField[G, C, T] ): Option[Component.Refined[T, V, Component.Ref[G, C]]] = { val variantIndexByteOffset = 0 - if (graph.unsafeReadFieldByIndex[C, T](arg.ix, variantIndexByteOffset) == ix) + if ( + graph.unsafeReadFieldByIndex[C, T]( + arg.ix, + variantIndexByteOffset + ) == ix + ) Some(Component.Refined[T, V, Component.Ref[G, C]](arg)) else None } @@ -504,8 +505,8 @@ object Graph { * @tparam C the type of the component to access * @return a reference to the component at `index` */ - def componentRefFromIndex[C <: Component](index: Int)( - implicit @unused ev: HasComponent[G, C] + def componentRefFromIndex[C <: Component](index: Int)(implicit + @unused ev: HasComponent[G, C] ): Graph.Component.Ref[G, C] = { Graph.Component.Ref(index) } @@ -522,8 +523,8 @@ object Graph { */ def unsafeSetVariantCase[C <: Component, F <: Component.Field, V <: F]( component: Component.Ref[G, C] - )( - implicit info: HasComponentField[G, C, F], + )(implicit + info: HasComponentField[G, C, F], indexed: VariantIndexed[F, V] ): Unit = { unsafeWriteField[C, F](component, indexed.ix) @@ -610,8 +611,8 @@ object Graph { def unsafeWriteField[C <: Component, F <: Component.Field]( component: Component.Ref[G, C], value: Int - )( - implicit ev: HasComponentField[G, C, F] + )(implicit + ev: HasComponentField[G, C, F] ): Unit = { unsafeWriteFieldByIndex[C, F](component.ix, ev.fieldOffset, value) } @@ -643,8 +644,8 @@ object Graph { * @tparam C the component type * @return a reference to the new component [[C]] */ - def addComponent[C <: Component]()( - implicit info: HasComponent[G, C] + def addComponent[C <: Component]()(implicit + info: HasComponent[G, C] ): Component.Ref[G, C] = { val compClsIx = info.componentIndex val compIx = components(compClsIx).length @@ -684,8 +685,7 @@ object Graph { ComponentList <: HList, ComponentSizeList >: HList, ComponentListLength <: Nat - ]( - implicit + ](implicit @unused ev1: Component.List.Aux[G, ComponentList], @unused ev2: hlist.Length.Aux[ComponentList, ComponentListLength], componentSizesEv: ComponentListToSizes[G, ComponentList], @@ -715,8 +715,7 @@ object Graph { PrevComponentList <: HList, ComponentIndex <: Nat, FieldList <: HList - ]( - implicit + ](implicit @unused ev1: Component.List.Aux[G, ComponentList], @unused ev2: Component.Field.List.Aux[G, C, FieldList], @unused ev3: HListTakeUntil.Aux[C, ComponentList, PrevComponentList], @@ -749,8 +748,7 @@ object Graph { C <: Component, F <: Component.Field, FieldList <: HList - ]( - implicit + ](implicit @unused ev1: Component.Field.List.Aux[G, C, FieldList], evx: HasComponent[G, C], fieldOffsetEv: SizeUntil[F, FieldList], @@ -777,8 +775,7 @@ object Graph { implicit def onNil[G <: Graph]: ComponentListToSizes[G, HNil] = new ComponentListToSizes[G, HNil] { val sizes = Vector[Int]() } - implicit def onCons[G <: Graph, C <: Component, Tail <: HList]( - implicit + implicit def onCons[G <: Graph, C <: Component, Tail <: HList](implicit tail: ComponentListToSizes[G, Tail], info: HasComponent[G, C] ): ComponentListToSizes[G, C :: Tail] = @@ -802,8 +799,8 @@ object Graph { G <: Graph, C <: Component, F <: Component.Field - ](val component: Component.Ref[G, C])( - implicit ev: HasComponentField[G, C, F], + ](val component: Component.Ref[G, C])(implicit + ev: HasComponentField[G, C, F], graph: GraphData[G] ) { @@ -816,8 +813,8 @@ object Graph { * @return `true` if [[component]] is of the form denoted by [[V]], `false` * otherwise */ - def is[V <: F]( - implicit variantIndexed: VariantIndexed[F, V] + def is[V <: F](implicit + variantIndexed: VariantIndexed[F, V] ): Boolean = { graph.unsafeReadField[C, F](component) == variantIndexed.ix } @@ -834,8 +831,8 @@ object Graph { * @return the component [[component]] refined to be the variant branch * [[V]] */ - def unsafeAs[V <: F]( - implicit @unused variantIndexed: VariantIndexed[F, V] + def unsafeAs[V <: F](implicit + @unused variantIndexed: VariantIndexed[F, V] ): Component.Refined[F, V, Component.Ref[G, C]] = { Component.Refined[F, V, Component.Ref[G, C]](component) } @@ -848,8 +845,8 @@ object Graph { * @tparam V the type of the variant case in question * @return [[Some]] if [[component]] is a [[V]], otherwise [[None]] */ - def as[V <: F]( - implicit variantIndexed: VariantIndexed[F, V] + def as[V <: F](implicit + variantIndexed: VariantIndexed[F, V] ): Option[Component.Refined[F, V, Component.Ref[G, C]]] = { if (is[V]) { Some(unsafeAs[V]) diff --git a/lib/scala/graph/src/main/scala/org/enso/graph/definition/Macro.scala b/lib/scala/graph/src/main/scala/org/enso/graph/definition/Macro.scala index 12b3041a36..eeb6712643 100644 --- a/lib/scala/graph/src/main/scala/org/enso/graph/definition/Macro.scala +++ b/lib/scala/graph/src/main/scala/org/enso/graph/definition/Macro.scala @@ -110,8 +110,8 @@ object Macro { mTemplate match { case Some(template) => { - val allVals = template.body.collect { - case valDef: ValDef => valDef + val allVals = template.body.collect { case valDef: ValDef => + valDef } allVals.filter(t => @@ -157,8 +157,8 @@ object Macro { ): (Tree, TypeName, TermName) = { val (opaqueType, opaqueStorageName) = paramType match { case AppliedTypeTree( - Ident(_), - typeName :: Ident(storageName) :: Nil + Ident(_), + typeName :: Ident(storageName) :: Nil ) => (typeName, storageName.toTypeName) } @@ -187,19 +187,19 @@ object Macro { for ((subfield, ix) <- subfields.view.zipWithIndex) { accessorDefs = accessorDefs :+ genSubfieldGetter( - subfield, - enclosingName, - ix, - graphTypeName, - isSimple - ) + subfield, + enclosingName, + ix, + graphTypeName, + isSimple + ) accessorDefs = accessorDefs :+ genSubfieldSetter( - subfield, - enclosingName, - ix, - graphTypeName, - isSimple - ) + subfield, + enclosingName, + ix, + graphTypeName, + isSimple + ) } val valClassAccessors = genValClassAccessors( @@ -647,12 +647,12 @@ object Macro { errorTName } else { val boundsNames = firstTParam.children - .collect { - case tree: TypeBoundsTree => tree + .collect { case tree: TypeBoundsTree => + tree } .map(_.hi) - .collect { - case Ident(name) => name.toTypeName + .collect { case Ident(name) => + name.toTypeName } boundsNames.head @@ -704,9 +704,11 @@ object Macro { val graphTermName = graphTypeName.toTermName val valClassName = TypeName(fieldTermName.toString + "Val") - if (subfields - .map(_.name.toString.toLowerCase) - .contains(fieldTermName.toString.toLowerCase)) { + if ( + subfields + .map(_.name.toString.toLowerCase) + .contains(fieldTermName.toString.toLowerCase) + ) { c.error( c.enclosingPosition, "YOu cannot define a subfield name that clashes with the field name." @@ -796,8 +798,8 @@ object Macro { .collect { case valDef: ValDef if isOpaqueParam(valDef) => valDef.tpt } - .collect { - case AppliedTypeTree(_, _ :: storageName :: Nil) => storageName + .collect { case AppliedTypeTree(_, _ :: storageName :: Nil) => + storageName } .distinct @@ -836,8 +838,10 @@ object Macro { val subfieldNamesLower = subfields.map(_.name.toString.toLowerCase) - if (subfieldNamesLower.contains(parentName.toString.toLowerCase) || - subfieldNamesLower.contains(typeName.toString.toLowerCase)) { + if ( + subfieldNamesLower.contains(parentName.toString.toLowerCase) || + subfieldNamesLower.contains(typeName.toString.toLowerCase) + ) { c.error( c.enclosingPosition, "You cannot define a variant subfield that clashes with either " + @@ -956,8 +960,8 @@ object Macro { errorName } else { val firstGName = gNames.head - val idents = firstGName.children.collect { - case Ident(name) => name.toTypeName + val idents = firstGName.children.collect { case Ident(name) => + name.toTypeName } if (idents.length != 1) { @@ -1024,8 +1028,8 @@ object Macro { // Note [Encoding Variant Size] val numTotalSize = variantResults - .map(_._2) - .foldLeft(0)((x: Int, y: Int) => Math.max(x, y)) + 1 + .map(_._2) + .foldLeft(0)((x: Int, y: Int) => Math.max(x, y)) + 1 val baseModuleStub: ModuleDef = q""" @@ -1120,7 +1124,6 @@ object Macro { * } * } * }}} - * */ @compileTimeOnly("please enable macro paradise to expand macro annotations") class component extends StaticAnnotation { @@ -1140,8 +1143,7 @@ object Macro { val baseBlock: Block = Block(List(), EmptyTree) - /** - * Appends a statement to a block with no return value. + /** Appends a statement to a block with no return value. * * @param block the block to append to * @param statement the statement to append to `block` @@ -1174,18 +1176,18 @@ object Macro { (errorTName, errorTName) } else { val tDef = typeDefs.head - val typeParams = tDef.children.collect { - case typeDef: TypeDef => typeDef + val typeParams = tDef.children.collect { case typeDef: TypeDef => + typeDef } if (typeParams.length == 1) { val boundNames = typeParams.head.children - .collect { - case tree: TypeBoundsTree => tree + .collect { case tree: TypeBoundsTree => + tree } .map(_.hi) - .collect { - case Ident(name) => name.toTypeName + .collect { case Ident(name) => + name.toTypeName } (tDef.name, boundNames.head) diff --git a/lib/scala/json-rpc-server-test/src/main/scala/org/enso/jsonrpc/test/JsonRpcServerTestKit.scala b/lib/scala/json-rpc-server-test/src/main/scala/org/enso/jsonrpc/test/JsonRpcServerTestKit.scala index 676fa2ff84..ff44ce83fa 100644 --- a/lib/scala/json-rpc-server-test/src/main/scala/org/enso/jsonrpc/test/JsonRpcServerTestKit.scala +++ b/lib/scala/json-rpc-server-test/src/main/scala/org/enso/jsonrpc/test/JsonRpcServerTestKit.scala @@ -17,8 +17,7 @@ import org.scalatest.{Assertion, BeforeAndAfterAll, BeforeAndAfterEach} import scala.concurrent.Await import scala.concurrent.duration._ -/** - * Test kit for testing JSON RPC servers. +/** Test kit for testing JSON RPC servers. */ abstract class JsonRpcServerTestKit extends TestKit(ActorSystem("TestSystem")) diff --git a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/ClientControllerFactory.scala b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/ClientControllerFactory.scala index 90637fe768..190741053e 100644 --- a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/ClientControllerFactory.scala +++ b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/ClientControllerFactory.scala @@ -4,15 +4,13 @@ import java.util.UUID import akka.actor.ActorRef -/** - * Classes implementing this trait are responsible for creating client +/** Classes implementing this trait are responsible for creating client * controllers upon a new connection. An client controller handles * communications between a single client and the JSON RPC server. */ trait ClientControllerFactory { - /** - * Creates a client controller actor. + /** Creates a client controller actor. * * @param clientId the internal client id. * @return an actor ref to the client controller diff --git a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonProtocol.scala b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonProtocol.scala index 9aa28f3022..4b370220eb 100644 --- a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonProtocol.scala +++ b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonProtocol.scala @@ -3,41 +3,34 @@ package org.enso.jsonrpc import io.circe.Decoder.Result import io.circe._ -/** - * An intermediate representation of JSON RPC messages, used for +/** An intermediate representation of JSON RPC messages, used for * (de)serialization. */ object JsonProtocol { import io.circe.generic.auto._ import io.circe.syntax._ - /** - * Supertype of all conceivable messages received from the web. + /** Supertype of all conceivable messages received from the web. */ sealed trait JsonMessage - /** - * A bare notification object. + /** A bare notification object. */ case class Notification(method: String, params: Json) extends JsonMessage - /** - * A bare request object. + /** A bare request object. */ case class Request(method: String, id: Id, params: Json) extends JsonMessage - /** - * A successful response object. + /** A successful response object. */ case class ResponseResult(id: Id, result: Json) extends JsonMessage - /** - * An error response object. + /** An error response object. */ case class ResponseError(id: Option[Id], error: ErrorData) extends JsonMessage - /** - * The error response details. + /** The error response details. */ case class ErrorData(code: Int, message: String) @@ -118,8 +111,8 @@ object JsonProtocol { override def apply(c: HCursor): Result[JsonMessage] = { val jsonRpcValid = c - .downField(Constants.jsonrpc) - .as[String] == Right(Constants.jsonrpcVersion) + .downField(Constants.jsonrpc) + .as[String] == Right(Constants.jsonrpcVersion) if (!jsonRpcValid) { return Left( DecodingFailure("Invalid JSON RPC version manifest.", List()) @@ -140,8 +133,7 @@ object JsonProtocol { } } - /** - * Parses a string into a valid JSON RPC message. + /** Parses a string into a valid JSON RPC message. * @param str the string to parse. * @return the data type corresponding to the message, if parsed * successfully. @@ -150,8 +142,7 @@ object JsonProtocol { io.circe.parser.parse(str).toOption.flatMap(_.as[JsonMessage].toOption) } - /** - * Encodes a message into a proper JSON RPC string. + /** Encodes a message into a proper JSON RPC string. * @param msg the message to encode. * @return a string representing a valid JSON RPC package. */ diff --git a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonRpcServer.scala b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonRpcServer.scala index 41f044ec90..978e5980c5 100644 --- a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonRpcServer.scala +++ b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/JsonRpcServer.scala @@ -14,8 +14,7 @@ import akka.stream.scaladsl.{Flow, Sink, Source} import scala.concurrent.{ExecutionContext, Future} import scala.concurrent.duration._ -/** - * Exposes a multi-client JSON RPC Server instance over WebSocket connections. +/** Exposes a multi-client JSON RPC Server instance over WebSocket connections. * * @param protocol a protocol supported be the server * @param clientControllerFactory a factory used to create a client controller @@ -57,7 +56,8 @@ class JsonRpcServer( .to( Sink.actorRef[MessageHandler.WebMessage]( messageHandler, - MessageHandler.Disconnected, { _: Any => + MessageHandler.Disconnected, + { _: Any => MessageHandler.Disconnected } ) @@ -84,8 +84,7 @@ class JsonRpcServer( get { handleWebSocketMessages(newUser()) } } - /** - * Binds this server instance to a given port and interface, allowing + /** Binds this server instance to a given port and interface, allowing * future connections. * * @param interface the interface to bind to. @@ -98,8 +97,7 @@ class JsonRpcServer( object JsonRpcServer { - /** - * A configuration object for properties of the JsonRpcServer. + /** A configuration object for properties of the JsonRpcServer. * * @param outgoingBufferSize the number of messages buffered internally * if the downstream connection is lagging behind. @@ -115,8 +113,7 @@ object JsonRpcServer { case object Config { - /** - * Creates a default instance of [[Config]]. + /** Creates a default instance of [[Config]]. * * @return a default config. */ diff --git a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/MessageHandler.scala b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/MessageHandler.scala index 6bcdabc99e..77d468f572 100644 --- a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/MessageHandler.scala +++ b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/MessageHandler.scala @@ -4,8 +4,7 @@ import akka.actor.{Actor, ActorRef, Stash} import io.circe.Json import org.enso.jsonrpc.Errors.InvalidParams -/** - * An actor responsible for passing parsed massages between the web and +/** An actor responsible for passing parsed massages between the web and * a controller actor. * @param protocol a protocol object describing supported messages and their * serialization modes. @@ -15,8 +14,7 @@ class MessageHandler(val protocol: Protocol, val controller: ActorRef) extends Actor with Stash { - /** - * A pre-initialization behavior, awaiting a to-web connection end. + /** A pre-initialization behavior, awaiting a to-web connection end. * @return the actor behavior. */ override def receive: Receive = { @@ -26,8 +24,7 @@ class MessageHandler(val protocol: Protocol, val controller: ActorRef) case _ => stash() } - /** - * A fully established connection behavior. + /** A fully established connection behavior. * @param webConnection the to-web connection end. * @param awaitingResponses a list of all requests sent to web, retained for * response deserialization. @@ -141,9 +138,8 @@ class MessageHandler(val protocol: Protocol, val controller: ActorRef) .resolveError(bareError.code) .getOrElse(Errors.UnknownError(bareError.code, bareError.message)) controller ! ResponseError(mayId, error) - mayId.foreach( - id => - context.become(established(webConnection, awaitingResponses - id)) + mayId.foreach(id => + context.become(established(webConnection, awaitingResponses - id)) ) } @@ -168,26 +164,22 @@ class MessageHandler(val protocol: Protocol, val controller: ActorRef) } yield decoder } -/** - * Control messages for the [[MessageHandler]] actor. +/** Control messages for the [[MessageHandler]] actor. */ object MessageHandler { - /** - * A message exchanged on the Web side of the boundary. + /** A message exchanged on the Web side of the boundary. * * @param message the serialized json contents of the message. */ case class WebMessage(message: String) - /** - * A control message used for [[MessageHandler]] initializations + /** A control message used for [[MessageHandler]] initializations * @param webConnection the actor representing the web. */ case class Connected(webConnection: ActorRef) - /** - * A control message usef to notify the controller about + /** A control message usef to notify the controller about * the connection being closed. */ case object Disconnected diff --git a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/Protocol.scala b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/Protocol.scala index 65d72a02b5..7042cb4f18 100644 --- a/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/Protocol.scala +++ b/lib/scala/json-rpc-server/src/main/scala/org/enso/jsonrpc/Protocol.scala @@ -5,8 +5,7 @@ import io.circe.{Decoder, Encoder, Json} import scala.annotation.unused import scala.reflect.ClassTag -/** - * Represents valid JSON RPC request ids. +/** Represents valid JSON RPC request ids. */ sealed trait Id @@ -27,8 +26,7 @@ object Id { .or(Decoder[Int].map(Number).widen[Id]) } -/** - * An object that can be used as params or result for a protocol message that +/** An object that can be used as params or result for a protocol message that * does not need params or result. */ case object Unused { @@ -40,8 +38,7 @@ case object Unused { } } -/** - * A typeclass implemented by all protocol messages that have params. +/** A typeclass implemented by all protocol messages that have params. * Declares the type of params associated with a given method. */ trait HasParams[M <: Method] { @@ -51,8 +48,7 @@ object HasParams { type Aux[M <: Method, P] = HasParams[M] { type Params = P } } -/** - * A typeclass implemented by all protocol messages that have results. +/** A typeclass implemented by all protocol messages that have results. * Declares the type of result associated with a given method. */ trait HasResult[M <: Method] { @@ -62,14 +58,12 @@ object HasResult { type Aux[M <: Method, Res] = HasResult[M] { type Result = Res } } -/** - * A superclass for supported API methods. +/** A superclass for supported API methods. * @param name the method name. */ abstract class Method(val name: String) -/** - * The basic JSON RPC request type. +/** The basic JSON RPC request type. */ case class Request[+M <: Method, +Params]( method: M, @@ -77,15 +71,13 @@ case class Request[+M <: Method, +Params]( params: Params )(implicit @unused ev: HasParams.Aux[M, Params]) -/** - * The basic JSON RPC notification type. +/** The basic JSON RPC notification type. */ case class Notification[+M <: Method, +Params](method: M, params: Params)( implicit @unused ev: HasParams.Aux[M, Params] ) -/** - * The basic JSON RPC successful response type. +/** The basic JSON RPC successful response type. */ case class ResponseResult[+M <: Method, +Result]( method: M, @@ -93,20 +85,17 @@ case class ResponseResult[+M <: Method, +Result]( data: Result )(implicit @unused ev: HasResult.Aux[M, Result]) -/** - * The basic JSON RPC error response type. +/** The basic JSON RPC error response type. */ case class ResponseError(id: Option[Id], error: Error) -/** - * A basic error type for responses. +/** A basic error type for responses. * @param code the error code. * @param message the error message. */ abstract class Error(val code: Int, val message: String) -/** - * Builtin error types, defined by JSON RPC. +/** Builtin error types, defined by JSON RPC. */ object Errors { case object ParseError extends Error(-32700, "Parse error") @@ -122,8 +111,7 @@ object Protocol { private case class InexhaustivePayloadsSerializerError(payload: Any) extends Exception - /** - * Creates an empty (no messages) instance of protocol. + /** Creates an empty (no messages) instance of protocol. * @return an empty instance of protocol. */ def empty = @@ -138,17 +126,15 @@ object Protocol { ) } -/** - * A type-safe wrapper for a JSON params decoder, allowing to construct valid +/** A type-safe wrapper for a JSON params decoder, allowing to construct valid * [[Request]] and [[Notification]] objects. */ -class ParamsDecoder[+M <: Method, +Params](method: M)( - implicit ev: HasParams.Aux[M, Params], +class ParamsDecoder[+M <: Method, +Params](method: M)(implicit + ev: HasParams.Aux[M, Params], decoder: Decoder[Params] ) { - /** - * Decodes given params into a request of this decoder's method. + /** Decodes given params into a request of this decoder's method. * @param id the request id. * @param params the request params. * @return an instance of request with the params decoded, if valid. @@ -156,8 +142,7 @@ class ParamsDecoder[+M <: Method, +Params](method: M)( def buildRequest(id: Id, params: Json): Option[Request[M, Params]] = decoder.decodeJson(params).toOption.map(Request(method, id, _)) - /** - * Decodes given params into a notification of this decoder's method. + /** Decodes given params into a notification of this decoder's method. * @param params the notification params. * @return an instance of notification with the params decoded, if valid. */ @@ -165,16 +150,14 @@ class ParamsDecoder[+M <: Method, +Params](method: M)( decoder.decodeJson(params).toOption.map(Notification(method, _)) } -/** - * A type-safe wrapper for a JSON results decoder. +/** A type-safe wrapper for a JSON results decoder. */ -class ResultDecoder[+M <: Method, +Result](method: M)( - implicit ev: HasResult.Aux[M, Result], +class ResultDecoder[+M <: Method, +Result](method: M)(implicit + ev: HasResult.Aux[M, Result], decoder: Decoder[Result] ) { - /** - * Builds a response for this decoder's method from JSON result. + /** Builds a response for this decoder's method from JSON result. * @param id the request id. * @param result the JSON encoded result payload. * @return an instance of response with the given result, if valid. @@ -183,8 +166,7 @@ class ResultDecoder[+M <: Method, +Result](method: M)( decoder.decodeJson(result).toOption.map(ResponseResult(method, id, _)) } -/** - * A description containing all the supported methods and ways of serializing +/** A description containing all the supported methods and ways of serializing * their params and results. * * @param methods all the supported methods. @@ -212,16 +194,14 @@ case class Protocol( private val methodsMap: Map[String, Method] = methods.map(tag => (tag.name, tag)).toMap - /** - * Resolves a method by name. + /** Resolves a method by name. * * @param name the method name. * @return an object representing the method, if exists. */ def resolveMethod(name: String): Option[Method] = methodsMap.get(name) - /** - * Looks up a params decoder for a given method. + /** Looks up a params decoder for a given method. * * @param method the method to lookup decoder for. * @return the params decoder, if found. @@ -231,8 +211,7 @@ case class Protocol( ): Option[ParamsDecoder[Method, Any]] = paramsDecoders.get(method) - /** - * Looks up a result decoder for a given method. + /** Looks up a result decoder for a given method. * * @param method the method to lookup decoder for. * @return the result decoder, if found. @@ -240,8 +219,7 @@ case class Protocol( def getResultDecoder(method: Method): Option[ResultDecoder[Method, Any]] = resultDecoders.get(method) - /** - * Looks up a proper error object by error code. + /** Looks up a proper error object by error code. * * @param code the error code to look up. * @return the corresponding custom error object, if exists. @@ -249,8 +227,7 @@ case class Protocol( def resolveError(code: Int): Option[Error] = builtinErrors.get(code).orElse(customErrors.get(code)) - /** - * Adds a request method to this protocol. + /** Adds a request method to this protocol. * * @param method the method to add. * @tparam M the method's type. @@ -262,8 +239,8 @@ case class Protocol( M <: Method, Params: ClassTag, Result: ClassTag - ](method: M)( - implicit paramsEv: HasParams.Aux[M, Params], + ](method: M)(implicit + paramsEv: HasParams.Aux[M, Params], resultEv: HasResult.Aux[M, Result], paramsEncoder: Encoder[Params], paramsDecoder: Decoder[Params], @@ -271,11 +248,9 @@ case class Protocol( resultDecoder: Decoder[Result] ): Protocol = copy( - methods = methods + method, - paramsDecoders = - paramsDecoders + (method -> new ParamsDecoder(method)), - resultDecoders = - resultDecoders + (method -> new ResultDecoder(method)), + methods = methods + method, + paramsDecoders = paramsDecoders + (method -> new ParamsDecoder(method)), + resultDecoders = resultDecoders + (method -> new ResultDecoder(method)), payloadsEncoder = { case params: Params => paramsEncoder(params) case result: Result => resultEncoder(result) @@ -283,8 +258,7 @@ case class Protocol( } ) - /** - * Adds a notification method to this protocol. + /** Adds a notification method to this protocol. * * @param method the method to add. * @tparam M the method's type. @@ -294,23 +268,21 @@ case class Protocol( def registerNotification[ M <: Method, Params: ClassTag - ](method: M)( - implicit paramsEv: HasParams.Aux[M, Params], + ](method: M)(implicit + paramsEv: HasParams.Aux[M, Params], paramsEncoder: Encoder[Params], paramsDecoder: Decoder[Params] ): Protocol = copy( - methods = methods + method, - paramsDecoders = - paramsDecoders + (method -> new ParamsDecoder(method)), + methods = methods + method, + paramsDecoders = paramsDecoders + (method -> new ParamsDecoder(method)), payloadsEncoder = { case params: Params => paramsEncoder(params) case other => payloadsEncoder(other) } ) - /** - * Adds a new error code to this protocol. + /** Adds a new error code to this protocol. * @param error the error to add. * @return a new [[Protocol]], recognizing `error` code. */ diff --git a/lib/scala/json-rpc-server/src/test/scala/org/enso/jsonrpc/MessageHandlerSpec.scala b/lib/scala/json-rpc-server/src/test/scala/org/enso/jsonrpc/MessageHandlerSpec.scala index e3a63839e0..fbf833a174 100644 --- a/lib/scala/json-rpc-server/src/test/scala/org/enso/jsonrpc/MessageHandlerSpec.scala +++ b/lib/scala/json-rpc-server/src/test/scala/org/enso/jsonrpc/MessageHandlerSpec.scala @@ -92,11 +92,14 @@ class MessageHandlerSpec MyNotificationParams("test") ) - expectJson(out, json""" + expectJson( + out, + json""" { "jsonrpc": "2.0", "method": "NotificationMethod", "params": { "spam": "test" } - }""") + }""" + ) } "receive notifications" in { diff --git a/lib/scala/logging-service/src/main/java-unix/org/enso/loggingservice/internal/NativeAnsiTerm.java b/lib/scala/logging-service/src/main/java-unix/org/enso/loggingservice/internal/NativeAnsiTerm.java index 19f8167fc6..1faedf9115 100755 --- a/lib/scala/logging-service/src/main/java-unix/org/enso/loggingservice/internal/NativeAnsiTerm.java +++ b/lib/scala/logging-service/src/main/java-unix/org/enso/loggingservice/internal/NativeAnsiTerm.java @@ -2,18 +2,17 @@ package org.enso.loggingservice.internal; /** * Provides a stub for enabling VT console mode. - *

- * We assume that VT is supported by default on UNIX platforms, so this function is never actually - * used. It is defined just to provide binary compatibility with the Windows counterpart, so that - * the code that uses it only on Windows, compiles on all platforms. + * + *

We assume that VT is supported by default on UNIX platforms, so this function is never + * actually used. It is defined just to provide binary compatibility with the Windows counterpart, + * so that the code that uses it only on Windows, compiles on all platforms. */ public class NativeAnsiTerm { /** * Enables VT emulation within the connected console. - *

- * The UNIX variant does nothing, as we assume that VT is supported out of the box. + * + *

The UNIX variant does nothing, as we assume that VT is supported out of the box. */ - public static void enableVT() { - } + public static void enableVT() {} } diff --git a/lib/scala/logging-service/src/main/java-windows/org/enso/loggingservice/internal/NativeAnsiTerm.java b/lib/scala/logging-service/src/main/java-windows/org/enso/loggingservice/internal/NativeAnsiTerm.java index c0562f78bd..91f846f29b 100755 --- a/lib/scala/logging-service/src/main/java-windows/org/enso/loggingservice/internal/NativeAnsiTerm.java +++ b/lib/scala/logging-service/src/main/java-windows/org/enso/loggingservice/internal/NativeAnsiTerm.java @@ -5,15 +5,13 @@ import org.graalvm.nativeimage.c.function.CFunction; import org.graalvm.nativeimage.c.type.CIntPointer; import org.graalvm.word.PointerBase; -/** - * Provides access to the native WinApi calls that enable VT emulation in a connected console. - */ +/** Provides access to the native WinApi calls that enable VT emulation in a connected console. */ public class NativeAnsiTerm { /** * Returns a handle to a console connected to one of the standard streams. - *

- * Refer to: https://docs.microsoft.com/en-us/windows/console/getstdhandle + * + *

Refer to: https://docs.microsoft.com/en-us/windows/console/getstdhandle * * @param nStdHandle constant representing one of the standard streams * @return pointer to the console handle or null if it could not be accessed @@ -25,9 +23,10 @@ public class NativeAnsiTerm { * Returns current console mode. * * @param hConsoleHandle console handle from [[GetStdHandle]] - * @param lpMode pointer to an integer that will be set to the current mode on success + * @param lpMode pointer to an integer that will be set to the current mode on success * @return non-zero integer on success - * @see GetConsoleMode */ @CFunction private static native int GetConsoleMode(PointerBase hConsoleHandle, CIntPointer lpMode); @@ -36,19 +35,21 @@ public class NativeAnsiTerm { * Sets console mode. * * @param hConsoleHandle console handle from [[GetStdHandle]] - * @param dwMode mode to set + * @param dwMode mode to set * @return non-zero integer on success - * @see SetConsoleMode + * @see SetConsoleMode */ @CFunction private static native int SetConsoleMode(PointerBase hConsoleHandle, int dwMode); /** * Returns error code of last error. - *

- * Can be called if a function returns a zero exit code to get the error code. * - * @see GetLastError + *

Can be called if a function returns a zero exit code to get the error code. + * + * @see GetLastError */ @CFunction private static native int GetLastError(); @@ -58,22 +59,24 @@ public class NativeAnsiTerm { * * @see GetStdHandle */ - private final static int STD_ERROR_HANDLE = -12; + private static final int STD_ERROR_HANDLE = -12; /** * Constant that can be used as part of a console mode which indicates that the output stream * should handle VT escape codes. * - * @see SetConsoleMode - * @see Console - * Virtual Terminal Sequences + * @see SetConsoleMode + * @see Console + * Virtual Terminal Sequences */ - private final static int ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004; + private static final int ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004; /** * Enables VT emulation within the connected console. - *

- * May throw an exception if it is not possible to do so. Can only be called from native-image + * + *

May throw an exception if it is not possible to do so. Can only be called from native-image * targets. */ public static void enableVT() { @@ -81,24 +84,26 @@ public class NativeAnsiTerm { try { var handle = GetStdHandle(STD_ERROR_HANDLE); if (handle.isNull()) { - throw new RuntimeException("Failed to get console handle. " + - "Perhaps the console is not connected. " + - "Error code: " + GetLastError()); + throw new RuntimeException( + "Failed to get console handle. " + + "Perhaps the console is not connected. " + + "Error code: " + + GetLastError()); } if (GetConsoleMode(handle, modePtr) == 0) { - throw new RuntimeException("Failed to get console mode. " + - "Error code: " + GetLastError()); + throw new RuntimeException( + "Failed to get console mode. " + "Error code: " + GetLastError()); } - var alteredMode = - modePtr.read() | ENABLE_VIRTUAL_TERMINAL_PROCESSING; + var alteredMode = modePtr.read() | ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (SetConsoleMode(handle, alteredMode) == 0) { - throw new RuntimeException("Failed to set console mode. " + - "Perhaps the console does not support VT codes. " + - "Error code: " + GetLastError()); + throw new RuntimeException( + "Failed to set console mode. " + + "Perhaps the console does not support VT codes. " + + "Error code: " + + GetLastError()); } } finally { UnmanagedMemory.free(modePtr); } } - } diff --git a/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 129561e7b0..6082481c26 100644 --- a/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -5,17 +5,15 @@ import org.slf4j.ILoggerFactory; /** * Binds the logging service as an SLF4J backend. - *

- * The public interface of this class must conform to what is expected by an - * SLF4J backend. See slf4j-simple for reference. + * + *

The public interface of this class must conform to what is expected by an SLF4J backend. See + * slf4j-simple for reference. */ public class StaticLoggerBinder { - /** - * Should be in sync with `slf4jVersion` in `build.sbt`. - */ + /** Should be in sync with `slf4jVersion` in `build.sbt`. */ public static String REQUESTED_API_VERSION = "1.7.30"; - final private static StaticLoggerBinder singleton = new StaticLoggerBinder(); + private static final StaticLoggerBinder singleton = new StaticLoggerBinder(); public static StaticLoggerBinder getSingleton() { return singleton; diff --git a/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMDCBinder.java index a2824879c3..55f3e7c8b7 100644 --- a/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -5,16 +5,16 @@ import org.slf4j.spi.MDCAdapter; /** * Provides a no-op MDC adapter for the SLF4J backend. - *

- * MDC handling is an optional SLF4J feature and currently the logging service does not support it, - * so it provides a no-op adapter. - *

- * The public interface of this class must conform to what is expected by an SLF4J backend. See + * + *

MDC handling is an optional SLF4J feature and currently the logging service does not support + * it, so it provides a no-op adapter. + * + *

The public interface of this class must conform to what is expected by an SLF4J backend. See * slf4j-simple for reference. */ public class StaticMDCBinder { - final private static StaticMDCBinder singleton = new StaticMDCBinder(); + private static final StaticMDCBinder singleton = new StaticMDCBinder(); public static StaticMDCBinder getSingleton() { return singleton; diff --git a/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index e14a38cf95..b55cac48e6 100644 --- a/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/lib/scala/logging-service/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -5,21 +5,20 @@ import org.slf4j.helpers.BasicMarkerFactory; /** * Provides a simple marker factory for the SLF4J backend. - *

- * The public interface of this class must conform to what is expected by an SLF4J backend. See + * + *

The public interface of this class must conform to what is expected by an SLF4J backend. See * slf4j-simple for reference. */ public class StaticMarkerBinder { - final private static StaticMarkerBinder singleton = new StaticMarkerBinder(); + private static final StaticMarkerBinder singleton = new StaticMarkerBinder(); public static StaticMarkerBinder getSingleton() { return singleton; } private final IMarkerFactory markerFactory = new BasicMarkerFactory(); - private final String markerFactoryClassStr = - BasicMarkerFactory.class.getName(); + private final String markerFactoryClassStr = BasicMarkerFactory.class.getName(); public IMarkerFactory getMarkerFactory() { return markerFactory; diff --git a/lib/scala/logging-service/src/main/scala/org/enso/logger/package.scala b/lib/scala/logging-service/src/main/scala/org/enso/logger/package.scala index d3abafd025..a202e35b03 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/logger/package.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/logger/package.scala @@ -4,13 +4,11 @@ import com.typesafe.scalalogging.Logger package object logger { - /** - * Provides syntax for entering a sub-logger. + /** Provides syntax for entering a sub-logger. */ implicit class LoggerSyntax(logger: Logger) { - /** - * Returns another [[Logger]] with name extended with a sub context. + /** Returns another [[Logger]] with name extended with a sub context. */ def enter(subContextName: String): Logger = { val name = logger.underlying.getName + "." + subContextName diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/JavaLoggingLogHandler.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/JavaLoggingLogHandler.scala index 373c8c1a1f..d786240752 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/JavaLoggingLogHandler.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/JavaLoggingLogHandler.scala @@ -4,8 +4,7 @@ import java.util.logging.{Handler, Level, LogRecord} import org.enso.loggingservice.internal.{InternalLogMessage, LoggerConnection} -/** - * A [[Handler]] implementation that allows to use the logging service as a +/** A [[Handler]] implementation that allows to use the logging service as a * backend for [[java.util.logging]]. */ class JavaLoggingLogHandler( @@ -13,8 +12,7 @@ class JavaLoggingLogHandler( connection: LoggerConnection ) extends Handler { - /** - * @inheritdoc + /** @inheritdoc */ override def publish(record: LogRecord): Unit = { val level = levelMapping(record.getLevel) @@ -30,35 +28,30 @@ class JavaLoggingLogHandler( } } - /** - * @inheritdoc + /** @inheritdoc */ override def flush(): Unit = {} - /** - * @inheritdoc + /** @inheritdoc */ override def close(): Unit = {} } object JavaLoggingLogHandler { - /** - * Creates a [[Handler]] with the provided mapping from Java's log levels to + /** Creates a [[Handler]] with the provided mapping from Java's log levels to * our log levels. */ def create(mapping: Level => LogLevel): JavaLoggingLogHandler = new JavaLoggingLogHandler(mapping, LoggingServiceManager.Connection) - /** - * Determines what is the smallest Java level that is still debug and not + /** Determines what is the smallest Java level that is still debug and not * trace. */ private val defaultLevelDebugCutOff = Seq(Level.FINE.intValue, Level.CONFIG.intValue).min - /** - * Default mapping of Java log levels to our log levels based + /** Default mapping of Java log levels to our log levels based */ def defaultLevelMapping(javaLevel: Level): LogLevel = { val level = javaLevel.intValue @@ -70,8 +63,7 @@ object JavaLoggingLogHandler { else LogLevel.Trace } - /** - * Approximate-inverse of [[defaultLevelMapping]] that returns a Java log + /** Approximate-inverse of [[defaultLevelMapping]] that returns a Java log * level corresponding to the given log level. */ def getJavaLogLevelFor(logLevel: LogLevel): Level = diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LogLevel.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LogLevel.scala index d92f54794e..f5416fa602 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LogLevel.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LogLevel.scala @@ -3,13 +3,11 @@ package org.enso.loggingservice import io.circe.syntax._ import io.circe.{Decoder, DecodingFailure, Encoder} -/** - * Defines a log level for log messages. +/** Defines a log level for log messages. */ sealed abstract class LogLevel(final val level: Int) { - /** - * Determines if a component running on `this` log level should log the + /** Determines if a component running on `this` log level should log the * `other`. * * Log levels smaller or equal to component's log level are logged. @@ -19,40 +17,35 @@ sealed abstract class LogLevel(final val level: Int) { } object LogLevel { - /** - * This log level should not be used by messages, instead it can be set as + /** This log level should not be used by messages, instead it can be set as * component's log level to completely disable logging for it. */ case object Off extends LogLevel(-1) { override def toString: String = "off" } - /** - * Log level corresponding to severe errors, should be understandable to the + /** Log level corresponding to severe errors, should be understandable to the * end-user. */ case object Error extends LogLevel(0) { override def toString: String = "error" } - /** - * Log level corresponding to important notices or issues that are not + /** Log level corresponding to important notices or issues that are not * severe. */ case object Warning extends LogLevel(1) { override def toString: String = "warning" } - /** - * Log level corresponding to usual information of what the application is + /** Log level corresponding to usual information of what the application is * doing. */ case object Info extends LogLevel(2) { override def toString: String = "info" } - /** - * Log level used for debugging the application. + /** Log level used for debugging the application. * * The messages can be more complex and targeted at developers diagnosing the * application. @@ -61,16 +54,14 @@ object LogLevel { override def toString: String = "debug" } - /** - * Log level used for advanced debugging, may be used for more throughout + /** Log level used for advanced debugging, may be used for more throughout * diagnostics. */ case object Trace extends LogLevel(4) { override def toString: String = "trace" } - /** - * Lists all available log levels. + /** Lists all available log levels. * * Can be used for example to automate parsing. */ @@ -83,16 +74,14 @@ object LogLevel { LogLevel.Trace ) - /** - * [[Ordering]] instance for [[LogLevel]]. + /** [[Ordering]] instance for [[LogLevel]]. * * The log levels are ordered from most severe. If a log level is enabled, it * usually means that all levels smaller than it are enabled too. */ implicit val ord: Ordering[LogLevel] = (x, y) => x.level - y.level - /** - * [[Encoder]] instance for [[LogLevel]]. + /** [[Encoder]] instance for [[LogLevel]]. */ implicit val encoder: Encoder[LogLevel] = { case Off => @@ -104,8 +93,7 @@ object LogLevel { level.level.asJson } - /** - * [[Decoder]] instance for [[LogLevel]]. + /** [[Decoder]] instance for [[LogLevel]]. */ implicit val decoder: Decoder[LogLevel] = { json => json.as[Int].flatMap { diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/Logger.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/Logger.scala index b8068345ac..fa13b6729b 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/Logger.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/Logger.scala @@ -6,8 +6,7 @@ import org.slf4j.{Logger => SLF4JLogger, Marker} import scala.annotation.unused -/** - * A [[SLF4JLogger]] instance for the SLF4J backend which passes all log +/** A [[SLF4JLogger]] instance for the SLF4J backend which passes all log * messages to a [[LoggerConnection]]. * * @param name name of the logger diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerFactory.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerFactory.scala index 3acd5fa1a4..c096ed0609 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerFactory.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerFactory.scala @@ -2,13 +2,11 @@ package org.enso.loggingservice import org.slf4j.{ILoggerFactory, Logger => SLF4JLogger} -/** - * A [[ILoggerFactory]] instance for the SLF4J backend. +/** A [[ILoggerFactory]] instance for the SLF4J backend. */ class LoggerFactory extends ILoggerFactory { - /** - * @inheritdoc + /** @inheritdoc */ override def getLogger(name: String): SLF4JLogger = { loggers.getOrElseUpdate( diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerMode.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerMode.scala index 76e99e96cb..5d37f6fc22 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerMode.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggerMode.scala @@ -3,8 +3,7 @@ package org.enso.loggingservice import akka.http.scaladsl.model.Uri import org.enso.loggingservice.printers.Printer -/** - * Represents modes the logging service can be running in. +/** Represents modes the logging service can be running in. * * @tparam InitializationResult type that is returned when * [[LoggingServiceManager]] sets up the given @@ -13,15 +12,13 @@ import org.enso.loggingservice.printers.Printer sealed trait LoggerMode[InitializationResult] object LoggerMode { - /** - * Forwards log messages to a logging service server. + /** Forwards log messages to a logging service server. * * @param endpoint URI that is used to connect to the server via WebSockets */ case class Client(endpoint: Uri) extends LoggerMode[Unit] - /** - * Starts gathering messages from this and other components. + /** Starts gathering messages from this and other components. * * Its initialization returns a [[ServerBinding]] that can be used to connect * to the initialized server. @@ -39,8 +36,7 @@ object LoggerMode { interface: String = "localhost" ) extends LoggerMode[ServerBinding] - /** - * Processes log messages locally. + /** Processes log messages locally. * * @param printers a list of printers that process the incoming messages */ diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggingServiceManager.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggingServiceManager.scala index 7ee4610254..837160930f 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggingServiceManager.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/LoggingServiceManager.scala @@ -11,35 +11,30 @@ import org.enso.loggingservice.printers.{Printer, StderrPrinter} import scala.concurrent.Future -/** - * Manages the logging service. +/** Manages the logging service. */ object LoggingServiceManager { private val messageQueue = new BlockingConsumerMessageQueue() private var currentLevel: LogLevel = LogLevel.Trace - /** - * The default [[LoggerConnection]] that should be used by all backends which + /** The default [[LoggerConnection]] that should be used by all backends which * want to use the logging service. */ object Connection extends LoggerConnection { - /** - * @inheritdoc + /** @inheritdoc */ override def send(message: InternalLogMessage): Unit = messageQueue.send(Left(message)) - /** - * @inheritdoc + /** @inheritdoc */ override def logLevel: LogLevel = currentLevel } private var currentService: Option[Service] = None - /** - * Sets up the logging service, but in a separate thread to avoid stalling + /** Sets up the logging service, but in a separate thread to avoid stalling * the application. * * The returned [[InitializationResult]] depends on the mode. @@ -58,8 +53,7 @@ object LoggingServiceManager { Future(doSetup(mode, logLevel)) } - /** - * Shuts down the logging service if it was initialized or runs + /** Shuts down the logging service if it was initialized or runs * [[handlePendingMessages]] to handle logs that would be dropped due to the * logging service never being initialized. * @@ -85,8 +79,7 @@ object LoggingServiceManager { Runtime.getRuntime.addShutdownHook(new Thread(() => tearDown())) - /** - * Terminates the currently running logging service (if any) and replaces it + /** Terminates the currently running logging service (if any) and replaces it * with a fallback logging service. * * Can be used if the currently logging service fails after initialization @@ -110,16 +103,14 @@ object LoggingServiceManager { } } - /** - * Removes any pending logs (so that [[handlePendingMessages]] will not print + /** Removes any pending logs (so that [[handlePendingMessages]] will not print * them). * * An internal method that is only used by [[TestLogger]]. */ def dropPendingLogs(): Unit = messageQueue.drain(LogLevel.Off) - /** - * Prints any messages that have been buffered but have not been logged yet + /** Prints any messages that have been buffered but have not been logged yet * due to no loggers being active. */ private def handlePendingMessages(): Unit = { diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/TestLogger.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/TestLogger.scala index 732af4301f..a5146d53ad 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/TestLogger.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/TestLogger.scala @@ -2,20 +2,17 @@ package org.enso.loggingservice import org.enso.loggingservice.printers.TestPrinter -/** - * A helper object for handling logs in tests. +/** A helper object for handling logs in tests. */ object TestLogger { - /** - * A log message returned by [[gatherLogs]]. + /** A log message returned by [[gatherLogs]]. * * It contains the loglevel and message, but ignores attached exceptions. */ case class TestLogMessage(logLevel: LogLevel, message: String) - /** - * Gathers logs logged during execution of `action`. + /** Gathers logs logged during execution of `action`. * * This method should be used only inside of tests. Any tests using it should * be ran with `parallelExecution` set to false, as global logger state has @@ -34,8 +31,7 @@ object TestLogger { printer.getLoggedMessages } - /** - * Drops any logs that are pending due to the logging service not being set + /** Drops any logs that are pending due to the logging service not being set * up. * * This method should be used only inside of tests. Any tests using it should diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/ANSIColorsMessageRenderer.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/ANSIColorsMessageRenderer.scala index 2b86da4221..b0a1cf1041 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/ANSIColorsMessageRenderer.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/ANSIColorsMessageRenderer.scala @@ -3,15 +3,13 @@ import org.enso.loggingservice.LogLevel import scala.io.AnsiColor -/** - * Renders log messages in the same way as [[DefaultLogMessageRenderer]] but +/** Renders log messages in the same way as [[DefaultLogMessageRenderer]] but * adds ANSI escape codes to display the log level in color. */ class ANSIColorsMessageRenderer(printExceptions: Boolean) extends DefaultLogMessageRenderer(printExceptions) { - /** - * @inheritdoc + /** @inheritdoc */ override def renderLevel(logLevel: LogLevel): String = { val color = logLevel match { diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/AnsiTerminal.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/AnsiTerminal.scala index dc7fd40fc7..5282b0d9d2 100755 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/AnsiTerminal.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/AnsiTerminal.scala @@ -3,13 +3,11 @@ package org.enso.loggingservice.internal import com.typesafe.scalalogging.Logger import org.graalvm.nativeimage.ImageInfo -/** - * Handles VT-compatible color output in the terminal. +/** Handles VT-compatible color output in the terminal. */ object AnsiTerminal { - /** - * Tries enabling ANSI colors in terminal output and returns true if it + /** Tries enabling ANSI colors in terminal output and returns true if it * succeeded. * * We assume that ANSI colors are supported by default on UNIX platforms. On @@ -38,13 +36,11 @@ object AnsiTerminal { private def isWindows: Boolean = System.getProperty("os.name").toLowerCase.contains("win") - /** - * Checks if output of this program may be piped. + /** Checks if output of this program may be piped. */ def isLikelyPiped: Boolean = System.console() == null - /** - * Checks if the output is connected to a terminal that can handle color + /** Checks if the output is connected to a terminal that can handle color * output. * * On Windows, this function also enables color output, so any code that diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BaseLogMessage.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BaseLogMessage.scala index 5ad999b88f..a7e80040ef 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BaseLogMessage.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BaseLogMessage.scala @@ -4,8 +4,7 @@ import java.time.Instant import org.enso.loggingservice.LogLevel -/** - * A base type for log messages parametrized by the exception representation. +/** A base type for log messages parametrized by the exception representation. */ trait BaseLogMessage[ExceptionType] { def level: LogLevel diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BlockingConsumerMessageQueue.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BlockingConsumerMessageQueue.scala index fe6b11458e..1d0d2ee9ee 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BlockingConsumerMessageQueue.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/BlockingConsumerMessageQueue.scala @@ -7,14 +7,12 @@ import org.enso.loggingservice.internal.protocol.WSLogMessage import scala.annotation.tailrec -/** - * A message queue that can be consumed by a thread in a loop with a limited +/** A message queue that can be consumed by a thread in a loop with a limited * buffer. */ class BlockingConsumerMessageQueue(bufferSize: Int = 5000) { - /** - * Enqueues the `message` to be sent and returns immediately. + /** Enqueues the `message` to be sent and returns immediately. * * If any underlying buffers are full, they may be removed and a warning will * be issued. @@ -27,8 +25,7 @@ class BlockingConsumerMessageQueue(bufferSize: Int = 5000) { } } - /** - * Returns next message in the queue, skipping messages that should be + /** Returns next message in the queue, skipping messages that should be * ignored and waiting if no messages are currently available. * * The distinction between internal and external messages is that internal @@ -45,8 +42,7 @@ class BlockingConsumerMessageQueue(bufferSize: Int = 5000) { else nextMessage(internalLogLevel) } - /** - * Returns all currently enqueued messages, skipping ones that should be + /** Returns all currently enqueued messages, skipping ones that should be * ignored. * * See [[nextMessage]] for explanation which messages are ignored. @@ -62,8 +58,7 @@ class BlockingConsumerMessageQueue(bufferSize: Int = 5000) { .map(_._1) } - /** - * All external messages are relevant, but internal messages relevancy depends + /** All external messages are relevant, but internal messages relevancy depends * on its log level. */ private def isMessageRelevant( @@ -71,8 +66,7 @@ class BlockingConsumerMessageQueue(bufferSize: Int = 5000) { )(message: WSLogMessage, internal: Boolean): Boolean = !internal || internalLogLevel.shouldLog(message.level) - /** - * Returns the encoded message and a boolean value indicating if it was + /** Returns the encoded message and a boolean value indicating if it was * internal. */ private def encodeMessage( diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/DefaultLogMessageRenderer.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/DefaultLogMessageRenderer.scala index aef7ffaf78..ff3db53175 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/DefaultLogMessageRenderer.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/DefaultLogMessageRenderer.scala @@ -9,15 +9,13 @@ import org.enso.loggingservice.internal.protocol.{ WSLogMessage } -/** - * Renders the log message using the default format, including attached +/** Renders the log message using the default format, including attached * exceptions if [[printExceptions]] is set. */ class DefaultLogMessageRenderer(printExceptions: Boolean) extends LogMessageRenderer { - /** - * @inheritdoc + /** @inheritdoc */ override def render(logMessage: WSLogMessage): String = { val level = renderLevel(logMessage.level) @@ -29,16 +27,14 @@ class DefaultLogMessageRenderer(printExceptions: Boolean) private val timestampZone = ZoneOffset.UTC - /** - * Renders the timestamp. + /** Renders the timestamp. */ def renderTimestamp(timestamp: Instant): String = ZonedDateTime .ofInstant(timestamp, timestampZone) .format(DateTimeFormatter.ISO_ZONED_DATE_TIME) - /** - * Adds attached exception's stack trace (if available) to the log if + /** Adds attached exception's stack trace (if available) to the log if * printing stack traces is enabled. */ def addException( @@ -51,8 +47,7 @@ class DefaultLogMessageRenderer(printExceptions: Boolean) case _ => message } - /** - * Renders an exception with its strack trace. + /** Renders an exception with its strack trace. */ def renderException(exception: SerializedException): String = { val head = s"${exception.name}: ${exception.message}" @@ -65,8 +60,7 @@ class DefaultLogMessageRenderer(printExceptions: Boolean) head + trace.map("\n" + _).mkString + cause } - /** - * Renders a log level. + /** Renders a log level. */ def renderLevel(logLevel: LogLevel): String = logLevel match { diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogMessage.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogMessage.scala index 43326e6ed9..ae3083dcd7 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogMessage.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogMessage.scala @@ -9,8 +9,7 @@ import org.enso.loggingservice.internal.protocol.{ WSLogMessage } -/** - * The internal log message that is used for local logging. +/** The internal log message that is used for local logging. * * @param level log level * @param timestamp timestamp indicating when the message was created @@ -26,8 +25,7 @@ case class InternalLogMessage( exception: Option[Throwable] ) extends BaseLogMessage[Throwable] { - /** - * Converts to [[WSLogMessage]] by serializing the attached exception. + /** Converts to [[WSLogMessage]] by serializing the attached exception. */ def toLogMessage: WSLogMessage = WSLogMessage( @@ -41,8 +39,7 @@ case class InternalLogMessage( object InternalLogMessage { - /** - * Creates a log message with the timestamp set to the current instant. + /** Creates a log message with the timestamp set to the current instant. */ def apply( level: LogLevel, diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogger.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogger.scala index 4ebd02bb85..d3d3f5fe7f 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogger.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/InternalLogger.scala @@ -1,7 +1,6 @@ package org.enso.loggingservice.internal -/** - * An internal logger used for reporting errors within the logging service +/** An internal logger used for reporting errors within the logging service * itself. * * As the logging service cannot be used to report its own errors (because a @@ -10,8 +9,7 @@ package org.enso.loggingservice.internal */ object InternalLogger { - /** - * Reports an internal logging service error with the given message. + /** Reports an internal logging service error with the given message. */ def error(message: String): Unit = { System.err.println(s"[internal-logger-error] $message") diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LogMessageRenderer.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LogMessageRenderer.scala index a761470a76..f67692e19c 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LogMessageRenderer.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LogMessageRenderer.scala @@ -2,13 +2,11 @@ package org.enso.loggingservice.internal import org.enso.loggingservice.internal.protocol.WSLogMessage -/** - * Specifies a strategy of rendering log messages to string. +/** Specifies a strategy of rendering log messages to string. */ trait LogMessageRenderer { - /** - * Creates a string representation of the log message that can be written to + /** Creates a string representation of the log message that can be written to * an output. */ def render(logMessage: WSLogMessage): String diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LoggerConnection.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LoggerConnection.scala index 6e0e57c14b..734fee52ac 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LoggerConnection.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/LoggerConnection.scala @@ -2,13 +2,11 @@ package org.enso.loggingservice.internal import org.enso.loggingservice.LogLevel -/** - * An interface that allows to send log messages to the logging service. +/** An interface that allows to send log messages to the logging service. */ trait LoggerConnection { - /** - * Sends a message to the logging service. + /** Sends a message to the logging service. * * It should return immediately. Sending a message usually means that it is * enqueued and will be encoded and sent to the logging service soon, but it @@ -17,16 +15,14 @@ trait LoggerConnection { */ def send(message: InternalLogMessage): Unit - /** - * Current log level. + /** Current log level. * * Only messages that have equal or smaller log level should be sent. Other * messages will be ignored. */ def logLevel: LogLevel - /** - * Tells if messages with the provided log level should be sent. + /** Tells if messages with the provided log level should be sent. */ def isEnabled(level: LogLevel): Boolean = implicitly[Ordering[LogLevel]].lteq(level, logLevel) diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/SerializedException.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/SerializedException.scala index 627f3af005..c21fbf958c 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/SerializedException.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/SerializedException.scala @@ -3,8 +3,7 @@ package org.enso.loggingservice.internal.protocol import io.circe.syntax._ import io.circe._ -/** - * Represents a language-agnostic exception that can be sent over the WebSocket +/** Represents a language-agnostic exception that can be sent over the WebSocket * connection. * * @param name name of the exception, corresponds to the qualified class name @@ -24,8 +23,7 @@ case class SerializedException( object SerializedException { - /** - * Creates a [[SerializedException]] with a cause. + /** Creates a [[SerializedException]] with a cause. */ def apply( name: String, @@ -40,8 +38,7 @@ object SerializedException { cause = Some(cause) ) - /** - * Creates a [[SerializedException]] without a cause. + /** Creates a [[SerializedException]] without a cause. */ def apply( name: String, @@ -55,14 +52,12 @@ object SerializedException { cause = None ) - /** - * Creates a [[SerializedException]] from a [[Throwable]]. + /** Creates a [[SerializedException]] from a [[Throwable]]. */ def apply(throwable: Throwable): SerializedException = fromException(throwable) - /** - * Encodes a JVM [[Throwable]] as [[SerializedException]]. + /** Encodes a JVM [[Throwable]] as [[SerializedException]]. */ def fromException(throwable: Throwable): SerializedException = { val clazz = throwable.getClass @@ -77,8 +72,7 @@ object SerializedException { ) } - /** - * Regular expression used to parse the stack trace elements format used by + /** Regular expression used to parse the stack trace elements format used by * [[StackTraceElement#toString]]. * * It assumes that the stack trace element has form `element(location)`, for @@ -91,8 +85,7 @@ object SerializedException { */ private val stackTraceRegex = "(.*)\\((.*)\\)".r - /** - * Encodes a [[StackTraceElement]] as [[TraceElement]]. + /** Encodes a [[StackTraceElement]] as [[TraceElement]]. */ private def encodeStackTraceElement( stackTraceElement: StackTraceElement @@ -116,8 +109,7 @@ object SerializedException { } } - /** - * Represents an element of a stack trace attached to the + /** Represents an element of a stack trace attached to the * [[SerializedException]]. * * @param element name of the stack location; for example, in Java this is @@ -138,13 +130,11 @@ object SerializedException { } } - /** - * [[Encoder]] instance for [[SerializedException]]. + /** [[Encoder]] instance for [[SerializedException]]. */ implicit val encoder: Encoder[SerializedException] = encodeException - /** - * Encodes a [[SerializedException]] as its JSON representation. + /** Encodes a [[SerializedException]] as its JSON representation. */ private def encodeException(exception: SerializedException): Json = { val base = JsonObject( @@ -163,13 +153,11 @@ object SerializedException { result.asJson } - /** - * [[Decoder]] instance for [[SerializedException]]. + /** [[Decoder]] instance for [[SerializedException]]. */ implicit def decoder: Decoder[SerializedException] = decodeException - /** - * Tries to decode a [[SerializedException]] from its JSON representation. + /** Tries to decode a [[SerializedException]] from its JSON representation. */ private def decodeException( json: HCursor @@ -188,8 +176,7 @@ object SerializedException { ) } - /** - * [[Encoder]] instance for [[TraceElement]]. + /** [[Encoder]] instance for [[TraceElement]]. */ implicit val traceEncoder: Encoder[TraceElement] = { traceElement => Json.obj( @@ -198,8 +185,7 @@ object SerializedException { ) } - /** - * [[Decoder]] instance for [[TraceElement]]. + /** [[Decoder]] instance for [[TraceElement]]. */ implicit val traceDecoder: Decoder[TraceElement] = { json => for { diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/WSLogMessage.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/WSLogMessage.scala index 8274b8c600..0360e4d1ea 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/WSLogMessage.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/protocol/WSLogMessage.scala @@ -7,8 +7,7 @@ import io.circe.{Decoder, Encoder, JsonObject} import org.enso.loggingservice.LogLevel import org.enso.loggingservice.internal.BaseLogMessage -/** - * The encoded log message that can be sent over the WebSocket connection or +/** The encoded log message that can be sent over the WebSocket connection or * passed to a printer. * * @param level log level @@ -34,8 +33,7 @@ object WSLogMessage { val Exception = "exception" } - /** - * [[Encoder]] instance for [[WSLogMessage]]. + /** [[Encoder]] instance for [[WSLogMessage]]. */ implicit val encoder: Encoder[WSLogMessage] = { message => val base = JsonObject( @@ -55,8 +53,7 @@ object WSLogMessage { result.asJson } - /** - * [[Decoder]] instance for [[WSLogMessage]]. + /** [[Decoder]] instance for [[WSLogMessage]]. */ implicit val decoder: Decoder[WSLogMessage] = { json => for { diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Client.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Client.scala index 761228907e..b7ed6547a9 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Client.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Client.scala @@ -17,8 +17,7 @@ import org.enso.loggingservice.{LogLevel, LoggingServiceManager} import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, Future} -/** - * A client [[Service]] that passes incoming log messages to a server. +/** A client [[Service]] that passes incoming log messages to a server. * * @param serverUri uri of the server to connect to * @param queue log message queue @@ -31,13 +30,11 @@ class Client( ) extends ThreadProcessingService with ServiceWithActorSystem { - /** - * @inheritdoc + /** @inheritdoc */ override protected def actorSystemName: String = "logging-service-client" - /** - * Starts the client service by trying to connect to the server. + /** Starts the client service by trying to connect to the server. * * Returns a future that is completed once the connection has been * established. @@ -75,8 +72,7 @@ class Client( private var webSocketQueue: Option[SourceQueueWithComplete[Message]] = None private var closedConnection: Option[Future[Done]] = None - /** - * Tries to send the log message to the server by appending it to the queue + /** Tries to send the log message to the server by appending it to the queue * of outgoing messages. * * It waits for the offer to complete for a long time to handle the case in @@ -112,8 +108,7 @@ class Client( @volatile private var shuttingDown: Boolean = false - /** - * If the remote server closes the connection, notifies the logging service + /** If the remote server closes the connection, notifies the logging service * to start the fallback logger. */ private def onDisconnected(): Unit = { @@ -125,8 +120,7 @@ class Client( } } - /** - * Closes the connection. + /** Closes the connection. */ override protected def terminateUser(): Future[_] = { shuttingDown = true @@ -142,8 +136,7 @@ class Client( } } - /** - * No additional actions are performed after the thread has been shut down as + /** No additional actions are performed after the thread has been shut down as * termination happens in [[terminateUser()]]. */ override protected def afterShutdown(): Unit = {} @@ -151,8 +144,7 @@ class Client( object Client { - /** - * Waits for the [[Client]] to start up and returns it or throws an exception + /** Waits for the [[Client]] to start up and returns it or throws an exception * on setup failure. * * @param serverUri uri of the server to connect to diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Local.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Local.scala index 819eb79e0d..66bbe50299 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Local.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Local.scala @@ -5,8 +5,7 @@ import org.enso.loggingservice.internal.BlockingConsumerMessageQueue import org.enso.loggingservice.internal.protocol.WSLogMessage import org.enso.loggingservice.printers.Printer -/** - * A local [[Service]] that handles all log messages locally. +/** A local [[Service]] that handles all log messages locally. * * @param logLevel log level used to filter messages * @param queue log message queue @@ -18,14 +17,12 @@ case class Local( printers: Seq[Printer] ) extends ThreadProcessingService { - /** - * Passes each message to all printers. + /** Passes each message to all printers. */ override protected def processMessage(message: WSLogMessage): Unit = printers.foreach(_.print(message)) - /** - * Shuts down the printers. + /** Shuts down the printers. */ override protected def afterShutdown(): Unit = { printers.foreach(_.shutdown()) @@ -34,8 +31,7 @@ case class Local( object Local { - /** - * Starts the [[Local]] service and returns it. + /** Starts the [[Local]] service and returns it. * * @param logLevel log level used to filter messages * @param queue log message queue diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Server.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Server.scala index 3fe6730c64..5d31ace323 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Server.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Server.scala @@ -23,8 +23,7 @@ import scala.annotation.nowarn import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, Future} -/** - * A server [[Service]] which handles both messages incoming from a WebSocket +/** A server [[Service]] which handles both messages incoming from a WebSocket * connection and local log messages. * * @param interface interface to bind to @@ -45,13 +44,11 @@ class Server( ) extends Local(logLevel, queue, printers) with ServiceWithActorSystem { - /** - * @inheritdoc + /** @inheritdoc */ override protected def actorSystemName: String = "logging-service-server" - /** - * Immediately starts processing local messages and returns a [[Future]] that + /** Immediately starts processing local messages and returns a [[Future]] that * will complete once the server has been started. */ def start(): Future[Unit] = { @@ -59,8 +56,7 @@ class Server( startWebSocketServer() } - /** - * Starts the WebSocket server. + /** Starts the WebSocket server. */ private def startWebSocketServer(): Future[Unit] = { val requestHandler: HttpRequest => HttpResponse = { @@ -92,8 +88,7 @@ class Server( } } - /** - * Returns the binding that describes how to connect to the started server. + /** Returns the binding that describes how to connect to the started server. * * This method can only be called after the future returned from [[start]] * has completed. @@ -110,8 +105,7 @@ class Server( private var bindingOption: Option[Http.ServerBinding] = None - /** - * Creates a separate message processor for each connection. + /** Creates a separate message processor for each connection. * * Each connection will only report the first invalid message, all further * invalid messages are silently ignored. @@ -143,8 +137,7 @@ class Server( private def decodeMessage(message: String): Either[Error, WSLogMessage] = parser.parse(message).flatMap(_.as[WSLogMessage]) - /** - * Shuts down the server. + /** Shuts down the server. */ override protected def terminateUser(): Future[_] = { bindingOption match { @@ -157,8 +150,7 @@ class Server( object Server { - /** - * Waits for the [[Server]] to start up and returns it or throws an exception + /** Waits for the [[Server]] to start up and returns it or throws an exception * on setup failure. * * @param interface interface to bind to diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Service.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Service.scala index 363d7ebf9d..d7298521d9 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Service.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/Service.scala @@ -1,12 +1,10 @@ package org.enso.loggingservice.internal.service -/** - * A service backend that is used to process incoming log messages. +/** A service backend that is used to process incoming log messages. */ trait Service { - /** - * Terminates the service and releases its resources. + /** Terminates the service and releases its resources. */ def terminate(): Unit = {} } diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ServiceWithActorSystem.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ServiceWithActorSystem.scala index 34c1a3f002..99dedc64f0 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ServiceWithActorSystem.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ServiceWithActorSystem.scala @@ -7,24 +7,20 @@ import org.enso.loggingservice.internal.InternalLogger import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, Future} -/** - * A mix-in for implementing services that use an Akka [[ActorSystem]]. +/** A mix-in for implementing services that use an Akka [[ActorSystem]]. */ trait ServiceWithActorSystem extends Service { - /** - * Name to use for the [[ActorSystem]]. + /** Name to use for the [[ActorSystem]]. */ protected def actorSystemName: String - /** - * The [[ActorSystem]] that can be used by the service. + /** The [[ActorSystem]] that can be used by the service. */ implicit protected val actorSystem: ActorSystem = initializeActorSystemForLoggingService(actorSystemName) - /** - * Initializes an [[ActorSystem]], overriding the default logging settings. + /** Initializes an [[ActorSystem]], overriding the default logging settings. * * The Actor System responsible for the logging service cannot use the * default configured logger, because this logger is likely to be the one @@ -59,8 +55,7 @@ trait ServiceWithActorSystem extends Service { ) } - /** - * Called before terminating the [[ActorSystem]], can be used to handle any + /** Called before terminating the [[ActorSystem]], can be used to handle any * actions that should happen before it is terminated. * * The actor system will wait with its termination until the returned future @@ -68,8 +63,7 @@ trait ServiceWithActorSystem extends Service { */ protected def terminateUser(): Future[_] - /** - * Waits for up to 3 seconds for the [[terminateUser]] and [[ActorSystem]] + /** Waits for up to 3 seconds for the [[terminateUser]] and [[ActorSystem]] * termination, then handles any other termination logic. */ abstract override def terminate(): Unit = { diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ThreadProcessingService.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ThreadProcessingService.scala index 6c8e2c330e..8ebaff9a22 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ThreadProcessingService.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/internal/service/ThreadProcessingService.scala @@ -9,41 +9,35 @@ import org.enso.loggingservice.internal.protocol.WSLogMessage import scala.util.control.NonFatal -/** - * A mix-in for implementing services that process messages from a +/** A mix-in for implementing services that process messages from a * [[BlockingConsumerMessageQueue]] in a separate thread. */ trait ThreadProcessingService extends Service { - /** - * The queue that is the source of messages. + /** The queue that is the source of messages. */ protected def queue: BlockingConsumerMessageQueue - /** - * Log level used for filtering messages from the queue. + /** Log level used for filtering messages from the queue. * @return */ protected def logLevel: LogLevel - /** - * Logic responsible for processing each message from [[queue]]. + /** Logic responsible for processing each message from [[queue]]. * * This function is guaranteed to be called synchronously from a single * thread. */ protected def processMessage(message: WSLogMessage): Unit - /** - * Called after the message processing thread has been stopped, can be used + /** Called after the message processing thread has been stopped, can be used * to finish termination. */ protected def afterShutdown(): Unit private var queueThread: Option[Thread] = None - /** - * Starts the thread processing messages from [[queue]]. + /** Starts the thread processing messages from [[queue]]. */ protected def startQueueProcessor(): Unit = { if (queueThread.isDefined) { @@ -57,8 +51,7 @@ trait ThreadProcessingService extends Service { thread.start() } - /** - * The runner filters out internal messages that have disabled log levels, + /** The runner filters out internal messages that have disabled log levels, * but passes through all external messages (as their log level is set * independently and can be lower). */ @@ -80,8 +73,7 @@ trait ThreadProcessingService extends Service { } } - /** - * @inheritdoc + /** @inheritdoc */ abstract override def terminate(): Unit = { super.terminate() diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/FileOutputPrinter.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/FileOutputPrinter.scala index 6d5df59630..a3219559c1 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/FileOutputPrinter.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/FileOutputPrinter.scala @@ -8,8 +8,7 @@ import java.time.{Instant, LocalDateTime, ZoneId} import org.enso.loggingservice.internal.DefaultLogMessageRenderer import org.enso.loggingservice.internal.protocol.WSLogMessage -/** - * Creates a new file in [[logDirectory]] and writes incoming log messages to +/** Creates a new file in [[logDirectory]] and writes incoming log messages to * this file. * * @param logDirectory the directory to create the logfile in @@ -22,24 +21,21 @@ class FileOutputPrinter(logDirectory: Path, printExceptions: Boolean) private val renderer = new DefaultLogMessageRenderer(printExceptions) private val writer = initializeWriter() - /** - * @inheritdoc + /** @inheritdoc */ override def print(message: WSLogMessage): Unit = { val lines = renderer.render(message) writer.println(lines) } - /** - * @inheritdoc + /** @inheritdoc */ override def shutdown(): Unit = { writer.flush() writer.close() } - /** - * Opens the log file for writing. + /** Opens the log file for writing. */ private def initializeWriter(): PrintWriter = { val logPath = logDirectory.resolve(makeLogFilename()) @@ -53,8 +49,7 @@ class FileOutputPrinter(logDirectory: Path, printExceptions: Boolean) ) } - /** - * Creates a log filename that is created based on the current timestamp. + /** Creates a log filename that is created based on the current timestamp. */ private def makeLogFilename(): String = { val timestampZone = ZoneId.of("UTC") @@ -67,8 +62,7 @@ class FileOutputPrinter(logDirectory: Path, printExceptions: Boolean) object FileOutputPrinter { - /** - * Creates a new [[FileOutputPrinter]]. + /** Creates a new [[FileOutputPrinter]]. */ def create( logDirectory: Path, diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/Printer.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/Printer.scala index b5460fc9ed..f8b8857d01 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/Printer.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/Printer.scala @@ -2,20 +2,17 @@ package org.enso.loggingservice.printers import org.enso.loggingservice.internal.protocol.WSLogMessage -/** - * Defines a strategy for outputting the log messages. +/** Defines a strategy for outputting the log messages. * * It can output them to the console, a file, a database etc. */ trait Printer { - /** - * Outputs the log message. + /** Outputs the log message. */ def print(message: WSLogMessage): Unit - /** - * Shuts down this output channel. + /** Shuts down this output channel. * * It should flush any buffers and release resources. */ diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinter.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinter.scala index 9873335c70..bc86b02ea1 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinter.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinter.scala @@ -3,24 +3,21 @@ package org.enso.loggingservice.printers import org.enso.loggingservice.internal.DefaultLogMessageRenderer import org.enso.loggingservice.internal.protocol.WSLogMessage -/** - * Prints the log messages to the standard error output. +/** Prints the log messages to the standard error output. * * @param printExceptions specifies if attached exceptions should be printed */ class StderrPrinter(printExceptions: Boolean) extends Printer { private val renderer = new DefaultLogMessageRenderer(printExceptions) - /** - * @inheritdoc + /** @inheritdoc */ override def print(logMessage: WSLogMessage): Unit = { val lines = renderer.render(logMessage) System.err.println(lines) } - /** - * @inheritdoc + /** @inheritdoc */ override def shutdown(): Unit = System.err.flush() @@ -28,8 +25,7 @@ class StderrPrinter(printExceptions: Boolean) extends Printer { object StderrPrinter { - /** - * Creates an instance of [[StderrPrinter]]. + /** Creates an instance of [[StderrPrinter]]. */ def create(printExceptions: Boolean = false): StderrPrinter = new StderrPrinter(printExceptions) diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinterWithColors.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinterWithColors.scala index 02941c798e..5d36427c90 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinterWithColors.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/StderrPrinterWithColors.scala @@ -8,8 +8,7 @@ import org.enso.loggingservice.internal.protocol.WSLogMessage import scala.io.AnsiColor -/** - * Prints the log messages to the standard error output with ANSI escape codes +/** Prints the log messages to the standard error output with ANSI escape codes * that allow to display log levels in color. * * @param printExceptions specifies if attached exceptions should be printed @@ -18,16 +17,14 @@ class StderrPrinterWithColors private (printExceptions: Boolean) extends Printer { private val renderer = new ANSIColorsMessageRenderer(printExceptions) - /** - * @inheritdoc + /** @inheritdoc */ override def print(message: WSLogMessage): Unit = { val lines = renderer.render(message) System.err.println(lines) } - /** - * @inheritdoc + /** @inheritdoc */ override def shutdown(): Unit = { System.err.print(AnsiColor.RESET) @@ -37,8 +34,7 @@ class StderrPrinterWithColors private (printExceptions: Boolean) object StderrPrinterWithColors { - /** - * Returns a color-supporting printer if color output is available in the + /** Returns a color-supporting printer if color output is available in the * console. */ def colorPrinterIfAvailable(printExceptions: Boolean): Printer = @@ -46,8 +42,7 @@ object StderrPrinterWithColors { new StderrPrinterWithColors(printExceptions) else new StderrPrinter(printExceptions) - /** - * Returns a color-supporting printer regardless of if color output is + /** Returns a color-supporting printer regardless of if color output is * available. * * Color output may be used even if it is unavailable in cases where the diff --git a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/TestPrinter.scala b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/TestPrinter.scala index fc8604aeb4..303f9d598f 100644 --- a/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/TestPrinter.scala +++ b/lib/scala/logging-service/src/main/scala/org/enso/loggingservice/printers/TestPrinter.scala @@ -3,16 +3,14 @@ package org.enso.loggingservice.printers import org.enso.loggingservice.TestLogger.TestLogMessage import org.enso.loggingservice.internal.protocol.WSLogMessage -/** - * A [[Printer]] instance that may be used in tests to gather reported log +/** A [[Printer]] instance that may be used in tests to gather reported log * messages. */ class TestPrinter extends Printer { private val messages = scala.collection.mutable.ListBuffer.empty[TestLogMessage] - /** - * @inheritdoc + /** @inheritdoc */ override def print(message: WSLogMessage): Unit = { val testMessage = @@ -24,20 +22,17 @@ class TestPrinter extends Printer { @volatile private var alreadyShutdown = false - /** - * @inheritdoc + /** @inheritdoc */ def shutdown(): Unit = { alreadyShutdown = true } - /** - * Reports if [[shutdown]] has been called. + /** Reports if [[shutdown]] has been called. */ def wasShutdown: Boolean = alreadyShutdown - /** - * Returns all log messages that have been gathered so far. + /** Returns all log messages that have been gathered so far. */ def getLoggedMessages: Seq[TestLogMessage] = messages.toSeq } diff --git a/lib/scala/parser/src/main/scala/org/enso/parser/Parser.scala b/lib/scala/parser/src/main/scala/org/enso/parser/Parser.scala index d2eaa2cddb..6894298e69 100644 --- a/lib/scala/parser/src/main/scala/org/enso/parser/Parser.scala +++ b/lib/scala/parser/src/main/scala/org/enso/parser/Parser.scala @@ -4,7 +4,6 @@ import org.enso.ast.Ast import scala.annotation.unused - /** This is the Enso language parser. * * It is a wrapper of parser written in Rust that uses JNI to efficiently @@ -20,16 +19,17 @@ import scala.annotation.unused * is going to fail at runtime with `UnsatisfiedLinkingError`. */ class Parser private () { - /** Parses a content of a single source file. */ + + /** Parses a content of a single source file. */ @native def parseStr(@unused input: String): Ast.AnyAst - /** Parses a single source file. */ + /** Parses a single source file. */ @native def parseFile(@unused filename: String): Ast.AnyAst - /** Parses a content of a single source file into a stream of tokens. */ + /** Parses a content of a single source file into a stream of tokens. */ @native def lexStr(@unused input: String): Ast.AnyAst - /** Parses a single source file into a stream of tokens. */ + /** Parses a single source file into a stream of tokens. */ @native def lexFile(@unused filename: String): Ast.AnyAst } diff --git a/lib/scala/parser/src/test/scala/org/enso/parser/ParserTest.scala b/lib/scala/parser/src/test/scala/org/enso/parser/ParserTest.scala index 9474362b74..294b574790 100644 --- a/lib/scala/parser/src/test/scala/org/enso/parser/ParserTest.scala +++ b/lib/scala/parser/src/test/scala/org/enso/parser/ParserTest.scala @@ -5,13 +5,12 @@ import org.enso.ast.Ast import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers - - class ParserTest extends AnyFlatSpec with Matchers { val parser: Parser = Parser() it should "parse file" in { - val expected = Ast.Ast(uid=None, len=0, off=0, ast=Ast.Txt.Text("Hello!")) + val expected = + Ast.Ast(uid = None, len = 0, off = 0, ast = Ast.Txt.Text("Hello!")) assert(expected == parser.parseStr("Hello!")) assert(expected == parser.parseFile("Hello!")) assert(expected == parser.lexStr("Hello!")) diff --git a/lib/scala/pkg/src/main/scala/org/enso/filesystem/FileSystem.scala b/lib/scala/pkg/src/main/scala/org/enso/filesystem/FileSystem.scala index 5d98411faa..bbace3d730 100644 --- a/lib/scala/pkg/src/main/scala/org/enso/filesystem/FileSystem.scala +++ b/lib/scala/pkg/src/main/scala/org/enso/filesystem/FileSystem.scala @@ -5,16 +5,14 @@ import java.io.{BufferedReader, BufferedWriter, File, IOException} import java.nio.file.Files import java.util.stream -/** - * A generic specification of file operations based on an abstract notion +/** A generic specification of file operations based on an abstract notion * of a path. * * @tparam F the path type of this implementation. */ trait FileSystem[F] { - /** - * Gets a child path of the given path. + /** Gets a child path of the given path. * * @param parent the parent path. * @param childName the child name. @@ -22,32 +20,28 @@ trait FileSystem[F] { */ def getChild(parent: F, childName: String): F - /** - * Gets a parent of the given path. + /** Gets a parent of the given path. * * @param path the path to process. * @return `path`'s parent. */ def getParent(path: F): F - /** - * Checks if a file specified by given path actually exists. + /** Checks if a file specified by given path actually exists. * * @param file the path to check. * @return `true` if file exists, `false` otherwise. */ def exists(file: F): Boolean - /** - * Creates a new directory and all non-existent parent directories. + /** Creates a new directory and all non-existent parent directories. * * @param file the directory to create. */ @throws[IOException] def createDirectories(file: F): Unit - /** - * Returns a relative path from `parent` to `child` + /** Returns a relative path from `parent` to `child` * * @param parent the parent dir. * @param child the child dir. @@ -55,24 +49,21 @@ trait FileSystem[F] { */ def relativize(parent: F, child: F): F - /** - * Returns a collection of all segments of the given path. + /** Returns a collection of all segments of the given path. * * @param file the path to get segments of. * @return the `file`'s segments. */ def getSegments(file: F): java.lang.Iterable[String] - /** - * Gets the name of the given file. + /** Gets the name of the given file. * * @param file * @return */ def getName(file: F): String - /** - * Creates a new buffered writer for the given file. + /** Creates a new buffered writer for the given file. * * @param file the file to open. * @return a buffered writer for `file`. @@ -80,8 +71,7 @@ trait FileSystem[F] { @throws[IOException] def newBufferedWriter(file: F): BufferedWriter - /** - * Creates a new buffered reader for the given file. + /** Creates a new buffered reader for the given file. * * @param file the file to open. * @return a buffered reader for `file`. @@ -89,8 +79,7 @@ trait FileSystem[F] { @throws[IOException] def newBufferedReader(file: F): BufferedReader - /** - * Lists all entries in the given directory. + /** Lists all entries in the given directory. * * @param file the directory to list. * @return a collection of all entries in `file`. @@ -98,8 +87,7 @@ trait FileSystem[F] { @throws[IOException] def list(file: F): java.util.stream.Stream[F] - /** - * Lists all files in the given directory, recursively. + /** Lists all files in the given directory, recursively. * * @param file the directory to traverse. * @return all files in the `file`'s subtree. @@ -107,16 +95,14 @@ trait FileSystem[F] { @throws[IOException] def walk(file: F): java.util.stream.Stream[F] - /** - * Checks if the file is a directory. + /** Checks if the file is a directory. * * @param file the file to check. * @return `true` if `file` is a directory, false otherwise. */ def isDirectory(file: F): Boolean - /** - * Checks if the file is a regular file. + /** Checks if the file is a regular file. * * @param file the file to check. * @return `true` if `file` is regular, false otherwise. @@ -127,8 +113,7 @@ trait FileSystem[F] { object FileSystem { - /** - * Exposes [[FileSystem]] operations through method call syntax. + /** Exposes [[FileSystem]] operations through method call syntax. * All methods have the same semantics as the corresponding [[FileSystem]] * methods. */ @@ -160,8 +145,7 @@ object FileSystem { def isRegularFile: Boolean = fs.isRegularFile(file) } - /** - * A [[File]] based implementation of [[FileSystem]]. + /** A [[File]] based implementation of [[FileSystem]]. */ object Default extends FileSystem[File] { override def getChild(parent: File, childName: String): File = diff --git a/lib/scala/pkg/src/main/scala/org/enso/home/HomeManager.scala b/lib/scala/pkg/src/main/scala/org/enso/home/HomeManager.scala index d1cc384b3f..ff8b054f96 100644 --- a/lib/scala/pkg/src/main/scala/org/enso/home/HomeManager.scala +++ b/lib/scala/pkg/src/main/scala/org/enso/home/HomeManager.scala @@ -4,8 +4,7 @@ import org.enso.filesystem.FileSystem import org.enso.pkg.{Package, PackageManager} import java.util.stream.Stream -/** - * Helper class for accessing files in the language home directory. +/** Helper class for accessing files in the language home directory. * * @param languageHomePath path to language home `component` directory. * @param fs file system to use in this object's operations. @@ -19,8 +18,7 @@ class HomeManager[F](languageHomePath: F, implicit val fs: FileSystem[F]) { val rootPath: F = languageHomePath.getParent val libPath: F = rootPath.getChild("std-lib") - /** - * @return a stream of packages found in the `std-lib` home directory. + /** @return a stream of packages found in the `std-lib` home directory. */ def loadStdLib: Stream[Package[F]] = { if (libPath.exists) diff --git a/lib/scala/pkg/src/main/scala/org/enso/pkg/Config.scala b/lib/scala/pkg/src/main/scala/org/enso/pkg/Config.scala index 98f500ae5d..39c7ee8904 100644 --- a/lib/scala/pkg/src/main/scala/org/enso/pkg/Config.scala +++ b/lib/scala/pkg/src/main/scala/org/enso/pkg/Config.scala @@ -7,15 +7,13 @@ import io.circe.yaml.Printer import scala.util.Try -/** - * An extra project dependency. +/** An extra project dependency. * @param name name of the package * @param version package version */ case class Dependency(name: String, version: String) -/** - * Contact information to a user. +/** Contact information to a user. * * Used for defining authors and maintainers. * At least one of the fields must not be None. @@ -28,8 +26,7 @@ case class Contact(name: Option[String], email: Option[String]) { "At least one of fields `name` or `email` must be defined." ) - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = { val space = if (name.isDefined && email.isDefined) " " else "" @@ -38,16 +35,14 @@ case class Contact(name: Option[String], email: Option[String]) { } object Contact { - /** - * Fields for use when serializing the [[Contact]]. + /** Fields for use when serializing the [[Contact]]. */ object Fields { val Name = "name" val Email = "email" } - /** - * [[Encoder]] instance for the [[Contact]]. + /** [[Encoder]] instance for the [[Contact]]. */ implicit val encoder: Encoder[Contact] = { contact => val name = contact.name.map(Fields.Name -> _.asJson) @@ -55,8 +50,7 @@ object Contact { Json.obj((name.toSeq ++ email.toSeq): _*) } - /** - * [[Decoder]] instance for the [[Contact]]. + /** [[Decoder]] instance for the [[Contact]]. */ implicit val decoder: Decoder[Contact] = { json => def verifyAtLeastOneDefined( @@ -80,8 +74,7 @@ object Contact { } } -/** - * Represents a package configuration stored in the `package.yaml` file. +/** Represents a package configuration stored in the `package.yaml` file. * * @param name package name * @param version package version @@ -108,8 +101,7 @@ case class Config( originalJson: Json = Json.obj() ) { - /** - * Converts the configuration into a YAML representation. + /** Converts the configuration into a YAML representation. */ def toYaml: String = Printer.spaces2.copy(preserveOrder = true).pretty(Config.encoder(this)) @@ -170,8 +162,7 @@ object Config { withDeps } - /** - * Tries to parse the [[Config]] from a YAML string. + /** Tries to parse the [[Config]] from a YAML string. */ def fromYaml(yamlString: String): Try[Config] = { yaml.parser.parse(yamlString).flatMap(_.as[Config]).toTry diff --git a/lib/scala/pkg/src/main/scala/org/enso/pkg/EnsoVersion.scala b/lib/scala/pkg/src/main/scala/org/enso/pkg/EnsoVersion.scala index 17e25e7a52..f4fe9d04a1 100644 --- a/lib/scala/pkg/src/main/scala/org/enso/pkg/EnsoVersion.scala +++ b/lib/scala/pkg/src/main/scala/org/enso/pkg/EnsoVersion.scala @@ -4,13 +4,11 @@ import io.circe.syntax._ import io.circe.{Decoder, DecodingFailure, Encoder} import nl.gn0s1s.bump.SemVer -/** - * Represents the engine version that is associated with a project. +/** Represents the engine version that is associated with a project. */ sealed trait EnsoVersion -/** - * Represents `default` Enso version. +/** Represents `default` Enso version. * * If `enso-version` is set to `default`, the locally default Enso engine * version is used for the project. @@ -18,27 +16,23 @@ sealed trait EnsoVersion case object DefaultEnsoVersion extends EnsoVersion { private val defaultEnsoVersion = "default" - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = defaultEnsoVersion } -/** - * An exact semantic versioning string. +/** An exact semantic versioning string. */ case class SemVerEnsoVersion(version: SemVer) extends EnsoVersion { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = version.toString } object EnsoVersion { - /** - * [[Decoder]] instance allowing to parse [[EnsoVersion]]. + /** [[Decoder]] instance allowing to parse [[EnsoVersion]]. */ implicit val decoder: Decoder[EnsoVersion] = { json => json.as[String].flatMap { string => @@ -57,8 +51,7 @@ object EnsoVersion { } } - /** - * [[Encoder]] instance allowing to convert [[EnsoVersion]] to JSON or YAML. + /** [[Encoder]] instance allowing to convert [[EnsoVersion]] to JSON or YAML. */ implicit val encoder: Encoder[EnsoVersion] = { version => version.toString.asJson diff --git a/lib/scala/pkg/src/main/scala/org/enso/pkg/Package.scala b/lib/scala/pkg/src/main/scala/org/enso/pkg/Package.scala index c42fe6369e..3c566062ad 100644 --- a/lib/scala/pkg/src/main/scala/org/enso/pkg/Package.scala +++ b/lib/scala/pkg/src/main/scala/org/enso/pkg/Package.scala @@ -12,16 +12,14 @@ import scala.util.{Failure, Try, Using} object CouldNotCreateDirectory extends Exception -/** - * Represents a source file with known qualified name. +/** Represents a source file with known qualified name. * * @param qualifiedName the qualified name of this file * @param file the location of this file */ case class SourceFile[F](qualifiedName: QualifiedName, file: F) -/** - * Represents an Enso package stored on the hard drive. +/** Represents an Enso package stored on the hard drive. * * @param root the root directory of this package * @param config the metadata contained in the package configuration @@ -39,8 +37,7 @@ case class Package[F]( val thumbFile = root.getChild(Package.thumbFileName) val polyglotDir = root.getChild(Package.polyglotExtensionsDirName) - /** - * Sets the package name. + /** Sets the package name. * * @param newName the new package name * @return a package with the updated name @@ -48,8 +45,7 @@ case class Package[F]( def setPackageName(newName: String): Package[F] = this.copy(config = config.copy(name = newName)) - /** - * Stores the package metadata on the hard drive. If the package does not exist, + /** Stores the package metadata on the hard drive. If the package does not exist, * creates the required directory structure. */ def save(): Unit = { @@ -58,8 +54,7 @@ case class Package[F]( saveConfig() } - /** - * Creates the package directory structure. + /** Creates the package directory structure. */ def createDirectories(): Unit = { val created = Try(root.createDirectories()).map(_ => true).getOrElse(false) @@ -67,8 +62,7 @@ case class Package[F]( createSourceDir() } - /** - * Changes the package name. + /** Changes the package name. * * @param newName the new package name * @return The package object with changed name. The old package is not @@ -76,8 +70,7 @@ case class Package[F]( */ def rename(newName: String): Package[F] = updateConfig(_.copy(name = newName)) - /** - * Updates the package config. + /** Updates the package config. * * The changes are automatically saved to the filesystem. * @@ -91,8 +84,7 @@ case class Package[F]( newPkg } - /** - * Creates the sources directory and populates it with a dummy Main file. + /** Creates the sources directory and populates it with a dummy Main file. */ def createSourceDir(): Unit = { Try(sourceDir.createDirectories()).getOrElse(throw CouldNotCreateDirectory) @@ -103,8 +95,7 @@ case class Package[F]( mainCodeSrc.close() } - /** - * Saves the config metadata into the package configuration file. + /** Saves the config metadata into the package configuration file. */ def saveConfig(): Unit = { val writer = configFile.newBufferedWriter @@ -112,8 +103,7 @@ case class Package[F]( writer.close() } - /** - * Gets the location of the package's Main file. + /** Gets the location of the package's Main file. * * @return the location of the Main file. */ @@ -121,21 +111,18 @@ case class Package[F]( sourceDir.getChild(Package.mainFileName) } - /** - * Checks if the package has a thumbnail file. + /** Checks if the package has a thumbnail file. * * @return `true` if the thumbnail file exists, `false` otherwise. */ def hasThumb: Boolean = thumbFile.exists - /** - * Returns the name of this package. + /** Returns the name of this package. * @return the name of this package. */ def name: String = config.name - /** - * Parses a file path into a qualified module name belonging to this + /** Parses a file path into a qualified module name belonging to this * package. * * @param file the source file path to translate into a qualified name. @@ -148,8 +135,7 @@ case class Package[F]( QualifiedName(name :: dirSegments, fileNameWithoutExtension) } - /** - * Lists the source files in this package. + /** Lists the source files in this package. * * @return the list of all source files in this package, together with their qualified names. */ @@ -162,8 +148,7 @@ case class Package[F]( sources.map { path => SourceFile(moduleNameForFile(path), path) } } - /** - * Lists contents of the polyglot extensions directory for a given language. + /** Lists contents of the polyglot extensions directory for a given language. * * @param languageName the language to list extenstions for * @return a list of files and directories contained in the relevant @@ -179,16 +164,14 @@ case class Package[F]( } } -/** - * A class responsible for creating and parsing package structures. +/** A class responsible for creating and parsing package structures. * @param fileSystem the file system to use. * @tparam F the type of paths used by `fileSystem`. */ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { import FileSystem.Syntax - /** - * Creates a new Package in a given location and with config file. + /** Creates a new Package in a given location and with config file. * * @param root the root location of the package. * @param config the config for the new package. @@ -203,8 +186,7 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { pkg } - /** - * Creates a new Package in a given location and with given name. Leaves all the other config fields blank. + /** Creates a new Package in a given location and with given name. Leaves all the other config fields blank. * * @param root the root location of the package. * @param name the name for the new package. @@ -231,8 +213,7 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { create(root, config) } - /** - * Tries to parse package structure from a given root location. + /** Tries to parse package structure from a given root location. * * @param root the root location to get package info from. * @return `Some(pkg)` if the location represents a package, `None` @@ -241,8 +222,7 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { def fromDirectory(root: F): Option[Package[F]] = loadPackage(root).toOption - /** - * Loads the package structure at the given root location and reports any + /** Loads the package structure at the given root location and reports any * errors. * * @param root the root location to get package info from. @@ -291,8 +271,7 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { } } - /** - * Tries to parse package structure from a given root location or creates a new package if it fails. + /** Tries to parse package structure from a given root location or creates a new package if it fails. * * @param root the package root location. * @return the package object for the package found or created in the root location. @@ -302,8 +281,7 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { existing.getOrElse(create(root, generateName(root))) } - /** - * Checks if a character is allowed in a project name. + /** Checks if a character is allowed in a project name. * * @param char the char to validate * @return `true` if it's allowed, `false` otherwise @@ -312,8 +290,7 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { char.isLetterOrDigit || char == '_' } - /** - * Takes a name containing letters, digits, and `_` characters and makes it + /** Takes a name containing letters, digits, and `_` characters and makes it * a proper `Upper_Snake_Case` name. * * @param string the input string @@ -324,27 +301,25 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { val chars = string.toList val charPairs = (beginMarker :: chars).zip(chars) charPairs - .map { - case (previous, current) => - if (previous == beginMarker) { - current.toString - } else if (previous.isLower && current.isUpper) { - s"_$current" - } else if (previous.isLetter && current.isDigit) { - s"_$current" - } else if (previous == '_' && current == '_') { - "" - } else if (previous.isDigit && current.isLetter) { - s"_${current.toUpper}" - } else { - current.toString - } + .map { case (previous, current) => + if (previous == beginMarker) { + current.toString + } else if (previous.isLower && current.isUpper) { + s"_$current" + } else if (previous.isLetter && current.isDigit) { + s"_$current" + } else if (previous == '_' && current == '_') { + "" + } else if (previous.isDigit && current.isLetter) { + s"_${current.toUpper}" + } else { + current.toString + } } .mkString("") } - /** - * Transforms the given string into a valid package name (i.e. a CamelCased identifier). + /** Transforms the given string into a valid package name (i.e. a CamelCased identifier). * * @param name the original name. * @return the transformed name conforming to the specification. @@ -357,8 +332,7 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { toUpperSnakeCase(onlyAlphanumeric) } - /** - * Generates a name for the package, by normalizing the last segment of its root path. + /** Generates a name for the package, by normalizing the last segment of its root path. * * @param file the root location of the package. * @return the generated package name. @@ -372,33 +346,28 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) { object PackageManager { val Default = new PackageManager[File]()(FileSystem.Default) - /** - * A general exception indicating that a package cannot be loaded. + /** A general exception indicating that a package cannot be loaded. */ class PackageLoadingException(message: String, cause: Throwable) extends RuntimeException(message, cause) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = message } - /** - * The error indicating that the requested package does not exist. + /** The error indicating that the requested package does not exist. */ case class PackageNotFound() extends PackageLoadingException(s"The package file does not exist.", null) - /** - * The error indicating that the package exists, but cannot be loaded. + /** The error indicating that the package exists, but cannot be loaded. */ case class PackageLoadingFailure(message: String, cause: Throwable) extends PackageLoadingException(message, cause) } -/** - * A companion object for static methods on the [[Package]] class. +/** A companion object for static methods on the [[Package]] class. */ object Package { val fileExtension = "enso" diff --git a/lib/scala/pkg/src/main/scala/org/enso/pkg/QualifiedName.scala b/lib/scala/pkg/src/main/scala/org/enso/pkg/QualifiedName.scala index 78ecd003e5..1e869aa1ae 100644 --- a/lib/scala/pkg/src/main/scala/org/enso/pkg/QualifiedName.scala +++ b/lib/scala/pkg/src/main/scala/org/enso/pkg/QualifiedName.scala @@ -1,7 +1,6 @@ package org.enso.pkg -/** - * Represents a qualified name of a source item. +/** Represents a qualified name of a source item. * * @param path the names of the package and directories the item is * contained in @@ -11,16 +10,14 @@ case class QualifiedName(path: List[String], item: String) { override def toString: String = (path :+ item).mkString(QualifiedName.separator) - /** - * Get the parent of this qualified name. + /** Get the parent of this qualified name. * * @return the parent of this qualified name. */ def getParent: Option[QualifiedName] = path.lastOption.map(QualifiedName(path.init, _)) - /** - * Create a child qualified name taking this name as a parent. + /** Create a child qualified name taking this name as a parent. * * @param name the name of a child node. * @return a new qualified name based on this name. @@ -28,8 +25,7 @@ case class QualifiedName(path: List[String], item: String) { def createChild(name: String): QualifiedName = QualifiedName(path :+ item, name) - /** - * Renames a project part of this [[QualifiedName]]. + /** Renames a project part of this [[QualifiedName]]. * * @param newName the new project name * @return a [[QualifiedName]] with the updated project name @@ -44,8 +40,7 @@ object QualifiedName { val separator = "." val separatorRegex = "\\." - /** - * Parses a dot-separated string representation of a qualified name into + /** Parses a dot-separated string representation of a qualified name into * a [[QualifiedName]] object. * * @param qualName the string representation of a qualified name. @@ -60,8 +55,7 @@ object QualifiedName { } } - /** - * Creates a qualified name with empty path. + /** Creates a qualified name with empty path. * * @param modName the module name. * @return a qualified name equivalent to `modName` diff --git a/lib/scala/pkg/src/main/scala/org/enso/pkg/SemVerJson.scala b/lib/scala/pkg/src/main/scala/org/enso/pkg/SemVerJson.scala index a634b9a5b6..d6b25ab3f5 100644 --- a/lib/scala/pkg/src/main/scala/org/enso/pkg/SemVerJson.scala +++ b/lib/scala/pkg/src/main/scala/org/enso/pkg/SemVerJson.scala @@ -6,8 +6,7 @@ import nl.gn0s1s.bump.SemVer object SemVerJson { - /** - * [[Decoder]] instance allowing to parse semantic versioning strings. + /** [[Decoder]] instance allowing to parse semantic versioning strings. */ implicit val semverDecoder: Decoder[SemVer] = { json => for { @@ -21,8 +20,7 @@ object SemVerJson { } yield version } - /** - * [[Encoder]] instance allowing to serialize semantic versioning strings. + /** [[Encoder]] instance allowing to serialize semantic versioning strings. */ implicit val semverEncoder: Encoder[SemVer] = _.toString.asJson } diff --git a/lib/scala/pkg/src/test/scala/org/enso/pkg/ConfigSpec.scala b/lib/scala/pkg/src/test/scala/org/enso/pkg/ConfigSpec.scala index e57d2cfbb2..d053fa2152 100644 --- a/lib/scala/pkg/src/test/scala/org/enso/pkg/ConfigSpec.scala +++ b/lib/scala/pkg/src/test/scala/org/enso/pkg/ConfigSpec.scala @@ -17,14 +17,13 @@ class ConfigSpec "unknown-key" -> Json.fromString("value") ) - inside(original.as[Config]) { - case Right(config) => - val serialized = Config.encoder(config) - serialized.asObject - .value("unknown-key") - .value - .asString - .value shouldEqual "value" + inside(original.as[Config]) { case Right(config) => + val serialized = Config.encoder(config) + serialized.asObject + .value("unknown-key") + .value + .asString + .value shouldEqual "value" } } diff --git a/lib/scala/project-manager/src/main/resources/logback.xml b/lib/scala/project-manager/src/main/resources/logback.xml index 6438014b07..0b49034d1b 100644 --- a/lib/scala/project-manager/src/main/resources/logback.xml +++ b/lib/scala/project-manager/src/main/resources/logback.xml @@ -1,16 +1,16 @@ - - - - %d{HH:mm:ss.SSS} %-5level [%-15thread] %-36logger{36} %msg%n - - + + + + %d{HH:mm:ss.SSS} %-5level [%-15thread] %-36logger{36} %msg%n + + - + - - - + + + diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/Globals.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/Globals.scala index 59b8c7a860..07beb78ac2 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/Globals.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/Globals.scala @@ -7,8 +7,7 @@ import zio.console.Console import zio.random.Random import zio.system.System -/** - * Constants manager for app constants. +/** Constants manager for app constants. */ object Globals { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/MainModule.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/MainModule.scala index 636dbae4c7..cc4a1356d5 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/MainModule.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/MainModule.scala @@ -30,8 +30,7 @@ import org.enso.projectmanager.service.{ import scala.concurrent.ExecutionContext -/** - * A main module containing all components of the project manager. +/** A main module containing all components of the project manager. */ class MainModule[ F[+_, +_]: Sync: ErrorChannel: Exec: CovariantFlatMap: Applicative: Async diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ProjectManager.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ProjectManager.scala index a973ac4e38..743abeb9a7 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ProjectManager.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ProjectManager.scala @@ -25,13 +25,11 @@ import zio.interop.catz.core._ import scala.concurrent.duration._ import scala.concurrent.{Await, ExecutionContext, ExecutionContextExecutor} -/** - * Project manager runner containing the main method. +/** Project manager runner containing the main method. */ object ProjectManager extends App with LazyLogging { - /** - * A configuration of the project manager. + /** A configuration of the project manager. */ val config: ProjectManagerConfig = ConfigSource @@ -50,14 +48,12 @@ object ProjectManager extends App with LazyLogging { th => logger.error("An expected error occurred", th) ) - /** - * ZIO runtime. + /** ZIO runtime. */ implicit val runtime = Runtime(Globals.zioEnvironment, new ZioPlatform(computeExecutionContext)) - /** - * Main process starting up the server. + /** Main process starting up the server. */ lazy val mainProcess: ZIO[ZEnv, IOException, Unit] = { val mainModule = @@ -110,8 +106,7 @@ object ProjectManager extends App with LazyLogging { } } - /** - * The main function of the application, which will be passed the command-line + /** The main function of the application, which will be passed the command-line * arguments to the program and has to return an `IO` with the errors fully handled. */ def runOpts(options: CommandLine): ZIO[ZEnv, Nothing, ExitCode] = { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ZioPlatform.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ZioPlatform.scala index 4f26649e39..6cc06f9a95 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ZioPlatform.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/ZioPlatform.scala @@ -9,8 +9,7 @@ import zio.internal.{Executor, Platform, Tracing} import scala.concurrent.ExecutionContext -/** - * An environment needed to execute ZIO actions. +/** An environment needed to execute ZIO actions. * * @param computeExecutionContext compute thread pool */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/configuration.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/configuration.scala index ddc99f0be4..7c7c77a197 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/configuration.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/boot/configuration.scala @@ -6,8 +6,7 @@ import scala.concurrent.duration.FiniteDuration object configuration { - /** - * A configuration object for properties of the Project Manager. + /** A configuration object for properties of the Project Manager. * * @param server a JSON RPC server configuration */ @@ -20,16 +19,14 @@ object configuration { supervision: SupervisionConfig ) - /** - * A configuration object for properties of the JSON RPC server. + /** A configuration object for properties of the JSON RPC server. * * @param host an address that the server listen on * @param port a port that the server listen on */ case class ServerConfig(host: String, port: Int) - /** - * A configuration object for properties of project storage. + /** A configuration object for properties of project storage. * * @param projectsRoot a project root * @param userProjectsPath a user project root @@ -44,8 +41,7 @@ object configuration { projectMetadataFileName: String ) - /** - * A configuration object for timeout properties. + /** A configuration object for timeout properties. * * @param ioTimeout a timeout for IO operations * @param requestTimeout a timeout for JSON RPC request timeout @@ -58,8 +54,7 @@ object configuration { socketCloseTimeout: FiniteDuration ) - /** - * A configuration object for networking. + /** A configuration object for networking. * * @param interface an interface to listen to * @param minPort min port for the LS @@ -67,8 +62,7 @@ object configuration { */ case class NetworkConfig(interface: String, minPort: Int, maxPort: Int) - /** - * A configuration object for bootloader properties. + /** A configuration object for bootloader properties. * * @param numberOfRetries how many times a bootloader should try to boot the LS * @param delayBetweenRetry delays between retries @@ -78,8 +72,7 @@ object configuration { delayBetweenRetry: FiniteDuration ) - /** - * A configuration object for supervisor properties. + /** A configuration object for supervisor properties. * * @param initialDelay a time that the supervisor wait before starts * monitoring diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Applicative.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Applicative.scala index 6e9c27ac0d..c5a4e12749 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Applicative.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Applicative.scala @@ -2,28 +2,23 @@ package org.enso.projectmanager.control.core import zio.ZIO -/** - * An applicative functor. +/** An applicative functor. */ trait Applicative[F[+_, +_]] { - /** - * Lifts value into the applicative functor. + /** Lifts value into the applicative functor. */ def pure[E, A](a: A): F[E, A] - /** - * Applies the function in the applicative context to the given value. + /** Applies the function in the applicative context to the given value. */ def ap[E, E1 >: E, A, B](ff: F[E, A => B])(fa: F[E1, A]): F[E1, B] - /** - * Applies function f to the given value. + /** Applies function f to the given value. */ def map[E, A, B](fa: F[E, A])(f: A => B): F[E, B] - /** - * Applies the binary function to the effectful falues ma and mb. + /** Applies the binary function to the effectful falues ma and mb. */ def map2[E, A, B, C](ma: F[E, A], mb: F[E, B])(f: (A, B) => C): F[E, C] } diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMap.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMap.scala index beb5593466..03ac21eaa0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMap.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMap.scala @@ -4,24 +4,21 @@ import zio._ import scala.util.{Either, Left, Right} -/** - * A class for covariant effects containing error channel used to chain +/** A class for covariant effects containing error channel used to chain * computations. * * @tparam F an effectful context */ trait CovariantFlatMap[F[+_, +_]] { - /** - * Lifts any value into a context F[Nothing, A]. + /** Lifts any value into a context F[Nothing, A]. * * @param value a value to lift * @return */ def pure[A](value: A): F[Nothing, A] - /** - * Chains `fa` with `f` arrow. + /** Chains `fa` with `f` arrow. * * @param fa an effectful computation * @param f dependent effectful function @@ -29,16 +26,14 @@ trait CovariantFlatMap[F[+_, +_]] { */ def flatMap[E1, E2 >: E1, A, B](fa: F[E1, A])(f: A => F[E2, B]): F[E2, B] - /** - * `if` lifted into monad. + /** `if` lifted into monad. */ def ifM[E, B]( fa: F[E, Boolean] )(ifTrue: => F[E, B], ifFalse: => F[E, B]): F[E, B] = flatMap(fa)(if (_) ifTrue else ifFalse) - /** - * Keeps calling `f` until a `scala.util.Right[B]` is returned. + /** Keeps calling `f` until a `scala.util.Right[B]` is returned. */ def tailRecM[E, A, B](a: A)(f: A => F[E, Either[A, B]]): F[E, B] = flatMap(f(a)) { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMapOps.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMapOps.scala index e2d405c8e8..325ea2253b 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMapOps.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/CovariantFlatMapOps.scala @@ -2,20 +2,20 @@ package org.enso.projectmanager.control.core class CovariantFlatMapOps[F[+_, +_]: CovariantFlatMap, E, A](fa: F[E, A]) { - /** @inheritdoc **/ + /** @inheritdoc */ def flatMap[E1 >: E, B](f: A => F[E1, B]): F[E1, B] = CovariantFlatMap[F].flatMap[E, E1, A, B](fa)(f) - /** @inheritdoc **/ + /** @inheritdoc */ def map[B](f: A => B): F[E, B] = flatMap(a => CovariantFlatMap[F].pure(f(a))) - /** @inheritdoc **/ + /** @inheritdoc */ def >>=[E1 >: E, B](f: A => F[E1, B]): F[E1, B] = flatMap(f) - /** @inheritdoc **/ + /** @inheritdoc */ def *>[E1 >: E, B](f: F[E1, B]): F[E1, B] = flatMap(_ => f) - /** @inheritdoc **/ + /** @inheritdoc */ def >>[E1 >: E, B](f: F[E1, B]): F[E1, B] = flatMap(_ => f) } diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Traverse.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Traverse.scala index db9489da60..7d74dd846e 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Traverse.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/Traverse.scala @@ -1,12 +1,10 @@ package org.enso.projectmanager.control.core -/** - * A traversal over a structure with effects. +/** A traversal over a structure with effects. */ trait Traverse[G[_]] { - /** - * Applies the function `f` to each element of the collection. + /** Applies the function `f` to each element of the collection. * * @param s a collection of elements * @param f the mapping function diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioApplicative.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioApplicative.scala index c0b052ec04..0d552c05da 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioApplicative.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioApplicative.scala @@ -2,8 +2,7 @@ package org.enso.projectmanager.control.core import zio.ZIO -/** - * An instance of [[Applicative]] class for ZIO. +/** An instance of [[Applicative]] class for ZIO. */ private[core] class ZioApplicative[R] extends Applicative[ZIO[R, +*, +*]] { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioCovariantFlatMap.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioCovariantFlatMap.scala index 72692a116e..bbded9000d 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioCovariantFlatMap.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/ZioCovariantFlatMap.scala @@ -2,8 +2,7 @@ package org.enso.projectmanager.control.core import zio.ZIO -/** - * Instance of [[CovariantFlatMap]] class for ZIO. +/** Instance of [[CovariantFlatMap]] class for ZIO. */ private[core] class ZioCovariantFlatMap[R] extends CovariantFlatMap[ZIO[R, +*, +*]] { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/syntax.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/syntax.scala index 98bf373318..3ef948199d 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/syntax.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/core/syntax.scala @@ -2,8 +2,7 @@ package org.enso.projectmanager.control.core object syntax { - /** - * Implicit conversion to [[CovariantFlatMapOps]] + /** Implicit conversion to [[CovariantFlatMapOps]] * * @param fa an effect * @return @@ -12,16 +11,14 @@ object syntax { fa: F[E, A] ): CovariantFlatMapOps[F, E, A] = new CovariantFlatMapOps[F, E, A](fa) - /** - * Implicit conversion to [[ApplicativeOps]]. + /** Implicit conversion to [[ApplicativeOps]]. */ implicit def toApplicativeOps[F[+_, +_]: Applicative, E, A]( fa: F[E, A] ): ApplicativeOps[F, E, A] = new ApplicativeOps[F, E, A](fa) - /** - * Implicit conversion to [[ApplicativeFunctionOps]]. + /** Implicit conversion to [[ApplicativeFunctionOps]]. */ implicit def toApplicativeFunctionOps[F[+_, +_]: Applicative, E, A, B]( ff: F[E, A => B] diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Async.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Async.scala index 79470e8010..418f2227f2 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Async.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Async.scala @@ -3,15 +3,13 @@ package org.enso.projectmanager.control.effect import scala.concurrent.Future import scala.util.Either -/** - * A class for asynchronous effects that do not block threads. +/** A class for asynchronous effects that do not block threads. * * @tparam F an effectful context */ trait Async[F[+_, +_]] { - /** - * Imports an asynchronous side-effect into a pure `F` value. + /** Imports an asynchronous side-effect into a pure `F` value. * * @param register is a function that should be called with a * callback for signaling the result once it is ready @@ -21,8 +19,7 @@ trait Async[F[+_, +_]] { */ def async[E, A](register: (Either[E, A] => Unit) => Unit): F[E, A] - /** - * Converts side-effecting future into a pure `F` value. + /** Converts side-effecting future into a pure `F` value. * * @param thunk a thunk that starts asynchronous computations * @tparam A a returned type diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannel.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannel.scala index 8f27aef0cc..b18d489b02 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannel.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannel.scala @@ -3,15 +3,13 @@ package org.enso.projectmanager.control.effect import shapeless.=:!= import zio.ZIO -/** - * A class for effectful computations which may fail. +/** A class for effectful computations which may fail. * * @tparam F a monadic context */ trait ErrorChannel[F[+_, +_]] { - /** - * Recovers from an error matched by recovery function. + /** Recovers from an error matched by recovery function. * * @param fa an effectful computation * @param recovery a recovery function @@ -21,8 +19,7 @@ trait ErrorChannel[F[+_, +_]] { recovery: PartialFunction[E, B] ): F[E, B] - /** - * Recovers from an error by executing effectful computation. + /** Recovers from an error by executing effectful computation. * * @param fa an effectful computation * @param recovery a recovery function @@ -32,8 +29,7 @@ trait ErrorChannel[F[+_, +_]] { recovery: PartialFunction[E, F[E1, B]] ): F[E1, B] - /** - * Recovers from an error by mapping it to fallback computations. + /** Recovers from an error by mapping it to fallback computations. * * @param fa an effectful computation * @param fallback a fallback function @@ -42,35 +38,31 @@ trait ErrorChannel[F[+_, +_]] { fallback: E => F[E1, B] ): F[E1, B] - /** - * Lifts either to the [[F]] monadic context + /** Lifts either to the [[F]] monadic context * * @param either the either to lift * @return */ def liftEither[E, A](either: Either[E, A]): F[E, A] - /** - * Maps error using the specified function/ + /** Maps error using the specified function/ * * @param fa an effectful computation * @param f a mapping function * @return */ - def mapError[E, A, E1](fa: F[E, A])(f: E => E1)( - implicit ev: E =:!= Nothing + def mapError[E, A, E1](fa: F[E, A])(f: E => E1)(implicit + ev: E =:!= Nothing ): F[E1, A] - /** - * Returns an effect that models failure with the specified error. + /** Returns an effect that models failure with the specified error. * * @param error a returned error * @return */ def fail[E](error: => E): F[E, Nothing] - /** - * Runs `cleanUp` effect if error is matched by partial function. + /** Runs `cleanUp` effect if error is matched by partial function. * * @param fa an effectful computation * @param cleanUp a cleanup function @@ -80,8 +72,7 @@ trait ErrorChannel[F[+_, +_]] { cleanUp: PartialFunction[E, F[Nothing, Unit]] ): F[E, A] - /** - * Runs `cleanUp` effect if effectful computation died due to exception. + /** Runs `cleanUp` effect if effectful computation died due to exception. * * @param fa an effectful computation * @param cleanUp a cleanup function diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannelOps.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannelOps.scala index d30bdb6f2f..21d6dd3775 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannelOps.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ErrorChannelOps.scala @@ -4,29 +4,29 @@ import shapeless.=:!= class ErrorChannelOps[F[+_, +_]: ErrorChannel, E, A](fa: F[E, A]) { - /** @inheritdoc **/ + /** @inheritdoc */ def recover[B >: A](recovery: PartialFunction[E, B]): F[E, B] = ErrorChannel[F].recover[E, A, B](fa)(recovery) - /** @inheritdoc **/ + /** @inheritdoc */ def recoverWith[B >: A, E1 >: E]( recovery: PartialFunction[E, F[E1, B]] ): F[E1, B] = ErrorChannel[F].recoverWith[E, A, B, E1](fa)(recovery) - /** @inheritdoc **/ + /** @inheritdoc */ def fallbackTo[B >: A, E1](fallback: E => F[E1, B]): F[E1, B] = ErrorChannel[F].fallbackTo[E, A, B, E1](fa)(fallback) - /** @inheritdoc **/ + /** @inheritdoc */ def mapError[E1](f: E => E1)(implicit ev: E =:!= Nothing): F[E1, A] = ErrorChannel[F].mapError(fa)(f) - /** @inheritdoc **/ + /** @inheritdoc */ def onError(cleanUp: PartialFunction[E, F[Nothing, Unit]]): F[E, A] = ErrorChannel[F].onError(fa)(cleanUp) - /** @inheritdoc **/ + /** @inheritdoc */ def onDie(cleanUp: PartialFunction[Throwable, F[Nothing, Unit]]): F[E, A] = ErrorChannel[F].onDie(fa)(cleanUp) diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Exec.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Exec.scala index 35ce6d9ce8..2bd7ad62d0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Exec.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Exec.scala @@ -4,15 +4,13 @@ import zio.ZEnv import scala.concurrent.Future -/** - * An executor type class for purely functional effects. +/** An executor type class for purely functional effects. * * @tparam F a monadic context */ trait Exec[F[_, _]] { - /** - * Executes effectful operation. + /** Executes effectful operation. * * @param op an effect * @tparam E error type diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/JvmSemaphore.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/JvmSemaphore.scala index 0ca3ed1298..a04ff88a45 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/JvmSemaphore.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/JvmSemaphore.scala @@ -6,8 +6,7 @@ import org.enso.projectmanager.control.core.CovariantFlatMap import org.enso.projectmanager.control.core.syntax._ import syntax._ -/** - * Java-backed pure semaphore implementation. +/** Java-backed pure semaphore implementation. * * @param permits * @tparam F a monadic context @@ -18,15 +17,15 @@ class JvmSemaphore[F[+_, +_]: Sync: ErrorChannel: CovariantFlatMap]( private val semaphore = new concurrent.Semaphore(permits, true) - /** @inheritdoc **/ + /** @inheritdoc */ override def acquire(): F[Nothing, Unit] = Sync[F].effect(semaphore.acquire()) - /** @inheritdoc **/ + /** @inheritdoc */ override def release(): F[Nothing, Unit] = Sync[F].effect(semaphore.release()) - /** @inheritdoc **/ + /** @inheritdoc */ override def withPermit[E, A](criticalSection: F[E, A]): F[E, A] = for { _ <- acquire() diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Semaphore.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Semaphore.scala index b373ab3dd0..ca1da48869 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Semaphore.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Semaphore.scala @@ -2,30 +2,26 @@ package org.enso.projectmanager.control.effect import org.enso.projectmanager.control.core.CovariantFlatMap -/** - * A pure functional semaphore. +/** A pure functional semaphore. * * @tparam F an effectful context */ trait Semaphore[F[+_, +_]] { - /** - * Acquires one permit from this semaphore, blocking until one is + /** Acquires one permit from this semaphore, blocking until one is * available. * * @return */ def acquire(): F[Nothing, Unit] - /** - * Releases one permit, returning it to the semaphore. + /** Releases one permit, returning it to the semaphore. * * @return */ def release(): F[Nothing, Unit] - /** - * Executes the critical section acquiring (before) and releasing (after) + /** Executes the critical section acquiring (before) and releasing (after) * one permit. * * @param criticalSection a code accessing shared resource diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Sync.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Sync.scala index 837124667b..2c12405bfd 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Sync.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/Sync.scala @@ -6,39 +6,34 @@ import zio.{ZEnv, ZIO} import scala.concurrent.duration.FiniteDuration -/** - * A class for synchronous effects that block threads. +/** A class for synchronous effects that block threads. * * @tparam F an effectful context */ trait Sync[F[+_, +_]] { - /** - * Lifts a total synchronous effect into a pure `F` context. + /** Lifts a total synchronous effect into a pure `F` context. * * @param effect an effect * @return */ def effect[A](effect: => A): F[Nothing, A] - /** - * Lifts a blocking operation into a pure `F` context. + /** Lifts a blocking operation into a pure `F` context. * * @param effect an effect * @return */ def blockingOp[A](effect: => A): F[Throwable, A] - /** - * Lifts a blocking IO operation into a pure `F` context. + /** Lifts a blocking IO operation into a pure `F` context. * * @param effect an effect * @return */ def blockingIO[A](effect: => A): F[IOException, A] - /** - * Returns an effect that will timeout `fa` effect. + /** Returns an effect that will timeout `fa` effect. * * @param fa an effectful computation * @param e a timeout error diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioAsync.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioAsync.scala index c3b33a0ee0..8354d87db9 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioAsync.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioAsync.scala @@ -5,15 +5,14 @@ import zio.ZIO import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success} -/** - * Instance of [[Async]] class for ZIO. +/** Instance of [[Async]] class for ZIO. */ class ZioAsync[R] extends Async[ZIO[R, +*, +*]] { implicit private val immediateEc = ExecutionContext.fromExecutor(ImmediateExecutor) - /** @inheritdoc **/ + /** @inheritdoc */ override def async[E, A]( register: (Either[E, A] => Unit) => Unit ): ZIO[R, E, A] = @@ -22,7 +21,7 @@ class ZioAsync[R] extends Async[ZIO[R, +*, +*]] { } - /** @inheritdoc **/ + /** @inheritdoc */ override def fromFuture[A](thunk: () => Future[A]): ZIO[R, Throwable, A] = ZIO.effectAsync[R, Throwable, A] { cb => thunk().onComplete { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioEnvExec.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioEnvExec.scala index 562468a00f..6624b9be5c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioEnvExec.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioEnvExec.scala @@ -4,8 +4,7 @@ import zio._ import scala.concurrent.{Future, Promise} -/** - * ZIO executor. +/** ZIO executor. * * @param runtime a ZIO runtime */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioErrorChannel.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioErrorChannel.scala index 74fc6ee78f..83869d47cc 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioErrorChannel.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioErrorChannel.scala @@ -5,23 +5,22 @@ import zio.{CanFail, ZIO} import scala.annotation.unused -/** - * Instance of [[ErrorChannel]] class for ZIO. +/** Instance of [[ErrorChannel]] class for ZIO. */ class ZioErrorChannel[R] extends ErrorChannel[ZIO[R, +*, +*]] { - implicit private def canFailEv[E]( - implicit @unused ev: E =:!= Nothing + implicit private def canFailEv[E](implicit + @unused ev: E =:!= Nothing ): CanFail[E] = CanFail - /** @inheritdoc **/ + /** @inheritdoc */ override def recover[E, A, B >: A](fa: ZIO[R, E, A])( recovery: PartialFunction[E, B] ): ZIO[R, E, B] = recoverWith[E, A, B, E](fa)(recovery.andThen(ZIO.succeed(_))) - /** @inheritdoc **/ + /** @inheritdoc */ override def recoverWith[E, A, B >: A, E1 >: E](fa: ZIO[R, E, A])( recovery: PartialFunction[E, ZIO[R, E1, B]] ): ZIO[R, E1, B] = @@ -33,7 +32,7 @@ class ZioErrorChannel[R] extends ErrorChannel[ZIO[R, +*, +*]] { success = ZIO.succeed(_) ) - /** @inheritdoc **/ + /** @inheritdoc */ override def fallbackTo[E, A, B >: A, E1](fa: ZIO[R, E, A])( fallback: E => ZIO[R, E1, B] ): ZIO[R, E1, B] = @@ -42,20 +41,20 @@ class ZioErrorChannel[R] extends ErrorChannel[ZIO[R, +*, +*]] { success = ZIO.succeed(_) ) - /** @inheritdoc **/ + /** @inheritdoc */ override def liftEither[E, A](either: Either[E, A]): ZIO[R, E, A] = ZIO.fromEither(either) - /** @inheritdoc **/ + /** @inheritdoc */ override def mapError[E, A, E1]( fa: ZIO[R, E, A] )(f: E => E1)(implicit ev: E =:!= Nothing): ZIO[R, E1, A] = fa.mapError(f) - /** @inheritdoc **/ + /** @inheritdoc */ override def fail[E](error: => E): ZIO[R, E, Nothing] = ZIO.fail(error) - /** @inheritdoc **/ + /** @inheritdoc */ override def onError[E, A]( fa: ZIO[R, E, A] )(cleanUp: PartialFunction[E, ZIO[R, Nothing, Unit]]): ZIO[R, E, A] = @@ -69,7 +68,7 @@ class ZioErrorChannel[R] extends ErrorChannel[ZIO[R, +*, +*]] { } } - /** @inheritdoc **/ + /** @inheritdoc */ override def onDie[E, A]( fa: ZIO[R, E, A] )(cleanUp: PartialFunction[Throwable, ZIO[R, Nothing, Unit]]): ZIO[R, E, A] = diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioSync.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioSync.scala index 4568e00bff..ce5fad5ebf 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioSync.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/ZioSync.scala @@ -8,24 +8,23 @@ import zio.duration.Duration import scala.concurrent.duration.FiniteDuration -/** - * Instance of [[Sync]] class for ZIO. +/** Instance of [[Sync]] class for ZIO. */ object ZioSync extends Sync[ZIO[ZEnv, +*, +*]] { - /** @inheritdoc **/ + /** @inheritdoc */ override def effect[A](effect: => A): ZIO[ZEnv, Nothing, A] = ZIO.effectTotal(effect) - /** @inheritdoc **/ + /** @inheritdoc */ override def blockingOp[A](effect: => A): ZIO[ZEnv, Throwable, A] = blocking.effectBlocking(effect) - /** @inheritdoc **/ + /** @inheritdoc */ override def blockingIO[A](effect: => A): ZIO[ZEnv, IOException, A] = blocking.effectBlockingIO(effect) - /** @inheritdoc **/ + /** @inheritdoc */ override def timeoutFail[E, E1 >: E, A](fa: ZIO[ZEnv, E, A])(e: E1)( timeout: FiniteDuration ): ZIO[zio.ZEnv, E1, A] = fa.timeoutFail(e)(Duration.fromScala(timeout)) diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/syntax.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/syntax.scala index 9f7b19081d..6a3ffda684 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/syntax.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/control/effect/syntax.scala @@ -2,8 +2,7 @@ package org.enso.projectmanager.control.effect object syntax { - /** - * Implicit conversion to [[ErrorChannelOps]] + /** Implicit conversion to [[ErrorChannelOps]] * * @param fa an effect * @return @@ -11,8 +10,7 @@ object syntax { implicit def toSyncOps[F[+_, +_]: Sync, E, A](fa: F[E, A]): SyncOps[F, E, A] = new SyncOps[F, E, A](fa) - /** - * Implicit conversion to [[ErrorChannelOps]] + /** Implicit conversion to [[ErrorChannelOps]] * * @param fa an effect * @return diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/Default.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/Default.scala index 6be7e1ea09..6f2af968ef 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/Default.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/Default.scala @@ -1,14 +1,12 @@ package org.enso.projectmanager.data -/** - * A class for types with a default value. +/** A class for types with a default value. * * @tparam A a type parameter */ trait Default[A] { - /** - * A default value. + /** A default value. */ val value: A diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/LanguageServerSockets.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/LanguageServerSockets.scala index 16f14596bb..b819ca2403 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/LanguageServerSockets.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/LanguageServerSockets.scala @@ -1,7 +1,6 @@ package org.enso.projectmanager.data -/** - * Sockets that a language server listens on. +/** Sockets that a language server listens on. * * @param jsonSocket a socket used for JSON-RPC protocol * @param binarySocket a socket used fot binary protocol diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/ProjectMetadata.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/ProjectMetadata.scala index 02b5b35c11..98cdfe6bff 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/ProjectMetadata.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/data/ProjectMetadata.scala @@ -3,8 +3,7 @@ package org.enso.projectmanager.data import java.time.OffsetDateTime import java.util.UUID -/** - * Contains project metadata. +/** Contains project metadata. * * @param name the name of the project * @param id the project id diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ClientEvent.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ClientEvent.scala index a17a1d56ce..03d42986b0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ClientEvent.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ClientEvent.scala @@ -2,22 +2,19 @@ package org.enso.projectmanager.event import java.util.UUID -/** - * Base trait for all client events. +/** Base trait for all client events. */ sealed trait ClientEvent extends Event object ClientEvent { - /** - * Notifies the Language Server about a new client connecting. + /** Notifies the Language Server about a new client connecting. * * @param clientId an object representing a client */ case class ClientConnected(clientId: UUID) extends ClientEvent - /** - * Notifies the Language Server about a client disconnecting. + /** Notifies the Language Server about a client disconnecting. * The client may not send any further messages after this one. * * @param clientId the internal id of this client diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/Event.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/Event.scala index 3db8ee86c8..7ed0b27940 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/Event.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/Event.scala @@ -1,6 +1,5 @@ package org.enso.projectmanager.event -/** - * Base trait for all kinds of events. +/** Base trait for all kinds of events. */ trait Event diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ProjectEvent.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ProjectEvent.scala index 47b97e64f1..facf52f38b 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ProjectEvent.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/event/ProjectEvent.scala @@ -2,15 +2,13 @@ package org.enso.projectmanager.event import java.util.UUID -/** - * Base trait for all project events. +/** Base trait for all project events. */ trait ProjectEvent extends Event object ProjectEvent { - /** - * Notifies that project has been closed. + /** Notifies that project has been closed. * * @param projectId the id of the project that was closed */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/config/ConfigurationReaders.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/config/ConfigurationReaders.scala index a059dc2dc0..824814e85b 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/config/ConfigurationReaders.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/config/ConfigurationReaders.scala @@ -4,8 +4,7 @@ import java.io.File import pureconfig.ConfigReader -/** - * Custom ConfigReaders which allow for reading custom types +/** Custom ConfigReaders which allow for reading custom types * from configuration. */ object ConfigurationReaders { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/BlockingFileSystem.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/BlockingFileSystem.scala index c755937109..9219f3fd31 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/BlockingFileSystem.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/BlockingFileSystem.scala @@ -14,8 +14,7 @@ import org.enso.projectmanager.infrastructure.file.FileSystemFailure._ import scala.concurrent.duration.FiniteDuration -/** - * ZIO implementation of [[FileSystem]]. This implementation uses blocking +/** ZIO implementation of [[FileSystem]]. This implementation uses blocking * API to access data on the disk. * * @param ioTimeout a timeout for IO operations @@ -24,8 +23,7 @@ class BlockingFileSystem[F[+_, +_]: Sync: ErrorChannel]( ioTimeout: FiniteDuration ) extends FileSystem[F] { - /** - * Reads the contents of a textual file. + /** Reads the contents of a textual file. * * @param file path to the file * @return either [[FileSystemFailure]] or the content of a file as a String @@ -36,8 +34,7 @@ class BlockingFileSystem[F[+_, +_]: Sync: ErrorChannel]( .mapError(toFsFailure) .timeoutFail(OperationTimeout)(ioTimeout) - /** - * Writes textual content to a file. + /** Writes textual content to a file. * * @param file path to the file * @param contents a textual contents of the file @@ -52,8 +49,7 @@ class BlockingFileSystem[F[+_, +_]: Sync: ErrorChannel]( .mapError(toFsFailure) .timeoutFail(OperationTimeout)(ioTimeout) - /** - * Deletes the specified directory recursively. + /** Deletes the specified directory recursively. * * @param path a path to the directory * @return either [[FileSystemFailure]] or Unit diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileStorage.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileStorage.scala index 4817c8f94c..2a3269b929 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileStorage.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileStorage.scala @@ -3,31 +3,27 @@ package org.enso.projectmanager.infrastructure.file import org.enso.projectmanager.infrastructure.file.FileStorage._ import shapeless._ -/** - * An abstraction for storing data object in the file. +/** An abstraction for storing data object in the file. * * @tparam A a datatype to store * @tparam F a monadic context */ trait FileStorage[A, F[+_, +_]] { - /** - * Loads the serialized object from the file. + /** Loads the serialized object from the file. * * @return either [[LoadFailure]] or the object */ def load(): F[LoadFailure, A] - /** - * Persists the provided object on the disk. + /** Persists the provided object on the disk. * * @param data a data object * @return either [[FileSystemFailure]] or success */ def persist(data: A): F[FileSystemFailure, Unit] - /** - * Atomically modifies persisted object using function `f`. + /** Atomically modifies persisted object using function `f`. * * @param f the update function that takes the current version of the object * loaded from the disk and returns a tuple containing the new @@ -41,15 +37,13 @@ trait FileStorage[A, F[+_, +_]] { object FileStorage { - /** - * Signals that representation + /** Signals that representation * * @param msg an error message */ case class CannotDecodeData(msg: String) - /** - * A failure type for load operation. + /** A failure type for load operation. */ type LoadFailure = CannotDecodeData :+: FileSystemFailure :+: CNil diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystem.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystem.scala index 50d201acc5..a0adfdd5d5 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystem.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystem.scala @@ -2,23 +2,20 @@ package org.enso.projectmanager.infrastructure.file import java.io.File -/** - * Represents abstraction for filesystem operations. +/** Represents abstraction for filesystem operations. * * @tparam F target bifunctor */ trait FileSystem[F[+_, +_]] { - /** - * Reads the contents of a textual file. + /** Reads the contents of a textual file. * * @param file path to the file * @return either [[FileSystemFailure]] or the content of a file as a String */ def readFile(file: File): F[FileSystemFailure, String] - /** - * Writes textual content to a file. + /** Writes textual content to a file. * * @param file path to the file * @param contents a textual contents of the file @@ -29,16 +26,14 @@ trait FileSystem[F[+_, +_]] { contents: String ): F[FileSystemFailure, Unit] - /** - * Deletes the specified directory recursively. + /** Deletes the specified directory recursively. * * @param path a path to the directory * @return either [[FileSystemFailure]] or Unit */ def removeDir(path: File): F[FileSystemFailure, Unit] - /** - * Move a file or directory recursively + /** Move a file or directory recursively * * @param from a path to the source * @param to a path to the destination @@ -46,16 +41,14 @@ trait FileSystem[F[+_, +_]] { */ def move(from: File, to: File): F[FileSystemFailure, Unit] - /** - * Tests if a file exists. + /** Tests if a file exists. * * @param file the file to check * @return true if exists */ def exists(file: File): F[FileSystemFailure, Boolean] - /** - * List files in the directory. + /** List files in the directory. * * @param directory a path to the directory * @return the directory contents diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystemFailure.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystemFailure.scala index e2cf061e71..72d9e96efd 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystemFailure.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/FileSystemFailure.scala @@ -1,39 +1,32 @@ package org.enso.projectmanager.infrastructure.file -/** - * Represents file system failures. +/** Represents file system failures. */ sealed trait FileSystemFailure object FileSystemFailure { - /** - * Signals that a user doesn't have access to a file. + /** Signals that a user doesn't have access to a file. */ case object AccessDenied extends FileSystemFailure - /** - * Signals that the file cannot be found. + /** Signals that the file cannot be found. */ case object FileNotFound extends FileSystemFailure - /** - * Signals that the file is not a directory. + /** Signals that the file is not a directory. */ case object NotDirectory extends FileSystemFailure - /** - * Signals that the file already exists. + /** Signals that the file already exists. */ case object FileExists extends FileSystemFailure - /** - * Signal that the operation timed out. + /** Signal that the operation timed out. */ case object OperationTimeout extends FileSystemFailure - /** - * Signals file system specific errors. + /** Signals file system specific errors. * * @param reason a reason of failure */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/JsonFileStorage.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/JsonFileStorage.scala index f1e1075aa3..3cf50f25af 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/JsonFileStorage.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/file/JsonFileStorage.scala @@ -12,8 +12,7 @@ import org.enso.projectmanager.control.effect.{ErrorChannel, Sync} import org.enso.projectmanager.infrastructure.file.FileStorage._ import shapeless.{:+:, CNil, _} -/** - * ZIO implementation of [[FileStorage]]. It uses circe [[Encoder]] and +/** ZIO implementation of [[FileStorage]]. It uses circe [[Encoder]] and * [[Decoder]] to encode/decode objects. * * @param path a path to a file that stores serialized object @@ -28,8 +27,7 @@ class JsonFileStorage[ fileSystem: FileSystem[F] ) extends FileStorage[A, F] { - /** - * Loads the serialized object from the file. + /** Loads the serialized object from the file. * * @return either [[LoadFailure]] or the object */ @@ -50,8 +48,7 @@ class JsonFileStorage[ } } - /** - * Persists the provided object on the disk. + /** Persists the provided object on the disk. * * @param data a data object * @return either [[FileSystemFailure]] or success @@ -59,8 +56,7 @@ class JsonFileStorage[ override def persist(data: A): F[FileSystemFailure, Unit] = fileSystem.overwriteFile(path, data.asJson.spaces2) - /** - * Atomically modifies persisted object using function `f`. + /** Atomically modifies persisted object using function `f`. * * @param f the update function that takes the current version of the object * loaded from the disk and returns a tuple containing the new diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnection.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnection.scala index c90fd74d8b..f083c17c35 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnection.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnection.scala @@ -16,14 +16,13 @@ import org.enso.projectmanager.infrastructure.http.WebSocketConnection.{ WebSocketStreamFailure } -/** - * An Akka-based bidirectional web socket connection. +/** An Akka-based bidirectional web socket connection. * * @param address a server address * @param system an actor system */ -class AkkaBasedWebSocketConnection(address: String)( - implicit system: ActorSystem +class AkkaBasedWebSocketConnection(address: String)(implicit + system: ActorSystem ) extends WebSocketConnection { import system.dispatcher @@ -64,11 +63,11 @@ class AkkaBasedWebSocketConnection(address: String)( private val flow = Flow.fromSinkAndSource(sink, source) - /** @inheritdoc **/ + /** @inheritdoc */ override def attachListener(listener: ActorRef): Unit = receiver ! Listen(listener) - /** @inheritdoc **/ + /** @inheritdoc */ def connect(): Unit = { val (future, _) = Http() @@ -88,10 +87,10 @@ class AkkaBasedWebSocketConnection(address: String)( () } - /** @inheritdoc **/ + /** @inheritdoc */ def send(message: String): Unit = outboundChannel ! message - /** @inheritdoc **/ + /** @inheritdoc */ def disconnect(): Unit = outboundChannel ! CloseWebSocket } diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnectionFactory.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnectionFactory.scala index e4f035704d..3c7e759f7a 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnectionFactory.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/AkkaBasedWebSocketConnectionFactory.scala @@ -2,13 +2,12 @@ package org.enso.projectmanager.infrastructure.http import akka.actor.ActorSystem import org.enso.projectmanager.data.Socket -/** - * A factory of Akka-based web socket connections. +/** A factory of Akka-based web socket connections. */ class AkkaBasedWebSocketConnectionFactory(implicit system: ActorSystem) extends WebSocketConnectionFactory { - /** @inheritdoc **/ + /** @inheritdoc */ override def createConnection(socket: Socket): WebSocketConnection = new AkkaBasedWebSocketConnection(s"ws://${socket.host}:${socket.port}") diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/FanOutReceiver.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/FanOutReceiver.scala index 93bc0053f9..41f3832cd3 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/FanOutReceiver.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/FanOutReceiver.scala @@ -3,8 +3,7 @@ package org.enso.projectmanager.infrastructure.http import akka.actor.{Actor, ActorRef} import org.enso.projectmanager.infrastructure.http.FanOutReceiver.Listen -/** - * A fan-out receiver that delivers messages to multiple listeners. +/** A fan-out receiver that delivers messages to multiple listeners. */ class FanOutReceiver extends Actor { @@ -19,8 +18,7 @@ class FanOutReceiver extends Actor { object FanOutReceiver { - /** - * An attach listener command. + /** An attach listener command. * * @param listener a listener to attach */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnection.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnection.scala index b749251203..7e58552ba8 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnection.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnection.scala @@ -2,30 +2,25 @@ package org.enso.projectmanager.infrastructure.http import akka.actor.ActorRef -/** - * An abstraction representing web socket connection. +/** An abstraction representing web socket connection. */ trait WebSocketConnection { - /** - * Connects to the server. + /** Connects to the server. */ def connect(): Unit - /** - * Disconnects from the server. + /** Disconnects from the server. */ def disconnect(): Unit - /** - * Sends a message to the server. + /** Sends a message to the server. * * @param message a message to sent */ def send(message: String): Unit - /** - * Attaches a listener of incoming messages. + /** Attaches a listener of incoming messages. * * @param listener a message listener for inbound channel */ @@ -35,25 +30,21 @@ trait WebSocketConnection { object WebSocketConnection { - /** - * Signals that a connection was established. + /** Signals that a connection was established. */ case object WebSocketConnected - /** - * An envelope for text messages. + /** An envelope for text messages. * * @param payload a text message */ case class WebSocketMessage(payload: String) - /** - * Signals that connection was closed. + /** Signals that connection was closed. */ case object WebSocketStreamClosed - /** - * Signals a connection failure. + /** Signals a connection failure. * * @param th a throwable */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnectionFactory.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnectionFactory.scala index 249718f5c8..74bd2dc177 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnectionFactory.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/http/WebSocketConnectionFactory.scala @@ -2,13 +2,11 @@ package org.enso.projectmanager.infrastructure.http import org.enso.projectmanager.data.Socket -/** - * Abstract connection factory. +/** Abstract connection factory. */ trait WebSocketConnectionFactory { - /** - * Creates web socket connection. + /** Creates web socket connection. * * @param socket a server address * @return a connection diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/HeartbeatSession.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/HeartbeatSession.scala index 6dcaf94441..ab30c294cf 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/HeartbeatSession.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/HeartbeatSession.scala @@ -22,8 +22,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * Implements one ping-pong session. +/** Implements one ping-pong session. * * @param socket a server socket * @param timeout a session timeout @@ -149,18 +148,15 @@ class HeartbeatSession( object HeartbeatSession { - /** - * Signals heartbeat timeout. + /** Signals heartbeat timeout. */ case object HeartbeatTimeout - /** - * Signals socket closure timeout. + /** Signals socket closure timeout. */ case object SocketClosureTimeout - /** - * Creates a configuration object used to create a [[LanguageServerSupervisor]]. + /** Creates a configuration object used to create a [[LanguageServerSupervisor]]. * * @param socket a server socket * @param timeout a session timeout diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerBootLoader.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerBootLoader.scala index 9d78cb2cc5..0e3eef7ee2 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerBootLoader.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerBootLoader.scala @@ -17,8 +17,7 @@ import org.enso.projectmanager.infrastructure.languageserver.LanguageServerBootL import org.enso.projectmanager.infrastructure.net.Tcp import org.enso.projectmanager.util.UnhandledLogging -/** - * It boots a Language Sever described by the `descriptor`. Upon boot failure +/** It boots a Language Sever described by the `descriptor`. Upon boot failure * looks up new available port and retries to boot the server. * * @param descriptor a LS descriptor @@ -112,8 +111,7 @@ class LanguageServerBootLoader( object LanguageServerBootLoader { - /** - * Creates a configuration object used to create a [[LanguageServerBootLoader]]. + /** Creates a configuration object used to create a [[LanguageServerBootLoader]]. * * @param descriptor a LS descriptor * @param config a bootloader config @@ -125,25 +123,21 @@ object LanguageServerBootLoader { ): Props = Props(new LanguageServerBootLoader(descriptor, config)) - /** - * Find free socket command. + /** Find free socket command. */ case object FindFreeSocket - /** - * Boot command. + /** Boot command. */ case object Boot - /** - * Signals that server boot failed. + /** Signals that server boot failed. * * @param th a throwable */ case class ServerBootFailed(th: Throwable) - /** - * Signals that server booted successfully. + /** Signals that server booted successfully. * * @param config a server config * @param server a server lifecycle component diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerController.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerController.scala index c853e4b8a8..7cb3291229 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerController.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerController.scala @@ -48,8 +48,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration._ -/** - * A language server controller responsible for managing the server lifecycle. +/** A language server controller responsible for managing the server lifecycle. * It delegates all tasks to other actors like bootloader or supervisor. * * @param project a project open by the server @@ -80,8 +79,8 @@ class LanguageServerController( ) override def supervisorStrategy: SupervisorStrategy = - OneForOneStrategy(10) { - case _ => SupervisorStrategy.Restart + OneForOneStrategy(10) { case _ => + SupervisorStrategy.Restart } override def preStart(): Unit = { @@ -259,11 +258,10 @@ class LanguageServerController( sender() ! PreviousInstanceNotShutDown } - private def waitingForChildren(): Receive = { - case Terminated(_) => - if (context.children.isEmpty) { - context.stop(self) - } + private def waitingForChildren(): Receive = { case Terminated(_) => + if (context.children.isEmpty) { + context.stop(self) + } } private def stop(): Unit = { @@ -282,8 +280,7 @@ class LanguageServerController( object LanguageServerController { - /** - * Creates a configuration object used to create a [[LanguageServerController]]. + /** Creates a configuration object used to create a [[LanguageServerController]]. * * @param project a project open by the server * @param networkConfig a net config @@ -311,18 +308,15 @@ object LanguageServerController { case object ShutDownServer - /** - * Signals boot timeout. + /** Signals boot timeout. */ case object BootTimeout - /** - * Boot command. + /** Boot command. */ case object Boot - /** - * Signals shutdown timeout. + /** Signals shutdown timeout. */ case object ShutdownTimeout diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerDescriptor.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerDescriptor.scala index 413c5cf67d..d585bcf06c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerDescriptor.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerDescriptor.scala @@ -4,8 +4,7 @@ import java.util.UUID import org.enso.projectmanager.boot.configuration.NetworkConfig -/** - * A descriptor used to start up a Language Server. +/** A descriptor used to start up a Language Server. * * @param name a name of the LS * @param rootId a content root id diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGateway.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGateway.scala index 92269e737d..fa8e7f5ac0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGateway.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGateway.scala @@ -12,15 +12,13 @@ import org.enso.projectmanager.infrastructure.languageserver.LanguageServerProto import org.enso.projectmanager.infrastructure.shutdown.ShutdownHook import org.enso.projectmanager.model.Project -/** - * A gateway to lang. server subsystem. +/** A gateway to lang. server subsystem. * * @tparam F a effectful context */ trait LanguageServerGateway[F[+_, +_]] { - /** - * Starts a language server. + /** Starts a language server. * * @param clientId a requester id * @param project a project to start @@ -31,8 +29,7 @@ trait LanguageServerGateway[F[+_, +_]] { project: Project ): F[ServerStartupFailure, LanguageServerSockets] - /** - * Stops a lang. server. + /** Stops a lang. server. * * @param clientId a requester id * @param projectId a project id to stop @@ -43,16 +40,14 @@ trait LanguageServerGateway[F[+_, +_]] { projectId: UUID ): F[ServerShutdownFailure, Unit] - /** - * Checks if server is running for project. + /** Checks if server is running for project. * * @param projectId a project id * @return true if project is open */ def isRunning(projectId: UUID): F[CheckTimeout.type, Boolean] - /** - * Request a language server to rename project. + /** Request a language server to rename project. * * @param projectId the project id * @param oldName the old project name @@ -65,15 +60,13 @@ trait LanguageServerGateway[F[+_, +_]] { newName: String ): F[ProjectRenameFailure, Unit] - /** - * Kills all running servers. + /** Kills all running servers. * * @return true if servers are killed, false otherwise */ def killAllServers(): F[Throwable, Boolean] - /** - * Registers a shutdown hook. + /** Registers a shutdown hook. * * @param projectId the project for which the hook will be registered * @param hook the shutdown hook to register @@ -84,8 +77,7 @@ trait LanguageServerGateway[F[+_, +_]] { hook: ShutdownHook[F] ): F[Nothing, Unit] - /** - * Waits until all shutdown hooks will be fired. + /** Waits until all shutdown hooks will be fired. * * @return */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGatewayImpl.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGatewayImpl.scala index 4b6ff7acb6..0e4b7100d7 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGatewayImpl.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerGatewayImpl.scala @@ -20,8 +20,7 @@ import org.enso.projectmanager.infrastructure.languageserver.ShutdownHookActivat import org.enso.projectmanager.infrastructure.shutdown.ShutdownHook import org.enso.projectmanager.model.Project -/** - * It is a proxy to actor based language subsystem. It a bridge between +/** It is a proxy to actor based language subsystem. It a bridge between * actor interface and pure functional effects. * * @param registry a lang. server registry @@ -37,7 +36,7 @@ class LanguageServerGatewayImpl[ timeoutConfig: TimeoutConfig ) extends LanguageServerGateway[F] { - /** @inheritdoc * */ + /** @inheritdoc */ override def start( clientId: UUID, project: Project @@ -55,7 +54,7 @@ class LanguageServerGatewayImpl[ } } - /** @inheritdoc * */ + /** @inheritdoc */ override def stop( clientId: UUID, projectId: UUID @@ -72,7 +71,7 @@ class LanguageServerGatewayImpl[ } } - /** @inheritdoc * */ + /** @inheritdoc */ override def isRunning(projectId: UUID): F[CheckTimeout.type, Boolean] = { implicit val timeout: Timeout = Timeout(timeoutConfig.requestTimeout) @@ -83,7 +82,7 @@ class LanguageServerGatewayImpl[ .mapError(_ => CheckTimeout) } - /** @inheritdoc * */ + /** @inheritdoc */ override def renameProject( projectId: UUID, oldName: String, diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerKiller.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerKiller.scala index fd436d80c1..f09391fad7 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerKiller.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerKiller.scala @@ -19,8 +19,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * An actor that shuts all running language servers. It orchestrates all +/** An actor that shuts all running language servers. It orchestrates all * language server controllers to shut down gracefully servers. When it is not * possible it kills all controller actors. * @@ -36,23 +35,22 @@ class LanguageServerKiller( import context.dispatcher - override def receive: Receive = { - case KillThemAll => - if (controllers.isEmpty) { - sender() ! AllServersKilled - context.stop(self) - } else { - log.info("Killing all servers") - controllers.foreach(context.watch) - controllers.foreach(_ ! ShutDownServer) - val cancellable = - context.system.scheduler.scheduleOnce( - shutdownTimeout, - self, - KillTimeout - ) - context.become(killing(controllers.toSet, cancellable, sender())) - } + override def receive: Receive = { case KillThemAll => + if (controllers.isEmpty) { + sender() ! AllServersKilled + context.stop(self) + } else { + log.info("Killing all servers") + controllers.foreach(context.watch) + controllers.foreach(_ ! ShutDownServer) + val cancellable = + context.system.scheduler.scheduleOnce( + shutdownTimeout, + self, + KillTimeout + ) + context.become(killing(controllers.toSet, cancellable, sender())) + } } private def killing( @@ -82,8 +80,7 @@ object LanguageServerKiller { private case object KillTimeout - /** - * Creates configuration object used to create a [[LanguageServerKiller]]. + /** Creates configuration object used to create a [[LanguageServerKiller]]. * * @param controllers running controllers * @param shutdownTimeout a shutdown timeout diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerProtocol.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerProtocol.scala index e08497874d..39cb925698 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerProtocol.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerProtocol.scala @@ -5,124 +5,103 @@ import java.util.UUID import org.enso.projectmanager.data.LanguageServerSockets import org.enso.projectmanager.model.Project -/** - * A language subsystem protocol. +/** A language subsystem protocol. */ object LanguageServerProtocol { - /** - * Command to start a server. + /** Command to start a server. * * @param clientId the requester id * @param project the project to start */ case class StartServer(clientId: UUID, project: Project) - /** - * Base trait for server startup results. + /** Base trait for server startup results. */ sealed trait ServerStartupResult - /** - * Signals that server started successfully. + /** Signals that server started successfully. * * @param sockets the server sockets */ case class ServerStarted(sockets: LanguageServerSockets) extends ServerStartupResult - /** - * Base trait for server startup failures. + /** Base trait for server startup failures. */ sealed trait ServerStartupFailure extends ServerStartupResult - /** - * Signals that server boot failed with exception. + /** Signals that server boot failed with exception. * * @param throwable an exception thrown by bootloader */ case class ServerBootFailed(throwable: Throwable) extends ServerStartupFailure - /** - * Signals server boot timeout. + /** Signals server boot timeout. */ case object ServerBootTimedOut extends ServerStartupFailure - /** - * Signals that previous instance of the server hasn't been shut down yet. + /** Signals that previous instance of the server hasn't been shut down yet. */ case object PreviousInstanceNotShutDown extends ServerStartupFailure - /** - * Command to stop a server. + /** Command to stop a server. * * @param clientId the requester id * @param projectId the project id */ case class StopServer(clientId: UUID, projectId: UUID) - /** - * A command that kills all running servers. + /** A command that kills all running servers. */ case object KillThemAll - /** - * Signals that all servers have been killed. + /** Signals that all servers have been killed. */ case object AllServersKilled - /** - * Base trait for server shutdown results. + /** Base trait for server shutdown results. */ sealed trait ServerShutdownResult - /** - * Signals that server stopped successfully. + /** Signals that server stopped successfully. */ case object ServerStopped extends ServerShutdownResult - /** - * Base trait for server shutdown failures. + /** Base trait for server shutdown failures. */ sealed trait ServerShutdownFailure extends ServerShutdownResult - /** - * Signals that server shutdown timed out. + /** Signals that server shutdown timed out. */ case object ServerShutdownTimedOut extends ServerShutdownFailure - /** - * Signals that an exception was thrown during stopping a server. + /** Signals that an exception was thrown during stopping a server. * * @param th an exception */ case class FailureDuringShutdown(th: Throwable) extends ServerShutdownFailure - /** - * Signals that server wasn't started. + /** Signals that server wasn't started. */ case object ServerNotRunning extends ServerShutdownFailure - /** - * Signals that server cannot be stopped, because other clients are connected + /** Signals that server cannot be stopped, because other clients are connected * to the server. */ case object CannotDisconnectOtherClients extends ServerShutdownFailure - /** - * Request to check is server is running. + /** Request to check is server is running. * * @param projectId the project id */ case class CheckIfServerIsRunning(projectId: UUID) - /** - * Signals that check timed out. + /** Signals that check timed out. */ case object CheckTimeout - /** - * A command requesting for project renaming. + /** A command requesting for project renaming. * * @param projectId the project id * @param oldName the old project name @@ -130,38 +109,31 @@ object LanguageServerProtocol { */ case class RenameProject(projectId: UUID, oldName: String, newName: String) - /** - * Base trait for project rename results. + /** Base trait for project rename results. */ sealed trait ProjectRenameResult - /** - * Signals that a project has been renamed successfully. + /** Signals that a project has been renamed successfully. */ case object ProjectRenamed extends ProjectRenameResult - /** - * Base trait for project rename failures. + /** Base trait for project rename failures. */ sealed trait ProjectRenameFailure extends ProjectRenameResult - /** - * Signals that a project is not opened. + /** Signals that a project is not opened. */ case object ProjectNotOpened extends ProjectRenameFailure - /** - * Signals that renaming operation timed out. + /** Signals that renaming operation timed out. */ case object RenameTimeout extends ProjectRenameFailure - /** - * Signals that cannot connect to a language server. + /** Signals that cannot connect to a language server. */ case object CannotConnectToServer extends ProjectRenameFailure - /** - * Signals a failure during project renaming. + /** Signals a failure during project renaming. * * @param code a failure code * @param message a failure message @@ -169,8 +141,7 @@ object LanguageServerProtocol { case class RenameFailure(code: Int, message: String) extends ProjectRenameFailure - /** - * Signals that a language server is unresponsive. + /** Signals that a language server is unresponsive. */ case object ServerUnresponsive extends ProjectRenameFailure diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerRegistry.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerRegistry.scala index 77f5efa451..68c4b21d84 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerRegistry.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerRegistry.scala @@ -21,8 +21,7 @@ import org.enso.projectmanager.infrastructure.languageserver.LanguageServerProto import org.enso.projectmanager.infrastructure.languageserver.LanguageServerRegistry.ServerShutDown import org.enso.projectmanager.util.UnhandledLogging -/** - * An actor that routes request regarding lang. server lifecycle to the +/** An actor that routes request regarding lang. server lifecycle to the * right controller that manages the server. * It creates a controller actor, if a server doesn't exists. * @@ -105,15 +104,13 @@ class LanguageServerRegistry( object LanguageServerRegistry { - /** - * A notification informing that a server has shut down. + /** A notification informing that a server has shut down. * * @param projectId a project id */ case class ServerShutDown(projectId: UUID) - /** - * Creates a configuration object used to create a [[LanguageServerRegistry]]. + /** Creates a configuration object used to create a [[LanguageServerRegistry]]. * * @param networkConfig a net config * @param bootloaderConfig a bootloader config diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisor.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisor.scala index c524f86638..50afb3528b 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisor.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisor.scala @@ -26,8 +26,7 @@ import org.enso.projectmanager.infrastructure.languageserver.LanguageServerSuper } import org.enso.projectmanager.util.UnhandledLogging -/** - * A supervisor process responsible for monitoring language server and +/** A supervisor process responsible for monitoring language server and * restarting it when the server is unresponsive. It delegates server * monitoring to the [[HeartbeatSession]] actor. * @@ -129,11 +128,10 @@ class LanguageServerSupervisor( stop() } - private def waitingForChildren(): Receive = { - case Terminated(_) => - if (context.children.isEmpty) { - context.stop(self) - } + private def waitingForChildren(): Receive = { case Terminated(_) => + if (context.children.isEmpty) { + context.stop(self) + } } private def stop(): Unit = { @@ -154,18 +152,15 @@ object LanguageServerSupervisor { private case object RestartServer - /** - * A command responsible for initiating heartbeat session. + /** A command responsible for initiating heartbeat session. */ case object SendHeartbeat - /** - * Signals that server is unresponsive. + /** Signals that server is unresponsive. */ case object ServerUnresponsive - /** - * Creates a configuration object used to create a [[LanguageServerSupervisor]]. + /** Creates a configuration object used to create a [[LanguageServerSupervisor]]. * * @param config a server config * @param server a server handle diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameAction.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameAction.scala index f0fb62e696..b6ff603ee7 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameAction.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameAction.scala @@ -30,8 +30,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * An action that encapsulates a request-reply flow responsible for refactoring +/** An action that encapsulates a request-reply flow responsible for refactoring * project name in a running language server. * * @param replyTo a recipient of a reply @@ -200,18 +199,15 @@ class ProjectRenameAction( object ProjectRenameAction { - /** - * Signals an action timeout. + /** Signals an action timeout. */ case object ActionTimeout - /** - * Signals a socket closure timeout. + /** Signals a socket closure timeout. */ case object SocketClosureTimeout - /** - * Creates a configuration object used to create a [[ProjectRenameAction]]. + /** Creates a configuration object used to create a [[ProjectRenameAction]]. * * @param replyTo a recipient of a reply * @param socket a server socket diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivationWatcher.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivationWatcher.scala index 7f9c5d8697..53cb7a1bb5 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivationWatcher.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivationWatcher.scala @@ -10,8 +10,7 @@ import org.enso.projectmanager.infrastructure.languageserver.ShutdownHookActivat import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration._ -/** - * An actor that waits until all shutdown hooks will be fired. +/** An actor that waits until all shutdown hooks will be fired. * * @param shutdownHookActivator a reference to an activator */ @@ -22,10 +21,9 @@ class ShutdownHookActivationWatcher(shutdownHookActivator: ActorRef) import context.dispatcher - override def receive: Receive = { - case Watch => - shutdownHookActivator ! ArePendingShutdownHooks - context.become(waitingForReply(sender())) + override def receive: Receive = { case Watch => + shutdownHookActivator ! ArePendingShutdownHooks + context.become(waitingForReply(sender())) } private def waitingForReply(client: ActorRef): Receive = { @@ -38,30 +36,26 @@ class ShutdownHookActivationWatcher(shutdownHookActivator: ActorRef) context.stop(self) } - private def sleeping(client: ActorRef): Receive = { - case WakeUp => - shutdownHookActivator ! ArePendingShutdownHooks - context.become(waitingForReply(client)) + private def sleeping(client: ActorRef): Receive = { case WakeUp => + shutdownHookActivator ! ArePendingShutdownHooks + context.become(waitingForReply(client)) } } object ShutdownHookActivationWatcher { - /** - * A command that starts watching for a completion of shutdown hooks. + /** A command that starts watching for a completion of shutdown hooks. */ case object Watch - /** - * Signals that all shutdown hooks are completed. + /** Signals that all shutdown hooks are completed. */ case object AllShutdownHooksFired private case object WakeUp - /** - * Creates a configuration object used to create a + /** Creates a configuration object used to create a * [[ShutdownHookActivationWatcher]]. * * @param shutdownHookActivator a reference to an activator diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivator.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivator.scala index 895037a1d6..70511598b4 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivator.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookActivator.scala @@ -13,8 +13,7 @@ import org.enso.projectmanager.infrastructure.languageserver.ShutdownHookActivat import org.enso.projectmanager.infrastructure.shutdown.ShutdownHook import org.enso.projectmanager.util.UnhandledLogging -/** - * The ShutdownHookActivator is responsible for receiving asynchronously +/** The ShutdownHookActivator is responsible for receiving asynchronously * [[ProjectClosed]] events and invoking all shutdown hooks for the closed * project. */ @@ -56,21 +55,18 @@ class ShutdownHookActivator[F[+_, +_]: Exec: CovariantFlatMap] object ShutdownHookActivator { - /** - * A command used to register a project shutdown hook. + /** A command used to register a project shutdown hook. */ case class RegisterShutdownHook[F[+_, +_]]( projectId: UUID, hook: ShutdownHook[F] ) - /** - * Requests an activator if there are pending shutdown hooks. + /** Requests an activator if there are pending shutdown hooks. */ case object ArePendingShutdownHooks - /** - * Creates a configuration object used to create a [[ShutdownHookActivator]]. + /** Creates a configuration object used to create a [[ShutdownHookActivator]]. * * @return a configuration object */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookRunner.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookRunner.scala index 906ab2bcb3..f9f2dfdac2 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookRunner.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/ShutdownHookRunner.scala @@ -11,8 +11,7 @@ import org.enso.projectmanager.infrastructure.languageserver.ShutdownHookRunner. import org.enso.projectmanager.infrastructure.shutdown.ShutdownHook import org.enso.projectmanager.util.UnhandledLogging -/** - * An actor that invokes a shutdown hook. +/** An actor that invokes a shutdown hook. * * @param projectId a project id for which a hook is invoked * @param hooks a hook to invoke @@ -30,11 +29,10 @@ class ShutdownHookRunner[F[+_, +_]: Exec: CovariantFlatMap]( self ! Run } - override def receive: Receive = { - case Run => - log.info(s"Firing shutdown hooks for project with id=$projectId") - Exec[F].exec { traverse(hooks) { _.execute() } } pipeTo self - context.become(running) + override def receive: Receive = { case Run => + log.info(s"Firing shutdown hooks for project with id=$projectId") + Exec[F].exec { traverse(hooks) { _.execute() } } pipeTo self + context.become(running) } private def running: Receive = { @@ -53,8 +51,8 @@ class ShutdownHookRunner[F[+_, +_]: Exec: CovariantFlatMap]( private def traverse[A, B]( fa: List[A] )(f: A => F[Nothing, B]): F[Nothing, List[B]] = - fa.foldLeft(CovariantFlatMap[F].pure(List.empty[B])) { - case (tail, hook) => map2(f(hook), tail)(_ :: _) + fa.foldLeft(CovariantFlatMap[F].pure(List.empty[B])) { case (tail, hook) => + map2(f(hook), tail)(_ :: _) } private def map2[A, B, C](fa: F[Nothing, A], fb: F[Nothing, B])( @@ -71,8 +69,7 @@ object ShutdownHookRunner { private case object Run - /** - * Creates a configuration object used to create a [[ShutdownHookRunner]]. + /** Creates a configuration object used to create a [[ShutdownHookRunner]]. * * @param projectId a project id for which a hook is invoked * @param hooks a hook to invoke diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/package.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/package.scala index 77b27a702f..448b98dd64 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/package.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/languageserver/package.scala @@ -2,8 +2,7 @@ package org.enso.projectmanager.infrastructure package object languageserver { - /** - * A stop command. + /** A stop command. */ case object GracefulStop diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Logging.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Logging.scala index 80d5de46f4..4a9a43e75e 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Logging.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Logging.scala @@ -1,7 +1,6 @@ package org.enso.projectmanager.infrastructure.log -/** - * A pure functional logging facility. +/** A pure functional logging facility. * * @tparam F a monadic context */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Slf4jLogging.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Slf4jLogging.scala index 586d902aa0..f80da0b45c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Slf4jLogging.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/log/Slf4jLogging.scala @@ -2,8 +2,7 @@ package org.enso.projectmanager.infrastructure.log import com.typesafe.scalalogging.LazyLogging import org.enso.projectmanager.control.effect.Sync -/** - * Slf4j logging interpreter. +/** Slf4j logging interpreter. */ class Slf4jLogging[F[+_, +_]: Sync] extends Logging[F] with LazyLogging { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/net/Tcp.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/net/Tcp.scala index b36cd9ab75..7211b1c31e 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/net/Tcp.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/net/Tcp.scala @@ -6,13 +6,11 @@ import javax.net.ServerSocketFactory import scala.annotation.tailrec import scala.util.Random -/** - * A namespace for TCP auxiliary functions. +/** A namespace for TCP auxiliary functions. */ object Tcp { - /** - * Finds first available socket. + /** Finds first available socket. * * @param host a host * @param minPort a minimum value of port @@ -30,8 +28,7 @@ object Tcp { } } - /** - * Checks if socket is available. + /** Checks if socket is available. * * @param host a host * @param port a port diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/Generator.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/Generator.scala index ec9dd336c1..48ec35307f 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/Generator.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/Generator.scala @@ -2,15 +2,13 @@ package org.enso.projectmanager.infrastructure.random import java.util.UUID -/** - * A pure functional abstraction for random generation. +/** A pure functional abstraction for random generation. * * @tparam F a monadic context */ trait Generator[F[+_, +_]] { - /** - * Returns random UUID in version 4. + /** Returns random UUID in version 4. * * @return a UUID */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/SystemGenerator.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/SystemGenerator.scala index a77951b4fb..cfd9062931 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/SystemGenerator.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/random/SystemGenerator.scala @@ -3,13 +3,11 @@ import java.util.UUID import org.enso.projectmanager.control.effect.Sync -/** - * A system pseudo-random numbers generator. +/** A system pseudo-random numbers generator. */ class SystemGenerator[F[+_, +_]: Sync] extends Generator[F] { - /** - * Returns random UUID in version 4. + /** Returns random UUID in version 4. * * @return a UUID */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/MetadataFileStorage.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/MetadataFileStorage.scala index bf185c3d12..7fc33f8f04 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/MetadataFileStorage.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/MetadataFileStorage.scala @@ -24,8 +24,7 @@ import org.enso.projectmanager.infrastructure.time.Clock import org.enso.projectmanager.model.{ProjectKind, ProjectMetadata} import shapeless.{Coproduct, Inl, Inr} -/** - * File based implementation of the project metadata storage. +/** File based implementation of the project metadata storage. * * @param directory a project directory * @param storageConfig a storage config diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectFileRepository.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectFileRepository.scala index 7931f7e643..03a68da91f 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectFileRepository.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectFileRepository.scala @@ -27,8 +27,7 @@ import org.enso.projectmanager.infrastructure.repository.ProjectRepositoryFailur import org.enso.projectmanager.infrastructure.time.Clock import org.enso.projectmanager.model.{Project, ProjectMetadata} -/** - * File based implementation of the project repository. +/** File based implementation of the project repository. * * @param storageConfig a storage config * @param clock a clock @@ -61,8 +60,8 @@ class ProjectFileRepository[ fileSystem .list(storageConfig.userProjectsPath) .map(_.filter(_.isDirectory)) - .recover { - case FileNotFound | NotDirectory => Nil + .recover { case FileNotFound | NotDirectory => + Nil } .mapError(th => StorageFailure(th.toString)) .flatMap(s => Traverse[List].traverse(s)(tryLoadProject).map(_.flatten)) @@ -150,7 +149,7 @@ class ProjectFileRepository[ case Some(project) => CovariantFlatMap[F].pure(project) } - /** @inheritdoc * */ + /** @inheritdoc */ def getPackageName(projectId: UUID): F[ProjectRepositoryFailure, String] = { for { project <- getProject(projectId) diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectIndex.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectIndex.scala index d1f544e3f5..ab8ef011da 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectIndex.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectIndex.scala @@ -5,15 +5,13 @@ import java.util.UUID import org.enso.projectmanager.data.Default import org.enso.projectmanager.model.Project -/** - * A helper data object enabling indexing of projects. +/** A helper data object enabling indexing of projects. * * @param projects user projects index */ case class ProjectIndex(projects: Map[UUID, Project] = Map.empty) { - /** - * Upserts a project to the index. + /** Upserts a project to the index. * * @param project the project to add * @return an updated project @@ -21,8 +19,7 @@ case class ProjectIndex(projects: Map[UUID, Project] = Map.empty) { def upsert(project: Project): ProjectIndex = ProjectIndex(projects + (project.id -> project)) - /** - * Updates a project inside the index using a modifcation function. + /** Updates a project inside the index using a modifcation function. * * @param id the project id * @param f the modification functionProjectRenameHandler @@ -30,8 +27,7 @@ case class ProjectIndex(projects: Map[UUID, Project] = Map.empty) { def update(id: UUID)(f: Project => Project): ProjectIndex = ProjectIndex(projects + (id -> f(projects(id)))) - /** - * Removes a project. + /** Removes a project. * * @param projectId the project id to remove * @return an updated project @@ -39,8 +35,7 @@ case class ProjectIndex(projects: Map[UUID, Project] = Map.empty) { def remove(projectId: UUID): ProjectIndex = ProjectIndex(projects - projectId) - /** - * Finds user project by ID. + /** Finds user project by ID. * * @param projectId a project id * @return optional project @@ -48,8 +43,7 @@ case class ProjectIndex(projects: Map[UUID, Project] = Map.empty) { def findById(projectId: UUID): Option[Project] = projects.get(projectId) - /** - * Queries index using a function that specifies criteria of result set. + /** Queries index using a function that specifies criteria of result set. * * @param predicate a predicate function * @return projects that meet the criteria @@ -57,8 +51,7 @@ case class ProjectIndex(projects: Map[UUID, Project] = Map.empty) { def find(predicate: Project => Boolean): List[Project] = projects.values.filter(predicate).toList - /** - * Checks if project with the provided name is in the index. + /** Checks if project with the provided name is in the index. * * @param name a project name * @return true if exists diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepository.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepository.scala index 585b38e660..0588175105 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepository.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepository.scala @@ -5,47 +5,41 @@ import java.util.UUID import org.enso.projectmanager.model.Project -/** - * An abstraction for accessing project domain objects from durable storage. +/** An abstraction for accessing project domain objects from durable storage. * * @tparam F a monadic context */ trait ProjectRepository[F[+_, +_]] { - /** - * Tests if project is present in the data storage. + /** Tests if project is present in the data storage. * * @param name a project name * @return true if project exists */ def exists(name: String): F[ProjectRepositoryFailure, Boolean] - /** - * Creates the provided user project in the storage. + /** Creates the provided user project in the storage. * * @param project the project to insert * @return */ def create(project: Project): F[ProjectRepositoryFailure, Unit] - /** - * Saves the provided user project in the index. + /** Saves the provided user project in the index. * * @param project the project to update * @return */ def update(project: Project): F[ProjectRepositoryFailure, Unit] - /** - * Removes the provided project from the storage. + /** Removes the provided project from the storage. * * @param projectId the project id to remove * @return either failure or success */ def delete(projectId: UUID): F[ProjectRepositoryFailure, Unit] - /** - * Renames a project. + /** Renames a project. * * @param projectId the project id to rename * @param name the new name @@ -53,8 +47,7 @@ trait ProjectRepository[F[+_, +_]] { */ def rename(projectId: UUID, name: String): F[ProjectRepositoryFailure, Unit] - /** - * Finds a project by project id. + /** Finds a project by project id. * * @param projectId a project id * @return option with the project entity @@ -63,8 +56,7 @@ trait ProjectRepository[F[+_, +_]] { projectId: UUID ): F[ProjectRepositoryFailure, Option[Project]] - /** - * Finds projects that meet criteria specified by predicate. + /** Finds projects that meet criteria specified by predicate. * * @param predicate a predicate function * @return projects that meet the criteria @@ -73,15 +65,13 @@ trait ProjectRepository[F[+_, +_]] { predicate: Project => Boolean ): F[ProjectRepositoryFailure, List[Project]] - /** - * Gets all projects from the data store. + /** Gets all projects from the data store. * * @return all projects stored in the project index */ def getAll(): F[ProjectRepositoryFailure, List[Project]] - /** - * Moves project to the target dir. + /** Moves project to the target dir. * * @param projectId the project id * @param newName the new project name @@ -91,8 +81,7 @@ trait ProjectRepository[F[+_, +_]] { newName: String ): F[ProjectRepositoryFailure, File] - /** - * Gets a package name for the specified project. + /** Gets a package name for the specified project. * * @param projectId the project id * @return either a failure or a package name diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepositoryFailure.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepositoryFailure.scala index 9dc71b16d7..d455950dcb 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepositoryFailure.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/ProjectRepositoryFailure.scala @@ -1,32 +1,27 @@ package org.enso.projectmanager.infrastructure.repository -/** - * Base interface for repository failures. +/** Base interface for repository failures. */ sealed trait ProjectRepositoryFailure object ProjectRepositoryFailure { - /** - * Signals that repository cannot load project index. + /** Signals that repository cannot load project index. * @param msg an error message */ case class CannotLoadIndex(msg: String) extends ProjectRepositoryFailure - /** - * Signals problems with underlying storage. + /** Signals problems with underlying storage. * * @param msg an error message */ case class StorageFailure(msg: String) extends ProjectRepositoryFailure - /** - * Signals that project is not present in the storage. + /** Signals that project is not present in the storage. */ case object ProjectNotFoundInIndex extends ProjectRepositoryFailure - /** - * Signals that precondition is not met for stored data. + /** Signals that precondition is not met for stored data. * * @param msg an error message */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/package.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/package.scala index 3fcc2af576..25b68f8c4c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/package.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/repository/package.scala @@ -10,8 +10,7 @@ import shapeless._ package object repository { - /** - * Polymorphic function converting [[org.enso.projectmanager.infrastructure.file.FileStorage]] + /** Polymorphic function converting [[org.enso.projectmanager.infrastructure.file.FileStorage]] * failures to [[ProjectRepositoryFailure]] */ object convertFileStorageFailure extends Poly1 { diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/shutdown/ShutdownHook.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/shutdown/ShutdownHook.scala index 6ccb64344a..030795f70c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/shutdown/ShutdownHook.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/shutdown/ShutdownHook.scala @@ -1,13 +1,11 @@ package org.enso.projectmanager.infrastructure.shutdown -/** - * Application-level shutdown hook. It allows to run functions before the +/** Application-level shutdown hook. It allows to run functions before the * applications completes its shutdown. */ trait ShutdownHook[F[+_, +_]] { - /** - * Executes this hook. + /** Executes this hook. */ def execute(): F[Nothing, Unit] diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/Clock.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/Clock.scala index 63b1f6462a..c8176a2b4d 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/Clock.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/Clock.scala @@ -2,23 +2,20 @@ package org.enso.projectmanager.infrastructure.time import java.time.OffsetDateTime -/** - * A clock abstraction providing pure access to the current date and time +/** A clock abstraction providing pure access to the current date and time * using a time-zone. * * @tparam F monadic context */ trait Clock[F[+_, +_]] { - /** - * Obtains the current date-time from the system clock in the default time-zone. + /** Obtains the current date-time from the system clock in the default time-zone. * * @return a date time */ def now(): F[Nothing, OffsetDateTime] - /** - * Obtains the current date-time from the system clock in the UTC time-zone. + /** Obtains the current date-time from the system clock in the UTC time-zone. * * @return a date time */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/RealClock.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/RealClock.scala index 13cfb25795..e4ebc45ed9 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/RealClock.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/infrastructure/time/RealClock.scala @@ -3,21 +3,18 @@ import java.time.{OffsetDateTime, ZoneOffset} import org.enso.projectmanager.control.effect.Sync -/** - * A system clock. +/** A system clock. */ class RealClock[F[+_, +_]: Sync] extends Clock[F] { - /** - * Obtains the current date-time from the system clock in the default time-zone. + /** Obtains the current date-time from the system clock in the default time-zone. * * @return a date time */ override def now(): F[Nothing, OffsetDateTime] = Sync[F].effect(OffsetDateTime.now()) - /** - * Obtains the current date-time from the system clock in the UTC time-zone. + /** Obtains the current date-time from the system clock in the UTC time-zone. * * @return a date time */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/Project.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/Project.scala index d981aa05ca..18d3248e3d 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/Project.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/Project.scala @@ -3,8 +3,7 @@ package org.enso.projectmanager.model import java.time.OffsetDateTime import java.util.UUID -/** - * Project entity. +/** Project entity. * * @param id a project id * @param name a project name diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectKind.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectKind.scala index d2d0709365..6772306ae7 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectKind.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectKind.scala @@ -2,15 +2,13 @@ package org.enso.projectmanager.model import enumeratum._ -/** - * Enum that distinguishes between different kinds of projects. +/** Enum that distinguishes between different kinds of projects. */ sealed trait ProjectKind extends EnumEntry object ProjectKind extends Enum[ProjectKind] with CirceEnum[ProjectKind] { - /** - * Enum value for user projects. + /** Enum value for user projects. */ case object UserProject extends ProjectKind diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectMetadata.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectMetadata.scala index 3ff275a2a7..a4a883f140 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectMetadata.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/model/ProjectMetadata.scala @@ -3,8 +3,7 @@ package org.enso.projectmanager.model import java.time.OffsetDateTime import java.util.UUID -/** - * Project metadata entity. +/** Project metadata entity. * * @param id a project id * @param kind a project kind @@ -20,8 +19,7 @@ case class ProjectMetadata( object ProjectMetadata { - /** - * Create an instance from the project entity. + /** Create an instance from the project entity. * * @param project the project entity * @return the project metadata diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ClientController.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ClientController.scala index 81b89926b0..fc805198c9 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ClientController.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ClientController.scala @@ -6,7 +6,10 @@ import akka.actor.{Actor, ActorLogging, ActorRef, Props, Stash} import org.enso.jsonrpc.{JsonRpcServer, MessageHandler, Method, Request} import org.enso.projectmanager.boot.configuration.TimeoutConfig import org.enso.projectmanager.control.effect.Exec -import org.enso.projectmanager.event.ClientEvent.{ClientConnected, ClientDisconnected} +import org.enso.projectmanager.event.ClientEvent.{ + ClientConnected, + ClientDisconnected +} import org.enso.projectmanager.protocol.ProjectManagementApi._ import org.enso.projectmanager.requesthandler._ import org.enso.projectmanager.service.ProjectServiceApi @@ -15,8 +18,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.annotation.unused import scala.concurrent.duration._ -/** - * An actor handling communications between a single client and the project +/** An actor handling communications between a single client and the project * manager. * * @param clientId the internal client id. @@ -68,7 +70,7 @@ class ClientController[F[+_, +_]: Exec]( context.system.eventStream.publish(ClientDisconnected(clientId)) context.stop(self) - case r @ Request(method, _, _) if (requestHandlers.contains(method)) => + case r @ Request(method, _, _) if requestHandlers.contains(method) => val handler = context.actorOf( requestHandlers(method), s"request-handler-$method-${UUID.randomUUID()}" @@ -79,8 +81,7 @@ class ClientController[F[+_, +_]: Exec]( object ClientController { - /** - * Creates a configuration object used to create a [[ClientController]]. + /** Creates a configuration object used to create a [[ClientController]]. * * @param clientId the internal client id. * @return a configuration object diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/JsonRpc.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/JsonRpc.scala index c765f570ca..418f39a5ae 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/JsonRpc.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/JsonRpc.scala @@ -6,8 +6,7 @@ import org.enso.projectmanager.protocol.ProjectManagementApi._ object JsonRpc { - /** - * A description of supported JSON RPC messages. + /** A description of supported JSON RPC messages. */ lazy val protocol: Protocol = Protocol.empty diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ManagerClientControllerFactory.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ManagerClientControllerFactory.scala index 4038b74b85..ebbe14d4fe 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ManagerClientControllerFactory.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ManagerClientControllerFactory.scala @@ -8,8 +8,7 @@ import org.enso.projectmanager.boot.configuration.TimeoutConfig import org.enso.projectmanager.control.effect.Exec import org.enso.projectmanager.service.ProjectServiceApi -/** - * Project manager client controller factory. +/** Project manager client controller factory. * * @param system the actor system */ @@ -19,8 +18,7 @@ class ManagerClientControllerFactory[F[+_, +_]: Exec]( timeoutConfig: TimeoutConfig ) extends ClientControllerFactory { - /** - * Creates a client controller actor. + /** Creates a client controller actor. * * @param clientId the internal client id. * @return an actor ref to the client controller diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ProjectManagementApi.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ProjectManagementApi.scala index 5935611bc3..309ffb141c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ProjectManagementApi.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/protocol/ProjectManagementApi.scala @@ -5,8 +5,7 @@ import java.util.UUID import org.enso.jsonrpc.{Error, HasParams, HasResult, Method, Unused} import org.enso.projectmanager.data.{ProjectMetadata, Socket} -/** - * The project management JSON RPC API provided by the project manager. +/** The project management JSON RPC API provided by the project manager. * See [[https://github.com/enso-org/enso/blob/main/docs/language-server/README.md]] * for message specifications. */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCloseHandler.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCloseHandler.scala index 0af125aa67..f427e886c0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCloseHandler.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCloseHandler.scala @@ -17,8 +17,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `project/close` commands. +/** A request handler for `project/close` commands. * * @param clientId the requester id * @param service a project service @@ -78,8 +77,7 @@ class ProjectCloseHandler[F[+_, +_]: Exec]( object ProjectCloseHandler { - /** - * Creates a configuration object used to create a [[ProjectCloseHandler]]. + /** Creates a configuration object used to create a [[ProjectCloseHandler]]. * * @param clientId the requester id * @param service a project service diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCreateHandler.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCreateHandler.scala index c17fb35261..9c2697c34f 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCreateHandler.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectCreateHandler.scala @@ -17,8 +17,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `project/create` commands. +/** A request handler for `project/create` commands. * * @param service a project service * @param requestTimeout a request timeout @@ -78,8 +77,7 @@ class ProjectCreateHandler[F[+_, +_]: Exec]( object ProjectCreateHandler { - /** - * Creates a configuration object used to create a [[ProjectCreateHandler]]. + /** Creates a configuration object used to create a [[ProjectCreateHandler]]. * * @param service a project service * @param requestTimeout a request timeout diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectDeleteHandler.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectDeleteHandler.scala index 5b5bc69281..5017ac6d91 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectDeleteHandler.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectDeleteHandler.scala @@ -15,8 +15,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `project/delete` commands. +/** A request handler for `project/delete` commands. * * @param service a project service * @param requestTimeout a request timeout @@ -72,8 +71,7 @@ class ProjectDeleteHandler[F[+_, +_]: Exec]( object ProjectDeleteHandler { - /** - * Creates a configuration object used to create a [[ProjectDeleteHandler]]. + /** Creates a configuration object used to create a [[ProjectDeleteHandler]]. * * @param service a project service * @param requestTimeout a request timeout diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectListHandler.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectListHandler.scala index 4cff02ffbd..aacfc632d0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectListHandler.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectListHandler.scala @@ -19,8 +19,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.annotation.unused import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `project/list` commands. +/** A request handler for `project/list` commands. * * @param clientId the requester id * @param service a project service @@ -72,8 +71,8 @@ class ProjectListHandler[F[+_, +_]: Exec]( context.stop(self) case Right(list: List[_]) => - val metadata = list.collect { - case meta: ProjectMetadata => meta + val metadata = list.collect { case meta: ProjectMetadata => + meta } replyTo ! ResponseResult( @@ -89,8 +88,7 @@ class ProjectListHandler[F[+_, +_]: Exec]( object ProjectListHandler { - /** - * Creates a configuration object used to create a [[ProjectListHandler]]. + /** Creates a configuration object used to create a [[ProjectListHandler]]. * * @param clientId the requester id * @param service a project service diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectOpenHandler.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectOpenHandler.scala index b326e5a384..47d6423e65 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectOpenHandler.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectOpenHandler.scala @@ -18,8 +18,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `project/open` commands. +/** A request handler for `project/open` commands. * * @param clientId the requester id * @param service a project service @@ -81,8 +80,7 @@ class ProjectOpenHandler[F[+_, +_]: Exec]( object ProjectOpenHandler { - /** - * Creates a configuration object used to create a [[ProjectOpenHandler]]. + /** Creates a configuration object used to create a [[ProjectOpenHandler]]. * * @param clientId the requester id * @param service a project service diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectRenameHandler.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectRenameHandler.scala index 3596afa1db..faa533dccf 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectRenameHandler.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectRenameHandler.scala @@ -15,8 +15,7 @@ import org.enso.projectmanager.util.UnhandledLogging import scala.concurrent.duration.FiniteDuration -/** - * A request handler for `project/rename` commands. +/** A request handler for `project/rename` commands. * * @param service a project service * @param requestTimeout a request timeout @@ -75,8 +74,7 @@ class ProjectRenameHandler[F[+_, +_]: Exec]( object ProjectRenameHandler { - /** - * Creates a configuration object used to create a [[ProjectRenameHandler]]. + /** Creates a configuration object used to create a [[ProjectRenameHandler]]. * * @param service a project service * @param requestTimeout a request timeout diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectServiceFailureMapper.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectServiceFailureMapper.scala index 76e002981d..cc6cbd92f4 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectServiceFailureMapper.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/ProjectServiceFailureMapper.scala @@ -12,8 +12,7 @@ import org.enso.projectmanager.service.ProjectServiceFailure.{ object ProjectServiceFailureMapper { - /** - * Maps project service failures to JSON RPC errors. + /** Maps project service failures to JSON RPC errors. */ val mapFailure: ProjectServiceFailure => Error = { case ValidationFailure(msg) => ProjectNameValidationError(msg) diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/RequestTimeout.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/RequestTimeout.scala index 502b99a205..1077ca8cd0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/RequestTimeout.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/requesthandler/RequestTimeout.scala @@ -1,6 +1,5 @@ package org.enso.projectmanager.requesthandler -/** - * Signals that request has timed out. +/** Signals that request has timed out. */ object RequestTimeout diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MonadicProjectValidator.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MonadicProjectValidator.scala index a7039b67d1..024d5f974c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MonadicProjectValidator.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MonadicProjectValidator.scala @@ -7,11 +7,10 @@ import org.enso.projectmanager.service.ValidationFailure.{ NameContainsForbiddenCharacter } -/** - * MTL implementation of the project validator. +/** MTL implementation of the project validator. */ -class MonadicProjectValidator[F[_, _]]( - implicit M: MonadError[F[ValidationFailure, *], ValidationFailure] +class MonadicProjectValidator[F[_, _]](implicit + M: MonadError[F[ValidationFailure, *], ValidationFailure] ) extends ProjectValidator[F] { import M._ @@ -20,8 +19,7 @@ class MonadicProjectValidator[F[_, _]]( char.isLetterOrDigit || char == '_' || char == '-' } - /** - * Validates a project name. + /** Validates a project name. * * @param name the project name * @return either validation failure or success diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MoveProjectDirCmd.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MoveProjectDirCmd.scala index 4411c1b39a..a85c824e71 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MoveProjectDirCmd.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/MoveProjectDirCmd.scala @@ -13,8 +13,7 @@ import org.enso.projectmanager.infrastructure.repository.{ } import org.enso.projectmanager.infrastructure.shutdown.ShutdownHook -/** - * A hook responsible for moving a project to the target dir. +/** A hook responsible for moving a project to the target dir. * * @param projectId a project id * @param newName a new project name diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectService.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectService.scala index 38fc52a32f..98741677e8 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectService.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectService.scala @@ -32,8 +32,7 @@ import org.enso.projectmanager.service.ValidationFailure.{ NameContainsForbiddenCharacter } -/** - * Implementation of business logic for project management. +/** Implementation of business logic for project management. * * @param validator a project validator * @param repo a project repository @@ -53,7 +52,7 @@ class ProjectService[F[+_, +_]: ErrorChannel: CovariantFlatMap: Sync]( import E._ - /** @inheritdoc * */ + /** @inheritdoc */ override def createUserProject( name: String ): F[ProjectServiceFailure, UUID] = { @@ -71,7 +70,7 @@ class ProjectService[F[+_, +_]: ErrorChannel: CovariantFlatMap: Sync]( // format: on } - /** @inheritdoc * */ + /** @inheritdoc */ override def deleteUserProject( projectId: UUID ): F[ProjectServiceFailure, Unit] = @@ -96,7 +95,7 @@ class ProjectService[F[+_, +_]: ErrorChannel: CovariantFlatMap: Sync]( .isRunning(projectId) .mapError(_ => ProjectOperationTimeout) - /** @inheritdoc * */ + /** @inheritdoc */ override def renameProject( projectId: UUID, name: String @@ -138,8 +137,8 @@ class ProjectService[F[+_, +_]: ErrorChannel: CovariantFlatMap: Sync]( oldPackage, newPackage ) - .recover { - case ProjectNotOpened => () + .recover { case ProjectNotOpened => + () } .mapError { case ProjectNotOpened => ProjectNotOpen //impossible @@ -167,7 +166,7 @@ class ProjectService[F[+_, +_]: ErrorChannel: CovariantFlatMap: Sync]( case Some(_) => CovariantFlatMap[F].pure(()) } - /** @inheritdoc * */ + /** @inheritdoc */ override def openProject( clientId: UUID, projectId: UUID @@ -206,7 +205,7 @@ class ProjectService[F[+_, +_]: ErrorChannel: CovariantFlatMap: Sync]( ) } - /** @inheritdoc * */ + /** @inheritdoc */ override def closeProject( clientId: UUID, projectId: UUID @@ -222,7 +221,7 @@ class ProjectService[F[+_, +_]: ErrorChannel: CovariantFlatMap: Sync]( } } - /** @inheritdoc * */ + /** @inheritdoc */ override def listProjects( maybeSize: Option[Int] ): F[ProjectServiceFailure, List[ProjectMetadata]] = diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceApi.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceApi.scala index 77bda0c2f6..862720e98c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceApi.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceApi.scala @@ -4,31 +4,27 @@ import java.util.UUID import org.enso.projectmanager.data.{LanguageServerSockets, ProjectMetadata} -/** - * A contract for the Project Service. +/** A contract for the Project Service. * * @tparam F a monadic context */ trait ProjectServiceApi[F[+_, +_]] { - /** - * Creates a user project. + /** Creates a user project. * * @param name the name of th project * @return projectId */ def createUserProject(name: String): F[ProjectServiceFailure, UUID] - /** - * Deletes a user project. + /** Deletes a user project. * * @param projectId the project id * @return either failure or unit representing success */ def deleteUserProject(projectId: UUID): F[ProjectServiceFailure, Unit] - /** - * Renames a project. + /** Renames a project. * * @param projectId the project id * @param name the new name @@ -39,8 +35,7 @@ trait ProjectServiceApi[F[+_, +_]] { name: String ): F[ProjectServiceFailure, Unit] - /** - * Opens a project. It starts up a Language Server if needed. + /** Opens a project. It starts up a Language Server if needed. * * @param clientId the requester id * @param projectId the project id @@ -51,8 +46,7 @@ trait ProjectServiceApi[F[+_, +_]] { projectId: UUID ): F[ProjectServiceFailure, LanguageServerSockets] - /** - * Closes a project. Tries to shut down the Language Server. + /** Closes a project. Tries to shut down the Language Server. * * @param clientId the requester id * @param projectId the project id @@ -63,8 +57,7 @@ trait ProjectServiceApi[F[+_, +_]] { projectId: UUID ): F[ProjectServiceFailure, Unit] - /** - * Lists the user's most recently opened projects.. + /** Lists the user's most recently opened projects.. * * @param maybeSize the size of result set * @return list of recent projects diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceFailure.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceFailure.scala index 0883b55887..a3d4bcdbc2 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceFailure.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectServiceFailure.scala @@ -1,73 +1,61 @@ package org.enso.projectmanager.service -/** - * Base interface for project service failures. +/** Base interface for project service failures. */ sealed trait ProjectServiceFailure object ProjectServiceFailure { - /** - * Signals validation failures. + /** Signals validation failures. * * @param msg a message */ case class ValidationFailure(msg: String) extends ProjectServiceFailure - /** - * Signals problems with underlying data store. + /** Signals problems with underlying data store. * * @param msg a message */ case class DataStoreFailure(msg: String) extends ProjectServiceFailure - /** - * Signals that the project already exists. + /** Signals that the project already exists. */ case object ProjectExists extends ProjectServiceFailure - /** - * Signals that the project doesn't exist. + /** Signals that the project doesn't exist. */ case object ProjectNotFound extends ProjectServiceFailure - /** - * Signals that a failure occurred during project startup. + /** Signals that a failure occurred during project startup. * * @param message a failure message */ case class ProjectOpenFailed(message: String) extends ProjectServiceFailure - /** - * Signals that a failure occurred during project shutdown. + /** Signals that a failure occurred during project shutdown. * * @param message a failure message */ case class ProjectCloseFailed(message: String) extends ProjectServiceFailure - /** - * Signals that operation cannot be executed, because a project is not open. + /** Signals that operation cannot be executed, because a project is not open. */ case object ProjectNotOpen extends ProjectServiceFailure - /** - * Signals that the project cannot be closed, because other clients are + /** Signals that the project cannot be closed, because other clients are * connected. */ case object ProjectOpenByOtherPeers extends ProjectServiceFailure - /** - * Signals that removal of project failed because one client still use it. + /** Signals that removal of project failed because one client still use it. */ case object CannotRemoveOpenProject extends ProjectServiceFailure - /** - * Signals operation timeout. + /** Signals operation timeout. */ case object ProjectOperationTimeout extends ProjectServiceFailure - /** - * Signals generic server failures. + /** Signals generic server failures. * * @param msg a description of a failure */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectValidator.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectValidator.scala index 777027f722..d98495fc97 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectValidator.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ProjectValidator.scala @@ -1,14 +1,12 @@ package org.enso.projectmanager.service -/** - * Abstraction for project validator. +/** Abstraction for project validator. * * @tparam F target bifunctor */ trait ProjectValidator[F[_, _]] { - /** - * Validates a project name. + /** Validates a project name. * * @param name the project name * @return either validation failure or success diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/RecentlyUsedProjectsOrdering.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/RecentlyUsedProjectsOrdering.scala index 0c44db278f..9bddf5810c 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/RecentlyUsedProjectsOrdering.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/RecentlyUsedProjectsOrdering.scala @@ -4,8 +4,7 @@ import java.time.OffsetDateTime import org.enso.projectmanager.model.Project -/** - * Defines ordering for `project/listRecent` command. The precedence in +/** Defines ordering for `project/listRecent` command. The precedence in * defining the order has `lastOpened` time, if both times are equal then the * creation time is taken into account. */ diff --git a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ValidationFailure.scala b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ValidationFailure.scala index 8860d17982..9a520e09c0 100644 --- a/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ValidationFailure.scala +++ b/lib/scala/project-manager/src/main/scala/org/enso/projectmanager/service/ValidationFailure.scala @@ -1,19 +1,16 @@ package org.enso.projectmanager.service -/** - * Base trait for validations failures. +/** Base trait for validations failures. */ sealed trait ValidationFailure object ValidationFailure { - /** - * Signals that a user provided empty name. + /** Signals that a user provided empty name. */ case object EmptyName extends ValidationFailure - /** - * Signals that a project name contains forbidden characters. + /** Signals that a project name contains forbidden characters. * * @param characters a forbidden characters in the provided project name */ diff --git a/lib/scala/project-manager/src/test/resources/logback-test.xml b/lib/scala/project-manager/src/test/resources/logback-test.xml index 799ef51555..5a77a8f8e5 100644 --- a/lib/scala/project-manager/src/test/resources/logback-test.xml +++ b/lib/scala/project-manager/src/test/resources/logback-test.xml @@ -1,18 +1,18 @@ - - - - %d{HH:mm:ss.SSS} [%-15thread] %-5level %logger{36} %msg%n - - + + + + %d{HH:mm:ss.SSS} [%-15thread] %-5level %logger{36} %msg%n + + - - - + + + - - - + + + diff --git a/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisorSpec.scala b/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisorSpec.scala index 09c8528290..a2c080bf8a 100644 --- a/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisorSpec.scala +++ b/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/LanguageServerSupervisorSpec.scala @@ -39,12 +39,11 @@ class LanguageServerSupervisorSpec "A language supervisor" should "monitor language server by sending ping requests on regular basis" taggedAs Flaky in new TestCtx { //given val probe = TestProbe() - fakeServer.withBehaviour { - case ping @ PingMatcher(requestId) => - probe.ref ! ping - ReplyWith( - s"""{ "jsonrpc": "2.0", "id": "$requestId", "result": null }""" - ) + fakeServer.withBehaviour { case ping @ PingMatcher(requestId) => + probe.ref ! ping + ReplyWith( + s"""{ "jsonrpc": "2.0", "id": "$requestId", "result": null }""" + ) } probe.expectNoMessage() //when @@ -70,17 +69,16 @@ class LanguageServerSupervisorSpec .thenReturn(Future.successful(ComponentRestarted)) val probe = TestProbe() @volatile var pingCount = 0 - fakeServer.withBehaviour { - case ping @ PingMatcher(requestId) => - probe.ref ! ping - pingCount += 1 - if (pingCount == 3) { - Reject - } else { - ReplyWith( - s"""{ "jsonrpc": "2.0", "id": "$requestId", "result": null }""" - ) - } + fakeServer.withBehaviour { case ping @ PingMatcher(requestId) => + probe.ref ! ping + pingCount += 1 + if (pingCount == 3) { + Reject + } else { + ReplyWith( + s"""{ "jsonrpc": "2.0", "id": "$requestId", "result": null }""" + ) + } } probe.expectNoMessage() //when @@ -114,10 +112,9 @@ class LanguageServerSupervisorSpec //given when(serverComponent.restart()).thenReturn(Future.failed(new Exception)) val probe = TestProbe() - fakeServer.withBehaviour { - case ping @ PingMatcher(_) => - probe.ref ! ping - Reject + fakeServer.withBehaviour { case ping @ PingMatcher(_) => + probe.ref ! ping + Reject } probe.expectNoMessage() //when diff --git a/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameActionSpec.scala b/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameActionSpec.scala index 118337d4dd..821e6c0557 100644 --- a/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameActionSpec.scala +++ b/lib/scala/project-manager/src/test/scala/org/enso/projectmanager/infrastructure/languageserver/ProjectRenameActionSpec.scala @@ -64,18 +64,17 @@ class ProjectRenameActionSpec it should "reply with an error when renaming fails" in new TestCtx { //given - fakeServer.withBehaviour { - case RenameRequestMatcher(requestId, _, _) => - ReplyWith( - s"""{ - | "jsonrpc": "2.0", - | "id": "$requestId", - | "error": { - | "code": 100, - | "message": "Test" - | } - |}""".stripMargin - ) + fakeServer.withBehaviour { case RenameRequestMatcher(requestId, _, _) => + ReplyWith( + s"""{ + | "jsonrpc": "2.0", + | "id": "$requestId", + | "error": { + | "code": 100, + | "message": "Test" + | } + |}""".stripMargin + ) } //when diff --git a/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlSuggestionsRepo.scala b/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlSuggestionsRepo.scala index 9c30b72764..7dd9bb9b78 100644 --- a/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlSuggestionsRepo.scala +++ b/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlSuggestionsRepo.scala @@ -160,16 +160,15 @@ final class SqlSuggestionsRepo(db: SqlDatabase)(implicit ec: ExecutionContext) val query = Suggestions .filter { row => calls - .map { - case (module, selfType, name) => - row.module === module && row.selfType === selfType && row.name === name + .map { case (module, selfType, name) => + row.module === module && row.selfType === selfType && row.name === name } .reduce(_ || _) } .map(row => (row.id, row.module, row.selfType, row.name)) query.result.map { tuples => - val result = tuples.map { - case (id, module, selfType, name) => (module, selfType, name) -> id + val result = tuples.map { case (id, module, selfType, name) => + (module, selfType, name) -> id }.toMap calls.map(result.get) } @@ -235,9 +234,9 @@ final class SqlSuggestionsRepo(db: SqlDatabase)(implicit ec: ExecutionContext) val (suggestionRow, args) = toSuggestionRow(suggestion) val query = for { id <- Suggestions.returning(Suggestions.map(_.id)) += suggestionRow - _ <- Arguments ++= args.zipWithIndex.map { - case (argument, ix) => toArgumentRow(id, ix, argument) - } + _ <- Arguments ++= args.zipWithIndex.map { case (argument, ix) => + toArgumentRow(id, ix, argument) + } _ <- incrementVersionQuery } yield id query.asTry.map { @@ -443,28 +442,26 @@ final class SqlSuggestionsRepo(db: SqlDatabase)(implicit ec: ExecutionContext) position: Option[Suggestion.Position] ): Query[SuggestionsTable, SuggestionRow, Seq] = { Suggestions - .filterOpt(module) { - case (row, value) => - row.scopeStartLine === ScopeColumn.EMPTY || row.module === value + .filterOpt(module) { case (row, value) => + row.scopeStartLine === ScopeColumn.EMPTY || row.module === value } - .filterOpt(selfType) { - case (row, value) => row.selfType === value + .filterOpt(selfType) { case (row, value) => + row.selfType === value } - .filterOpt(returnType) { - case (row, value) => row.returnType === value + .filterOpt(returnType) { case (row, value) => + row.returnType === value } - .filterOpt(kinds) { - case (row, value) => row.kind inSet value.map(SuggestionKind(_)) + .filterOpt(kinds) { case (row, value) => + row.kind inSet value.map(SuggestionKind(_)) } - .filterOpt(position) { - case (row, value) => - (row.scopeStartLine === ScopeColumn.EMPTY) || - ( - row.scopeStartLine <= value.line && - row.scopeStartOffset <= value.character && - row.scopeEndLine >= value.line && - row.scopeEndOffset >= value.character - ) + .filterOpt(position) { case (row, value) => + (row.scopeStartLine === ScopeColumn.EMPTY) || + ( + row.scopeStartLine <= value.line && + row.scopeStartOffset <= value.character && + row.scopeEndLine >= value.line && + row.scopeEndOffset >= value.character + ) } } diff --git a/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlVersionsRepo.scala b/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlVersionsRepo.scala index 91ca9cb04d..c55e88f716 100644 --- a/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlVersionsRepo.scala +++ b/lib/scala/searcher/src/main/scala/org/enso/searcher/sql/SqlVersionsRepo.scala @@ -107,7 +107,6 @@ final class SqlVersionsRepo(db: SqlDatabase)(implicit ec: ExecutionContext) else DBIO.successful(None) } yield !versionsEquals - /** The query to update the versions in batch. * * @param versions files with corresponding digests diff --git a/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/FileVersionsRepoTest.scala b/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/FileVersionsRepoTest.scala index 5d15db0073..3f9e153159 100644 --- a/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/FileVersionsRepoTest.scala +++ b/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/FileVersionsRepoTest.scala @@ -117,8 +117,8 @@ class FileVersionsRepoTest extends AnyWordSpec with Matchers with RetrySpec { val input = Seq(file1 -> digest1, file2 -> digest2) val action = for { - _ <- repo.setVersion(file1, digest0) - _ <- repo.updateVersions(input) + _ <- repo.setVersion(file1, digest0) + _ <- repo.updateVersions(input) v1 <- repo.getVersion(file1) v2 <- repo.getVersion(file2) } yield (v1, v2) diff --git a/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/SuggestionsRepoTest.scala b/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/SuggestionsRepoTest.scala index 3e5ff0cdbe..56b05d3000 100644 --- a/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/SuggestionsRepoTest.scala +++ b/lib/scala/searcher/src/test/scala/org/enso/searcher/sql/SuggestionsRepoTest.scala @@ -204,21 +204,22 @@ class SuggestionsRepoTest extends AnyWordSpec with Matchers with RetrySpec { inserted should contain theSameElementsAs removed } - "remove all suggestions by empty module" taggedAs Retry in withRepo { repo => - val action = for { - (_, idsIns) <- repo.insertAll( - Seq( - suggestion.atom, - suggestion.method, - suggestion.function, - suggestion.local + "remove all suggestions by empty module" taggedAs Retry in withRepo { + repo => + val action = for { + (_, idsIns) <- repo.insertAll( + Seq( + suggestion.atom, + suggestion.method, + suggestion.function, + suggestion.local + ) ) - ) - (_, idsRem) <- repo.removeAllByModule(Seq()) - } yield (idsIns.flatten, idsRem) + (_, idsRem) <- repo.removeAllByModule(Seq()) + } yield (idsIns.flatten, idsRem) - val (_, removed) = Await.result(action, Timeout) - removed.isEmpty shouldBe true + val (_, removed) = Await.result(action, Timeout) + removed.isEmpty shouldBe true } "remove all suggestions" taggedAs Retry in withRepo { repo => diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/AST.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/AST.scala index cbeaaf09e1..a19887ce11 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/AST.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/AST.scala @@ -105,8 +105,7 @@ object OffsetZip { //// AbsolutePosition ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -/** - * Represents an expression's absolute positioning in a source file. +/** Represents an expression's absolute positioning in a source file. * @param start the inclusive, 0-indexed position of the beginning * of the expression * @param end the exclusive, 0-indexed position of the end of @@ -929,8 +928,8 @@ object Shape extends ShapeImplicit { t => R + t.head + t.body implicit def ozip[T: HasSpan]: OffsetZip[Segment, T] = t => { - t.copy(body = OffsetZip(t.body).map { - case (i, s) => s.map((i + Size(t.head.span), _)) + t.copy(body = OffsetZip(t.body).map { case (i, s) => + s.map((i + Size(t.head.span), _)) }) } implicit def span[T: HasSpan]: HasSpan[Segment[T]] = @@ -1603,8 +1602,8 @@ object AST { var asts = List[(Index, AST)](Index.Start -> t) while (asts.nonEmpty) { val (off, ast) = asts.head - val children = ast.zipWithOffset().toList.map { - case (o, ast) => (o + off.asSize, ast) + val children = ast.zipWithOffset().toList.map { case (o, ast) => + (o + off.asSize, ast) } if (ast.id.nonEmpty) ids +:= Span(off, ast) -> ast.id.get diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/Debug.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/Debug.scala index 6c74eb611f..3e9a34cb01 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/Debug.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/Debug.scala @@ -2,13 +2,11 @@ package org.enso.syntax.text import scala.annotation.tailrec -/** - * Useful debugging tools for the parser AST. +/** Useful debugging tools for the parser AST. */ object Debug { - /** - * Pretty prints the parser AST string representation in a more readable + /** Pretty prints the parser AST string representation in a more readable * format. * * @param str the string representation of the parser AST @@ -54,12 +52,13 @@ object Debug { } case ')' => go(ind - 1, ss, s2 :: newline(ind - 1) :: out) - case ',' => if (ss.startsWith(" ")) { - go(ind, ss.drop(1), newline(ind) :: s2 :: out) - } else { - go(ind, ss, newline(ind) :: s2 :: out) - } - case _ => go(ind, ss, s2 :: out) + case ',' => + if (ss.startsWith(" ")) { + go(ind, ss.drop(1), newline(ind) :: s2 :: out) + } else { + go(ind, ss, newline(ind) :: s2 :: out) + } + case _ => go(ind, ss, s2 :: out) } } } diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Doc.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Doc.scala index eb7678a9ac..784f4a2604 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Doc.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Doc.scala @@ -181,12 +181,12 @@ object Doc { val htmlStyle = HTML.`style` := "inline-block" val elemsHTML = elems.toList.map(elem => elem.html) val btnAction = onclick := - s"""var code = document.getElementById("$uniqueIDCode"); - |var btn = document.getElementById("$uniqueIDBtn").firstChild; - |btn.data = btn.data == "Show" ? "Hide" : "Show"; - |code.style.display = code.style.display == - |"inline-block" ? "none" : "inline-block";""".stripMargin - .replaceAll("\n", "") + s"""var code = document.getElementById("$uniqueIDCode"); + |var btn = document.getElementById("$uniqueIDBtn").firstChild; + |btn.data = btn.data == "Show" ? "Hide" : "Show"; + |code.style.display = code.style.display == + |"inline-block" ? "none" : "inline-block";""".stripMargin + .replaceAll("\n", "") val btn = HTML.button(btnAction)(htmlIdBtn)("Show") if (isInGui) { Seq(HTML.div(htmlCls())(htmlStyle)(elemsHTML)) @@ -278,12 +278,12 @@ object Doc { final case class List(indent: Int, typ: List.Type, elems: List1[Elem]) extends Elem { val repr: Repr.Builder = R + indent + typ.marker + elems.head + elems.tail - .map { - case elem @ (_: Elem.Invalid) => R + Newline + elem - case elem @ (_: List) => R + Newline + elem - case elem => - R + Newline + indent + typ.marker + elem - } + .map { + case elem @ (_: Elem.Invalid) => R + Newline + elem + case elem @ (_: List) => R + Newline + elem + case elem => + R + Newline + indent + typ.marker + elem + } val html: HTML = { val elemsHTML = elems.toList.map { @@ -478,8 +478,8 @@ object Doc { final case class Body(elems: List1[Section]) extends Symbol { val newLn: Elem = Elem.Newline val repr: Repr.Builder = R + newLn + elems.head + elems.tail.map( - R + newLn + _ - ) + R + newLn + _ + ) val html: HTML = Seq( HTML.div(htmlCls())(elems.toList.map(_.html)) ) diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Repr2.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Repr2.scala index f73eecf3d9..6685000828 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Repr2.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/Repr2.scala @@ -154,10 +154,13 @@ object Repr { implicit val monoidForBuilder: Monoid[Builder] = new Monoid[Builder] { def empty: Builder = Empty() def combine(l: Builder, r: Builder): Builder = - Builder(l.span + r.span, (bldr: StringBuilder) => { - l.buildMe(bldr) - r.buildMe(bldr) - }) + Builder( + l.span + r.span, + (bldr: StringBuilder) => { + l.buildMe(bldr) + r.buildMe(bldr) + } + ) } def Empty() = Builder(0, identity(_): Unit) diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Info.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Info.scala index 3bb59a30dd..fe822d4bf0 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Info.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Info.scala @@ -1,8 +1,8 @@ package org.enso.syntax.text.ast.opr object Info { - val map: Map[String, (Int, Assoc)] = Prec.map.map { - case (name, prec) => name -> ((prec, Assoc.of(name))) + val map: Map[String, (Int, Assoc)] = Prec.map.map { case (name, prec) => + name -> ((prec, Assoc.of(name))) } def of(op: String) = map.getOrElse(op, (Prec.default, Assoc.of(op))) diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Prec.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Prec.scala index d3dee8e770..3a3fd2f5f1 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Prec.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/ast/opr/Prec.scala @@ -1,6 +1,7 @@ package org.enso.syntax.text.ast.opr object Prec { + /** The precedence hierarchy, from loosest binding to tightest binding. */ val hierarchy = List( List("=", "#="), @@ -28,8 +29,8 @@ object Prec { ) val map: Map[String, Int] = - hierarchy.zipWithIndex.flatMap { - case (ops, prec) => ops.map(_ -> prec) + hierarchy.zipWithIndex.flatMap { case (ops, prec) => + ops.map(_ -> prec) }.toMap val default = map.getOrElse("^", 0) diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/DocParserDef.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/DocParserDef.scala index ad832d109b..c0605c2739 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/DocParserDef.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/DocParserDef.scala @@ -418,8 +418,8 @@ case class DocParserDef() extends Parser[Doc] { ')' ).many1 >> newline val invalidPatternEOF: Pattern = (imageNameTrigger | urlNameTrigger) >> not( - ')' - ).many1 >> eof + ')' + ).many1 >> eof } ROOT || link.imagePattern || link.onCreatingImage() @@ -751,11 +751,11 @@ case class DocParserDef() extends Parser[Doc] { section.current match { case Some(marker) => section.stack +:= Section.Marked( - indentBeforeMarker, - indentAfterMarker, - marker, - result.stack - ) + indentBeforeMarker, + indentAfterMarker, + marker, + result.stack + ) case None => section.stack +:= Section.Raw(currentIndentRaw, result.stack) } diff --git a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/ParserDef.scala b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/ParserDef.scala index 4b24500c07..8753aefbc1 100644 --- a/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/ParserDef.scala +++ b/lib/scala/syntax/definition/src/main/scala/org/enso/syntax/text/spec/ParserDef.scala @@ -748,7 +748,7 @@ case class ParserDef() extends flexer.Parser[AST.Module] { case Some(line) => line.toOptional +: current.lines.reverse } val line :: lines = (current.emptyLines - .map(AST.Block.Line(None, _)): List[AST.Block.OptLine]) ++ body + .map(AST.Block.Line(None, _)): List[AST.Block.OptLine]) ++ body val module = AST.Module(line, lines) result.current = Some(module) logger.endGroup() diff --git a/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/DocParserBench.scala b/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/DocParserBench.scala index 8280617e3c..d9d803f5f7 100644 --- a/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/DocParserBench.scala +++ b/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/DocParserBench.scala @@ -55,8 +55,8 @@ object DocParserBench extends Bench.OfflineRegressionReport { def run(str: String): Result[Doc] = DocParser.run(str) performance of "DocParser" in { - tests.foreach { - case (name, gen) => measure method name in (using(gen) in run) + tests.foreach { case (name, gen) => + measure method name in (using(gen) in run) } } } diff --git a/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/ParserBenchmark.scala b/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/ParserBenchmark.scala index 093ba9748c..c041740a6d 100644 --- a/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/ParserBenchmark.scala +++ b/lib/scala/syntax/specialization/shared/src/bench/scala/org/enso/syntax/ParserBenchmark.scala @@ -119,8 +119,8 @@ object ParserBenchmark extends Bench.OfflineRegressionReport { def run(str: String) = Parser().run(str) performance of "parser" in { - parserInput.foreach { - case (name, gen) => measure method name in (using(gen) in run) + parserInput.foreach { case (name, gen) => + measure method name in (using(gen) in run) } } diff --git a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/CommentRemover.scala b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/CommentRemover.scala index 9f11d03fc7..a7cf418db5 100644 --- a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/CommentRemover.scala +++ b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/CommentRemover.scala @@ -1,7 +1,6 @@ package org.enso.syntax.text -/** - * A dirty hack that replaces all disable comments with whitespace. +/** A dirty hack that replaces all disable comments with whitespace. * Documentation comments are left untouched. * * @param input the original input file diff --git a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/DocParser.scala b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/DocParser.scala index c1b9637fea..4e37158271 100644 --- a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/DocParser.scala +++ b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/DocParser.scala @@ -15,8 +15,7 @@ import org.enso.syntax.text.Shape.Block.Line //// Doc Parser //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -/** - * This is the class used to invoke Documentation Parser. +/** This is the class used to invoke Documentation Parser. * * It is used to create structured documentation from the blocks of commented * text created by the main Enso parser. @@ -29,8 +28,7 @@ class DocParser { private val engine = newEngine() private val errMsg = "Internal Documentation Parser Error" - /** - * Used to match result of [[run]] function to possibly retrieve Doc + /** Used to match result of [[run]] function to possibly retrieve Doc * * @param input - input string to Doc Parser * @return - If it was able to retrieve Doc, then retrieved data, else @@ -42,8 +40,7 @@ class DocParser { case _ => throw new Exception(errMsg) } - /** - * Used to initialize Doc Parser with input string to get parsed Doc + /** Used to initialize Doc Parser with input string to get parsed Doc * * @param input - input string to Doc Parser * @return - unmatched result possibly containing Doc @@ -55,8 +52,7 @@ object DocParser { type Result[T] = flexer.Parser.Result[T] private val newEngine = flexer.Parser.compile(DocParserDef()) - /** - * Doc Parser running methods, as described above, in class [[DocParser]] + /** Doc Parser running methods, as described above, in class [[DocParser]] */ def runMatched(input: String): Doc = new DocParser().runMatched(input) def run(input: String): Result[Doc] = new DocParser().run(input) @@ -66,8 +62,7 @@ object DocParser { //// Doc Parser Runner ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -/** - * This is Doc Parser Runner. +/** This is Doc Parser Runner. * * Essentially it binds together Enso Parser with Doc Parser. * When Parser finishes its job it invokes runner with AST created by it after @@ -80,8 +75,7 @@ object DocParserRunner { ////////////////////////////////////////////////////////////////////////////// //// Created Doc's in right places with appropriate AST ////////////////////// ////////////////////////////////////////////////////////////////////////////// - /** - * This function invokes the documentation parser on every instance of + /** This function invokes the documentation parser on every instance of * [[AST.Comment]]. * * It matches on [[AST.Module]] or [[AST.Def]] in order to traverse @@ -107,8 +101,7 @@ object DocParserRunner { } } - /** - * This is a helper function for [[createDocs]] to traverse through + /** This is a helper function for [[createDocs]] to traverse through * [[AST.Module]] and create Docs from comments with appropriate [[AST]] */ def createDocsFromModule(m: AST.Module): AST.Module = { @@ -118,8 +111,7 @@ object DocParserRunner { AST.Module(transformedLines) } - /** - * This is a helper function for [[createDocs]] to traverse through + /** This is a helper function for [[createDocs]] to traverse through * [[AST.Def]] and create Docs from comments inside [[AST.Def]] with * appropriate [[AST]] */ @@ -139,8 +131,7 @@ object DocParserRunner { AST.Def(name, args, Some(body)) } - /** - * This is a helper function for creating docs with AST. + /** This is a helper function for creating docs with AST. * Essentially it traverses through lines and tries to find a pattern on them * * @param lines - AST lines @@ -188,8 +179,7 @@ object DocParserRunner { case Nil => Nil } - /** - * Creates Docs from comments found in parsed data + /** Creates Docs from comments found in parsed data * * @param comment - comment found in AST * @return - Documentation @@ -199,8 +189,7 @@ object DocParserRunner { DocParser.runMatched(in) } - /** - * Function for creating documented lines in [[attachDocToSubsequentAST]] + /** Function for creating documented lines in [[attachDocToSubsequentAST]] * method with [[AST.App.Infix]] as Documented AST * * @param com - comment found in AST @@ -222,8 +211,7 @@ object DocParserRunner { docLine :: attachDocToSubsequentAST(rest) } - /** - * Function for creating documented lines in [[attachDocToSubsequentAST]] + /** Function for creating documented lines in [[attachDocToSubsequentAST]] * method with [[AST.Def]] as Documented AST * * @param com - comment found in AST @@ -244,8 +232,7 @@ object DocParserRunner { docLine :: attachDocToSubsequentAST(rest) } - /** - * Function for creating documented lines in [[attachDocToSubsequentAST]] + /** Function for creating documented lines in [[attachDocToSubsequentAST]] * method * * @param comment - comment found in AST @@ -270,16 +257,14 @@ object DocParserRunner { //// Doc Parser HTML Generator ///////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -/** - * This is Doc Parser HTML Generator. +/** This is Doc Parser HTML Generator. * * Essentially it enables Doc Parser to create pretty HTML files from * documented code. */ object DocParserHTMLGenerator { - /** - * This method is used for generation of HTML files from parsed and + /** This method is used for generation of HTML files from parsed and * reformatted [[AST.Documented]] * * @param ast - parsed AST.Module and reformatted using Doc Parser @@ -300,8 +285,7 @@ object DocParserHTMLGenerator { new String } - /** - * Function to generate HTML File from pure doc comment w/o connection to AST + /** Function to generate HTML File from pure doc comment w/o connection to AST * * @param doc - Doc from Doc Parser * @return - HTML Code from Doc @@ -314,8 +298,7 @@ object DocParserHTMLGenerator { //// HTML Rendering of Documentation ///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - /** - * Used to create HTML files from Doc with or without title after Doc Parser + /** Used to create HTML files from Doc with or without title after Doc Parser * Runner finished it's job * * @param documented - documented made by Doc Parser Runner from AST and Doc @@ -334,8 +317,7 @@ object DocParserHTMLGenerator { } case class htmlFile(code: TypedTag[String], name: String) - /** - * Function invoked by [[onHTMLRendering]] to render HTML File + /** Function invoked by [[onHTMLRendering]] to render HTML File * * @param ast - AST from Parser * @param doc - Doc from Doc Parser @@ -348,8 +330,7 @@ object DocParserHTMLGenerator { HTML.html(createHTMLHead(title), HTML.body(documentation)) } - /** - * This function is used to get HTML content of Doc and try to render AST, + /** This function is used to get HTML content of Doc and try to render AST, * by finding if it also contains Documented to retrieve Doc and it's AST, * or simply call show() method on other element of AST. * @@ -392,8 +373,7 @@ object DocParserHTMLGenerator { } } - /** - * This case class is used to hold HTML-rendered AST + /** This case class is used to hold HTML-rendered AST * * @param header - header of AST - name of module/method with parameters * @param body - body of AST - All of AST's documented submodules/methods @@ -411,8 +391,7 @@ object DocParserHTMLGenerator { new astHtmlRepr(HTML.div(), None) } - /** - * Function invoked by [[DocumentedToHtml]] to create HTML from AST in + /** Function invoked by [[DocumentedToHtml]] to create HTML from AST in * [[AST.Documented]] on every matching element * * @param ast - AST @@ -435,8 +414,7 @@ object DocParserHTMLGenerator { } } - /** - * Helper function for [[createHTMLFromAST]] to generate appropriate code + /** Helper function for [[createHTMLFromAST]] to generate appropriate code * from [[AST.Def]] with traversing through body and creating HTML code * on elements in it * @@ -467,8 +445,7 @@ object DocParserHTMLGenerator { astHtmlRepr(HTML.div(cls)(head), HTML.div(cls)(lines)) } - /** - * Helper function for [[createHTMLFromAST]] to generate appropriate code + /** Helper function for [[createHTMLFromAST]] to generate appropriate code * from [[AST.Def]] when it doesn't contain anything in it's body * * @param name - Def Name @@ -483,8 +460,7 @@ object DocParserHTMLGenerator { HTML.div(cls)(createDefTitle(name, args)) } - /** - * Helper function for [[createDefWithBody]] or [[createDefWithoutBody]] + /** Helper function for [[createDefWithBody]] or [[createDefWithoutBody]] * to generate [[AST.Def]] title form it's name and args * * @param name - Def Name @@ -505,8 +481,7 @@ object DocParserHTMLGenerator { HTML.a(pageHref)(innerDiv) } - /** - * Helper function for [[createHTMLFromAST]] to generate appropriate HTML + /** Helper function for [[createHTMLFromAST]] to generate appropriate HTML * code from [[AST.App.Infix]] * * @param infix - AST Infix @@ -515,14 +490,13 @@ object DocParserHTMLGenerator { def createInfixHtmlRepr(infix: AST.App.Infix): TypedTag[String] = { val cls = HTML.`class` := "Infix" val pageHref = HTML.`href` := infix.larg - .show() - .replaceAll(" ", "_") + ".html" + .show() + .replaceAll(" ", "_") + ".html" val innerDiv = HTML.div(cls)(infix.larg.show()) HTML.a(pageHref)(innerDiv) } - /** - * Helper function for [[createDefWithBody]] to traverse through body's lines + /** Helper function for [[createDefWithBody]] to traverse through body's lines * and try to generate HTML code from [[AST.Documented]] parts of it. It also * tries to find nested [[AST.Def]] and [[AST.App.Infix]] inside of body * @@ -551,8 +525,7 @@ object DocParserHTMLGenerator { } } - /** - * Function invoked by [[DocumentedToHtml]] to create HTML.Head part of file + /** Function invoked by [[DocumentedToHtml]] to create HTML.Head part of file * * @param title - HTML page title * @return - HTML Head Code diff --git a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/InHoisting.scala b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/InHoisting.scala index bf4d27439c..a0ebf9fb5a 100644 --- a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/InHoisting.scala +++ b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/InHoisting.scala @@ -23,11 +23,11 @@ case object InHoisting { } /** Maps over the token stream, replacing occurrences of `Var("in")` with - * `Opr("in")` at the same location. - * - * @param ast the ast element to process - * @return `ast`, with occurrences of "in" replaced - */ + * `Opr("in")` at the same location. + * + * @param ast the ast element to process + * @return `ast`, with occurrences of "in" replaced + */ def process(ast: AST): AST = ast match { case App.Prefix.any(app) => App.Prefix(process(app.func), app.off, process(app.arg)) diff --git a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/Parser.scala b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/Parser.scala index 4952b768b1..2c56b90804 100644 --- a/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/Parser.scala +++ b/lib/scala/syntax/specialization/shared/src/main/scala/org/enso/syntax/text/Parser.scala @@ -190,8 +190,7 @@ class Parser { SourceFile(run(new Reader(input), idmap), metadata) } - /** - * Parse contents of the program source file, attaching any IDs defined + /** Parse contents of the program source file, attaching any IDs defined * in the metadata section and dropping macros resolution data. * * @param input the code parse. @@ -205,9 +204,8 @@ class Parser { } private def attachIds(module: AST.Module, ids: IDMap): AST.Module = { - val idMap: Map[Location, AST.ID] = ids.map { - case (span, id) => - (Location(span.index.value, span.index.value + span.size.value), id) + val idMap: Map[Location, AST.ID] = ids.map { case (span, id) => + (Location(span.index.value, span.index.value + span.size.value), id) }.toMap def go(ast: AST): AST = { @@ -236,8 +234,7 @@ class Parser { resolved } - /** - * Processes an input [[AST.Module]], attaching absolute span information + /** Processes an input [[AST.Module]], attaching absolute span information * to it and all its children. */ def attachModuleLocations(ast: AST.Module): AST.Module = { @@ -256,8 +253,7 @@ class Parser { unspannedModule.setLocation(Location(toplevelOffset, ast.span)) } - /** - * Processes an AST block, attaching absolute span information to it + /** Processes an AST block, attaching absolute span information to it * and all children. * * @param ast the AST block to mark with absolute positions @@ -293,8 +289,7 @@ class Parser { ) } - /** - * Attaches absolute span information to arbitrary AST. + /** Attaches absolute span information to arbitrary AST. * * [[App.Prefix]] nodes are treated specially, since at the stage this * method is run, we expect a token-stream-like AST, where App nodes act as @@ -367,8 +362,7 @@ class Parser { * different variants, we can say it is safe and coerce the types. */ - /** - * Automatically derives source location for an AST node, based on its + /** Automatically derives source location for an AST node, based on its * children's locations * * @param ast the AST to derive location for @@ -386,8 +380,7 @@ class Parser { ast } - /** - * Derives location (see [[deriveLocation]]) for a node and all its + /** Derives location (see [[deriveLocation]]) for a node and all its * descendants. * * @param ast the AST to derive location for diff --git a/lib/scala/syntax/specialization/shared/src/test/scala/org/enso/syntax/text/ParserTest.scala b/lib/scala/syntax/specialization/shared/src/test/scala/org/enso/syntax/text/ParserTest.scala index 1f439ff6d5..de0724688e 100644 --- a/lib/scala/syntax/specialization/shared/src/test/scala/org/enso/syntax/text/ParserTest.scala +++ b/lib/scala/syntax/specialization/shared/src/test/scala/org/enso/syntax/text/ParserTest.scala @@ -220,11 +220,11 @@ class ParserTest extends AnyFlatSpec with Matchers { "\"\"\" \n\n X\n\n Y" ?= Text.Raw(1, 0, line(" X", 0), line(" Y", 0)) "a \"\"\"\n\n\n X\n\n Y" ?= "a" $_ Text.Raw( - 0, - 1, - line("X", 0, 0), - line("Y", 0) - ) + 0, + 1, + line("X", 0, 0), + line("Y", 0) + ) //// Escapes //// @@ -258,16 +258,16 @@ class ParserTest extends AnyFlatSpec with Matchers { } "say \n '''\n Hello\n `World`\npal" ??= Module( - OptLine( - "say" $_ Block(2, Text(0, 2, line("Hello"), line(expr("World")))) - ), - OptLine("pal") - ) + OptLine( + "say" $_ Block(2, Text(0, 2, line("Hello"), line(expr("World")))) + ), + OptLine("pal") + ) "say '''\n Hello\n `World`\npal" ??= Module( - OptLine("say" $_ Text(0, 2, line("Hello"), line(expr("World")))), - OptLine("pal") - ) + OptLine("say" $_ Text(0, 2, line("Hello"), line(expr("World")))), + OptLine("pal") + ) //// // // Comments ////// expr("#" , Comment) @@ -375,13 +375,13 @@ class ParserTest extends AnyFlatSpec with Matchers { // ) // "if a then b" ?= Mixfix( - List1[AST.Ident]("if", "then"), - List1[AST]("a", "b") - ) + List1[AST.Ident]("if", "then"), + List1[AST]("a", "b") + ) "if a then b else c" ?= Mixfix( - List1[AST.Ident]("if", "then", "else"), - List1[AST]("a", "b", "c") - ) + List1[AST.Ident]("if", "then", "else"), + List1[AST]("a", "b", "c") + ) "if a" ?= amb_if_("a": AST) "(if a) b" ?= Group(amb_if_("a": AST)) $_ "b" diff --git a/lib/scala/testkit/src/main/scala/org/enso/testkit/FlakySpec.scala b/lib/scala/testkit/src/main/scala/org/enso/testkit/FlakySpec.scala index 6bd9e4a800..452c443613 100644 --- a/lib/scala/testkit/src/main/scala/org/enso/testkit/FlakySpec.scala +++ b/lib/scala/testkit/src/main/scala/org/enso/testkit/FlakySpec.scala @@ -2,8 +2,7 @@ package org.enso.testkit import org.scalatest._ -/** - * Trait is used to mark the tests in the suite as _flaky_ and make them +/** Trait is used to mark the tests in the suite as _flaky_ and make them * pass. It changes the behavior for failed tests to return 'pending' instead * of failing the suite. * diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CharView.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CharView.scala index caff4c2e7c..78815c15a7 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CharView.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CharView.scala @@ -1,15 +1,13 @@ package org.enso.text.buffer -/** - * Exposes a character-based API for rope operations. +/** Exposes a character-based API for rope operations. * Also exposes a [[CharSequence]] interface, for no-copy use with Java APIs. * * @param rope the underlying rope. */ case class CharView(rope: Rope) extends CharSequence { - /** - * Splits the rope into two parts at a given offset. + /** Splits the rope into two parts at a given offset. * * @param offset the number of characters in the first part. * @return a sub-rope containing `offset` characters and a sub-rope @@ -18,24 +16,21 @@ case class CharView(rope: Rope) extends CharSequence { def splitAt(offset: Int): (Rope, Rope) = rope.splitWith(offset, CharView.Ops) - /** - * Takes a prefix of the rope of the given length. + /** Takes a prefix of the rope of the given length. * * @param len the length of the prefix to take. * @return a prefix of `this` containing `len` characters. */ def take(len: Int): Rope = rope.takeWith(len, CharView.Ops) - /** - * Takes a suffix of the rope by removing the first `len` characters. + /** Takes a suffix of the rope by removing the first `len` characters. * * @param len the number of characters to remove. * @return the suffix consisting of the remaining characters. */ def drop(len: Int): Rope = rope.dropWith(len, CharView.Ops) - /** - * Takes a substring of the rope, with the first character at `startOffset` + /** Takes a substring of the rope, with the first character at `startOffset` * and the last at `endOffset` - 1. * * @param startOffset the offset of the first character. @@ -45,23 +40,20 @@ case class CharView(rope: Rope) extends CharSequence { def substring(startOffset: Int, endOffset: Int): Rope = drop(startOffset).characters.take(endOffset - startOffset) - /** - * Gets the number of characters in this rope. + /** Gets the number of characters in this rope. * * @return the length of this rope. */ override def length: Int = rope.root.measure.utf16Size - /** - * Gets the character at a specified position. + /** Gets the character at a specified position. * * @param index the index of the character to get. * @return the character at `index` */ override def charAt(index: Int): Char = rope.getWith(index, CharView.Ops) - /** - * Takes a substring of the rope, with the first character at `start` + /** Takes a substring of the rope, with the first character at `start` * and the last at `end` - 1. * * @param start the offset of the first character. diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CodePointView.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CodePointView.scala index 37caf8a631..a61a0f5f83 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CodePointView.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/CodePointView.scala @@ -1,14 +1,12 @@ package org.enso.text.buffer -/** - * Exposes a code points based view over rope indexing operations. +/** Exposes a code points based view over rope indexing operations. * * @param rope the underlying rope. */ case class CodePointView(rope: Rope) { - /** - * Splits the rope into two parts at a given offset. + /** Splits the rope into two parts at a given offset. * * @param offset the number of code points in the first part. * @return a sub-rope containing `offset` code points and a sub-rope @@ -17,24 +15,21 @@ case class CodePointView(rope: Rope) { def splitAt(offset: Int): (Rope, Rope) = rope.splitWith(offset, CodePointView.Ops) - /** - * Takes a prefix of the rope of the given length. + /** Takes a prefix of the rope of the given length. * * @param len the length of the prefix to take. * @return a prefix of `this` containing `len` code points. */ def take(len: Int): Rope = rope.takeWith(len, CodePointView.Ops) - /** - * Takes a suffix of the rope by removing the first `len` code points. + /** Takes a suffix of the rope by removing the first `len` code points. * * @param len the number of code points to remove. * @return the suffix consisting of the remaining code points. */ def drop(len: Int): Rope = rope.dropWith(len, CodePointView.Ops) - /** - * Takes a substring of the rope, with the first code point at `startOffset` + /** Takes a substring of the rope, with the first code point at `startOffset` * and the last at `endOffset` - 1. * * @param startOffset the offset of the first code point. @@ -44,16 +39,14 @@ case class CodePointView(rope: Rope) { def substring(startOffset: Int, endOffset: Int): Rope = take(endOffset).codePoints.drop(startOffset) - /** - * Gets the code point at a specified position. + /** Gets the code point at a specified position. * * @param index the index of the code point to get. * @return the code point at `index` */ def at(index: Int): Int = rope.root.get(index, CodePointView.Ops) - /** - * Gets the number of code points in this rope. + /** Gets the number of code points in this rope. * * @return the length of this rope. */ diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/LineView.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/LineView.scala index cd2bc2d320..69678717a0 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/LineView.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/LineView.scala @@ -1,30 +1,26 @@ package org.enso.text.buffer -/** - * Exposes a line-based API for the rope. +/** Exposes a line-based API for the rope. * * @param rope the underlying rope. */ case class LineView(rope: Rope) { - /** - * Takes a prefix of the rope of the given length. + /** Takes a prefix of the rope of the given length. * * @param len the length of the prefix to take. * @return a prefix of `this` containing `len` lines. */ def take(len: Int): Rope = rope.takeWith(len, LineView.Ops) - /** - * Takes a suffix of the rope by removing the first `len` lines. + /** Takes a suffix of the rope by removing the first `len` lines. * * @param len the number of lines to remove. * @return the suffix consisting of the remaining lines. */ def drop(len: Int): Rope = rope.dropWith(len, LineView.Ops) - /** - * Splits the rope into two parts at a given offset. + /** Splits the rope into two parts at a given offset. * * @param offset the number of lines in the first part. * @return a sub-rope containing `offset` lines and a sub-rope @@ -32,8 +28,7 @@ case class LineView(rope: Rope) { */ def splitAt(offset: Int): (Rope, Rope) = rope.splitWith(offset, LineView.Ops) - /** - * Gets the number of lines in this rope. + /** Gets the number of lines in this rope. * * @return the length of this rope. */ @@ -46,7 +41,7 @@ object LineView { index: Int, measure: StringMeasure ): Boolean = - (index < measure.fullLines || (index == measure.fullLines && !measure.endsInNewLine)) + index < measure.fullLines || (index == measure.fullLines && !measure.endsInNewLine) override def isOffsetAfterBegin( index: Int, diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Rope.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Rope.scala index 4ab35b0053..10939056d2 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Rope.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Rope.scala @@ -2,8 +2,7 @@ package org.enso.text.buffer import cats.Monoid -/** - * The measure used for storing strings in the b-tree. +/** The measure used for storing strings in the b-tree. * * @param utf16Size number of characters. * @param utf32Size number of code points. @@ -17,8 +16,7 @@ case class StringMeasure( endsInNewLine: Boolean ) { - /** - * Number of lines measured, including the possibly non-terminated last line. + /** Number of lines measured, including the possibly non-terminated last line. * * @return the number of lines. */ @@ -38,8 +36,7 @@ object StringMeasure { } } -/** - * Represents a string using a tree. +/** Represents a string using a tree. * * Provides fast indexing operations by lines, characters and code points, * as well as fast concatenation. @@ -53,16 +50,14 @@ object StringMeasure { case class Rope(root: Node[String, StringMeasure]) { import Rope._ - /** - * Concates another rope at the end of this one. + /** Concates another rope at the end of this one. * * @param that the rope to add at the end. * @return the result of concatenating the two ropes. */ def ++(that: Rope): Rope = Rope(this.root ++ that.root) - /** - * Converts this rope to a String. + /** Converts this rope to a String. * * @return a String with this rope's contents */ @@ -95,22 +90,19 @@ case class Rope(root: Node[String, StringMeasure]) { elemOps: ElemOps[Int, String, StringMeasure] ): elemOps.Elem = root.get(index, elemOps) - /** - * Returns a code points based view of this rope. + /** Returns a code points based view of this rope. * * @return a code points view for this rope. */ def codePoints: CodePointView = CodePointView(this) - /** - * Returns a characters view of this rope. + /** Returns a characters view of this rope. * * @return a characters view for this rope. */ def characters: CharView = CharView(this) - /** - * Returns a lines view of this rope. + /** Returns a lines view of this rope. * * @return a lines view of this rope. */ @@ -135,8 +127,7 @@ object Rope { ) } - /** - * Creates a new Rope from a given string. + /** Creates a new Rope from a given string. * * @param str a string to convert into a rope. * @return a rope with the same contents as `str` @@ -147,8 +138,7 @@ object Rope { Rope(Node.mergeTrees(nodes)) } - /** - * Creates an empty rope. + /** Creates an empty rope. * * @return an empty rope. */ diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Tree.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Tree.scala index 3b95ad4023..0094eec5c4 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Tree.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/Tree.scala @@ -2,16 +2,14 @@ package org.enso.text.buffer import cats.Monoid -/** - * A super class of nodes stored in the tree. +/** A super class of nodes stored in the tree. * * @tparam C the container for leaf elements. * @tparam M the monoid used for sizing subtrees. */ sealed trait NodeVal[C, M] { - /** - * Iterates through all leaves, passing their contents to the specified + /** Iterates through all leaves, passing their contents to the specified * consumer function. * * @param f the consumer function. @@ -19,8 +17,7 @@ sealed trait NodeVal[C, M] { def foreach(f: C => Unit): Unit } -/** - * An empty leaf of the tree. +/** An empty leaf of the tree. * * @tparam C the container for leaf elements. * @tparam M the monoid used for sizing subtrees. @@ -29,8 +26,7 @@ case class Empty[C, M]() extends NodeVal[C, M] { override def foreach(f: C => Unit): Unit = () } -/** - * An internal node of the tree, storing children nodes. +/** An internal node of the tree, storing children nodes. * * @param children the children nodes. * @tparam C the container for leaf elements. @@ -43,8 +39,7 @@ case class Internal[C, M]( children.foreach(_.value.foreach(f)) } -/** - * A leaf node, storing a collection of type `C`. +/** A leaf node, storing a collection of type `C`. * * @param elements the collection stored in this leaf. * @tparam C the container for leaf elements. @@ -56,8 +51,7 @@ case class Leaf[C, M]( override def foreach(f: C => Unit): Unit = f(elements) } -/** - * A B-Tree node. +/** A B-Tree node. * * A node must satisfy the following invariants to be considered valid: * 1. All leaves appear at the same depth (i.e. for each node, the height of @@ -98,8 +92,7 @@ case class Node[C, M]( case Empty() => false } - /** - * Concatenates two trees, attaching `that` after `this`, ensuring the + /** Concatenates two trees, attaching `that` after `this`, ensuring the * result is a valid node. * * @param that the node to attach at the end of `this`. @@ -166,8 +159,7 @@ case class Node[C, M]( } } - /** - * Constructs a subtree consisting of an initial subset of elements. + /** Constructs a subtree consisting of an initial subset of elements. * * @param offset the length of the subsequence to construct. * @param measureOps operations to interpret this tree's measure. @@ -181,8 +173,8 @@ case class Node[C, M]( def take[I]( offset: I, measureOps: RangeOps[I, C, M] - )( - implicit measureMonoid: Monoid[M], + )(implicit + measureMonoid: Monoid[M], measurable: Measurable[C, M], treeShape: TreeShape ): Node[C, M] = { @@ -202,8 +194,7 @@ case class Node[C, M]( } } - /** - * Constructs a subtree by removing the first `offset` elements. + /** Constructs a subtree by removing the first `offset` elements. * * @param offset the number of elements to drop. * @param measureOps operations to interpret this tree's measure. @@ -217,8 +208,8 @@ case class Node[C, M]( def drop[I]( offset: I, measureOps: RangeOps[I, C, M] - )( - implicit measureMonoid: Monoid[M], + )(implicit + measureMonoid: Monoid[M], measurable: Measurable[C, M], treeShape: TreeShape ): Node[C, M] = { @@ -261,8 +252,7 @@ case class Node[C, M]( } } - /** - * Splits the tree into 2 subtrees, semantically equivalent to + /** Splits the tree into 2 subtrees, semantically equivalent to * `(this.take(offset, measureOps), this.drop(offset, measureOps)`. * * @param offset the number of elements to take and drop. @@ -276,8 +266,8 @@ case class Node[C, M]( def splitAt[I]( offset: I, measureOps: RangeOps[I, C, M] - )( - implicit measureMonoid: Monoid[M], + )(implicit + measureMonoid: Monoid[M], measurable: Measurable[C, M], treeShape: TreeShape ): (Node[C, M], Node[C, M]) = { @@ -303,8 +293,7 @@ case class Node[C, M]( } } - /** - * Gets an element at a specified index. + /** Gets an element at a specified index. * * @param index the index to get an element at. * @param elemOps interpretation of indexes and elements in this tree type. @@ -336,8 +325,7 @@ case class Node[C, M]( object Node { - /** - * Creates a new leaf node with provided elements. + /** Creates a new leaf node with provided elements. * * @param elems the elements to store. * @param measurable the operations for measuring the collection. @@ -348,8 +336,7 @@ object Node { def apply[C, M](elems: C)(implicit measurable: Measurable[C, M]): Node[C, M] = Node(0, measurable.measure(elems), Leaf[C, M](elems)) - /** - * An unsafe operation, creating a node with given children, without + /** An unsafe operation, creating a node with given children, without * checking the invariants. Should only be used if the invariants are * checked externally. * @@ -366,8 +353,7 @@ object Node { Node(height, size, Internal(children)) } - /** - * An unsafe operation, creating a new node from two collections of children. + /** An unsafe operation, creating a new node from two collections of children. * It does check the size invariants, but height invariants must be checked * externally. * @@ -394,16 +380,14 @@ object Node { } } - /** - * Creates an empty tree. + /** Creates an empty tree. * * @return an empty tree. */ def empty[C, M](implicit measureMonoid: Monoid[M]): Node[C, M] = Node(0, measureMonoid.empty, Empty()) - /** - * A safe operation for concatenating multliple valid trees into one. + /** A safe operation for concatenating multliple valid trees into one. * * @param nodes the nodes to merge into a tree. * @return a new tree representing a concatenation of all the supplied diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/TreeOps.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/TreeOps.scala index 266d60af28..aa17054fbb 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/TreeOps.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/buffer/TreeOps.scala @@ -1,7 +1,6 @@ package org.enso.text.buffer -/** - * Encodes element-level operation on a tree. +/** Encodes element-level operation on a tree. * * @tparam I the type of indices. * @tparam C the type of leaf nodes contents. @@ -9,13 +8,11 @@ package org.enso.text.buffer */ trait ElemOps[I, C, M] extends RangeOps[I, C, M] { - /** - * the type of elements associated with this interpretation of indexing. + /** the type of elements associated with this interpretation of indexing. */ type Elem - /** - * Gets an element at `index` from the `container`. + /** Gets an element at `index` from the `container`. * * @param container the container to look up index in. * @param index the index look up. @@ -23,8 +20,7 @@ trait ElemOps[I, C, M] extends RangeOps[I, C, M] { */ def get(container: C, index: I): Elem - /** - * Bounds check for the index. + /** Bounds check for the index. * * @param index the index to check. * @param measure the size of the container according to specific measure. @@ -33,8 +29,7 @@ trait ElemOps[I, C, M] extends RangeOps[I, C, M] { def contains(index: I, measure: M): Boolean } -/** - * Encodes slicing operations on a container with respect to a specific +/** Encodes slicing operations on a container with respect to a specific * measure. * @tparam I the type of indices. * @tparam C the type of leaf nodes contents. @@ -42,8 +37,7 @@ trait ElemOps[I, C, M] extends RangeOps[I, C, M] { */ trait RangeOps[I, C, M] { - /** - * Is the offset strictly before the end of a container of a given measure? + /** Is the offset strictly before the end of a container of a given measure? * e.g. if measure is the length of an array, this operation would be just * `offset < measure`. * @@ -53,8 +47,7 @@ trait RangeOps[I, C, M] { */ def isOffsetBeforeEnd(offset: I, measure: M): Boolean - /** - * Is the offset strictly after the beginning of a container of a given + /** Is the offset strictly after the beginning of a container of a given * measure? * e.g. if measure is the length of an array, this operation would be just * `offset > 0`. @@ -66,8 +59,7 @@ trait RangeOps[I, C, M] { */ def isOffsetAfterBegin(offset: I, measure: M): Boolean - /** - * Moves the offset by a given measure. I.e. if we have a container + /** Moves the offset by a given measure. I.e. if we have a container * `c = c1 ++ c2`, where `c1` and `c2` have measures `m1` and `m2` * respectively and an offset `off` inside `c`, then `shiftLeft(off, m1)` * would be the offset of `off` inside `c2` alone. @@ -78,8 +70,7 @@ trait RangeOps[I, C, M] { */ def shiftLeft(offset: I, measure: M): I - /** - * Takes `len` elements from the start of `container`. + /** Takes `len` elements from the start of `container`. * * @param container the container to take the prefix of. * @param len the length of the prefix. @@ -87,8 +78,7 @@ trait RangeOps[I, C, M] { */ def take(container: C, len: I): C - /** - * Drops `len` elements from the start of `container`. + /** Drops `len` elements from the start of `container`. * * @param container the container to take the suffix of. * @param len the length of the dropped prefix. @@ -98,8 +88,7 @@ trait RangeOps[I, C, M] { def drop(container: C, len: I): C } -/** - * Encodes the act of measuring a container with respect to a specific +/** Encodes the act of measuring a container with respect to a specific * measure. * * @tparam C the type of measured containers. @@ -107,27 +96,23 @@ trait RangeOps[I, C, M] { */ trait Measurable[C, M] { - /** - * Measures a container with respect to measure `M`. + /** Measures a container with respect to measure `M`. * @param container the container to measure. * @return the measure of the container. */ def measure(container: C): M } -/** - * The tree shape constants, used to regulate the depth and width of B-Trees. +/** The tree shape constants, used to regulate the depth and width of B-Trees. */ trait TreeShape { - /** - * The maximum number of children a node can have. + /** The maximum number of children a node can have. * @return the max number of children. */ val maxChildren: Int - /** - * The minimum number of children a node can have. + /** The minimum number of children a node can have. * For the tree invariants to be possible to maintain, it must be true that * `maxChildren + 1 >= 2 * minChildren`. * In practice it does not really make sense to choose a smaller value here. diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/EditorOps.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/EditorOps.scala index 7a0f12d698..95962f93b7 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/EditorOps.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/EditorOps.scala @@ -3,20 +3,17 @@ package org.enso.text.editing import cats.implicits._ import org.enso.text.editing.model.TextEdit -/** - * Auxiliary operations that edit a buffer validating diffs before applying it. +/** Auxiliary operations that edit a buffer validating diffs before applying it. */ object EditorOps { - /** - * Type alias for editor computations. + /** Type alias for editor computations. * * @tparam A a result of computations */ type EditorOp[A] = Either[TextEditValidationFailure, A] - /** - * Edits a buffer and validates diff. + /** Edits a buffer and validates diff. * * @param buffer a text buffer * @param diff a change to the buffer @@ -28,8 +25,7 @@ object EditorOps { .validate(buffer, diff) .map(_ => TextEditor[A].edit(buffer, diff)) - /** - * Applies a series of edits to the buffer and validates each diff against + /** Applies a series of edits to the buffer and validates each diff against * the buffer. * * @param buffer a text buffer @@ -38,8 +34,8 @@ object EditorOps { * @return either validation failure or a modified buffer */ def applyEdits[A: TextEditor](buffer: A, diffs: Seq[TextEdit]): EditorOp[A] = - diffs.foldLeft[EditorOp[A]](Right(buffer)) { - case (maybeBuffer, diff) => maybeBuffer >>= (edit(_, diff)) + diffs.foldLeft[EditorOp[A]](Right(buffer)) { case (maybeBuffer, diff) => + maybeBuffer >>= (edit(_, diff)) } } diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/JavaEditorAdapter.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/JavaEditorAdapter.scala index 7d445e85a5..6fcfa2760e 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/JavaEditorAdapter.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/JavaEditorAdapter.scala @@ -7,14 +7,12 @@ import org.enso.text.editing.model.TextEdit import scala.jdk.CollectionConverters._ -/** - * A convenience class for using the text editor logic from Java code. +/** A convenience class for using the text editor logic from Java code. */ object JavaEditorAdapter { implicit private val editor: TextEditor[Rope] = RopeTextEditor - /** - * Applies a series of edits to a given text. + /** Applies a series of edits to a given text. * * @param rope the initial text. * @param edits the edits to apply. diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/RopeTextEditor.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/RopeTextEditor.scala index 248289b116..d73c16e177 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/RopeTextEditor.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/RopeTextEditor.scala @@ -3,13 +3,11 @@ package org.enso.text.editing import org.enso.text.buffer.Rope import org.enso.text.editing.model.TextEdit -/** - * Instance of the [[TextEditor]] type class for the [[Rope]] type. +/** Instance of the [[TextEditor]] type class for the [[Rope]] type. */ object RopeTextEditor extends TextEditor[Rope] { - /** - * Edits a buffer. + /** Edits a buffer. * * @param buffer a text buffer * @param diff a change to the buffer @@ -43,16 +41,14 @@ object RopeTextEditor extends TextEditor[Rope] { .codePoints .drop(diff.range.end.character) - /** - * Returns a number of lines in a buffer. + /** Returns a number of lines in a buffer. * * @param buffer a text buffer * @return a number of lines in the buffer */ override def getLineCount(buffer: Rope): Int = buffer.lines.length - /** - * Cuts out one line from the buffer. + /** Cuts out one line from the buffer. * * @param buffer a text buffer * @param lineNumber a number of line diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidationFailure.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidationFailure.scala index 35b4a1bbb4..8d4ea44c6c 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidationFailure.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidationFailure.scala @@ -2,23 +2,19 @@ package org.enso.text.editing import org.enso.text.editing.model.Position -/** - * Base trait for text edit validation failures. +/** Base trait for text edit validation failures. */ sealed trait TextEditValidationFailure -/** - * Signals that an end position is before a start position. +/** Signals that an end position is before a start position. */ case object EndPositionBeforeStartPosition extends TextEditValidationFailure -/** - * Signals the a position object contains negative coordinates. +/** Signals the a position object contains negative coordinates. */ case object NegativeCoordinateInPosition extends TextEditValidationFailure -/** - * Signals that a position is outside the buffer. +/** Signals that a position is outside the buffer. * * @param position an invalid position */ diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidator.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidator.scala index 7847a03f02..d40ce95df6 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidator.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditValidator.scala @@ -3,13 +3,11 @@ package org.enso.text.editing import cats.implicits._ import org.enso.text.editing.model.TextEdit -/** - * A validator of [[TextEdit]] object. +/** A validator of [[TextEdit]] object. */ object TextEditValidator { - /** - * Validates [[TextEdit]] object against the provided buffer. + /** Validates [[TextEdit]] object against the provided buffer. * * @param buffer a text buffer * @param textEdit a change to the buffer diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditor.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditor.scala index d00dcd9df3..11ade62ccb 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditor.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/TextEditor.scala @@ -3,16 +3,14 @@ package org.enso.text.editing import org.enso.text.buffer.Rope import org.enso.text.editing.model.TextEdit -/** - * TextEditor is a type class that specifies a set of function for text +/** TextEditor is a type class that specifies a set of function for text * manipulation on a type variable representing a buffer. * * @tparam A a buffer type */ trait TextEditor[A] { - /** - * Edits a buffer. + /** Edits a buffer. * * @param buffer a text buffer * @param diff a change to the buffer @@ -20,16 +18,14 @@ trait TextEditor[A] { */ def edit(buffer: A, diff: TextEdit): A - /** - * Returns a line count for a buffer. + /** Returns a line count for a buffer. * * @param buffer a text buffer * @return a number of lines in the buffer */ def getLineCount(buffer: A): Int - /** - * Cuts out one line from the buffer. + /** Cuts out one line from the buffer. * * @param buffer a text buffer * @param lineNumber a number of line diff --git a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala index 1602731f4a..888a5ac538 100644 --- a/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala +++ b/lib/scala/text-buffer/src/main/scala/org/enso/text/editing/model.scala @@ -2,8 +2,7 @@ package org.enso.text.editing object model { - /** - * A representation of a position in a text file. + /** A representation of a position in a text file. * * @param line a line position in a document (zero-based). * @param character a character offset @@ -25,16 +24,14 @@ object model { } - /** - * A representation of a range of text in a text file. + /** A representation of a range of text in a text file. * * @param start the range's start position * @param end the range's end position */ case class Range(start: Position, end: Position) - /** - * A representation of a change to a text file at a given position + /** A representation of a change to a text file at a given position * * @param range a range of text in a text file * @param text a change to a text file diff --git a/lib/scala/text-buffer/src/test/scala/org/enso/text/editing/EditorOpsSpec.scala b/lib/scala/text-buffer/src/test/scala/org/enso/text/editing/EditorOpsSpec.scala index fe9f3bcdbe..35666d3ad4 100644 --- a/lib/scala/text-buffer/src/test/scala/org/enso/text/editing/EditorOpsSpec.scala +++ b/lib/scala/text-buffer/src/test/scala/org/enso/text/editing/EditorOpsSpec.scala @@ -51,8 +51,8 @@ class EditorOpsSpec extends AnyFlatSpec with Matchers with EitherValues { | IO.println "hello" |""".stripMargin ) - val range = Range(Position(0,0), Position(3, 0)) - val diff = TextEdit(range, "123") + val range = Range(Position(0, 0), Position(3, 0)) + val diff = TextEdit(range, "123") //when val result = EditorOps.applyEdits(codeToEdit, Seq(diff)) //then @@ -62,8 +62,8 @@ class EditorOpsSpec extends AnyFlatSpec with Matchers with EitherValues { it should "append text at the beginning of a buffer" in { //given val codeToEdit = Rope("123") - val range = Range(Position(0,0), Position(0, 0)) - val diff = TextEdit(range, "foo") + val range = Range(Position(0, 0), Position(0, 0)) + val diff = TextEdit(range, "foo") //when val result = EditorOps.applyEdits(codeToEdit, Seq(diff)) //then @@ -73,8 +73,8 @@ class EditorOpsSpec extends AnyFlatSpec with Matchers with EitherValues { it should "be able to insert changes to the empty buffer" in { //given val codeToEdit = Rope("") - val range = Range(Position(0,0), Position(0, 0)) - val diff = TextEdit(range, "foo") + val range = Range(Position(0, 0), Position(0, 0)) + val diff = TextEdit(range, "foo") //when val result = EditorOps.applyEdits(codeToEdit, Seq(diff)) //then diff --git a/lib/scala/version-output/src/main/scala/org/enso/version/VersionDescription.scala b/lib/scala/version-output/src/main/scala/org/enso/version/VersionDescription.scala index de4fd01a77..e79cce7084 100644 --- a/lib/scala/version-output/src/main/scala/org/enso/version/VersionDescription.scala +++ b/lib/scala/version-output/src/main/scala/org/enso/version/VersionDescription.scala @@ -2,8 +2,7 @@ package org.enso.version import buildinfo.Info -/** - * Represents a description of a version string that can be rendered as a +/** Represents a description of a version string that can be rendered as a * human-readable string or in JSON format. */ trait VersionDescription { @@ -14,8 +13,7 @@ trait VersionDescription { if (useJson) asJSONString else asHumanReadableString } -/** - * Defines an additional parameter for the version description. +/** Defines an additional parameter for the version description. * * @param humanReadableName the human readable prefix added when printing this * parameter in human-readable format @@ -32,8 +30,7 @@ case class VersionDescriptionParameter( object VersionDescription { - /** - * Creates a [[VersionDescription]] instance. + /** Creates a [[VersionDescription]] instance. * * @param header header displayed as the first line of the human-readable * representation diff --git a/project/BenchTasks.scala b/project/BenchTasks.scala index f4f642464b..aa71ebc1e8 100644 --- a/project/BenchTasks.scala +++ b/project/BenchTasks.scala @@ -1,9 +1,8 @@ package org.enso.build -import sbt.{Tags, inputKey, taskKey} +import sbt.{inputKey, taskKey, Tags} -/** - * Defines benchmarking related task keys. +/** Defines benchmarking related task keys. */ object BenchTasks { lazy val Exclusive = Tags.Tag("Exclusive") diff --git a/project/BuildInfo.scala b/project/BuildInfo.scala index e8b1c270f6..419e8eff00 100644 --- a/project/BuildInfo.scala +++ b/project/BuildInfo.scala @@ -5,8 +5,7 @@ import scala.sys.process._ object BuildInfo { - /** - * Writes build-time information to a Scala object that can be used by the + /** Writes build-time information to a Scala object that can be used by the * components. * * If the `ENSO_RELEASE_MODE` environment variable is set to `true`, will set @@ -59,8 +58,7 @@ object BuildInfo { private def isReleaseMode: Boolean = if (sys.env.get("ENSO_RELEASE_MODE").contains("true")) true else false - /** - * Information regarding the Git repository that was used in the build. + /** Information regarding the Git repository that was used in the build. * * @param ref if available, name of the branch that was checked out; if a * branch is not available, but the current commit is tagged, name @@ -113,8 +111,7 @@ object BuildInfo { None } - /** - * Fallback instance of [[GitInformation]] that can be used if the build is + /** Fallback instance of [[GitInformation]] that can be used if the build is * outside of a repository or the git information cannot be obtained for * other reasons. */ diff --git a/project/Cargo.scala b/project/Cargo.scala index ffe5f32354..7bc727b373 100644 --- a/project/Cargo.scala +++ b/project/Cargo.scala @@ -18,8 +18,7 @@ object Cargo { run(args, rustVersion.value, state.value.log) } - /** - * Checks rust version and executes the command `cargo $args`. + /** Checks rust version and executes the command `cargo $args`. * * @param args arguments to pass to cargo * @param rustVersion Rust version that should be used diff --git a/project/CopyTruffleJAR.scala b/project/CopyTruffleJAR.scala index 35be533d74..4ca0de75c9 100644 --- a/project/CopyTruffleJAR.scala +++ b/project/CopyTruffleJAR.scala @@ -4,8 +4,7 @@ import sbt.internal.util.ManagedLogger object CopyTruffleJAR { - /** - * The task that is used for copying the Truffle JAR file to our target + /** The task that is used for copying the Truffle JAR file to our target * directory. It should be ran when setting-up the project and after each * update of Graal version. * @@ -35,8 +34,7 @@ object CopyTruffleJAR { } } - /** - * This task should be added as a dependency of compileInputs in the runtime + /** This task should be added as a dependency of compileInputs in the runtime * subproject. It ensures that the compilation will not proceed unless the * JARs have not been bootstrapped. If the JARs were out of date, they are * updated within this task, so bootstrap does not have to be re-run. @@ -75,8 +73,7 @@ object CopyTruffleJAR { } } - /** - * Checks the Truffle JARs and updates them if necessary. + /** Checks the Truffle JARs and updates them if necessary. * * @param libraryUpdates the value of Compile / updates * @return true if an update has been performed and the JVM needs a restart diff --git a/project/Distribution.scala b/project/Distribution.scala index 1b766577ab..4789f542ef 100644 --- a/project/Distribution.scala +++ b/project/Distribution.scala @@ -15,8 +15,7 @@ import scala.reflect.macros.blackbox object Distribution { - /** - * Creates a [[DistributionDescription]]. + /** Creates a [[DistributionDescription]]. */ def apply( name: String, @@ -25,15 +24,13 @@ object Distribution { ): DistributionDescription = DistributionDescription(name, packageDestination, sbtComponents) - /** - * A macro that creates [[SBTDistributionComponent]] descriptions from a list + /** A macro that creates [[SBTDistributionComponent]] descriptions from a list * of project references. */ def sbtProjects(projects: Project*): Seq[SBTDistributionComponent] = macro sbtProjectsImpl - /** - * Implementation of the [[sbtProjects]] macro. + /** Implementation of the [[sbtProjects]] macro. * * It triggers execution of the tasks that are used to get information from * SBT on each project. diff --git a/project/EnvironmentCheck.scala b/project/EnvironmentCheck.scala index fd75659cf5..568ebc4dcd 100644 --- a/project/EnvironmentCheck.scala +++ b/project/EnvironmentCheck.scala @@ -64,8 +64,7 @@ object EnvironmentCheck { graalOk && javaOk } - /** - * Runs `rustc --version` to ensure that it is properly installed and + /** Runs `rustc --version` to ensure that it is properly installed and * checks if the reported version is consistent with expectations. * * @param expectedVersion rust version that is expected to be installed, @@ -92,8 +91,7 @@ object EnvironmentCheck { } } - /** - * Augments a state transition to do a Rust and GraalVM version check. + /** Augments a state transition to do a Rust and GraalVM version check. * * @param graalVersion the GraalVM version that should be used for * building this project diff --git a/project/FixInstrumentsGeneration.scala b/project/FixInstrumentsGeneration.scala index c005306b2c..a28c42c087 100644 --- a/project/FixInstrumentsGeneration.scala +++ b/project/FixInstrumentsGeneration.scala @@ -3,8 +3,7 @@ import sbt._ object FixInstrumentsGeneration { - /** - * This task detects any changes in source files of Instruments and forces + /** This task detects any changes in source files of Instruments and forces * recompilation of all instruments on any change. This is to ensure that the * Annotation Processor registers all of the instruments. * @@ -44,8 +43,7 @@ object FixInstrumentsGeneration { } } - /** - * This task detects if just a subset of the Instruments has been recompiled + /** This task detects if just a subset of the Instruments has been recompiled * (right now we did not find a way of detecting this before compilation). If * the Instrumentation state is detected to be inconsistent, current * compilation is aborted and classfiles are deleted to ensure that when diff --git a/project/GatherLicenses.scala b/project/GatherLicenses.scala index eff1729590..b4e98a1aec 100644 --- a/project/GatherLicenses.scala +++ b/project/GatherLicenses.scala @@ -15,8 +15,7 @@ import src.main.scala.licenses.{DependencySummary, DistributionDescription} import scala.collection.JavaConverters._ import scala.sys.process._ -/** - * The task and configuration for automatically gathering license information. +/** The task and configuration for automatically gathering license information. */ object GatherLicenses { val distributions = taskKey[Seq[DistributionDescription]]( @@ -27,8 +26,7 @@ object GatherLicenses { settingKey[Set[String]]("The ivy configurations we consider in the review.") private val stateFileName = "report-state" - /** - * The task that performs the whole license gathering process. + /** The task that performs the whole license gathering process. */ lazy val run = Def.task { val log = state.value.log @@ -184,8 +182,7 @@ object GatherLicenses { case class LegalReviewException(string: String) extends RuntimeException(string) - /** - * Launches a server that allows to easily review the generated report. + /** Launches a server that allows to easily review the generated report. * * Requires `npm` to be on the system PATH. */ @@ -196,8 +193,7 @@ object GatherLicenses { .exitValue() } - /** - * A task that prints which sub-projects use a dependency and what + /** A task that prints which sub-projects use a dependency and what * dependencies use it (so that one can track where dependencies come from). */ lazy val analyzeDependency = Def.inputTask { diff --git a/project/GenerateAST.scala b/project/GenerateAST.scala index 3e6a4eca6a..66aa9b01bb 100644 --- a/project/GenerateAST.scala +++ b/project/GenerateAST.scala @@ -2,8 +2,6 @@ import sbt.Keys._ import sbt._ import sbt.internal.util.ManagedLogger - - object GenerateAST { lazy val task = Def.task { @@ -13,31 +11,30 @@ object GenerateAST { val output = sourceManaged.value / "main/org/enso/ast/Ast.scala" val cache = streams.value.cacheStoreFactory.make("ast_source") - Tracked.diffInputs(cache, FileInfo.lastModified)(Set(source)) - { source: ChangeReport[File] => - val rustVersion = Cargo.rustVersion.value - if (source.modified.nonEmpty) { + Tracked.diffInputs(cache, FileInfo.lastModified)(Set(source)) { + source: ChangeReport[File] => + val rustVersion = Cargo.rustVersion.value + if (source.modified.nonEmpty) { output.getParentFile.mkdirs generateAST(rustVersion, output, log) - } + } } Seq(output) } - /** - * Generates the Scala AST in the specified file. All errors are reported in + /** Generates the Scala AST in the specified file. All errors are reported in * stderr and raise a runtime exception. * * @param out the file where the generated AST is going to be placed */ - def generateAST - (rustVersion: String, out: File, log: ManagedLogger): Unit = { + def generateAST(rustVersion: String, out: File, log: ManagedLogger): Unit = { val args = s"run -p ast -- --generate-scala-ast $out" log.info(s"Generating Scala AST from Rust definitions.") - try Cargo.run(args, rustVersion, log) catch { + try Cargo.run(args, rustVersion, log) + catch { case ex: RuntimeException => log.error(s"Generation of the Scala AST failed.") throw ex diff --git a/project/GenerateFlatbuffers.scala b/project/GenerateFlatbuffers.scala index e0fce0b7a5..06c6a306ff 100644 --- a/project/GenerateFlatbuffers.scala +++ b/project/GenerateFlatbuffers.scala @@ -74,8 +74,7 @@ object GenerateFlatbuffers { * only happen if the file has been edited during compilation). */ - /** - * Runs flatc to ensure that it is properly installed and checks if the + /** Runs flatc to ensure that it is properly installed and checks if the * reported version is consistent with expectations. * * @param expectedVersion flatc version that is expected to be installed, @@ -143,8 +142,7 @@ object GenerateFlatbuffers { } } - /** - * Runs flatc to discover what sources will be generated. + /** Runs flatc to discover what sources will be generated. * flatc will fail if there are errors in the files, as this is the first * time it is run on the files, the errors are captured and reported * (see Note [flatc Error Reporting]). diff --git a/project/LauncherShimsForTest.scala b/project/LauncherShimsForTest.scala index 5e2b70319a..483db66d62 100644 --- a/project/LauncherShimsForTest.scala +++ b/project/LauncherShimsForTest.scala @@ -3,8 +3,7 @@ import sbt._ object LauncherShimsForTest { - /** - * Creates a task that compiles the launcher shims which are used for some of + /** Creates a task that compiles the launcher shims which are used for some of * the launcher tests. * * @param rustcVersion Rust version that should be used diff --git a/project/NativeImage.scala b/project/NativeImage.scala index 1bb6743a46..8f93742f6b 100644 --- a/project/NativeImage.scala +++ b/project/NativeImage.scala @@ -9,14 +9,12 @@ import scala.sys.process._ object NativeImage { - /** - * Specifies whether the build executable should include debug symbols. Should + /** Specifies whether the build executable should include debug symbols. Should * be set to false for production builds. May work only on Linux. */ private val includeDebugInfo: Boolean = false - /** - * Creates a task that builds a native image for the current project. + /** Creates a task that builds a native image for the current project. * * @param artifactName name of the artifact to create * @param staticOnLinux specifies whether to link statically (applies only @@ -100,8 +98,7 @@ object NativeImage { } .dependsOn(Compile / compile) - /** - * Creates a task which watches for changes of any compiled files or + /** Creates a task which watches for changes of any compiled files or * dependencies and triggers a rebuild if and only if there are any changes. * * @param actualBuild reference to the task doing the actual Native Image @@ -153,8 +150,7 @@ object NativeImage { } } - /** - * [[File]] representing the artifact called `name` built with the Native + /** [[File]] representing the artifact called `name` built with the Native * Image. */ def artifactFile(name: String): File = @@ -165,8 +161,7 @@ object NativeImage { "https://github.com/gradinac/musl-bundle-example/releases/download/" + "v1.0/musl.tar.gz" - /** - * Ensures that the `musl` bundle is installed. + /** Ensures that the `musl` bundle is installed. * * Checks for existence of its directory and if it does not exist, downloads * and extracts the bundle. After extracting it does the required @@ -242,8 +237,7 @@ object NativeImage { binaryLocation.toPath.toAbsolutePath.normalize } - /** - * Replaces paths in `musl-gcc.specs` with absolute paths to the bundle. + /** Replaces paths in `musl-gcc.specs` with absolute paths to the bundle. * * The paths in `musl-gcc.specs` start with `/build/bundle` which is not a * valid path by default. Instead, these prefixes are replaced with an @@ -259,8 +253,7 @@ object NativeImage { IO.write(specs, replaced) } - /** - * Creates a simple shell script called `musl-gcc` which calls the original + /** Creates a simple shell script called `musl-gcc` which calls the original * `gcc` and ensures the bundle's configuration (`musl-gcc.specs`) is loaded. */ private def createGCCWrapper(bundleLocation: File): Unit = { diff --git a/project/Platform.scala b/project/Platform.scala index 64f610a2ca..03f1c33b2b 100644 --- a/project/Platform.scala +++ b/project/Platform.scala @@ -1,19 +1,16 @@ object Platform { - /** - * Returns true if the build system is running on Windows. + /** Returns true if the build system is running on Windows. */ def isWindows: Boolean = sys.props("os.name").toLowerCase().contains("windows") - /** - * Returns true if the build system is running on Linux. + /** Returns true if the build system is running on Linux. */ def isLinux: Boolean = sys.props("os.name").toLowerCase().contains("linux") - /** - * Returns true if the build system is running on macOS. + /** Returns true if the build system is running on macOS. */ def isMacOS: Boolean = sys.props("os.name").toLowerCase().contains("mac") diff --git a/project/RecompileParser.scala b/project/RecompileParser.scala index 355de28516..d3f760843a 100644 --- a/project/RecompileParser.scala +++ b/project/RecompileParser.scala @@ -5,8 +5,7 @@ import sbtcrossproject.CrossPlugin.autoImport._ object RecompileParser { - /** - * Ensures that the project is recompiled whenever the project from + /** Ensures that the project is recompiled whenever the project from * `syntaxDefinition` is changed. Should be attached to the `compile` task as * a dependency. */ diff --git a/project/StdBits.scala b/project/StdBits.scala index 151b9d2847..5201439b3d 100644 --- a/project/StdBits.scala +++ b/project/StdBits.scala @@ -5,8 +5,7 @@ import sbt.librarymanagement.{ConfigurationFilter, DependencyFilter} object StdBits { - /** - * Discovers dependencies of a project and copies them into the destination + /** Discovers dependencies of a project and copies them into the destination * directory. * * @param destination location where to put the dependencies diff --git a/project/build.properties b/project/build.properties index d9c1e9606f..603fb0e47c 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1,2 +1,2 @@ -sbt.version=1.3.13 +sbt.version=1.4.1 diff --git a/project/plugins.sbt b/project/plugins.sbt index 0c78c99cae..9e7533153b 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,5 +1,5 @@ -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.10") -addSbtPlugin("ch.epfl.scala" % "sbt-bloop" % "1.4.0-RC1") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.15.0") +addSbtPlugin("ch.epfl.scala" % "sbt-bloop" % "1.4.4") addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0") addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.1.0") addSbtPlugin("com.typesafe.sbt" % "sbt-license-report" % "1.2.0") diff --git a/project/src/main/scala/licenses/Attachment.scala b/project/src/main/scala/licenses/Attachment.scala index b1e0e7a7c6..de98f07f17 100644 --- a/project/src/main/scala/licenses/Attachment.scala +++ b/project/src/main/scala/licenses/Attachment.scala @@ -4,13 +4,11 @@ import java.nio.file.Path import sbt.IO -/** - * Represents a licensing information related to a dependency. +/** Represents a licensing information related to a dependency. */ sealed trait Attachment -/** - * Represents a file attached to the dependency's sources. +/** Represents a file attached to the dependency's sources. * * This may be a license file, a copyright notice, a credits file etc. */ @@ -20,22 +18,19 @@ case class AttachedFile( origin: Option[String] = None ) extends Attachment { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = { val originRepr = origin.map(o => s", origin = $o") s"AttachedFile($path, ...$originRepr)" } - /** - * Name of the file. + /** Name of the file. */ def fileName: String = path.getFileName } -/** - * Represents a copyright mention extracted from a file. +/** Represents a copyright mention extracted from a file. * * The copyright mention may come from comments in the source code, for * example. @@ -54,16 +49,14 @@ case class CopyrightMention( origins: Seq[PortablePath] ) extends Attachment { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = s"CopyrightMention('$content')" } object CopyrightMention { - /** - * Creates a [[CopyrightMention]] converting `origins` to [[PortablePath]]. + /** Creates a [[CopyrightMention]] converting `origins` to [[PortablePath]]. */ def from( content: String, @@ -72,8 +65,7 @@ object CopyrightMention { ): CopyrightMention = CopyrightMention(content, contexts, origins.map(PortablePath(_))) - /** - * Creates a [[CopyrightMention]] with no origins. + /** Creates a [[CopyrightMention]] with no origins. */ def apply( content: String, @@ -81,8 +73,7 @@ object CopyrightMention { ): CopyrightMention = CopyrightMention(content, contexts, Seq.empty[PortablePath]) - /** - * Transforms the sequence of copyright mentions by merging ones that have + /** Transforms the sequence of copyright mentions by merging ones that have * equal content. */ def mergeByContent(copyrights: Seq[CopyrightMention]): Seq[CopyrightMention] = @@ -91,8 +82,7 @@ object CopyrightMention { .map({ case (_, equal) => mergeEqual(equal) }) .toSeq - /** - * Transforms the sequence of copyright mentions by merging ones that have + /** Transforms the sequence of copyright mentions by merging ones that have * equal context. * * This may be useful as a single comment block may contain multiple mentions @@ -106,16 +96,14 @@ object CopyrightMention { copyrights: Seq[CopyrightMention] ): Seq[CopyrightMention] = { val (eligible, rest) = copyrights.partition(_.contexts.size == 1) - val merged = eligible.groupBy(c => c.contexts.head).map { - case (_, equal) => - val ref = findBestRepresentative(equal) - ref.copy(origins = equal.flatMap(_.origins).distinct) + val merged = eligible.groupBy(c => c.contexts.head).map { case (_, equal) => + val ref = findBestRepresentative(equal) + ref.copy(origins = equal.flatMap(_.origins).distinct) } (merged ++ rest).toSeq } - /** - * Returns the best representative to use as content of the merged set of + /** Returns the best representative to use as content of the merged set of * copyrights that share a context. * * Usually, mentions that start with the word 'copyright' are most @@ -132,8 +120,7 @@ object CopyrightMention { .getOrElse(copyrights.head) } - /** - * Merges multiple copyright mentions that have equal content. + /** Merges multiple copyright mentions that have equal content. * * Their contexts and origins are concatenated (ignoring duplicates). */ @@ -152,8 +139,7 @@ object CopyrightMention { ) } - /** - * Strips comment-related characters from the prefix and whitespace from + /** Strips comment-related characters from the prefix and whitespace from * suffix of the copyright line. */ def cleanup(string: String): String = { @@ -166,8 +152,7 @@ object CopyrightMention { object AttachedFile { - /** - * Reads a file at the given path into an [[AttachedFile]]. + /** Reads a file at the given path into an [[AttachedFile]]. * * If `relativizeTo` is provided, the path included in the resulting * [[AttachedFile]] is relative to the one provided. diff --git a/project/src/main/scala/licenses/DependencyInformation.scala b/project/src/main/scala/licenses/DependencyInformation.scala index 05861f3b0f..87b8cc000d 100644 --- a/project/src/main/scala/licenses/DependencyInformation.scala +++ b/project/src/main/scala/licenses/DependencyInformation.scala @@ -5,16 +5,14 @@ import java.nio.file.Path import com.typesafe.sbt.license.{DepModuleInfo, LicenseInfo} import src.main.scala.licenses.report.Review -/** - * Defines a way to access sources of a dependency. +/** Defines a way to access sources of a dependency. * * This may involve various actions, such as downloading or extracting files * into a temporary directory. */ trait SourceAccess { - /** - * Calls the callback with a path to the available sources. + /** Calls the callback with a path to the available sources. * * The provided path is only valid during the callbacks invocation and is * considered invalid as soon as that function completes. @@ -22,8 +20,7 @@ trait SourceAccess { def access[R](withSources: Path => R): R } -/** - * Information about a single dependency. +/** Information about a single dependency. * * @param moduleInfo description of the module * @param license information about the module's discovered license @@ -37,8 +34,7 @@ case class DependencyInformation( url: Option[String] ) { - /** - * Normalized name of the package that uniquely identifies the dependency. + /** Normalized name of the package that uniquely identifies the dependency. */ def packageName: String = Review.normalizeName( diff --git a/project/src/main/scala/licenses/DependencySummary.scala b/project/src/main/scala/licenses/DependencySummary.scala index a64805e9c9..988950a47a 100644 --- a/project/src/main/scala/licenses/DependencySummary.scala +++ b/project/src/main/scala/licenses/DependencySummary.scala @@ -7,87 +7,73 @@ import src.main.scala.licenses.report.{ WithWarnings } -/** - * Contains a sequence of dependencies and any attachments found. +/** Contains a sequence of dependencies and any attachments found. */ case class DependencySummary( dependencies: Seq[(DependencyInformation, Seq[Attachment])] ) -/** - * Review status of the [[Attachment]]. +/** Review status of the [[Attachment]]. */ sealed trait AttachmentStatus { - /** - * Determines if the attachment with this status should be included in the + /** Determines if the attachment with this status should be included in the * final package. */ def included: Boolean } object AttachmentStatus { - /** - * Indicates that the attachment should be kept. + /** Indicates that the attachment should be kept. */ case object Keep extends AttachmentStatus { - /** - * @inheritdoc + /** @inheritdoc */ override def included: Boolean = true } - /** - * Indicates that the copyright mention should be kept, but its whole context + /** Indicates that the copyright mention should be kept, but its whole context * should be used instead of its content. * * Only valid for [[CopyrightMention]]. */ case object KeepWithContext extends AttachmentStatus { - /** - * @inheritdoc + /** @inheritdoc */ override def included: Boolean = true } - /** - * Indicates that the attachment should be ignored. + /** Indicates that the attachment should be ignored. */ case object Ignore extends AttachmentStatus { - /** - * @inheritdoc + /** @inheritdoc */ override def included: Boolean = false } - /** - * Indicates that the attachment has been added manually. + /** Indicates that the attachment has been added manually. */ case object Added extends AttachmentStatus { - /** - * @inheritdoc + /** @inheritdoc */ override def included: Boolean = true } - /** - * Indicates that the attachment was not yet reviewed. + /** Indicates that the attachment was not yet reviewed. */ case object NotReviewed extends AttachmentStatus { - /** - * @inheritdoc + /** @inheritdoc */ override def included: Boolean = false } } -/** - * Gathers information related to a dependency after the review. +/** Gathers information related to a dependency after the review. * * @param information original [[DependencyInformation]] * @param licenseReview review status of the dependency's main license @@ -103,8 +89,7 @@ case class ReviewedDependency( copyrights: Seq[(CopyrightMention, AttachmentStatus)] ) -/** - * Summarizes the dependency review. +/** Summarizes the dependency review. * * The reviewed version of [[DependencySummary]]. * @@ -119,8 +104,7 @@ case class ReviewedSummary( additionalFiles: Seq[AttachedFile] ) { - /** - * Returns a license-like file that is among attached files that are included + /** Returns a license-like file that is among attached files that are included * (if such file exists). */ def includedLicense(dependency: ReviewedDependency): Option[AttachedFile] = @@ -136,8 +120,7 @@ case class ReviewedSummary( object ReviewedSummary { - /** - * Returns a list of warnings that indicate missing reviews or other issues. + /** Returns a list of warnings that indicate missing reviews or other issues. */ def warnAboutMissingReviews(summary: ReviewedSummary): WithWarnings[Unit] = { val warnings = summary.dependencies.flatMap { dep => diff --git a/project/src/main/scala/licenses/DistributionDescription.scala b/project/src/main/scala/licenses/DistributionDescription.scala index 0736690bd4..10b8a85c8e 100644 --- a/project/src/main/scala/licenses/DistributionDescription.scala +++ b/project/src/main/scala/licenses/DistributionDescription.scala @@ -4,8 +4,7 @@ import com.typesafe.sbt.license.LicenseReport import sbt.File import sbt.librarymanagement.UpdateReport -/** - * Describes a component included in the distribution managed by SBT. +/** Describes a component included in the distribution managed by SBT. * * @param name name of the component * @param licenseReport license report generated by the `updateLicenses` task @@ -17,8 +16,7 @@ case class SBTDistributionComponent( classifiedArtifactsReport: UpdateReport ) -/** - * Describes an artifact consisting of multiple components that is distributed +/** Describes an artifact consisting of multiple components that is distributed * independently. * * @param artifactName name of the artifact @@ -36,8 +34,7 @@ case class DistributionDescription( sbtComponents: Seq[SBTDistributionComponent] ) { - /** - * Returns names of root components included in the distribution. + /** Returns names of root components included in the distribution. */ def rootComponentsNames: Seq[String] = sbtComponents.map(_.name) } diff --git a/project/src/main/scala/licenses/FilesHelper.scala b/project/src/main/scala/licenses/FilesHelper.scala index 496cf96ba6..c34e2fad1d 100644 --- a/project/src/main/scala/licenses/FilesHelper.scala +++ b/project/src/main/scala/licenses/FilesHelper.scala @@ -7,8 +7,7 @@ import scala.collection.JavaConverters._ object FilesHelper { - /** - * A helper method that recursively traverses the directory structure at + /** A helper method that recursively traverses the directory structure at * `root` and collects results of calling `action` on each encountered entry. * * The action is called for all kinds of entries that are encountered. diff --git a/project/src/main/scala/licenses/PortablePath.scala b/project/src/main/scala/licenses/PortablePath.scala index 461145c983..2660335b42 100644 --- a/project/src/main/scala/licenses/PortablePath.scala +++ b/project/src/main/scala/licenses/PortablePath.scala @@ -5,33 +5,28 @@ import java.nio.file.Path import sbt.File -/** - * A wrapper for [[Path]] that ensures portable string representation on all +/** A wrapper for [[Path]] that ensures portable string representation on all * platforms. */ case class PortablePath(path: Path) { - /** - * @inheritdoc + /** @inheritdoc */ override def toString: String = path.toString.replace(JFile.separatorChar, '/') - /** - * A utility method converting the wrapped path to [[File]]. + /** A utility method converting the wrapped path to [[File]]. */ def toFile: File = path.toFile - /** - * A utility method returning filename of the wrapped path. + /** A utility method returning filename of the wrapped path. */ def getFileName: String = path.getFileName.toString } object PortablePath { - /** - * A utility method that parses [[Path]] and immediately wraps it into + /** A utility method that parses [[Path]] and immediately wraps it into * [[PortablePath]]. */ def of(first: String, more: String*): PortablePath = diff --git a/project/src/main/scala/licenses/backend/AttachmentGatherer.scala b/project/src/main/scala/licenses/backend/AttachmentGatherer.scala index 52c94b8fab..11a75ab81f 100644 --- a/project/src/main/scala/licenses/backend/AttachmentGatherer.scala +++ b/project/src/main/scala/licenses/backend/AttachmentGatherer.scala @@ -4,20 +4,17 @@ import java.nio.file.Path import src.main.scala.licenses.{Attachment, SourceAccess} -/** - * Common interface for algorithms that gather attachments based on available +/** Common interface for algorithms that gather attachments based on available * sources. */ trait AttachmentGatherer { - /** - * Runs the algorithm that will scan the sources located in `root` and return + /** Runs the algorithm that will scan the sources located in `root` and return * any attachments found. */ def run(root: Path): Seq[Attachment] - /** - * A helper function that uses the provided [[SourceAccess]] instances to + /** A helper function that uses the provided [[SourceAccess]] instances to * analyze sources provided by them and return any attachments found. */ def run(sources: Seq[SourceAccess]): Seq[Attachment] = { diff --git a/project/src/main/scala/licenses/backend/CombinedBackend.scala b/project/src/main/scala/licenses/backend/CombinedBackend.scala index 46cf4acc67..019ef5af3d 100644 --- a/project/src/main/scala/licenses/backend/CombinedBackend.scala +++ b/project/src/main/scala/licenses/backend/CombinedBackend.scala @@ -3,15 +3,13 @@ import java.nio.file.Path import src.main.scala.licenses.Attachment -/** - * An [[AttachmentGatherer]] that combines results from running multiple +/** An [[AttachmentGatherer]] that combines results from running multiple * algorithms. */ class CombinedBackend(backends: Seq[AttachmentGatherer]) extends AttachmentGatherer { - /** - * @inheritdoc + /** @inheritdoc */ override def run(root: Path): Seq[Attachment] = { backends.flatMap(_.run(root)) @@ -20,8 +18,7 @@ class CombinedBackend(backends: Seq[AttachmentGatherer]) object CombinedBackend { - /** - * Creates a [[CombinedBackend]] from multiple [[AttachmentGatherer]]s. + /** Creates a [[CombinedBackend]] from multiple [[AttachmentGatherer]]s. */ def apply(backends: AttachmentGatherer*): CombinedBackend = new CombinedBackend(backends) diff --git a/project/src/main/scala/licenses/backend/GatherCopyrights.scala b/project/src/main/scala/licenses/backend/GatherCopyrights.scala index cf37ab197b..ea750e5600 100644 --- a/project/src/main/scala/licenses/backend/GatherCopyrights.scala +++ b/project/src/main/scala/licenses/backend/GatherCopyrights.scala @@ -6,8 +6,7 @@ import src.main.scala.licenses.{Attachment, CopyrightMention, FilesHelper} import scala.util.control.NonFatal -/** - * The algorithm for gathering any copyright notices inside of source files. +/** The algorithm for gathering any copyright notices inside of source files. * * It reads all text files and gathers any lines that contain the word * copyright - it may introduce some false positives but these can be manually @@ -19,8 +18,7 @@ import scala.util.control.NonFatal */ object GatherCopyrights extends AttachmentGatherer { - /** - * @inheritdoc + /** @inheritdoc */ override def run(root: Path): Seq[Attachment] = { val allCopyrights = FilesHelper.walk(root) { path => @@ -31,13 +29,12 @@ object GatherCopyrights extends AttachmentGatherer { lines .filter(l => mayBeCopyright(l._1)) .map { case (str, idx) => (str, findContext(lines)(idx)) } - .map { - case (line, context) => - CopyrightMention.from( - CopyrightMention.cleanup(line), - Seq(context), - Seq(relativePath) - ) + .map { case (line, context) => + CopyrightMention.from( + CopyrightMention.cleanup(line), + Seq(context), + Seq(relativePath) + ) } } catch { case NonFatal(e) => @@ -58,14 +55,12 @@ object GatherCopyrights extends AttachmentGatherer { ) } - /** - * Decides if the line may contain a copyright. + /** Decides if the line may contain a copyright. */ private def mayBeCopyright(line: String): Boolean = line.toLowerCase.contains("copyright") - /** - * Finds context of the given line. + /** Finds context of the given line. * * If the selected line seems to be a part of a block comment, the context * becomes the whole comment, otherwise it just includes 2 lines before and diff --git a/project/src/main/scala/licenses/backend/GatherNotices.scala b/project/src/main/scala/licenses/backend/GatherNotices.scala index 346cc20960..53578d8583 100644 --- a/project/src/main/scala/licenses/backend/GatherNotices.scala +++ b/project/src/main/scala/licenses/backend/GatherNotices.scala @@ -4,8 +4,7 @@ import java.nio.file.{Files, Path} import src.main.scala.licenses.{AttachedFile, Attachment, FilesHelper} -/** - * The algorithm for gathering any copyright-related files found in the +/** The algorithm for gathering any copyright-related files found in the * sources. * * It gathers any files whose name contains one of the keywords from @@ -13,8 +12,7 @@ import src.main.scala.licenses.{AttachedFile, Attachment, FilesHelper} */ object GatherNotices extends AttachmentGatherer { - /** - * @inheritdoc + /** @inheritdoc */ override def run(root: Path): Seq[Attachment] = { FilesHelper.walk(root) { path => @@ -24,8 +22,7 @@ object GatherNotices extends AttachmentGatherer { } } - /** - * Decides if the path may be relevant and should be included in the result. + /** Decides if the path may be relevant and should be included in the result. */ def mayBeRelevant(fileName: String): Boolean = { val extension = { @@ -41,14 +38,12 @@ object GatherNotices extends AttachmentGatherer { } } - /** - * Decides if the filename is relevant and should be included in the result. + /** Decides if the filename is relevant and should be included in the result. */ def mayBeRelevant(path: Path): Boolean = mayBeRelevant(path.getFileName.toString.toLowerCase) - /** - * File extensions that are ignored. + /** File extensions that are ignored. * * Source files are ignored because they are scanned for copyright notices by * [[GatherCopyrights]], they are not likely to constitute separate copyright @@ -56,8 +51,7 @@ object GatherNotices extends AttachmentGatherer { */ private val ignoredExtensions = Seq("scala", "java") - /** - * File name keywords that indicate that a file should be included. + /** File name keywords that indicate that a file should be included. */ val possibleNames = Seq( diff --git a/project/src/main/scala/licenses/backend/GithubHeuristic.scala b/project/src/main/scala/licenses/backend/GithubHeuristic.scala index adbbd71740..fd61751eac 100644 --- a/project/src/main/scala/licenses/backend/GithubHeuristic.scala +++ b/project/src/main/scala/licenses/backend/GithubHeuristic.scala @@ -14,8 +14,7 @@ import src.main.scala.licenses.{ import scala.sys.process._ import scala.util.control.NonFatal -/** - * Tries to find copyright mentions in the GitHub project homepage and any +/** Tries to find copyright mentions in the GitHub project homepage and any * copyright-related files contained in the repository root. * * This is a fallback backend that may be used if the primary backends do not @@ -25,8 +24,7 @@ import scala.util.control.NonFatal */ case class GithubHeuristic(info: DependencyInformation, log: Logger) { - /** - * Runs the gathering process and returns any attachments found. + /** Runs the gathering process and returns any attachments found. * * It proceeds only if the project has an URL that seems to point to GitHub. */ @@ -38,8 +36,7 @@ case class GithubHeuristic(info: DependencyInformation, log: Logger) { } } - /** - * Downloads the project homepage at `address` and looks for any copyright + /** Downloads the project homepage at `address` and looks for any copyright * mentions or links that may lead to copyright-related files. * * Any found files are fetched and saved into the results. @@ -53,25 +50,24 @@ case class GithubHeuristic(info: DependencyInformation, log: Logger) { .map(m => (m.group("name"), m.group("href"))) .filter(p => mayBeRelevant(p._1)) .toList - matches.flatMap { - case (_, href) => - try { - val content = - url("https://github.com" + href.replace("blob", "raw")).cat.!! - Seq( - AttachedFile( - PortablePath.of(href), - content, - origin = Some("github.com") - ) + matches.flatMap { case (_, href) => + try { + val content = + url("https://github.com" + href.replace("blob", "raw")).cat.!! + Seq( + AttachedFile( + PortablePath.of(href), + content, + origin = Some("github.com") ) - } catch { - case NonFatal(error) => - log.warn( - s"Found file $href but cannot download it: $error" - ) - Seq() - } + ) + } catch { + case NonFatal(error) => + log.warn( + s"Found file $href but cannot download it: $error" + ) + Seq() + } } } catch { case NonFatal(error) => @@ -79,8 +75,7 @@ case class GithubHeuristic(info: DependencyInformation, log: Logger) { Seq() } - /** - * Decides if the file may be relevant and should be included in the result. + /** Decides if the file may be relevant and should be included in the result. * * Filenames that contain spaces are ignored because they are usually normal * links and do not lead to relevant files. diff --git a/project/src/main/scala/licenses/frontend/DependencyFilter.scala b/project/src/main/scala/licenses/frontend/DependencyFilter.scala index 0ad1dd922e..f74aa3ec22 100644 --- a/project/src/main/scala/licenses/frontend/DependencyFilter.scala +++ b/project/src/main/scala/licenses/frontend/DependencyFilter.scala @@ -2,8 +2,7 @@ package src.main.scala.licenses.frontend import src.main.scala.licenses.DependencyInformation -/** - * Filters out irrelevant dependencies. +/** Filters out irrelevant dependencies. * * Currently, dependencies whose organisation is `org.enso` are ignored, as * they are owned by us, so they do not require any additional licensing @@ -11,8 +10,7 @@ import src.main.scala.licenses.DependencyInformation */ object DependencyFilter { - /** - * Decides if the dependency should be kept for further processing. + /** Decides if the dependency should be kept for further processing. */ def shouldKeep(dependencyInformation: DependencyInformation): Boolean = dependencyInformation.moduleInfo.organization != "org.enso" diff --git a/project/src/main/scala/licenses/frontend/SbtLicenses.scala b/project/src/main/scala/licenses/frontend/SbtLicenses.scala index a0100de269..2a7a63a689 100644 --- a/project/src/main/scala/licenses/frontend/SbtLicenses.scala +++ b/project/src/main/scala/licenses/frontend/SbtLicenses.scala @@ -16,13 +16,11 @@ import src.main.scala.licenses.{ import scala.collection.JavaConverters._ -/** - * Defines the algorithm for discovering dependency metadata. +/** Defines the algorithm for discovering dependency metadata. */ object SbtLicenses { - /** - * Defines configurations that are deemed relevant for dependency discovery. + /** Defines configurations that are deemed relevant for dependency discovery. * * Currently we only analyse Compile dependencies as these are the ones that * get packaged. @@ -34,8 +32,7 @@ object SbtLicenses { */ val relevantConfigurations = Seq(Compile) - /** - * Analyzes the provided [[SBTDistributionComponent]]s collecting their + /** Analyzes the provided [[SBTDistributionComponent]]s collecting their * unique dependencies and issuing any warnings. * * @param components description of SBT components included in the @@ -112,16 +109,14 @@ object SbtLicenses { (relevantDeps, missingWarnings ++ unexpectedWarnings ++ reportsWarnings) } - /** - * Returns a project URL if it is defined for the dependency or None. + /** Returns a project URL if it is defined for the dependency or None. */ private def tryFindingUrl(dependency: Dependency): Option[String] = Option(dependency.ivyNode.getDescriptor).flatMap(descriptor => Option(descriptor.getHomePage) ) - /** - * Creates a [[SourceAccess]] instance that unpacks the source files from a + /** Creates a [[SourceAccess]] instance that unpacks the source files from a * JAR archive into a temporary directory. * * It removes the temporary directory after the analysis is finished. @@ -135,15 +130,13 @@ object SbtLicenses { } } - /** - * Returns a sequence of [[SourceAccess]] instances that give access to any + /** Returns a sequence of [[SourceAccess]] instances that give access to any * sources JARs that are available with the dependency. */ private def findSources(dependency: Dependency): Seq[SourceAccess] = dependency.sourcesJARPaths.map(createSourceAccessFromJAR) - /** - * Wraps information related to a dependency. + /** Wraps information related to a dependency. * * @param depLicense information on the license * @param ivyNode Ivy node that can be used to find metadata @@ -155,8 +148,7 @@ object SbtLicenses { sourcesJARPaths: Seq[Path] ) - /** - * Returns [[DepModuleInfo]] for an [[IvyNode]] if it is defined, or None. + /** Returns [[DepModuleInfo]] for an [[IvyNode]] if it is defined, or None. */ def safeModuleInfo(dep: IvyNode): Option[DepModuleInfo] = for { diff --git a/project/src/main/scala/licenses/report/HTMLWriter.scala b/project/src/main/scala/licenses/report/HTMLWriter.scala index e0111e7c28..efc0e60f25 100644 --- a/project/src/main/scala/licenses/report/HTMLWriter.scala +++ b/project/src/main/scala/licenses/report/HTMLWriter.scala @@ -5,16 +5,14 @@ import java.nio.file.Files import sbt.File -/** - * Allows to create very simple HTML reports. +/** Allows to create very simple HTML reports. * * @param bufferedWriter writer to which the generated code will be written */ class HTMLWriter(bufferedWriter: BufferedWriter) { val writer = new PrintWriter(bufferedWriter) - /** - * Writes the header containing basic styles and scripts for the reports. + /** Writes the header containing basic styles and scripts for the reports. * * @param title the page title */ @@ -48,23 +46,20 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { writer.println(heading) } - /** - * A helper class that allows to manage columns in a table row. + /** A helper class that allows to manage columns in a table row. * * @param columns expected columns count */ class RowWriter(columns: Int) { var added = 0 - /** - * A helper function that adds a column just containing plain text. + /** A helper function that adds a column just containing plain text. */ def addColumn(text: String): Unit = { addColumn(writeText(text)) } - /** - * Adds a cell in the next column that will contain anything that is + /** Adds a cell in the next column that will contain anything that is * written when executing the `writeAction`. */ def addColumn(writeAction: => Unit): Unit = { @@ -74,8 +69,7 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { added += 1 } - /** - * Finishes the current row and ensures that all expected columns have been + /** Finishes the current row and ensures that all expected columns have been * added. */ def finish(): Unit = { @@ -84,8 +78,7 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { } } - /** - * Writes a HTML table based on the provided descriptiom. + /** Writes a HTML table based on the provided descriptiom. * * @param headers sequence of header names for each column * @param rows sequence of functions that will be called to create rows of @@ -112,8 +105,7 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { writer.println("") } - /** - * Writes an unordered list. + /** Writes an unordered list. * * @param elements sequence of functions that will be called to write each of * the list's elements; everything written inside of each @@ -129,8 +121,7 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { writer.println("") } - /** - * Writes a link. + /** Writes a link. * * @param text link text * @param url link target @@ -138,34 +129,29 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { def writeLink(text: String, url: String): Unit = writer.println(s"""$text""") - /** - * Writes a H1 heading. + /** Writes a H1 heading. */ def writeHeading(heading: String): Unit = writer.println(s"

$heading

") - /** - * Writes a H2 heading. + /** Writes a H2 heading. */ def writeSubHeading(heading: String): Unit = writer.println(s"

$heading

") - /** - * Writes a paragraph of styled text. + /** Writes a paragraph of styled text. */ def writeParagraph(text: String, styles: Style*): Unit = writer.println(s"""

$text

""") - /** - * Writes plain (but potentially styled) text. + /** Writes plain (but potentially styled) text. */ def writeText(text: String, styles: Style*): Unit = if (styles.nonEmpty) writer.println(s"""$text""") else writer.println(text) - /** - * Writes a collapsible entry that by default just displays the `title`, but + /** Writes a collapsible entry that by default just displays the `title`, but * expands when clicked to show the `content`. */ def writeCollapsible( @@ -181,8 +167,7 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { |""".stripMargin) } - /** - * Writes an empty element that can be overridden by an injected script. + /** Writes an empty element that can be overridden by an injected script. * * Parameters names and values need to be properly escaped to fit for HTML. */ @@ -191,23 +176,21 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { params: (String, String)* ): String = { val mappedParams = params - .map { - case (name, value) => s"""data-$name="$value" """ + .map { case (name, value) => + s"""data-$name="$value" """ } .mkString(" ") s""" |""".stripMargin } - /** - * Escapes a string that may contain HTML markup to not be rendered but + /** Escapes a string that may contain HTML markup to not be rendered but * displayed as normal text. */ def escape(string: String): String = string.replace("&", "&").replace("<", "<").replace(">", ">") - /** - * Finishes writing the document and closes the output. + /** Finishes writing the document and closes the output. */ def close(): Unit = { writer.println("") @@ -217,50 +200,43 @@ class HTMLWriter(bufferedWriter: BufferedWriter) { object HTMLWriter { - /** - * Creates an [[HTMLWriter]] that writes its output to a [[File]] (creating + /** Creates an [[HTMLWriter]] that writes its output to a [[File]] (creating * it or overwriting if it exists). */ def toFile(destination: File): HTMLWriter = new HTMLWriter(Files.newBufferedWriter(destination.toPath)) } -/** - * Styles that can be used to make text stand out. +/** Styles that can be used to make text stand out. */ sealed trait Style object Style { - /** - * Makes the text bold. + /** Makes the text bold. */ case object Bold extends Style { override def toString: String = "font-weight:bold" } - /** - * Makes the text red. + /** Makes the text red. */ case object Red extends Style { override def toString: String = "color:red" } - /** - * Makes the text gray. + /** Makes the text gray. */ case object Gray extends Style { override def toString: String = "color:gray" } - /** - * Makes the text green. + /** Makes the text green. */ case object Green extends Style { override def toString: String = "color:green" } - /** - * Makes the text black. + /** Makes the text black. */ case object Black extends Style { override def toString: String = "color:black" diff --git a/project/src/main/scala/licenses/report/LicenseReview.scala b/project/src/main/scala/licenses/report/LicenseReview.scala index ecae4f9d36..c9108c22ba 100644 --- a/project/src/main/scala/licenses/report/LicenseReview.scala +++ b/project/src/main/scala/licenses/report/LicenseReview.scala @@ -2,19 +2,16 @@ package src.main.scala.licenses.report import java.nio.file.Path -/** - * Review status of a license within a specific dependency. +/** Review status of a license within a specific dependency. */ sealed trait LicenseReview object LicenseReview { - /** - * The license used by that dependency was not reviewed. + /** The license used by that dependency was not reviewed. */ case object NotReviewed extends LicenseReview - /** - * The license has been reviewed and points to the default file for this license type. + /** The license has been reviewed and points to the default file for this license type. * * This status is assigned automatically if the license type for the artifact is already reviewed * and there is no custom override for the given dependency. @@ -30,8 +27,7 @@ object LicenseReview { case class Default(path: Path, allowAdditionalCustomLicenses: Boolean) extends LicenseReview - /** - * The lciense for that dependency has been overridden with a custom one. + /** The lciense for that dependency has been overridden with a custom one. * * The attached files of the dependency should contain a file with the provided filename. */ diff --git a/project/src/main/scala/licenses/report/PackageNotices.scala b/project/src/main/scala/licenses/report/PackageNotices.scala index 7a8bb8b029..746c49094d 100644 --- a/project/src/main/scala/licenses/report/PackageNotices.scala +++ b/project/src/main/scala/licenses/report/PackageNotices.scala @@ -13,13 +13,11 @@ import src.main.scala.licenses.{ import scala.annotation.tailrec -/** - * Defines writing the notices package for distribution. +/** Defines writing the notices package for distribution. */ object PackageNotices { - /** - * Creates the notices package based on the `summary` in `destination`. + /** Creates the notices package based on the `summary` in `destination`. * * The `destination` directory is cleaned before creating the new notices. * @@ -119,8 +117,8 @@ object PackageNotices { if (copyrights.nonEmpty) { val compiledCopyrights = copyrights - .map { - case (m, s) => renderCopyright(m, s) + .map { case (m, s) => + renderCopyright(m, s) } .mkString("\n\n") val freeName = findFreeName(packageRoot, gatheredNoticesFilename) @@ -131,14 +129,12 @@ object PackageNotices { IO.write(destination / "NOTICE", mainNotice.toString() + "\n") } - /** - * Name of the generated file that contains concatenated copyright notices that were found in the + /** Name of the generated file that contains concatenated copyright notices that were found in the * project. */ val gatheredNoticesFilename = "NOTICES" - /** - * Finds a filename that is not taken. + /** Finds a filename that is not taken. * * First tries the `name` and adds increasing numerical suffixes if the * previous names were taken. @@ -151,8 +147,7 @@ object PackageNotices { else file } - /** - * Writes attached files to the given directory. + /** Writes attached files to the given directory. */ def writeFiles(root: File, files: Seq[AttachedFile]): Unit = { for (attachedFile <- files) { diff --git a/project/src/main/scala/licenses/report/Report.scala b/project/src/main/scala/licenses/report/Report.scala index e193ca4694..28b63cf009 100644 --- a/project/src/main/scala/licenses/report/Report.scala +++ b/project/src/main/scala/licenses/report/Report.scala @@ -6,8 +6,7 @@ import java.util.Base64 import sbt.{File, IO} import src.main.scala.licenses._ -/** - * Allows to write a report summarizing current status of the review. +/** Allows to write a report summarizing current status of the review. * * The report lists all dependencies and status of found attachments. * @@ -16,8 +15,7 @@ import src.main.scala.licenses._ */ object Report { - /** - * Writes the report in HTML format. + /** Writes the report in HTML format. * * @param description description of the distribution * @param summary reviewed summary of findings @@ -71,8 +69,7 @@ object Report { } } - /** - * Renders [[AttachmentStatus]] as HTML that will show the status name and a + /** Renders [[AttachmentStatus]] as HTML that will show the status name and a * color associated with it. */ private def renderStatus(attachmentStatus: AttachmentStatus): String = { @@ -86,8 +83,7 @@ object Report { s"""$attachmentStatus""" } - /** - * Renders a message about similarity of the file to a selected license file. + /** Renders a message about similarity of the file to a selected license file. * * If the filename is license-like, the file is compared with the selected * license (if any). If the file differs from the selected license and is @@ -119,8 +115,7 @@ object Report { } else "" } - /** - * Writes a table containing summary of dependencies and their gathered + /** Writes a table containing summary of dependencies and their gathered * copyright information. */ private def writeDependencySummary( @@ -208,24 +203,23 @@ object Report { rowWriter.addColumn { if (files.isEmpty) writer.writeText("No attached files.") else - writer.writeList(files.map { - case (file, status) => - () => - val injection = writer.makeInjectionHandler( - "file-ui", - "package" -> dep.information.packageName, - "filename" -> file.path.toString, - "status" -> status.toString - ) - val origin = file.origin - .map(origin => s" (Found at $origin)") - .getOrElse("") - writer.writeCollapsible( - s"${file.fileName} (${renderStatus(status)})$origin " + - s"${renderSimilarity(defaultLicense, file, status)}", - injection + - writer.escape(file.content) - ) + writer.writeList(files.map { case (file, status) => + () => + val injection = writer.makeInjectionHandler( + "file-ui", + "package" -> dep.information.packageName, + "filename" -> file.path.toString, + "status" -> status.toString + ) + val origin = file.origin + .map(origin => s" (Found at $origin)") + .getOrElse("") + writer.writeCollapsible( + s"${file.fileName} (${renderStatus(status)})$origin " + + s"${renderSimilarity(defaultLicense, file, status)}", + injection + + writer.escape(file.content) + ) }) } rowWriter.addColumn { diff --git a/project/src/main/scala/licenses/report/Review.scala b/project/src/main/scala/licenses/report/Review.scala index a31e5ea0f0..8529fa7db7 100644 --- a/project/src/main/scala/licenses/report/Review.scala +++ b/project/src/main/scala/licenses/report/Review.scala @@ -8,8 +8,7 @@ import src.main.scala.licenses._ import scala.util.control.NonFatal -/** - * Reads settings from the `root` to add review statuses to discovered +/** Reads settings from the `root` to add review statuses to discovered * attachments and add any additional attachments coming from the settings. * * The review settings consist of the following files or directories (all are @@ -69,8 +68,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { val defaultAndCustomLicense = "default-and-custom-license" } - /** - * Runs the review process, returning a [[ReviewedDependency]] which includes + /** Runs the review process, returning a [[ReviewedDependency]] which includes * information from the [[DependencySummary]] enriched with review statuses. */ def run(): WithWarnings[ReviewedSummary] = @@ -88,8 +86,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { _ <- warnAboutMissingDependencies(existingPackages) } yield summary - /** - * Returns a list of warnings for dependencies whose configuration has been + /** Returns a list of warnings for dependencies whose configuration has been * detected but which have not been detected. * * This may be used to detect dependencies that have been removed after an @@ -110,14 +107,12 @@ case class Review(root: File, dependencySummary: DependencySummary) { WithWarnings.justWarnings(warnings) } - /** - * Finds a header defined in the settings or + /** Finds a header defined in the settings or */ private def findHeader(): String = readFile(root / Paths.noticeHeader).getOrElse(Review.defaultHeader) - /** - * Reads files from the provided directory as [[AttachedFile]]. + /** Reads files from the provided directory as [[AttachedFile]]. */ private def findAdditionalFiles(dir: File): Seq[AttachedFile] = listFiles(dir).map { f => @@ -130,8 +125,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { AttachedFile.read(f.toPath, Some(dir.toPath)) } - /** - * Splits the sequence of attachments into sequences of files and copyrights. + /** Splits the sequence of attachments into sequences of files and copyrights. */ private def splitAttachments( attachments: Seq[Attachment] @@ -141,8 +135,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { (notices, copyrights) } - /** - * Returns only such copyrights that are not included in one of the + /** Returns only such copyrights that are not included in one of the * discovered files. */ private def removeCopyrightsIncludedInNotices( @@ -158,8 +151,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { copyrights.filter(shouldKeepCopyright) } - /** - * Returns the review status of the license and any attachments associated + /** Returns the review status of the license and any attachments associated * with the dependency. */ private def reviewDependency( @@ -185,8 +177,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { ) } - /** - * Enriches the file attachments with their review status. + /** Enriches the file attachments with their review status. */ private def reviewFiles( packageRoot: File, @@ -209,8 +200,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { } } - /** - * Returns any additional file attachments that are manually added in the + /** Returns any additional file attachments that are manually added in the * review. */ private def addFiles( @@ -219,8 +209,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { findAdditionalFiles(packageRoot / Paths.filesAdd) .map((_, AttachmentStatus.Added)) - /** - * Enriches the copyright attachments with their review status. + /** Enriches the copyright attachments with their review status. */ private def reviewCopyrights( packageRoot: File, @@ -248,8 +237,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { } } - /** - * Returns any additional copyright attachments that are manually added in + /** Returns any additional copyright attachments that are manually added in * the review. */ private def addCopyrights( @@ -267,8 +255,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { ) .toSeq - /** - * Checks review status of the license associated with the given dependency. + /** Checks review status of the license associated with the given dependency. */ private def reviewLicense( packageRoot: File, @@ -312,8 +299,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { .getOrElse(WithWarnings(LicenseReview.NotReviewed)) } - /** - * Reads the file as lines. + /** Reads the file as lines. * * Returns an empty sequence if the file cannot be read. */ @@ -321,8 +307,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { try { IO.readLines(file).map(_.strip).filter(_.nonEmpty) } catch { case NonFatal(_) => Seq() } - /** - * Reads the file as lines and reports any lines that were not expected to be + /** Reads the file as lines and reports any lines that were not expected to be * found. */ private def readExpectedLines( @@ -341,8 +326,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { WithWarnings(lines, warnings) } - /** - * Reads the file as a [[String]]. + /** Reads the file as a [[String]]. * * Returns None if the file cannot be read. */ @@ -350,8 +334,7 @@ case class Review(root: File, dependencySummary: DependencySummary) { try { Some(IO.read(file)) } catch { case NonFatal(_) => None } - /** - * Returns a sequence of files contained in a directory. + /** Returns a sequence of files contained in a directory. * * If the directory does not exist or otherwise cannot be queried, returns an * empty sequence. @@ -364,16 +347,14 @@ case class Review(root: File, dependencySummary: DependencySummary) { object Review { - /** - * Normalizes a name so that it can be used as a filename. + /** Normalizes a name so that it can be used as a filename. */ def normalizeName(string: String): String = { val charsToReplace = " /:;," charsToReplace.foldLeft(string)((str, char) => str.replace(char, '_')) } - /** - * Default NOTICE header. + /** Default NOTICE header. */ val defaultHeader: String = { val yearStart = 2020 diff --git a/project/src/main/scala/licenses/report/WithWarnings.scala b/project/src/main/scala/licenses/report/WithWarnings.scala index 9e6863d9f5..aeebede216 100644 --- a/project/src/main/scala/licenses/report/WithWarnings.scala +++ b/project/src/main/scala/licenses/report/WithWarnings.scala @@ -1,17 +1,14 @@ package src.main.scala.licenses.report -/** - * A simple monad for storing warnings related to a result. +/** A simple monad for storing warnings related to a result. */ case class WithWarnings[+A](value: A, warnings: Seq[String] = Seq()) { - /** - * Returns a result with a mapped value and the same warnings. + /** Returns a result with a mapped value and the same warnings. */ def map[B](f: A => B): WithWarnings[B] = WithWarnings(f(value), warnings) - /** - * Combines two computations returning warnings, preserving warnings from + /** Combines two computations returning warnings, preserving warnings from * both of them. */ def flatMap[B](f: A => WithWarnings[B]): WithWarnings[B] = { @@ -23,8 +20,7 @@ case class WithWarnings[+A](value: A, warnings: Seq[String] = Seq()) { object WithWarnings { implicit class SeqWithWarningsSyntax[+A](seq: Seq[WithWarnings[A]]) { - /** - * Turns a sequence of [[WithWarnings]] instances into a single + /** Turns a sequence of [[WithWarnings]] instances into a single * [[WithWarnings]] that contains the sequence of values and combined * warnings. */ @@ -34,8 +30,7 @@ object WithWarnings { implicit class SeqLikeSyntax[A](seq: WithWarnings[Seq[A]]) { - /** - * A shorthand syntax to concatenate two sequences wrapped with warnings, + /** A shorthand syntax to concatenate two sequences wrapped with warnings, * combining their warnings. */ def ++(other: WithWarnings[Seq[A]]): WithWarnings[Seq[A]] = @@ -44,8 +39,7 @@ object WithWarnings { rhs <- other } yield lhs ++ rhs - /** - * A shorthand syntax to concatenate an ordinary sequence to a sequence + /** A shorthand syntax to concatenate an ordinary sequence to a sequence * with warnings. */ def ++(other: Seq[A]): WithWarnings[Seq[A]] = @@ -54,8 +48,7 @@ object WithWarnings { } yield lhs ++ other } - /** - * Creates a [[WithWarnings]] containing Unit and a provided sequence of + /** Creates a [[WithWarnings]] containing Unit and a provided sequence of * warnings. */ def justWarnings(warnings: Seq[String]): WithWarnings[Unit] =