Skip to content

Commit

Permalink
Merge pull request #174 from alephium/scalafmt_2
Browse files Browse the repository at this point in the history
Scalafmt
  • Loading branch information
simerplaha authored Apr 11, 2024
2 parents 6445831 + 3b78188 commit 7204407
Show file tree
Hide file tree
Showing 154 changed files with 2,000 additions and 1,331 deletions.
66 changes: 66 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
version = "3.8.1"
maxColumn = 180
includeNoParensInSelectChains = true
importSelectors = binPack

runner {
dialect = scala213
}

indent {
extendSite = 2
withSiteRelativeToExtends = 3
}

align {
closeParenSite = false
openParenDefnSite = true
openParenCallSite = true
stripMargin = true
preset = more
}

newlines {
implicitParamListModifierPrefer = before
neverInResultType = true
sometimesBeforeColonInMethodReturnType = false
beforeCurlyLambdaParams = always
topLevelBodyMinStatements = 1
topLevelBodyIfMinStatements = [before, after]
topLevelStatementBlankLines = [ { blanks = 1 } ]
}

verticalMultiline {
atDefnSite = true
arityThreshold = 2
}

danglingParentheses {
defnSite = false
ctrlSite = false
callSite = true
tupleSite = true
}

docstrings {
style = Asterisk
wrap = no
}

rewrite {
rules = [PreferCurlyFors, SortModifiers, RedundantParens, RedundantBraces]
redundantBraces {
generalExpressions = true
stringInterpolation = true
defnBodies = true
}
trailingCommas {
style = never
}
sortModifiers {
order = [
"private", "protected", "final", "sealed",
"abstract", "override", "implicit", "lazy"
]
}
}
23 changes: 12 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ Run the plugin by selecting the menu option `Run -> Run Without Debugging` or `R

# Run LSP in neovim

Install the [ralph.vim](https://github.com/tdroxler/ralph.vim) plugin with your favorite plugin manager, for file type detection, highlighting, etc.
Install the [ralph.vim](https://github.com/tdroxler/ralph.vim) plugin with your favorite plugin manager, for file type
detection, highlighting, etc.

## [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig)

Expand Down Expand Up @@ -81,16 +82,16 @@ You can use the following sample as reference:

```json
{
"compilerOptions": {
"ignoreUnusedConstantsWarnings": false,
"ignoreUnusedVariablesWarnings": false,
"ignoreUnusedFieldsWarnings": false,
"ignoreUnusedPrivateFunctionsWarnings": false,
"ignoreUpdateFieldsCheckWarnings": false,
"ignoreCheckExternalCallerWarnings": false
},
"contractPath": "contracts",
"artifactPath": "artifacts"
"compilerOptions": {
"ignoreUnusedConstantsWarnings": false,
"ignoreUnusedVariablesWarnings": false,
"ignoreUnusedFieldsWarnings": false,
"ignoreUnusedPrivateFunctionsWarnings": false,
"ignoreUpdateFieldsCheckWarnings": false,
"ignoreCheckExternalCallerWarnings": false
},
"contractPath": "contracts",
"artifactPath": "artifacts"
}
```

Expand Down
33 changes: 18 additions & 15 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ val commonSettings =
"-Ywarn-unused:privates",
"-Ywarn-value-discard"
) ++ inliningOptions,
Compile / doc / scalacOptions ++= Seq(
"-no-link-warnings"
)
Compile / doc / scalacOptions ++= Seq(
"-no-link-warnings"
)
)

lazy val `compiler-access` =
Expand Down Expand Up @@ -88,7 +88,8 @@ lazy val `presentation-compiler` =
Dependencies.logback,
Dependencies.scalaLogging
)
).dependsOn(`compiler-access` % "test->test;compile->compile")
)
.dependsOn(`compiler-access` % "test->test;compile->compile")

/** Copies the JAR generated by assembly to VSCode's out directory */
lazy val copyJARToVSCode =
Expand All @@ -99,12 +100,12 @@ lazy val `lsp-server` =
.settings(
commonSettings,
scalacOptions += "-Xmixin-force-forwarders:false", // duplicate RPC method initialized.
assembly / mainClass := Some(MAIN_CLASS),
assembly / mainClass := Some(MAIN_CLASS),
assembly / assemblyJarName := JAR_NAME,
assemblyMergeStrategy := {
case PathList("module-info.class") => MergeStrategy.discard
case PathList("module-info.class") => MergeStrategy.discard
case x if x.endsWith("module-info.class") => MergeStrategy.discard
case other => assemblyMergeStrategy.value(other)
case other => assemblyMergeStrategy.value(other)
},
copyJARToVSCode :=
IO.copyFile(
Expand All @@ -121,26 +122,28 @@ lazy val `lsp-server` =
Dependencies.logback,
Dependencies.scalaLogging
)
).dependsOn(`presentation-compiler`)
)
.dependsOn(`presentation-compiler`)

lazy val `ralph-lsp` =
(project in file("."))
.settings(
commonSettings,
Compile / mainClass := Some(MAIN_CLASS),
).dependsOn(`lsp-server`)
commonSettings,
Compile / mainClass := Some(MAIN_CLASS)
)
.dependsOn(`lsp-server`)
.aggregate(`compiler-access`, `presentation-compiler`, `lsp-server`)
.enablePlugins(JavaAppPackaging)

lazy val downloadWeb3AndInstallStd = taskKey[Unit]("Download alephium-web3 source code and copy std interface to the correct resource folder")

downloadWeb3AndInstallStd := {
val web3Dir = new File(s"target/web3/alephium-web3-${Version.web3}")
val stdDir = new File("compiler-access/src/main/resources/std")
val web3Dir = new File(s"target/web3/alephium-web3-${Version.web3}")
val stdDir = new File("compiler-access/src/main/resources/std")
val web3StdDir = new File(s"target/web3/alephium-web3-${Version.web3}/packages/web3/std")

if(java.nio.file.Files.notExists(web3Dir.toPath())) {
IO.unzipURL(new URL(s"https://github.com/alephium/alephium-web3/archive/refs/tags/v${Version.web3}.zip"), new File("target/web3"))
if (java.nio.file.Files.notExists(web3Dir.toPath())) {
IO.unzipURL(new URL(s"https://github.com/alephium/alephium-web3/archive/refs/tags/v${Version.web3}.zip"), new File("target/web3"))
}

IO.copyDirectory(web3StdDir, stdDir)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ package org.alephium.ralph.lsp.access.compiler

import org.alephium.ralph.lsp.access.compiler.ast.Tree
import org.alephium.ralph.lsp.access.compiler.message.CompilerMessage
import org.alephium.ralph.{Ast, CompiledContract, CompiledScript, CompilerOptions}
import org.alephium.ralph.{CompiledScript, Ast, CompilerOptions, CompiledContract}

import java.net.URI

object CompilerAccess {

val RALPH_FILE_EXTENSION = "ral"

def ralphc: CompilerAccess =
RalphCompilerAccess

}

/**
Expand All @@ -28,16 +30,19 @@ trait CompilerAccess {
* @param code Code to parse.
* @return Parsing error or successfully parsed AST.
*/
def parseContracts(fileURI: URI, code: String): Either[CompilerMessage.AnyError, Tree.Root]
def parseContracts(
fileURI: URI,
code: String): Either[CompilerMessage.AnyError, Tree.Root]

/**
* Given the parsed AST and compiler options, compile the contracts.
*
* @param workspaceErrorURI The [[URI]] to report errors to when `fileURI` is absent from compilation errors.
*/
def compileContracts(contracts: Seq[Ast.ContractWithState],
structs: Seq[Ast.Struct],
options: CompilerOptions,
workspaceErrorURI: URI): Either[CompilerMessage.AnyError, (Array[CompiledContract], Array[CompiledScript])]
def compileContracts(
contracts: Seq[Ast.ContractWithState],
structs: Seq[Ast.Struct],
options: CompilerOptions,
workspaceErrorURI: URI): Either[CompilerMessage.AnyError, (Array[CompiledContract], Array[CompiledScript])]

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ import java.net.URI
private object RalphCompilerAccess extends CompilerAccess {

/** @inheritdoc */
def parseContracts(fileURI: URI, code: String): Either[CompilerMessage.AnyError, Tree.Root] =
def parseContracts(
fileURI: URI,
code: String): Either[CompilerMessage.AnyError, Tree.Root] =
try
fastparse.parse(code, RalphParserExtension.multiContract(fileURI)(_)) match {
case Parsed.Success(source: Tree.Root, _) =>
Expand All @@ -31,10 +33,11 @@ private object RalphCompilerAccess extends CompilerAccess {
catch TryUtil.catchAllThrows(fileURI)

/** @inheritdoc */
def compileContracts(contracts: Seq[Ast.ContractWithState],
structs: Seq[Ast.Struct],
options: CompilerOptions,
workspaceErrorURI: URI): Either[CompilerMessage.AnyError, (Array[CompiledContract], Array[CompiledScript])] =
def compileContracts(
contracts: Seq[Ast.ContractWithState],
structs: Seq[Ast.Struct],
options: CompilerOptions,
workspaceErrorURI: URI): Either[CompilerMessage.AnyError, (Array[CompiledContract], Array[CompiledScript])] =
try {
val multiContract =
Ast.MultiContract(contracts, structs, None)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package org.alephium.ralph.lsp.access.compiler
import fastparse._
import org.alephium.ralph.lsp.access.compiler.ast.Tree
import org.alephium.ralph.lsp.access.compiler.message.SourceIndexExtra._
import org.alephium.ralph.{Ast, SourceIndex, StatefulParser}
import org.alephium.ralph.{SourceIndex, Ast, StatefulParser}

import java.net.URI

Expand Down Expand Up @@ -33,7 +33,9 @@ object RalphParserExtension {
}

/** Parse an import identifier ignoring errors */
def lazyParseImportIdentifier(identifier: String, fileURI: URI): Option[Tree.Import] =
def lazyParseImportIdentifier(
identifier: String,
fileURI: URI): Option[Tree.Import] =
fastparse.parse(s"import \"$identifier\"", importStatement(fileURI)(_)) match {
case Parsed.Success(tree, _) =>
Some(tree)
Expand Down Expand Up @@ -77,7 +79,9 @@ object RalphParserExtension {
*
* @param name The String value to parse.
*/
private def parsePath(name: Tree.Name, fileURI: URI): Option[Tree.ImportPath] =
private def parsePath(
name: Tree.Name,
fileURI: URI): Option[Tree.ImportPath] =
fastparse.parse(name.value, importPaths(fileURI)(_)) match {
case Parsed.Success((packagePath, filePath), _) =>
// the above parse occurs on a string value, add the offset such
Expand Down Expand Up @@ -131,14 +135,12 @@ object RalphParserExtension {
(packagePath, filePath)
}


/**
*
* Parse a ralphc contract.
*
* This function is a clone of [[org.alephium.ralph.StatefulParser.multiContract]]
* but without the requirement that it be the start of the file, so imports are allowed.
* */
*/
private def sourceStatement[Unknown: P](fileURI: URI): P[Tree.Source] = {
val ralphParser =
new StatefulParser(Some(fileURI))
Expand Down Expand Up @@ -169,7 +171,7 @@ object RalphParserExtension {
case _: Ast.AssetScript =>
// parser functions from ralphc also result in the `Ast.AssetScript` type.
// For whatever reason, if `AssetScript` is returned, report it as a parser failure since it is unexpected.
val ctx = implicitly[P[_]]
val ctx = implicitly[P[_]]
val fail = ctx.freshFailure()
ctx.setMsg(fromIndex, () => "TxScript, Contract, Interface or Struct. Found AssetScript.")
fail
Expand All @@ -184,7 +186,7 @@ object RalphParserExtension {
* {{{
* import "package_name/file"
* }}}
* */
*/
private def stringLiteral[Unknown: P](fileURI: URI): P[Tree.StringLiteral] =
P(Index ~~ "\"" ~~ Index ~~ CharsWhile(_ != '"').!.? ~~ Index ~~ "\"" ~~ Index) map { // TODO: See if negative look ahead with AnyChar.rep would work instead of `CharsWhile`
case (fromIndex, nameFromIndex, string, nameToIndex, toIndex) =>
Expand Down Expand Up @@ -214,4 +216,5 @@ object RalphParserExtension {
index = index
)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ object AstExtra {
* @param ident The identifier of the variable to search for.
* @return True if the variable definition contains a named variable with the given identifier, false otherwise.
*/
def containsNamedVar[A <: StatelessContext](varDef: Ast.VarDef[A],
ident: Ast.Ident): Boolean =
def containsNamedVar[A <: StatelessContext](
varDef: Ast.VarDef[A],
ident: Ast.Ident): Boolean =
varDef
.vars
.exists {
Expand Down
Loading

0 comments on commit 7204407

Please sign in to comment.