From a965d71c42fc694c76c2bf94f7d7863fac492884 Mon Sep 17 00:00:00 2001 From: Harald Date: Sat, 18 Nov 2023 19:52:33 +0100 Subject: [PATCH] Maintenance toolchain update 2023 (#159) * Update sbt version * Set Scala to 2.12.18 * Fix all warnings * Fix deprecations * Explicit type annotation instead of type inference * Plugins update * Apply new scalafmt version * Add .ds_store to ignore --- .gitignore | 4 + .scalafix.conf | 7 + .scalafmt.conf | 2 +- build.sbt | 20 ++- project/build.properties | 2 +- project/plugins.sbt | 8 +- .../djinni/GeneratorIntegrationTest.scala | 10 +- src/it/scala/djinni/IntegrationTest.scala | 2 +- src/main/scala/djinni/BaseObjcGenerator.scala | 8 +- src/main/scala/djinni/CWrapperGenerator.scala | 62 ++++++--- src/main/scala/djinni/CWrapperMarshal.scala | 101 ++++++++------- src/main/scala/djinni/CffiGenerator.scala | 11 +- src/main/scala/djinni/CppCliGenerator.scala | 49 ++++--- src/main/scala/djinni/CppCliMarshal.scala | 20 +-- src/main/scala/djinni/CppGenerator.scala | 75 ++++++----- src/main/scala/djinni/CppMarshal.scala | 29 +++-- src/main/scala/djinni/JNIGenerator.scala | 85 +++++++------ src/main/scala/djinni/JNIMarshal.scala | 30 +++-- src/main/scala/djinni/JavaGenerator.scala | 89 +++++++------ src/main/scala/djinni/JavaMarshal.scala | 29 +++-- src/main/scala/djinni/Main.scala | 26 ++-- src/main/scala/djinni/Marshal.scala | 25 ++-- src/main/scala/djinni/ObjcGenerator.scala | 83 ++++++------ src/main/scala/djinni/ObjcMarshal.scala | 36 ++++-- src/main/scala/djinni/ObjcppGenerator.scala | 44 ++++--- src/main/scala/djinni/ObjcppMarshal.scala | 30 +++-- src/main/scala/djinni/PythonGenerator.scala | 87 +++++++------ src/main/scala/djinni/PythonMarshal.scala | 56 ++++---- .../djinni/SwiftBridgingHeaderGenerator.scala | 25 ++-- src/main/scala/djinni/YamlGenerator.scala | 43 ++++--- src/main/scala/djinni/ast/ast.scala | 3 +- src/main/scala/djinni/generator.scala | 120 ++++++++++-------- src/main/scala/djinni/meta.scala | 1 + src/main/scala/djinni/parser.scala | 74 ++++++----- src/main/scala/djinni/resolver.scala | 34 ++--- src/main/scala/djinni/syntax/syntax.scala | 4 +- src/main/scala/djinni/writer.scala | 16 +-- 37 files changed, 771 insertions(+), 579 deletions(-) create mode 100644 .scalafix.conf diff --git a/.gitignore b/.gitignore index 5f6ff94e..c2b52298 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,7 @@ project/metals.sbt # for personal trials / tests that shall be ignored but stay on your disk ztest/ .bsp/ + +# OS specific +.DS_Store + diff --git a/.scalafix.conf b/.scalafix.conf new file mode 100644 index 00000000..7c7d319c --- /dev/null +++ b/.scalafix.conf @@ -0,0 +1,7 @@ +rules = [ + ProcedureSyntax, + ExplicitResultTypes, + NoAutoTupling, + OrganizeImports, + RemoveUnused +] diff --git a/.scalafmt.conf b/.scalafmt.conf index 1c83d1e9..8df0f876 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,2 +1,2 @@ -version = 3.0.6 +version = 3.7.15 runner.dialect = scala213 diff --git a/build.sbt b/build.sbt index 96c50119..d332f489 100644 --- a/build.sbt +++ b/build.sbt @@ -1,11 +1,21 @@ import sbtassembly.AssemblyPlugin.defaultUniversalScript -ThisBuild / scalaVersion := "2.13.6" +ThisBuild / scalaVersion := "2.12.18" ThisBuild / organization := "com.github.cross-language-cpp" +ThisBuild / semanticdbEnabled := true // enable SemanticDB +ThisBuild / semanticdbVersion := scalafixSemanticdb.revision // use Scalafix compatible version + +// Keep this as a reminder, we will use that later +// ThisBuild / scalacOptions += "-Ywarn-unused" +// us: sbt 'set ThisBuild / scalacOptions += "-Ywarn-unused"' scalafix +// until the last 2 unused warnings are fixed +ThisBuild / scalacOptions ++= Seq("-deprecation", "-unchecked") + val binExt = if (System.getProperty("os.name").startsWith("Windows")) ".bat" else "" lazy val djinni = (project in file(".")) .configs(IntegrationTest) + .enablePlugins(ScalafixPlugin) // enable Scalafix for this project .settings( name := "djinni", Defaults.itSettings, @@ -15,8 +25,12 @@ lazy val djinni = (project in file(".")) libraryDependencies += "org.yaml" % "snakeyaml" % "1.29", libraryDependencies += "com.github.scopt" %% "scopt" % "4.0.1", libraryDependencies += "commons-io" % "commons-io" % "2.11.0", - assembly / assemblyOutputPath := { file("target/bin") / s"${(assembly / assemblyJarName).value}${binExt}" }, + assembly / assemblyOutputPath := { + val dir = file("target/bin") + IO.createDirectory(dir) + dir / s"${(assembly / assemblyJarName).value}${binExt}" + }, assembly / assemblyJarName := s"${name.value}", - assembly / assemblyOption := (assembly / assemblyOption).value.copy(prependShellScript = Some(defaultUniversalScript(shebang = false))), + assembly / assemblyPrependShellScript := Some(defaultUniversalScript(shebang = false)), assembly / test := {} ) diff --git a/project/build.properties b/project/build.properties index 10fd9eee..e8a1e246 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.5.5 +sbt.version=1.9.7 diff --git a/project/plugins.sbt b/project/plugins.sbt index c966ca85..22d052b0 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,3 +1,5 @@ -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.15.0") -addSbtPlugin("com.dwijnand" % "sbt-dynver" % "4.1.1") -addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.4") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.1.4") +addSbtPlugin("com.github.sbt" % "sbt-dynver" % "5.0.1") +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.2") +addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.11.1") +addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.3") diff --git a/src/it/scala/djinni/GeneratorIntegrationTest.scala b/src/it/scala/djinni/GeneratorIntegrationTest.scala index 6d6d64c7..9e12584c 100644 --- a/src/it/scala/djinni/GeneratorIntegrationTest.scala +++ b/src/it/scala/djinni/GeneratorIntegrationTest.scala @@ -732,15 +732,15 @@ class GeneratorIntegrationTest extends IntegrationTest with GivenWhenThen { } it(s"skip-generate should not generate any files") { - var idlFile = "all_datatypes" - var outputPath = "src/it/resources/result/skip_generate" + val idlFile = "all_datatypes" + val outputPath = "src/it/resources/result/skip_generate" Given(s"`$idlFile.djinni`") When(s"passing skip-generation true") djinni(djinniParams(idlFile, outputPath) + " --skip-generation true") Then(s"`$outputPath` should have been created") - var dir = new java.io.File(outputPath, idlFile) + val dir = new java.io.File(outputPath, idlFile) dir.exists should be(true) Then(s"genreated-files.txt should have been generated") @@ -748,7 +748,7 @@ class GeneratorIntegrationTest extends IntegrationTest with GivenWhenThen { gen.exists should be(true) Then(s"only the generated-files.txt should be generated") - var files = dir.listFiles() + val files = dir.listFiles() files should contain only (gen) } @@ -815,7 +815,7 @@ class GeneratorIntegrationTest extends IntegrationTest with GivenWhenThen { When( "calling the generator with `--cpp-namespace custom_namespace, --cpp-json-serialization nlohmann_json and --cpp-out`" ) - val output = djinni( + val _ = djinni( s"--idl src/it/resources/${idlFile}.djinni --cpp-namespace custom_namespace --cpp-json-serialization nlohmann_json --cpp-out $outputPath/cpp --cpp-header-out $outputPath/cpp-headers" ) Then( diff --git a/src/it/scala/djinni/IntegrationTest.scala b/src/it/scala/djinni/IntegrationTest.scala index a8e45eb5..8db8d13a 100644 --- a/src/it/scala/djinni/IntegrationTest.scala +++ b/src/it/scala/djinni/IntegrationTest.scala @@ -10,7 +10,7 @@ import scala.sys.process._ import scala.reflect.io.Directory import java.io.File -import java.nio.file.Paths +//import java.nio.file.Paths // Base class for integration tests, providing a few handy helper functions class IntegrationTest extends AnyFunSpec { diff --git a/src/main/scala/djinni/BaseObjcGenerator.scala b/src/main/scala/djinni/BaseObjcGenerator.scala index b3bf244d..285ccc63 100644 --- a/src/main/scala/djinni/BaseObjcGenerator.scala +++ b/src/main/scala/djinni/BaseObjcGenerator.scala @@ -41,7 +41,7 @@ abstract class BaseObjcGenerator(spec: Spec) extends Generator(spec) { consts: Seq[Const], selfName: String, genType: ObjcConstantType.Value - ) = { + ): Unit = { def boxedPrimitive(ty: TypeRef): String = { val (_, needRef) = marshal.toObjcType(ty) if (needRef) "@" else "" @@ -78,16 +78,16 @@ abstract class BaseObjcGenerator(spec: Spec) extends Generator(spec) { } } - def writeObjcConstMethImpl(c: Const, w: IndentWriter) { + def writeObjcConstMethImpl(c: Const, w: IndentWriter): Unit = { val label = "+" val nullability = marshal.nullability(c.ty.resolved).fold("")(" __" + _) val ret = marshal.fqFieldType(c.ty) + nullability val decl = s"$label ($ret)${idObjc.method(c.ident)}" - writeAlignedObjcCall(w, decl, List(), "", p => ("", "")) + writeAlignedObjcCall(w, decl, List(), "", _ => ("", "")) w.wl w.braced { - var static_var = s"s_${idObjc.method(c.ident)}" + val static_var = s"s_${idObjc.method(c.ident)}" w.w(s"static ${marshal.fqFieldType(c.ty)} const ${static_var} = ") writeObjcConstValue(w, c.ty, c.value) w.wl(";") diff --git a/src/main/scala/djinni/CWrapperGenerator.scala b/src/main/scala/djinni/CWrapperGenerator.scala index c5b2be8f..628b5eb9 100644 --- a/src/main/scala/djinni/CWrapperGenerator.scala +++ b/src/main/scala/djinni/CWrapperGenerator.scala @@ -19,7 +19,6 @@ import djinni.ast._ import djinni.generatorTools._ import djinni.meta._ import djinni.writer.IndentWriter -import sun.reflect.generics.tree.ReturnType import scala.collection.mutable @@ -30,7 +29,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { val cppMarshal = new CppMarshal(spec) val dw = "djinni_this" - def getCppDefArgs(m: Interface.Method, self: String) = { + def getCppDefArgs(m: Interface.Method, self: String): String = { if (m.static || self == "") { marshal.cArgDecl( m.params.map(p => @@ -47,7 +46,11 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { } } - def getDefArgs(m: Interface.Method, self: String, forHeader: Boolean) = { + def getDefArgs( + m: Interface.Method, + self: String, + forHeader: Boolean + ): String = { if (m.static || self == "") { marshal.cArgDecl( m.params.map(p => @@ -66,13 +69,17 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { } } - def getCArgTypes(m: Interface.Method, self: String, forHeader: Boolean) = { + def getCArgTypes( + m: Interface.Method, + self: String, + forHeader: Boolean + ): String = { marshal.cArgDecl( Seq(self) ++ m.params.map(p => marshal.cParamType(p.ty, forHeader)) ) } - def getRecordTypes(r: Record, forHeader: Boolean) = { + def getRecordTypes(r: Record, forHeader: Boolean): Seq[String] = { r.fields.map(f => marshal.cParamType(f.ty, forHeader)) } @@ -240,6 +247,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { classAsMethodName: String, w: IndentWriter ): Unit = { + val _ = retType // unused, TODO, check remove val elTyRef = getContainerElTypeRef(tm, 0, ident) val addToList = marshal.callback(idCpp.method(classAsMethodName + "__add")) declareObjectUniquePointerHandle(tm, classAsMethodName, w) @@ -326,6 +334,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { classAsMethodName: String, w: IndentWriter ): Unit = { + val _ = retType // unused, TODO, check remove val addToMap = marshal.callback(idCpp.method(classAsMethodName + "__add")) val keyTyRef = getContainerElTypeRef(tm, 0, ident) val valTyRef = getContainerElTypeRef(tm, 1, ident) @@ -397,8 +406,8 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { classAsMethodName: String, w: IndentWriter ): Unit = { - val createMap = - marshal.callback(idCpp.method(classAsMethodName + "__create")) + val _ = retType // unused, TODO, check remove + marshal.callback(idCpp.method(classAsMethodName + "__create")) val addToMap = marshal.callback(idCpp.method(classAsMethodName + "__add")) val keyTyRef = getContainerElTypeRef(tm, 0, ident) declareObjectUniquePointerHandle(tm, classAsMethodName, w) @@ -428,8 +437,8 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { getReturnType: String, addCArgs: String ): Unit = { + val _ = (tm, ident, retType) // unused, TODO, check remove val handle = "DjinniObjectHandle *" - var ret = "" var cArgs = "" if (getName != "") { @@ -462,8 +471,8 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { getReturnType: String, addCArgs: String ): Unit = { + val _ = (tm, ident, retType) // unused, TODO, check remove val handle = "struct DjinniObjectHandle *" - var ret = "" var cArgs = "" if (getName != "") { @@ -550,6 +559,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { deleteMethod: String, w: IndentWriter ): Unit = { + val _ = handle // unused, TODO, check remove w.wl( "djinni::Handle" + t(optHandle) + " " + djinniWrapper + "::fromCpp" + p( spec.cppOptionalTemplate + t(retType) + " dc" @@ -579,6 +589,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { deleteMethod: String, w: IndentWriter ): Unit = { + val _ = reinterpret // unused, TODO, check remove w.wl( spec.cppOptionalTemplate + t(retTypeStr) + djinniWrapper + "::toCpp" + p( "djinni::Handle" + t(optHandle) + " dh" @@ -609,6 +620,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { retType: String, w: IndentWriter ): Unit = { + val _ = (handle, optHandle) // unused, TODO, check remove w.wl( "static " + "djinni::Handle" + t(cppHandle) + " fromCpp" + p( cppMarshal.fqParamType(tm) + " dc" @@ -641,6 +653,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { h: mutable.TreeSet[String], hpp: mutable.TreeSet[String] ): Unit = { + val _ = className // unused, TODO, check remove // className is the composed idl named of the container type val handle = "DjinniObjectHandle" val handlePtr = handle + " *" @@ -763,6 +776,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { h: mutable.TreeSet[String], hpp: mutable.TreeSet[String] ): Unit = { + val _ = className // unused, TODO, check remove // className is the composed idl named of the container type val handle = "DjinniObjectHandle" val handlePtr = "DjinniObjectHandle *" @@ -934,6 +948,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { h: mutable.TreeSet[String], hpp: mutable.TreeSet[String] ): Unit = { + val _ = className // unused, TODO, check remove // className is the composed idl named of the container type val handle = "DjinniObjectHandle" val handlePtr = "DjinniObjectHandle *" @@ -1059,13 +1074,13 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { } class CRefs(ident: Ident, origin: String) { - var hpp = mutable.TreeSet[String]() - var h = mutable.TreeSet[String]() + var hpp: mutable.TreeSet[String] = mutable.TreeSet[String]() + var h: mutable.TreeSet[String] = mutable.TreeSet[String]() - def collect(ty: TypeRef, justCollect: Boolean) { + def collect(ty: TypeRef, justCollect: Boolean): Unit = { collect(ty.resolved, justCollect) } - def collect(tm: MExpr, justCollect: Boolean) { + def collect(tm: MExpr, justCollect: Boolean): Unit = { tm.args.foreach(t => collect(t, justCollect)) collect(tm.base, justCollect) @@ -1093,7 +1108,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { } } } - def collect(m: Meta, justCollect: Boolean) = if (justCollect) + def collect(m: Meta, justCollect: Boolean): Unit = if (justCollect) for (r <- marshal references (m, ident)) r match { case ImportRef(arg) => if (arg.endsWith(".hpp\"") || !arg.contains(".")) @@ -1109,6 +1124,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { methods: Seq[Interface.Method], w: IndentWriter ): Unit = { + val _ = cClassWrapper // unused, TODO, check remove for (m <- methods) { val ret = marshal.cReturnType(m.ret, false) val cArgs = getCArgTypes(m, marshal.djinniObjectHandle + " * ", false) @@ -1132,7 +1148,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { prefix: String, number: Int, w: IndentWriter - ) = { + ): Unit = { val recordAsMethodName = idCpp.method(ident.name) var field_number = number for (f <- r.fields) { @@ -1167,7 +1183,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { prefix: String, number: Int, w: IndentWriter - ) = { + ): Unit = { val recordAsMethodName = idCpp.method(ident.name) var field_number = number for (f <- r.fields) { @@ -1207,7 +1223,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { prefix: String, number: Int, w: IndentWriter - ) = { + ): IndentWriter = { val recordAsFqClassType = withCppNs(idCpp.ty(ident.name)) val recordAsMethodName = idCpp.method(ident.name) var field_number = number @@ -1263,7 +1279,8 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { prefix: String, number: Int, w: IndentWriter - ) = { + ): IndentWriter = { + val _ = (prefix, number) // unused, TODO, check remove val recordAsMethodName = idCpp.method(ident.name) for (f <- r.fields) { @@ -1306,7 +1323,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { includes: Iterable[String], create: Boolean, f: IndentWriter => Unit - ) { + ): Unit = { if (create) createFile( spec.cWrapperOutFolder.get, @@ -1363,6 +1380,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { create: Boolean, f: IndentWriter => Unit ): Unit = { + val _ = cppClass // unused, TODO, check remove if (create) createFile( spec.cWrapperHeaderOutFolder.get, @@ -1400,6 +1418,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { create: Boolean, f: IndentWriter => Unit ): Unit = { + val _ = cppClass // unused, TODO, check remove // hpp file contains definition of DjinniStruct wrapper over cpp shared_ptr // meant to facilitate interuse of interfaces across files if (create) @@ -1546,6 +1565,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { w: IndentWriter, className: String ): Unit = { + val _ = ident // unused, TODO, check remove w.wl("struct " + marshal.wrappedName(className) + " final {").nested { w.wl( marshal.wrappedName(className) + p( @@ -1756,7 +1776,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { djinniWrapper: String, cMethodName: String, w: IndentWriter - ) = { + ): IndentWriter = { w.wl( "struct " + djinniWrapper + " * " + " make_proxy_object_from_handle_" + cMethodName + p( "struct " + marshal.djinniObjectHandle + " * " + "c_ptr" @@ -2148,7 +2168,7 @@ class CWrapperGenerator(spec: Spec) extends Generator(spec) { def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum): Unit = { val refs = new CRefs(ident, origin) - writeCHeader(marshal.dh + ident.name, origin, "", refs.h, true, w => {}) + writeCHeader(marshal.dh + ident.name, origin, "", refs.h, true, _ => {}) writeCppHeader( marshal.dh + ident.name, diff --git a/src/main/scala/djinni/CWrapperMarshal.scala b/src/main/scala/djinni/CWrapperMarshal.scala index d9c6ad4b..83c43938 100644 --- a/src/main/scala/djinni/CWrapperMarshal.scala +++ b/src/main/scala/djinni/CWrapperMarshal.scala @@ -33,9 +33,9 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much cParamType(tm, forHeader) override def typename(tm: MExpr): String = cParamType(tm, false) def typename(name: String, ty: TypeDef): String = ty match { - case e: Enum => idCpp.enumType(name) - case i: Interface => idCpp.ty(name) - case r: Record => idCpp.ty(name) + case _: Enum => idCpp.enumType(name) + case _: Interface => idCpp.ty(name) + case _: Record => idCpp.ty(name) } override def fqTypename(tm: MExpr): String = throw new NotImplementedError() @@ -56,40 +56,44 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much override def fqReturnType(ret: Option[TypeRef]): String = throw new NotImplementedError() - def cFieldType(tm: MExpr, forHeader: Boolean) = ctypename(tm, forHeader) + def cFieldType(tm: MExpr, forHeader: Boolean): String = + ctypename(tm, forHeader) override def fieldType(tm: MExpr): String = ctypename(tm, false) override def fqFieldType(tm: MExpr): String = throw new NotImplementedError() // override def toCpp(tm: MExpr, expr: String): String = throw new AssertionError("cpp to cpp conversion") // override def fromCpp(tm: MExpr, expr: String): String = throw new AssertionError("cpp to cpp conversion") - def references(m: Meta, exclude: String): Seq[SymbolReference] = m match { - case p: MPrimitive => - p.idlName match { - case "i8" | "i16" | "i32" | "i64" => - List(ImportRef("" + pythonCdefIgnore)) - case "bool" => List(ImportRef("" + pythonCdefIgnore)) - case _ => List() - } - case MDate => List(ImportRef("" + pythonSetSourceIgnore)) - case MBinary => - List( - ImportRef("" + pythonSetSourceIgnore), - ImportRef("" + pythonCdefIgnore) - ) - case MOptional => List(ImportRef(spec.cppOptionalHeader)) - case d: MDef => - d.defType match { - case DInterface => List(ImportRef(q(cw + d.name + ".hpp"))) - case DRecord => List(ImportRef(q(dh + d.name + ".hpp"))) - case DEnum => - List( - ImportRef(q(d.name + ".hpp")), - ImportRef(q(dh + d.name + ".hpp")) - ) - } - case e: MExtern => throw new NotImplementedError() - case _ => List() + def references(m: Meta, exclude: String): Seq[SymbolReference] = { + val _ = exclude // unused, TODO: remove + m match { + case p: MPrimitive => + p.idlName match { + case "i8" | "i16" | "i32" | "i64" => + List(ImportRef("" + pythonCdefIgnore)) + case "bool" => List(ImportRef("" + pythonCdefIgnore)) + case _ => List() + } + case MDate => List(ImportRef("" + pythonSetSourceIgnore)) + case MBinary => + List( + ImportRef("" + pythonSetSourceIgnore), + ImportRef("" + pythonCdefIgnore) + ) + case MOptional => List(ImportRef(spec.cppOptionalHeader)) + case d: MDef => + d.defType match { + case DInterface => List(ImportRef(q(cw + d.name + ".hpp"))) + case DRecord => List(ImportRef(q(dh + d.name + ".hpp"))) + case DEnum => + List( + ImportRef(q(d.name + ".hpp")), + ImportRef(q(dh + d.name + ".hpp")) + ) + } + case _: MExtern => throw new NotImplementedError() + case _ => List() + } } // Types that need RAII will be placed in unique pointers at acquisition time, and released when the language @@ -106,11 +110,11 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much } case MOptional => tm.args.head.base match { - case mp: MPrimitive => true - case MDate => true - case _ => needsRAII(tm.args.head) + case _: MPrimitive => true + case MDate => true + case _ => needsRAII(tm.args.head) } - case e: MExtern => throw new NotImplementedError() + case _: MExtern => throw new NotImplementedError() case _ => false } @@ -118,12 +122,12 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much case MString | MBinary => true case MOptional => tm.args.head.base match { - case mp: MPrimitive => true + case _: MPrimitive => true case MString | MBinary => true case MDate => true case _ => false } - case e: MExtern => throw new NotImplementedError() + case _: MExtern => throw new NotImplementedError() case _ => false } @@ -162,7 +166,7 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much structPrefix + djinniWrapper + idCpp.ty(d.name) + " *" } case p: MParam => idCpp.typeParam(p.name) - case e: MExtern => throw new NotImplementedError() + case _: MExtern => throw new NotImplementedError() } } def expr(tm: MExpr): String = { @@ -202,7 +206,6 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much case _ => throw new NotImplementedError() } - private def toCIdlType(ty: TypeRef): String = toCIdlType(ty.resolved) private def toCIdlType(tm: MExpr): String = { def baseToIdl(m: Meta): String = m match { case p: MPrimitive => p.cName @@ -213,11 +216,11 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much case DEnum => "enum_" + d.name } case p: MParam => idCpp.typeParam(p.name) - case e: MExtern => "extern" + case _: MExtern => "extern" case MOptional => tm.args.head.base match { - case mp: MPrimitive => "boxed" - case _ => "optional" + case _: MPrimitive => "boxed" + case _ => "optional" } case _ => m.asInstanceOf[MOpaque].idlName } @@ -253,7 +256,7 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much val valueType = cType def toType(expr: MExpr): String = expr.base match { - case p: MPrimitive => valueType + case _: MPrimitive => valueType case MString => valueType // DjinniString case MBinary => valueType // DjinniBinary case MDate => valueType // uint64_t @@ -268,7 +271,7 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much case DRecord => valueType case _ => refType } - case e: MExtern => throw new NotImplementedError() + case _: MExtern => throw new NotImplementedError() case _ => refType } toType(tm) @@ -336,7 +339,7 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much cppExpr ) } - case e: MExtern => throw new NotImplementedError() + case _: MExtern => throw new NotImplementedError() case _ => cppExpr // MParam <- didn't need to do anything here } } @@ -377,14 +380,14 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much case DRecord => "Djinni" + idCpp.ty(d.name) + "::fromCpp" + p(cppExpr) case DEnum => "int32_from_enum_" + idCpp.method(d.name) + p(cppExpr) } - case e: MExtern => throw new NotImplementedError() + case _: MExtern => throw new NotImplementedError() case _ => cppExpr // TODO: MParam <- didn't need to do anything here } } - def checkForException(s: String) = "lib.check_for_exception" + p(s) + def checkForException(s: String): String = "lib.check_for_exception" + p(s) - def cArgDecl(args: Seq[String]) = { + def cArgDecl(args: Seq[String]): String = { if (args.isEmpty) { // CWrapper headers need to be parsed as C. `()` in C means "unspecified args" and triggers // -Wstrict-prototypes. `(void)` means no args in C. In C++ the two forms are equivalent. @@ -394,7 +397,7 @@ class CWrapperMarshal(spec: Spec) extends Marshal(spec) { // modeled(pretty much } } - def cArgVals(args: Seq[String]) = { + def cArgVals(args: Seq[String]): String = { args.mkString("(", ", ", ")") } } diff --git a/src/main/scala/djinni/CffiGenerator.scala b/src/main/scala/djinni/CffiGenerator.scala index 92c25e3b..90271054 100644 --- a/src/main/scala/djinni/CffiGenerator.scala +++ b/src/main/scala/djinni/CffiGenerator.scala @@ -21,9 +21,14 @@ import djinni.writer.IndentWriter class CffiGenerator(spec: Spec) extends Generator(spec) { val marshal = new PythonMarshal(spec) - val cffi = spec.pycffiPackageName + "_cffi" + val cffi: String = spec.pycffiPackageName + "_cffi" - def writeCffiFile(ident: String, origin: String, f: IndentWriter => Unit) { + def writeCffiFile( + ident: String, + origin: String, + f: IndentWriter => Unit + ): Unit = { + val _ = (ident, origin) // unused, TODO: remove createFileOnce( spec.pycffiOutFolder.get, "pycffi_lib_build" + ".py", @@ -53,7 +58,7 @@ class CffiGenerator(spec: Spec) extends Generator(spec) { w.wl("ffi = FFI()") w.wl // Paths relative to test-suite/pybuild - //TODO: raise exception if not at least 2 arguments? + // TODO: raise exception if not at least 2 arguments? w.wl("args = sys.argv[1:]") w.wl( "cdef_headers = sort_by_import_order(clean_headers_for(args, 'python_cdef_ignore'))" diff --git a/src/main/scala/djinni/CppCliGenerator.scala b/src/main/scala/djinni/CppCliGenerator.scala index c2ce4565..36aea632 100644 --- a/src/main/scala/djinni/CppCliGenerator.scala +++ b/src/main/scala/djinni/CppCliGenerator.scala @@ -41,10 +41,10 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { ) ) - def find(ty: TypeRef, forwardDeclareOnly: Boolean) { + def find(ty: TypeRef, forwardDeclareOnly: Boolean): Unit = { find(ty.resolved, forwardDeclareOnly) } - def find(tm: MExpr, forwardDeclareOnly: Boolean) { + def find(tm: MExpr, forwardDeclareOnly: Boolean): Unit = { tm.args.foreach(x => find(x, forwardDeclareOnly)) find(tm.base, forwardDeclareOnly) } @@ -62,12 +62,14 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { def withCppCliNs(namespace: String, t: String): String = withNs(Some(namespace), t) - val writeCppCliCppFile = writeCppFileGeneric( - spec.cppCliOutFolder.get, - spec.cppCliNamespace, - spec.cppCliIdentStyle.file, - "" - ) _ + val writeCppCliCppFile + : (String, String, Iterable[String], IndentWriter => Unit) => Unit = + writeCppFileGeneric( + spec.cppCliOutFolder.get, + spec.cppCliNamespace, + spec.cppCliIdentStyle.file, + "" + ) _ def writeCppCliHppFile( name: String, @@ -75,8 +77,8 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { includes: Iterable[String], fwds: Iterable[String], f: IndentWriter => Unit, - f2: IndentWriter => Unit = w => {} - ) = + f2: IndentWriter => Unit = _ => {} + ): Unit = writeHppFileGeneric( spec.cppCliOutFolder.get, spec.cppCliNamespace, @@ -164,7 +166,12 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { } } - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { val refs = new CppCliRefs(ident.name) writeCppCliHppFile( @@ -199,7 +206,7 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { val refs = new CppCliRefs(ident.name) refs.find(MString, false) // for: String^ ToString(); r.fields.foreach(f => refs.find(f.ty, false)) @@ -207,7 +214,7 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { def call(f: Field) = { f.ty.resolved.base match { - case p: MPrimitive => "." + case _: MPrimitive => "." case MOptional => "." case MDate => "." case e: MExtern => if (e.cs.reference.get) "->" else "." @@ -300,7 +307,7 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { writeDoc(w, f.doc) w.wl( s"${marshal.fqFieldType(f.ty.resolved, fieldNamesInScope)} ${idCs - .field(f.ident)};" + .field(f.ident)};" ) } } @@ -369,7 +376,7 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { .map(f => { val property = idCs.property(f.ident) f.ty.resolved.base match { - case p: MPrimitive => s"$property == other->$property" + case _: MPrimitive => s"$property == other->$property" case _ => s"$property${call(f)}Equals(other->$property)" } }) @@ -459,7 +466,7 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { val refs = new CppCliRefs(ident.name) i.methods.foreach(m => { m.params.foreach(p => refs.find(p.ty, true)) @@ -592,11 +599,11 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { ) w.wl(";") - m.ret.fold()(r => + m.ret.fold(())(r => w.wl(s"return ${marshal.fromCpp(r, "cs_result")};") ) } - m.ret.fold()(r => + m.ret.fold(())(r => w.wl( s"return ${dummyConstant(r)}; // Unreachable! (Silencing compiler warnings.)" ) @@ -647,11 +654,11 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { ) w.wl(";") - m.ret.fold()(r => + m.ret.fold(())(r => w.wl(s"return ${marshal.fromCpp(r, "cs_result")};") ) } - m.ret.fold()(r => + m.ret.fold(())(r => w.wl( s"return ${dummyConstant(r)}; // Unreachable! (Silencing compiler warnings.)" ) @@ -705,7 +712,7 @@ class CppCliGenerator(spec: Spec) extends Generator(spec) { p => s"${marshal.fromCpp(p.ty, idCpp.local(p.ident))}" ) w.wl(";") - m.ret.fold()(ty => { + m.ret.fold(())(ty => { w.wl("// TODO check cs_result for null") w.wl(s"return ${marshal.toCpp(ty, "cs_result")};") }) diff --git a/src/main/scala/djinni/CppCliMarshal.scala b/src/main/scala/djinni/CppCliMarshal.scala index 784d4007..0b524fdb 100644 --- a/src/main/scala/djinni/CppCliMarshal.scala +++ b/src/main/scala/djinni/CppCliMarshal.scala @@ -26,7 +26,10 @@ class CppCliMarshal(spec: Spec) extends Marshal(spec) { toCppCliType(tm, None, Seq(), needsHandle = true) def typename(ty: TypeRef, needsHandle: Boolean): String = toCppCliType(ty, None, Seq(), needsHandle) - def typename(name: String, ty: TypeDef): String = idCs.ty(name) + def typename(name: String, ty: TypeDef): String = { + val _ = ty // unused, TODO: remove + idCs.ty(name) + } override def fqTypename(tm: meta.MExpr): String = toCppCliType(tm, Some(spec.cppCliNamespace), Seq(), needsHandle = true) @@ -67,13 +70,14 @@ class CppCliMarshal(spec: Spec) extends Marshal(spec) { } def include(ident: String, isExtendedRecord: Boolean = false): String = { + val _ = isExtendedRecord // unused, TODO: remove q(spec.cppCliIdentStyle.file(ident) + "." + spec.cppHeaderExt) } def isReference(td: TypeDecl): Boolean = td.body match { - case i: Interface => true - case r: Record => true - case e: Enum => false + case _: Interface => true + case _: Record => true + case _: Enum => false } def references( @@ -83,7 +87,7 @@ class CppCliMarshal(spec: Spec) extends Marshal(spec) { ): Seq[SymbolReference] = m match { case d: MDef => d.body match { - case i: Interface => + case _: Interface => if (d.name != exclude) { if (forwardDeclareOnly) { List( @@ -247,9 +251,9 @@ class CppCliMarshal(spec: Spec) extends Marshal(spec) { case MList => "List" case MSet => "Set" case MMap => "Map" - case d: MDef => throw new AssertionError("unreachable") - case e: MExtern => throw new AssertionError("unreachable") - case p: MParam => throw new AssertionError("not applicable") + case _: MDef => throw new AssertionError("unreachable") + case _: MExtern => throw new AssertionError("unreachable") + case _: MParam => throw new AssertionError("not applicable") } ) } diff --git a/src/main/scala/djinni/CppGenerator.scala b/src/main/scala/djinni/CppGenerator.scala index aba4743d..ced2b138 100644 --- a/src/main/scala/djinni/CppGenerator.scala +++ b/src/main/scala/djinni/CppGenerator.scala @@ -28,20 +28,22 @@ class CppGenerator(spec: Spec) extends Generator(spec) { val marshal = new CppMarshal(spec) - val writeCppFile = writeCppFileGeneric( - spec.cppOutFolder.get, - spec.cppNamespace, - spec.cppFileIdentStyle, - spec.cppIncludePrefix - ) _ + val writeCppFile + : (String, String, Iterable[String], IndentWriter => Unit) => Unit = + writeCppFileGeneric( + spec.cppOutFolder.get, + spec.cppNamespace, + spec.cppFileIdentStyle, + spec.cppIncludePrefix + ) _ def writeHppFile( name: String, origin: String, includes: Iterable[String], fwds: Iterable[String], f: IndentWriter => Unit, - f2: IndentWriter => Unit = (w => {}) - ) = + f2: IndentWriter => Unit = (_ => {}) + ): Unit = writeHppFileGeneric( spec.cppHeaderOutFolder.get, spec.cppNamespace, @@ -60,9 +62,9 @@ class CppGenerator(spec: Spec) extends Generator(spec) { spec.cppHeaderOutFolder.get, cppNamespace, spec.cppFileIdentStyle - )(name, origin, includes, fwds, f, (w => {})) + )(name, origin, includes, fwds, f, (_ => {})) - def writeJsonExtensionFile(f: IndentWriter => Unit) { + def writeJsonExtensionFile(f: IndentWriter => Unit): Unit = { createFileOnce( spec.cppHeaderOutFolder.get, "json+extension.hpp", @@ -75,7 +77,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { ) } - def writeNlohmannJsonExtensionFile() { + def writeNlohmannJsonExtensionFile(): Unit = { val extensionContent = Source .fromResource("extension/json/nlohmann/json+extension.hpp") .getLines @@ -85,35 +87,35 @@ class CppGenerator(spec: Spec) extends Generator(spec) { }) } - def writeDeprecated(w: IndentWriter, doc: Doc) { + def writeDeprecated(w: IndentWriter, doc: Doc): Unit = { deprecatedText(doc) match { case None => case Some("") => w.wl("[[deprecated]]") - case Some(s) => w.wl(s"[[deprecated(\"$s\")]]") + case Some(s) => w.wl(s"""[[deprecated(\"$s\")]]""") } } - def deprecatedAttr(doc: Doc) = { + def deprecatedAttr(doc: Doc): String = { deprecatedText(doc) match { case None => "" case Some("") => " [[deprecated]]" - case Some(s) => s" [[deprecated(\"$s\")]]" + case Some(s) => s""" [[deprecated(\"$s\")]]""" } } class CppRefs(name: String, extension: String = "") { - var hpp = mutable.TreeSet[String]() - var hppFwds = mutable.TreeSet[String]() - var cpp = mutable.TreeSet[String]() + var hpp: mutable.TreeSet[String] = mutable.TreeSet[String]() + var hppFwds: mutable.TreeSet[String] = mutable.TreeSet[String]() + var cpp: mutable.TreeSet[String] = mutable.TreeSet[String]() - def find(ty: TypeRef, forwardDeclareOnly: Boolean) { + def find(ty: TypeRef, forwardDeclareOnly: Boolean): Unit = { find(ty.resolved, forwardDeclareOnly) } - def find(tm: MExpr, forwardDeclareOnly: Boolean) { + def find(tm: MExpr, forwardDeclareOnly: Boolean): Unit = { tm.args.foreach((x) => find(x, forwardDeclareOnly)) find(tm.base, forwardDeclareOnly) } - def find(m: Meta, forwardDeclareOnly: Boolean) = { + def find(m: Meta, forwardDeclareOnly: Boolean): Unit = { for (r <- marshal.hppReferences(m, name, forwardDeclareOnly, extension)) r match { case ImportRef(arg) => hpp.add("#include " + arg) @@ -127,7 +129,12 @@ class CppGenerator(spec: Spec) extends Generator(spec) { } } - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { val refs = new CppRefs(ident.name) val self = marshal.typename(ident, e) @@ -155,7 +162,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { if (e.flags) { // Define some operators to make working with "enum class" flags actually practical - def binaryOp(op: String) { + def binaryOp(op: String): Unit = { w.w(s"constexpr $self operator$op($self lhs, $self rhs) noexcept") .braced { w.wl( @@ -303,19 +310,19 @@ class CppGenerator(spec: Spec) extends Generator(spec) { } } - def shouldConstexpr(c: Const) = { + def shouldConstexpr(c: Const): Boolean = { // Make sure we don't constexpr optionals as some might not support it val canConstexpr = c.ty.resolved.base match { - case p: MPrimitive if c.ty.resolved.base != MOptional => true + case _: MPrimitive if c.ty.resolved.base != MOptional => true case _ => false } canConstexpr } - def generateHppConstants(w: IndentWriter, consts: Seq[Const]) = { + def generateHppConstants(w: IndentWriter, consts: Seq[Const]): Unit = { for (c <- consts) { // set value in header if can constexpr (only primitives) - var constexpr = shouldConstexpr(c) + val constexpr = shouldConstexpr(c) var constValue = ";" if (constexpr) { constValue = c.value match { @@ -343,7 +350,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { w: IndentWriter, consts: Seq[Const], selfName: String - ) = { + ): Unit = { def writeCppConst(w: IndentWriter, ty: TypeRef, v: Any): Unit = v match { case l: Long => w.w(l.toString) case d: Double if marshal.fieldType(ty) == "float" => @@ -403,7 +410,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { val refs = new CppRefs(ident.name) r.fields.foreach(f => refs.find(f.ty, false)) r.consts.foreach(c => refs.find(c.ty, false)) @@ -437,7 +444,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { val deprecationType = deprecatedAttr(doc) + " " // C++ Header - def writeCppPrototype(w: IndentWriter) { + def writeCppPrototype(w: IndentWriter): Unit = { if (r.ext.cpp) { w.w(s"struct $self; // Requiring extended class") w.wl @@ -561,7 +568,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { case DRecord => w.w(s"""if (j.contains("$name"))""").braced { w.wl(s"""result.$name = j.at("$name").get<${marshal - .fqTypename(fields(i).ty)}>();""") + .fqTypename(fields(i).ty)}>();""") } case DEnum => w.w(s"""if (j.contains("$name"))""").braced { @@ -690,7 +697,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { val refs = new CppRefs(ident.name) i.methods.map(m => { m.params.map(p => refs.find(p.ty, true)) @@ -734,7 +741,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { } else { val constFlag = if (m.const) " const" else "" w.wl(s"virtual $ret ${idCpp.method(m.ident)}${params - .mkString("(", ", ", ")")}$constFlag = 0;") + .mkString("(", ", ", ")")}$constFlag = 0;") } } } @@ -755,7 +762,7 @@ class CppGenerator(spec: Spec) extends Generator(spec) { } - def writeCppTypeParams(w: IndentWriter, params: Seq[TypeParam]) { + def writeCppTypeParams(w: IndentWriter, params: Seq[TypeParam]): Unit = { if (params.isEmpty) return w.wl( "template " + params diff --git a/src/main/scala/djinni/CppMarshal.scala b/src/main/scala/djinni/CppMarshal.scala index a3adb0b2..33c377b9 100644 --- a/src/main/scala/djinni/CppMarshal.scala +++ b/src/main/scala/djinni/CppMarshal.scala @@ -16,17 +16,17 @@ class CppMarshal(spec: Spec) extends Marshal(spec) { def typename(ty: TypeRef, scopeSymbols: Seq[String]): String = typename(ty.resolved, scopeSymbols) def typename(name: String, ty: TypeDef): String = ty match { - case e: Enum => idCpp.enumType(name) - case i: Interface => idCpp.ty(name) - case r: Record => idCpp.ty(name) + case _: Enum => idCpp.enumType(name) + case _: Interface => idCpp.ty(name) + case _: Record => idCpp.ty(name) } override def fqTypename(tm: MExpr): String = toCppType(tm, Some(spec.cppNamespace), Seq()) def fqTypename(name: String, ty: TypeDef): String = ty match { - case e: Enum => withNs(Some(spec.cppNamespace), idCpp.enumType(name)) - case i: Interface => withNs(Some(spec.cppNamespace), idCpp.ty(name)) - case r: Record => withNs(Some(spec.cppNamespace), idCpp.ty(name)) + case _: Enum => withNs(Some(spec.cppNamespace), idCpp.enumType(name)) + case _: Interface => withNs(Some(spec.cppNamespace), idCpp.ty(name)) + case _: Record => withNs(Some(spec.cppNamespace), idCpp.ty(name)) } def paramType(tm: MExpr, scopeSymbols: Seq[String]): String = @@ -109,7 +109,7 @@ class CppMarshal(spec: Spec) extends Marshal(spec) { } else { List() } - case i: Interface => + case _: Interface => val base = if (d.name != exclude) { List( ImportRef(""), @@ -134,7 +134,7 @@ class CppMarshal(spec: Spec) extends Marshal(spec) { List(ImportRef(""), ImportRef(e.cpp.header.get)) case _ => List(ImportRef(e.cpp.header.get)) } - case p: MParam => List() + case _: MParam => List() } def cppReferences( @@ -155,7 +155,7 @@ class CppMarshal(spec: Spec) extends Marshal(spec) { } else { List() } - case e: Enum => + case _: Enum => if (d.name != exclude) { List(ImportRef(include(d.name))) } else { @@ -187,8 +187,9 @@ class CppMarshal(spec: Spec) extends Marshal(spec) { ty: TypeRef, namespace: Option[String] = None, scopeSymbols: Seq[String] = Seq() - ): String = + ): String = { toCppType(ty.resolved, namespace, scopeSymbols) + } private def toCppType( tm: MExpr, @@ -285,7 +286,7 @@ class CppMarshal(spec: Spec) extends Marshal(spec) { } def byValue(tm: MExpr): Boolean = tm.base match { - case p: MPrimitive => true + case _: MPrimitive => true case d: MDef => d.defType match { case DEnum => true @@ -302,9 +303,9 @@ class CppMarshal(spec: Spec) extends Marshal(spec) { } def byValue(td: TypeDecl): Boolean = td.body match { - case i: Interface => false - case r: Record => false - case e: Enum => true + case _: Interface => false + case _: Record => false + case _: Enum => true } // this can be used in c++ generation to know whether a const& should be applied to the parameter or not diff --git a/src/main/scala/djinni/JNIGenerator.scala b/src/main/scala/djinni/JNIGenerator.scala index f212c890..93d265b9 100644 --- a/src/main/scala/djinni/JNIGenerator.scala +++ b/src/main/scala/djinni/JNIGenerator.scala @@ -26,23 +26,26 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { val jniMarshal = new JNIMarshal(spec) val cppMarshal = new CppMarshal(spec) val javaMarshal = new JavaMarshal(spec) - val jniBaseLibClassIdentStyle = IdentStyle.prefix("H", IdentStyle.camelUpper) + val jniBaseLibClassIdentStyle: String => String = + IdentStyle.prefix("H", IdentStyle.camelUpper) val jniBaseLibFileIdentStyle = jniBaseLibClassIdentStyle - val writeJniCppFile = writeCppFileGeneric( - spec.jniOutFolder.get, - spec.jniNamespace, - spec.jniFileIdentStyle, - spec.jniIncludePrefix - ) _ + val writeJniCppFile + : (String, String, Iterable[String], IndentWriter => Unit) => Unit = + writeCppFileGeneric( + spec.jniOutFolder.get, + spec.jniNamespace, + spec.jniFileIdentStyle, + spec.jniIncludePrefix + ) _ def writeJniHppFile( name: String, origin: String, includes: Iterable[String], fwds: Iterable[String], f: IndentWriter => Unit, - f2: IndentWriter => Unit = (w => {}) - ) = + f2: IndentWriter => Unit = (_ => {}) + ): Unit = writeHppFileGeneric( spec.jniHeaderOutFolder.get, spec.jniNamespace, @@ -71,10 +74,11 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { } class JNIRefs(name: String, cppPrefixOverride: Option[String] = None) { - var jniHpp = mutable.TreeSet[String]() - var jniCpp = mutable.TreeSet[String]() + var jniHpp: mutable.TreeSet[String] = mutable.TreeSet[String]() + var jniCpp: mutable.TreeSet[String] = mutable.TreeSet[String]() - val cppPrefix = cppPrefixOverride.getOrElse(spec.jniIncludeCppPrefix) + val cppPrefix: String = + cppPrefixOverride.getOrElse(spec.jniIncludeCppPrefix) jniHpp.add( "#include " + q( cppPrefix + spec.cppFileIdentStyle(name) + "." + spec.cppHeaderExt @@ -88,18 +92,24 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { case _ => } - def find(ty: TypeRef) { find(ty.resolved) } - def find(tm: MExpr) { + def find(ty: TypeRef): Unit = { find(ty.resolved) } + def find(tm: MExpr): Unit = { tm.args.foreach(find) find(tm.base) } - def find(m: Meta) = for (r <- jniMarshal.references(m, name)) r match { - case ImportRef(arg) => jniCpp.add("#include " + arg) - case _ => - } + def find(m: Meta): Unit = for (r <- jniMarshal.references(m, name)) + r match { + case ImportRef(arg) => jniCpp.add("#include " + arg) + case _ => + } } - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { val refs = new JNIRefs(ident.name) val jniHelper = jniMarshal.helperClass(ident) val cppSelf = cppMarshal.fqTypename(ident, e) @@ -150,7 +160,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { val prefixOverride: Option[String] = if (r.ext.cpp) { Some(spec.cppExtendedRecordIncludePrefix) } else { @@ -162,7 +172,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { val jniHelper = jniMarshal.helperClass(ident) val cppSelf = cppMarshal.fqTypename(ident, r) + cppTypeArgs(params) - def writeJniPrototype(w: IndentWriter) { + def writeJniPrototype(w: IndentWriter): Unit = { writeJniTypeParams(w, params) w.w(s"class $jniHelper final").bracedSemi { w.wlOutdent("public:") @@ -200,7 +210,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { } } - def writeJniBody(w: IndentWriter) { + def writeJniBody(w: IndentWriter): Unit = { val jniHelperWithParams = jniHelper + typeParamsSignature(params) // Defining ctor/dtor in the cpp file reduces build times writeJniTypeParams(w, params) @@ -214,7 +224,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { w.w( s"auto $jniHelperWithParams::fromCpp(JNIEnv* jniEnv, const CppType& c) -> ::djinni::LocalRef" ).braced { - //w.wl(s"::${spec.jniNamespace}::JniLocalScope jscope(jniEnv, 10);") + // w.wl(s"::${spec.jniNamespace}::JniLocalScope jscope(jniEnv, 10);") if (r.fields.isEmpty) w.wl( "(void)c; // Suppress warnings in release builds for empty records" @@ -287,7 +297,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { val refs = new JNIRefs(ident.name) i.methods.foreach(m => { m.params.foreach(p => refs.find(p.ty)) @@ -303,7 +313,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { val classLookup = jniMarshal.undecoratedTypename(ident, i) val baseType = s"::djinni::JniInterface<$cppSelf, $jniSelf>" - def writeJniPrototype(w: IndentWriter) { + def writeJniPrototype(w: IndentWriter): Unit = { writeJniTypeParams(w, typeParams) w.w(s"class $jniSelf final : $baseType").bracedSemi { w.wlOutdent(s"public:") @@ -329,8 +339,8 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { s"""DJINNI_ASSERT_MSG(j, jniEnv, "$jniSelf::fromCpp requires a non-null Java object");""" ) w.wl(s"""return ${nnCheck( - s"::djinni::JniClass<$jniSelf>::get()._fromJava(jniEnv, j)" - )};""") + s"::djinni::JniClass<$jniSelf>::get()._fromJava(jniEnv, j)" + )};""") } } else { w.wl( @@ -388,7 +398,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { } } - def writeJniBody(w: IndentWriter) { + def writeJniBody(w: IndentWriter): Unit = { // Defining ctor/dtor in the cpp file reduces build times val baseClassParam = if (i.ext.cpp) q(classLookup + "$CppProxy") else "" val jniSelfWithParams = jniSelf + typeParamsSignature(typeParams) @@ -448,9 +458,9 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { w.w(")") w.wl(";") w.wl(s"::djinni::jniExceptionCheck(jniEnv);") - m.ret.fold()(ty => { + m.ret.fold(())(ty => { (spec.cppNnCheckExpression, isInterface(ty.resolved)) match { - case (Some(check), true) => { + case (Some(_), true) => { // We have a non-optional interface, assert that we're getting a non-null value val javaParams = m.params.map(p => javaMarshal.fqParamType(p.ty) + " " + idJava @@ -494,7 +504,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { val jniRetType = jniMarshal.fqReturnType(ret) w.wl val methodNameMunged = name.replaceAllLiterally("_", "_1") - val zero = ret.fold("")(s => "0 /* value doesn't matter */") + val zero = ret.fold("")(_ => "0 /* value doesn't matter */") if (static) { w.wl( s"CJNIEXPORT $jniRetType JNICALL ${prefix}_00024CppProxy_$methodNameMunged(JNIEnv* jniEnv, jobject /*this*/${preComma(paramList)})" @@ -534,7 +544,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { m.static, m.params, m.ret, { - //w.wl(s"::${spec.jniNamespace}::JniLocalScope jscope(jniEnv, 10);") + // w.wl(s"::${spec.jniNamespace}::JniLocalScope jscope(jniEnv, 10);") if (!m.static) w.wl( s"const auto& ref = ::djinni::objectFromHandleAddress<$cppSelf>(nativeRef);" @@ -561,7 +571,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { } }) val methodName = idCpp.method(m.ident) - val ret = m.ret.fold("")(r => "auto r = ") + val ret = m.ret.fold("")(_ => "auto r = ") val call = if (m.static) s"$cppSelf::$methodName(" else s"ref->$methodName(" @@ -573,7 +583,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { p => jniMarshal.toCpp(p.ty, "j_" + idJava.local(p.ident)) ) w.wl(";") - m.ret.fold()(r => + m.ret.fold(())(r => w.wl( s"return ::djinni::release(${jniMarshal.fromCpp(r, "r")});" ) @@ -601,7 +611,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { refs: JNIRefs, writeProto: IndentWriter => Unit, writeBody: IndentWriter => Unit - ) { + ): Unit = { if (allInHeader) { // Template class. Write both parts to .hpp. writeJniHppFile( @@ -622,7 +632,7 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { } } - def writeJniTypeParams(w: IndentWriter, params: Seq[TypeParam]) { + def writeJniTypeParams(w: IndentWriter, params: Seq[TypeParam]): Unit = { if (params.isEmpty) return w.wl( "template " + params @@ -631,7 +641,8 @@ class JNIGenerator(spec: Spec) extends Generator(spec) { ) } - def typeParamsSignature(params: Seq[TypeParam]) = if (params.isEmpty) "" + def typeParamsSignature(params: Seq[TypeParam]): String = if (params.isEmpty) + "" else params.map(p => spec.jniClassIdentStyle(p.ident)).mkString("<", ", ", ">") diff --git a/src/main/scala/djinni/JNIMarshal.scala b/src/main/scala/djinni/JNIMarshal.scala index f364fec4..0b669e0d 100644 --- a/src/main/scala/djinni/JNIMarshal.scala +++ b/src/main/scala/djinni/JNIMarshal.scala @@ -9,7 +9,7 @@ class JNIMarshal(spec: Spec) extends Marshal(spec) { // For JNI typename() is always fully qualified and describes the mangled Java type to be used in field/method signatures override def typename(tm: MExpr): String = javaTypeSignature(tm) - def typename(name: String, ty: TypeDef) = + def typename(name: String, ty: TypeDef): String = ty match { case e: Enum if e.flags => "Ljava/util/EnumSet;" case _ => s"L${undecoratedTypename(name, ty)};" @@ -36,20 +36,22 @@ class JNIMarshal(spec: Spec) extends Marshal(spec) { } // Name for the autogenerated class containing field/method IDs and toJava()/fromJava() methods - def helperClass(name: String) = spec.jniClassIdentStyle(name) + def helperClass(name: String): String = spec.jniClassIdentStyle(name) private def helperClass(tm: MExpr): String = helperName(tm) + helperTemplates(tm) - def references(m: Meta, exclude: String = ""): Seq[SymbolReference] = + def references(m: Meta, exclude: String = ""): Seq[SymbolReference] = { + val _ = exclude // unused, TODO: remove m match { - case o: MOpaque => + case _: MOpaque => List(ImportRef(q(jniBaseLibIncludePrefix + "Marshal.hpp"))) case d: MDef => List(ImportRef(include(d.name))) case e: MExtern => List(ImportRef(e.jni.header.get)) case _ => List() } + } - def include(ident: String) = q( + def include(ident: String): String = q( spec.jniIncludePrefix + spec.jniFileIdentStyle( ident ) + "." + spec.cppHeaderExt @@ -62,13 +64,14 @@ class JNIMarshal(spec: Spec) extends Marshal(spec) { case MOptional => toJniType(m.args.head, true) case MBinary => "jbyteArray" case tp: MParam => helperClass(tp.name) + "::JniType" - case e: MExtern => + case _: MExtern => helperClass(m) + (if (needRef) "::Boxed" else "") + "::JniType" case _ => "jobject" } // The mangled Java typename without the "L...;" decoration useful only for class reflection on our own type def undecoratedTypename(name: String, ty: TypeDef): String = { + val _ = ty // unused, TODO: remove val javaClassName = idJava.ty(name) spec.javaPackage.fold(javaClassName)(p => p.replaceAllLiterally(".", "/") + "/" + javaClassName @@ -86,7 +89,7 @@ class JNIMarshal(spec: Spec) extends Marshal(spec) { tm.args.head.base match { case p: MPrimitive => s"Ljava/lang/${p.jBoxed};" case MOptional => throw new AssertionError("nested optional?") - case m => javaTypeSignature(tm.args.head) + case _ => javaTypeSignature(tm.args.head) } case MList => "Ljava/util/ArrayList;" case MSet => "Ljava/util/HashSet;" @@ -101,7 +104,10 @@ class JNIMarshal(spec: Spec) extends Marshal(spec) { } } - def javaMethodSignature(params: Iterable[Field], ret: Option[TypeRef]) = { + def javaMethodSignature( + params: Iterable[Field], + ret: Option[TypeRef] + ): String = { params.map(f => typename(f.ty)).mkString("(", "", ")") + ret.fold("V")( typename ) @@ -131,9 +137,9 @@ class JNIMarshal(spec: Spec) extends Marshal(spec) { case MList => "List" case MSet => "Set" case MMap => "Map" - case d: MDef => throw new AssertionError("unreachable") - case e: MExtern => throw new AssertionError("unreachable") - case p: MParam => throw new AssertionError("not applicable") + case _: MDef => throw new AssertionError("unreachable") + case _: MExtern => throw new AssertionError("unreachable") + case _: MParam => throw new AssertionError("not applicable") } ) } @@ -144,7 +150,7 @@ class JNIMarshal(spec: Spec) extends Marshal(spec) { tm.base match { case MOptional => assert(tm.args.size == 1) - //assert(!isInterface(tm.args.head)) + // assert(!isInterface(tm.args.head)) val argHelperClass = helperClass(tm.args.head) s"<${spec.cppOptionalTemplate}, $argHelperClass>" case MList | MSet => diff --git a/src/main/scala/djinni/JavaGenerator.scala b/src/main/scala/djinni/JavaGenerator.scala index 90811dd3..71557e7f 100755 --- a/src/main/scala/djinni/JavaGenerator.scala +++ b/src/main/scala/djinni/JavaGenerator.scala @@ -25,29 +25,29 @@ import scala.collection.mutable class JavaGenerator(spec: Spec) extends Generator(spec) { - val javaAnnotationHeader = + val javaAnnotationHeader: Option[String] = spec.javaAnnotation.map(pkg => '@' + pkg.split("\\.").last) - val javaNullableAnnotation = + val javaNullableAnnotation: Option[String] = spec.javaNullableAnnotation.map(pkg => '@' + pkg.split("\\.").last) - val javaNonnullAnnotation = + val javaNonnullAnnotation: Option[String] = spec.javaNonnullAnnotation.map(pkg => '@' + pkg.split("\\.").last) - val javaClassAccessModifierString = + val javaClassAccessModifierString: String = JavaAccessModifier.getCodeGenerationString(spec.javaClassAccessModifier) val marshal = new JavaMarshal(spec) class JavaRefs() { - var java = mutable.TreeSet[String]() + var java: mutable.TreeSet[String] = mutable.TreeSet[String]() spec.javaAnnotation.foreach(pkg => java.add(pkg)) spec.javaNullableAnnotation.foreach(pkg => java.add(pkg)) spec.javaNonnullAnnotation.foreach(pkg => java.add(pkg)) - def find(ty: TypeRef) { find(ty.resolved) } - def find(tm: MExpr) { + def find(ty: TypeRef): Unit = { find(ty.resolved) } + def find(tm: MExpr): Unit = { tm.args.foreach(find) find(tm.base) } - def find(m: Meta) = for (r <- marshal.references(m)) r match { + def find(m: Meta): Unit = for (r <- marshal.references(m)) r match { case ImportRef(arg) => java.add(arg) case _ => } @@ -58,7 +58,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { origin: String, refs: Iterable[String], f: IndentWriter => Unit - ) { + ): Unit = { createFile( spec.javaOutFolder.get, idJava.ty(ident) + ".java", @@ -76,7 +76,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { ) } - def writeDocAnnotations(w: IndentWriter, doc: Doc) { + def writeDocAnnotations(w: IndentWriter, doc: Doc): Unit = { writeDeprecated(w, doc, "@Deprecated") } @@ -84,7 +84,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { w: IndentWriter, consts: Seq[Const], forJavaInterface: Boolean - ) = { + ): Unit = { def writeJavaConst(w: IndentWriter, ty: TypeRef, v: Any): Unit = v match { case l: Long if marshal.fieldType(ty).equalsIgnoreCase("long") => @@ -134,7 +134,12 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { } } - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { val refs = new JavaRefs() writeJavaFile( @@ -165,7 +170,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { val refs = new JavaRefs() i.methods.map(m => { @@ -343,7 +348,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { val refs = new JavaRefs() r.fields.foreach(f => refs.find(f.ty)) @@ -480,31 +485,31 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { f.ty.resolved.base match { case MBinary => w.w(s"java.util.Arrays.equals(${idJava - .field(f.ident)}, other.${idJava.field(f.ident)})") + .field(f.ident)}, other.${idJava.field(f.ident)})") case MList | MSet | MMap | MString | MDate => w.w( s"this.${idJava.field(f.ident)}.equals(other.${idJava - .field(f.ident)})" + .field(f.ident)})" ) case MOptional => w.w( s"((this.${idJava.field(f.ident)} == null && other.${idJava - .field(f.ident)} == null) || " + .field(f.ident)} == null) || " ) w.w(s"(this.${idJava.field(f.ident)} != null && this.${idJava - .field(f.ident)}.equals(other.${idJava.field(f.ident)})))") - case t: MPrimitive => + .field(f.ident)}.equals(other.${idJava.field(f.ident)})))") + case _: MPrimitive => w.w(s"this.${idJava.field(f.ident)} == other.${idJava - .field(f.ident)}") + .field(f.ident)}") case df: MDef => df.defType match { case DRecord => w.w(s"this.${idJava.field(f.ident)}.equals(other.${idJava - .field(f.ident)})") + .field(f.ident)})") case DEnum => w.w( s"this.${idJava.field(f.ident)} == other.${idJava - .field(f.ident)}" + .field(f.ident)}" ) case _ => throw new AssertionError("Unreachable") } @@ -514,16 +519,16 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { if (e.java.reference.get) { w.w( s"this.${idJava.field(f.ident)}.equals(other.${idJava - .field(f.ident)})" + .field(f.ident)})" ) } else { w.w(s"this.${idJava.field(f.ident)} == other.${idJava - .field(f.ident)}") + .field(f.ident)}") } case DEnum => w.w( s"this.${idJava.field(f.ident)} == other.${idJava - .field(f.ident)}" + .field(f.ident)}" ) case _ => throw new AssertionError("Unreachable") } @@ -551,7 +556,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { case MList | MSet | MMap | MString | MDate => s"${idJava.field(f.ident)}.hashCode()" // Need to repeat this case for MDef - case df: MDef => s"${idJava.field(f.ident)}.hashCode()" + case _: MDef => s"${idJava.field(f.ident)}.hashCode()" case MOptional => s"(${idJava.field(f.ident)} == null ? 0 : ${idJava.field(f.ident)}.hashCode())" case t: MPrimitive => @@ -563,7 +568,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { s"Float.floatToIntBits(${idJava.field(f.ident)})" case "double" => s"((int) (Double.doubleToLongBits(${idJava.field(f.ident)}) ^ (Double.doubleToLongBits(${idJava - .field(f.ident)}) >>> 32)))" + .field(f.ident)}) >>> 32)))" case "boolean" => s"(${idJava.field(f.ident)} ? 1 : 0)" case _ => throw new AssertionError("Unreachable") } @@ -606,7 +611,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { writeParcelable(w, self, r) if (r.derivingTypes.contains(DerivingType.Ord)) { - def primitiveCompare(ident: Ident) { + def primitiveCompare(ident: Ident): Unit = { w.wl( s"if (this.${idJava.field(ident)} < other.${idJava.field(ident)}) {" ).nested { @@ -633,16 +638,16 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { f.ty.resolved.base match { case MString | MDate => w.wl(s"tempResult = this.${idJava.field(f.ident)}.compareTo(other.${idJava - .field(f.ident)});") - case t: MPrimitive => primitiveCompare(f.ident) + .field(f.ident)});") + case _: MPrimitive => primitiveCompare(f.ident) case df: MDef => df.defType match { case DRecord => w.wl(s"tempResult = this.${idJava.field(f.ident)}.compareTo(other.${idJava - .field(f.ident)});") + .field(f.ident)});") case DEnum => w.w(s"tempResult = this.${idJava.field(f.ident)}.compareTo(other.${idJava - .field(f.ident)});") + .field(f.ident)});") case _ => throw new AssertionError("Unreachable") } case e: MExtern => @@ -650,11 +655,11 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { case DRecord => if (e.java.reference.get) w.wl(s"tempResult = this.${idJava.field(f.ident)}.compareTo(other.${idJava - .field(f.ident)});") + .field(f.ident)});") else primitiveCompare(f.ident) case DEnum => w.w(s"tempResult = this.${idJava.field(f.ident)}.compareTo(other.${idJava - .field(f.ident)});") + .field(f.ident)});") case _ => throw new AssertionError("Unreachable") } case _ => throw new AssertionError("Unreachable") @@ -676,7 +681,11 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { if (params.isEmpty) "" else params.map(p => idJava.typeParam(p.ident)).mkString("<", ", ", ">") - def writeParcelable(w: IndentWriter, self: String, r: Record) = { + def writeParcelable( + w: IndentWriter, + self: String, + r: Record + ): IndentWriter = { // Generates the methods and the constructor to implement the interface android.os.Parcelable // CREATOR @@ -695,7 +704,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { } // constructor (Parcel) - def deserializeField(f: Field, m: Meta, inOptional: Boolean) { + def deserializeField(f: Field, m: Meta, inOptional: Boolean): Unit = { m match { case MString => w.wl(s"this.${idJava.field(f.ident)} = in.readString();") @@ -746,7 +755,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { e.defType match { case DRecord => w.wl(s"this.${idJava.field(f.ident)} = ${e.java.readFromParcel - .format(marshal.typename(f.ty))};") + .format(marshal.typename(f.ty))};") case DEnum => { if (marshal.isEnumFlags(m)) { w.wl( @@ -778,7 +787,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { s"in.readList(${idJava.field(f.ident)}Temp, getClass().getClassLoader());" ) w.wl(s"this.${idJava.field(f.ident)} = new ${marshal - .typename(f.ty)}(${idJava.field(f.ident)}Temp);") + .typename(f.ty)}(${idJava.field(f.ident)}Temp);") } case MMap => { w.wl( @@ -816,7 +825,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { } // writeToParcel - def serializeField(f: Field, m: Meta, inOptional: Boolean) { + def serializeField(f: Field, m: Meta, inOptional: Boolean): Unit = { m match { case MString => w.wl(s"out.writeString(this.${idJava.field(f.ident)});") case MBinary => { @@ -876,7 +885,7 @@ class JavaGenerator(spec: Spec) extends Generator(spec) { marshal.typename(f.ty).replaceFirst("HashSet<(.*)>", "$1") w.wl( s"out.writeList(new ArrayList<${collectionTypeName}>(this.${idJava - .field(f.ident)}));" + .field(f.ident)}));" ) } case MMap => w.wl(s"out.writeMap(this.${idJava.field(f.ident)});") diff --git a/src/main/scala/djinni/JavaMarshal.scala b/src/main/scala/djinni/JavaMarshal.scala index 378cec1e..2c56b7e8 100644 --- a/src/main/scala/djinni/JavaMarshal.scala +++ b/src/main/scala/djinni/JavaMarshal.scala @@ -21,17 +21,22 @@ import djinni.meta._ class JavaMarshal(spec: Spec) extends Marshal(spec) { - val javaNullableAnnotation = + val javaNullableAnnotation: Option[String] = spec.javaNullableAnnotation.map(pkg => '@' + pkg.split("\\.").last) - val javaNonnullAnnotation = + val javaNonnullAnnotation: Option[String] = spec.javaNonnullAnnotation.map(pkg => '@' + pkg.split("\\.").last) override def typename(tm: MExpr): String = toJavaType(tm, None) - def typename(name: String, ty: TypeDef): String = idJava.ty(name) + def typename(name: String, ty: TypeDef): String = { + val _ = ty // unused, TODO: remove + idJava.ty(name) + } override def fqTypename(tm: MExpr): String = toJavaType(tm, spec.javaPackage) - def fqTypename(name: String, ty: TypeDef): String = + def fqTypename(name: String, ty: TypeDef): String = { + val _ = ty // unused, TODO: remove withPackage(spec.javaPackage, idJava.ty(name)) + } override def paramType(tm: MExpr): String = toJavaValueType(tm, None) override def fqParamType(tm: MExpr): String = @@ -64,7 +69,7 @@ class JavaMarshal(spec: Spec) extends Marshal(spec) { case _ => List() } - val interfaceNullityAnnotation = + val interfaceNullityAnnotation: Option[String] = if (spec.cppNnType.nonEmpty) javaNonnullAnnotation else javaNullableAnnotation @@ -73,7 +78,7 @@ class JavaMarshal(spec: Spec) extends Marshal(spec) { def nullityAnnotation(ty: TypeRef): Option[String] = { ty.resolved.base match { case MOptional => javaNullableAnnotation - case p: MPrimitive => None + case _: MPrimitive => None case m: MDef => m.defType match { case DInterface => interfaceNullityAnnotation @@ -91,10 +96,10 @@ class JavaMarshal(spec: Spec) extends Marshal(spec) { } } - def isReference(td: TypeDecl) = td.body match { - case i: Interface => true - case r: Record => true - case e: Enum => true + def isReference(td: TypeDecl): Boolean = td.body match { + case _: Interface => true + case _: Record => true + case _: Enum => true } def isEnumFlags(m: Meta): Boolean = m match { @@ -127,7 +132,7 @@ class JavaMarshal(spec: Spec) extends Marshal(spec) { arg.base match { case p: MPrimitive => p.jBoxed case MOptional => throw new AssertionError("nested optional?") - case m => f(arg, true) + case _ => f(arg, true) } case e: MExtern => (if (needRef) e.java.boxed.get else e.java.typename.get) + (if ( @@ -148,7 +153,7 @@ class JavaMarshal(spec: Spec) extends Marshal(spec) { case MSet => "HashSet" case MMap => "HashMap" case d: MDef => withPackage(packageName, idJava.ty(d.name)) - case e: MExtern => throw new AssertionError("unreachable") + case _: MExtern => throw new AssertionError("unreachable") case p: MParam => idJava.typeParam(p.name) } base + args(tm) diff --git a/src/main/scala/djinni/Main.scala b/src/main/scala/djinni/Main.scala index 7b603e2f..a667588c 100644 --- a/src/main/scala/djinni/Main.scala +++ b/src/main/scala/djinni/Main.scala @@ -15,20 +15,19 @@ package djinni -import java.io.{ - BufferedWriter, - File, - FileNotFoundException, - FileWriter, - IOException -} - import djinni.generatorTools._ -import scopt.{OptionDef, OptionParser} +import scopt.OptionDef +import scopt.OptionParser + +import java.io.BufferedWriter +import java.io.File +import java.io.FileNotFoundException +import java.io.FileWriter +import java.io.IOException object Main { - def main(args: Array[String]) { + def main(args: Array[String]): Unit = { var idlFile: File = null var idlIncludePaths: List[String] = List("") var cppOutFolder: Option[File] = None @@ -62,7 +61,7 @@ object Main { var jniIncludePrefix: String = "" var jniIncludeCppPrefix: String = "" var jniFileIdentStyleOptional: Option[IdentConverter] = None - var jniBaseLibClassIdentStyleOptional: Option[IdentConverter] = None + val jniBaseLibClassIdentStyleOptional: Option[IdentConverter] = None var jniGenerateMain: Boolean = true var cppHeaderOutFolderOptional: Option[File] = None var cppExt: String = "cpp" @@ -759,8 +758,7 @@ object Main { else cWrapperOutFolder val jniClassIdentStyle = jniClassIdentStyleOptional.getOrElse(cppIdentStyle.ty) - val jniBaseLibClassIdentStyle = - jniBaseLibClassIdentStyleOptional.getOrElse(jniClassIdentStyle) + jniBaseLibClassIdentStyleOptional.getOrElse(jniClassIdentStyle) val jniFileIdentStyle = jniFileIdentStyleOptional.getOrElse(cppFileIdentStyle) var objcFileIdentStyle = @@ -816,7 +814,7 @@ object Main { if (!validJsonSerializers.contains(cppJsonSerialization.get)) { System.err.println( s"Error: Invalid value for --cpp-json-serializers '${cppJsonSerialization.get}'. Available serializers: ['${validJsonSerializers - .mkString(",")}']." + .mkString(",")}']." ) System.exit(1); return } diff --git a/src/main/scala/djinni/Marshal.scala b/src/main/scala/djinni/Marshal.scala index 8ddffe06..52e46507 100644 --- a/src/main/scala/djinni/Marshal.scala +++ b/src/main/scala/djinni/Marshal.scala @@ -3,6 +3,7 @@ package djinni import djinni.ast._ import djinni.generatorTools._ import djinni.meta._ + import scala.language.implicitConversions // Generate code for marshalling a specific type from/to C++ including header and type names. @@ -30,10 +31,16 @@ abstract class Marshal(spec: Spec) { def fqFieldType(tm: MExpr): String def fqFieldType(ty: TypeRef): String = fqFieldType(ty.resolved) // Generate code for an expression that transforms an expression `expr` of the non-C++ type `tm` to its C++ counterpart - def toCpp(tm: MExpr, expr: String): String = "" + def toCpp(tm: MExpr, expr: String): String = { + val _ = (tm, expr) // unused, TODO: remove + "" + } def toCpp(ty: TypeRef, expr: String): String = toCpp(ty.resolved, expr) // Generate code for an expression that transforms an expression `expr` of the C++ type `tm` to its non-C++ counterpart - def fromCpp(tm: MExpr, expr: String): String = "" + def fromCpp(tm: MExpr, expr: String): String = { + val _ = (tm, expr) // unused, TODO: remove + "" + } def fromCpp(ty: TypeRef, expr: String): String = fromCpp(ty.resolved, expr) implicit def identToString(ident: Ident): String = ident.name @@ -43,11 +50,13 @@ abstract class Marshal(spec: Spec) { protected val idPython = spec.pyIdentStyle protected val idCs = spec.cppCliIdentStyle - protected def withNs(namespace: Option[String], t: String) = namespace match { - case None => t - case Some("") => "::" + t - case Some(s) => "::" + s + "::" + t - } + protected def withNs(namespace: Option[String], t: String): String = + namespace match { + case None => t + case Some("") => "::" + t + case Some(s) => "::" + s + "::" + t + } - protected def withCppNs(t: String) = withNs(Some(spec.cppNamespace), t) + protected def withCppNs(t: String): String = + withNs(Some(spec.cppNamespace), t) } diff --git a/src/main/scala/djinni/ObjcGenerator.scala b/src/main/scala/djinni/ObjcGenerator.scala index 9e5c8c7a..18cf511b 100644 --- a/src/main/scala/djinni/ObjcGenerator.scala +++ b/src/main/scala/djinni/ObjcGenerator.scala @@ -26,21 +26,26 @@ import scala.collection.mutable class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { class ObjcRefs() { - var body = mutable.TreeSet[String]() - var header = mutable.TreeSet[String]() + var body: mutable.TreeSet[String] = mutable.TreeSet[String]() + var header: mutable.TreeSet[String] = mutable.TreeSet[String]() - def find(ty: TypeRef) { find(ty.resolved) } - def find(tm: MExpr) { + def find(ty: TypeRef): Unit = { find(ty.resolved) } + def find(tm: MExpr): Unit = { tm.args.foreach(find) find(tm.base) } - def find(m: Meta) = for (r <- marshal.references(m)) r match { + def find(m: Meta): Unit = for (r <- marshal.references(m)) r match { case ImportRef(arg) => header.add("#import " + arg) case DeclRef(decl, _) => header.add(decl) } } - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { val refs = new ObjcRefs() refs.header.add("#import ") @@ -76,26 +81,26 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { ident ) + "." + spec.objcppExt // Must be a Obj-C++ file in case the constants are not compile-time constant expressions - def writeObjcConstMethDecl(c: Const, w: IndentWriter) { + def writeObjcConstMethDecl(c: Const, w: IndentWriter): Unit = { val label = "+" val nullability = marshal.nullability(c.ty.resolved).fold("")(" __" + _) val ret = marshal.fqFieldType(c.ty) + nullability val decl = s"$label ($ret)${idObjc.method(c.ident)}" - writeAlignedObjcCall(w, decl, List(), ";", p => ("", "")) + writeAlignedObjcCall(w, decl, List(), ";", _ => ("", "")) } def deprecatedAttr(doc: Doc): String = { deprecatedText(doc) match { case Some("") => " __deprecated" - case Some(message) => s" __deprecated_msg(\"$message\")" + case Some(message) => s""" __deprecated_msg(\"$message\")""" case None => "" } } - def writeDocAttributes(w: IndentWriter, doc: Doc) { + def writeDocAttributes(w: IndentWriter, doc: Doc): Unit = { deprecatedText(doc) match { case Some("") => w.wl("__deprecated") - case Some(message) => w.wl(s" __deprecated_msg(\"$message\")") + case Some(message) => w.wl(s""" __deprecated_msg(\"$message\")""") case None => } } @@ -108,7 +113,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { val refs = new ObjcRefs() i.methods.map(m => { m.params.map(p => refs.find(p.ty)) @@ -122,7 +127,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { refs.header.add("#import ") - def writeObjcFuncDecl(method: Interface.Method, w: IndentWriter) { + def writeObjcFuncDecl(method: Interface.Method, w: IndentWriter): Unit = { val label = if (method.static) "+" else "-" val ret = marshal.returnType(method.ret) val decl = s"$label ($ret)${idObjc.method(method.ident)}" @@ -212,7 +217,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { val refs = new ObjcRefs() for (c <- r.consts) refs.find(c.ty) @@ -260,7 +265,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { writeDocAttributes(w, doc) w.wl(s"@interface $self : NSObject") - def writeInitializer(sign: String, prefix: String) { + def writeInitializer(sign: String, prefix: String): Unit = { val decl = s"$sign (nonnull instancetype)$prefix$firstInitializerArg" writeAlignedObjcCall( w, @@ -293,7 +298,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { val deprecated = deprecatedAttr(f.doc) w.wl(s"@property (nonatomic, readonly${nullability}) ${marshal - .fqFieldType(f.ty)} ${idObjc.field(f.ident)}${deprecated};") + .fqFieldType(f.ty)} ${idObjc.field(f.ident)}${deprecated};") } if (r.derivingTypes.contains(DerivingType.Ord)) { w.wl @@ -415,54 +420,54 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { case MBinary => w.w( s"[self.${idObjc.field(f.ident)} isEqualToData:typedOther.${idObjc - .field(f.ident)}]" + .field(f.ident)}]" ) case MList => w.w(s"[self.${idObjc.field(f.ident)} isEqualToArray:typedOther.${idObjc - .field(f.ident)}]") + .field(f.ident)}]") case MSet => w.w( s"[self.${idObjc.field(f.ident)} isEqualToSet:typedOther.${idObjc - .field(f.ident)}]" + .field(f.ident)}]" ) case MMap => w.w(s"[self.${idObjc.field(f.ident)} isEqualToDictionary:typedOther.${idObjc - .field(f.ident)}]") + .field(f.ident)}]") case MOptional => f.ty.resolved.args.head.base match { case df: MDef if df.defType == DEnum => w.w( s"self.${idObjc.field(f.ident)} == typedOther.${idObjc - .field(f.ident)}" + .field(f.ident)}" ) case _ => w.w(s"((self.${idObjc.field(f.ident)} == nil && typedOther.${idObjc - .field(f.ident)} == nil) || ") + .field(f.ident)} == nil) || ") w.w(s"(self.${idObjc.field(f.ident)} != nil && [self.${idObjc - .field(f.ident)} isEqual:typedOther.${idObjc.field(f.ident)}]))") + .field(f.ident)} isEqual:typedOther.${idObjc.field(f.ident)}]))") } case MString => w.w(s"[self.${idObjc.field(f.ident)} isEqualToString:typedOther.${idObjc - .field(f.ident)}]") + .field(f.ident)}]") case MDate => w.w( s"[self.${idObjc.field(f.ident)} isEqualToDate:typedOther.${idObjc - .field(f.ident)}]" + .field(f.ident)}]" ) - case t: MPrimitive => + case _: MPrimitive => w.w(s"self.${idObjc.field(f.ident)} == typedOther.${idObjc - .field(f.ident)}") + .field(f.ident)}") case df: MDef => df.defType match { case DRecord => w.w( s"[self.${idObjc.field(f.ident)} isEqual:typedOther.${idObjc - .field(f.ident)}]" + .field(f.ident)}]" ) case DEnum => w.w( s"self.${idObjc.field(f.ident)} == typedOther.${idObjc - .field(f.ident)}" + .field(f.ident)}" ) case _ => throw new AssertionError("Unreachable") } @@ -472,16 +477,16 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { if (e.objc.pointer.get) { w.w( s"[self.${idObjc.field(f.ident)} isEqual:typedOther.${idObjc - .field(f.ident)}]" + .field(f.ident)}]" ) } else { w.w(s"self.${idObjc.field(f.ident)} == typedOther.${idObjc - .field(f.ident)}") + .field(f.ident)}") } case DEnum => w.w( s"self.${idObjc.field(f.ident)} == typedOther.${idObjc - .field(f.ident)}" + .field(f.ident)}" ) case _ => throw new AssertionError("Unreachable") } @@ -506,7 +511,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { w.w(s"(NSUInteger)self.${idObjc.field(f.ident)}") case _ => w.w(s"self.${idObjc.field(f.ident)}.hash") } - case t: MPrimitive => + case _: MPrimitive => w.w(s"(NSUInteger)self.${idObjc.field(f.ident)}") case df: MDef => df.defType match { @@ -558,13 +563,13 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { f.ty.resolved.base match { case MString | MDate => w.wl(s"tempResult = [self.${idObjc - .field(f.ident)} compare:other.${idObjc.field(f.ident)}];") - case t: MPrimitive => generatePrimitiveOrder(f.ident, w) + .field(f.ident)} compare:other.${idObjc.field(f.ident)}];") + case _: MPrimitive => generatePrimitiveOrder(f.ident, w) case df: MDef => df.defType match { case DRecord => w.wl(s"tempResult = [self.${idObjc - .field(f.ident)} compare:other.${idObjc.field(f.ident)}];") + .field(f.ident)} compare:other.${idObjc.field(f.ident)}];") case DEnum => generatePrimitiveOrder(f.ident, w) case _ => throw new AssertionError("Unreachable") } @@ -572,7 +577,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { e.defType match { case DRecord => if (e.objc.pointer.get) w.wl(s"tempResult = [self.${idObjc - .field(f.ident)} compare:other.${idObjc.field(f.ident)}];") + .field(f.ident)} compare:other.${idObjc.field(f.ident)}];") else generatePrimitiveOrder(f.ident, w) case DEnum => generatePrimitiveOrder(f.ident, w) case _ => throw new AssertionError("Unreachable") @@ -600,7 +605,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { w.w(", ") f.ty.resolved.base match { case MOptional => w.w(s"self.${idObjc.field(f.ident)}") - case t: MPrimitive => w.w(s"@(self.${idObjc.field(f.ident)})") + case _: MPrimitive => w.w(s"@(self.${idObjc.field(f.ident)})") case df: MDef => df.defType match { case DEnum => w.w(s"@(self.${idObjc.field(f.ident)})") @@ -631,7 +636,7 @@ class ObjcGenerator(spec: Spec) extends BaseObjcGenerator(spec) { origin: String, refs: Iterable[String], f: IndentWriter => Unit - ) { + ): Unit = { val folder = if (isHeader) spec.objcHeaderOutFolder else spec.objcOutFolder val fileName = if (isHeader) marshal.headerName(objcName) else bodyName(objcName) diff --git a/src/main/scala/djinni/ObjcMarshal.scala b/src/main/scala/djinni/ObjcMarshal.scala index 90f8fa2f..5714e9a9 100644 --- a/src/main/scala/djinni/ObjcMarshal.scala +++ b/src/main/scala/djinni/ObjcMarshal.scala @@ -10,7 +10,10 @@ class ObjcMarshal(spec: Spec) extends Marshal(spec) { val (name, _) = toObjcType(tm) name } - def typename(name: String, ty: TypeDef): String = idObjc.ty(name) + def typename(name: String, ty: TypeDef): String = { + val _ = (name, ty) // unused, TODO: remove + idObjc.ty(name) + } override def fqTypename(tm: MExpr): String = typename(tm) def fqTypename(name: String, ty: TypeDef): String = typename(name, ty) @@ -57,9 +60,10 @@ class ObjcMarshal(spec: Spec) extends Marshal(spec) { override def fromCpp(tm: MExpr, expr: String): String = throw new AssertionError("direct cpp to objc conversion not possible") - def references(m: Meta, exclude: String = ""): Seq[SymbolReference] = + def references(m: Meta, exclude: String = ""): Seq[SymbolReference] = { + val _ = exclude // unused, TODO: remove m match { - case o: MOpaque => + case _: MOpaque => List(ImportRef("")) case d: MDef => d.defType match { @@ -86,22 +90,26 @@ class ObjcMarshal(spec: Spec) extends Marshal(spec) { List(ImportRef(q(prefix + headerName(d.name)))) } case e: MExtern => List(ImportRef(e.objc.header.get)) - case p: MParam => List() + case _: MParam => List() } + } - def headerName(ident: String) = idObjc.ty(ident) + "." + spec.objcHeaderExt - def include(ident: String) = q(spec.objcIncludePrefix + headerName(ident)) + def headerName(ident: String): String = + idObjc.ty(ident) + "." + spec.objcHeaderExt + def include(ident: String): String = q( + spec.objcIncludePrefix + headerName(ident) + ) - def isPointer(td: TypeDecl) = td.body match { - case i: Interface => true - case r: Record => true - case e: Enum => false + def isPointer(td: TypeDecl): Boolean = td.body match { + case _: Interface => true + case _: Record => true + case _: Enum => false } - def boxedTypename(td: TypeDecl) = td.body match { + def boxedTypename(td: TypeDecl): String = td.body match { case i: Interface => typename(td.ident, i) case r: Record => typename(td.ident, r) - case e: Enum => "NSNumber" + case _: Enum => "NSNumber" } // Return value: (Type_Name, Is_Class_Or_Not) @@ -121,7 +129,7 @@ class ObjcMarshal(spec: Spec) extends Marshal(spec) { val arg = tm.args.head arg.base match { case MOptional => throw new AssertionError("nested optional?") - case m => f(arg, true) + case _ => f(arg, true) } case o => val base = o match { @@ -161,7 +169,7 @@ class ObjcMarshal(spec: Spec) extends Marshal(spec) { else if (needRef) (e.objc.boxed.get, true) else (e.objc.typename.get, e.objc.pointer.get) } - case p: MParam => + case _: MParam => throw new AssertionError( "Parameter should not happen at Obj-C top level" ) diff --git a/src/main/scala/djinni/ObjcppGenerator.scala b/src/main/scala/djinni/ObjcppGenerator.scala index 0c6c210e..0c721593 100644 --- a/src/main/scala/djinni/ObjcppGenerator.scala +++ b/src/main/scala/djinni/ObjcppGenerator.scala @@ -15,13 +15,12 @@ package djinni -import java.io.StringWriter - import djinni.ast._ import djinni.generatorTools._ import djinni.meta._ import djinni.writer.IndentWriter +import java.io.StringWriter import scala.collection.mutable class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { @@ -30,15 +29,15 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { val cppMarshal = new CppMarshal(spec) class ObjcRefs() { - var body = mutable.TreeSet[String]() - var privHeader = mutable.TreeSet[String]() + var body: mutable.TreeSet[String] = mutable.TreeSet[String]() + var privHeader: mutable.TreeSet[String] = mutable.TreeSet[String]() - def find(ty: TypeRef) { find(ty.resolved) } - def find(tm: MExpr) { + def find(ty: TypeRef): Unit = { find(ty.resolved) } + def find(tm: MExpr): Unit = { tm.args.foreach(find) find(tm.base) } - def find(m: Meta) = for (r <- objcppMarshal.references(m)) r match { + def find(m: Meta): Unit = for (r <- objcppMarshal.references(m)) r match { case ImportRef(arg) => body.add("#import " + arg) case _ => } @@ -50,8 +49,13 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { ) + ");" ) - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { - var imports = mutable.TreeSet[String]() + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { + val imports = mutable.TreeSet[String]() imports.add( "#import " + q( objcppMarshal.objcBaseLibIncludePrefix + "DJIMarshal+Private.h" @@ -65,7 +69,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { ) ) - writeObjcFile(ident.name, isHeader = true, origin, imports, w => {}) + writeObjcFile(ident.name, isHeader = true, origin, imports, _ => {}) } def headerName(ident: String): String = @@ -82,7 +86,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { val refs = new ObjcRefs() i.methods.map(m => { m.params.map(p => refs.find(p.ty)) @@ -117,7 +121,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { case _ => } - def writeObjcFuncDecl(method: Interface.Method, w: IndentWriter) { + def writeObjcFuncDecl(method: Interface.Method, w: IndentWriter): Unit = { val label = if (method.static) "+" else "-" val ret = objcMarshal.fqReturnType(method.ret) val decl = s"$label ($ret)${idObjc.method(method.ident)}" @@ -285,7 +289,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { ) w.wl(";") - m.ret.fold()(r => + m.ret.fold(())(r => w.wl(s"return ${objcppMarshal.fromCpp(r, "objcpp_result_")};") ) } @@ -328,7 +332,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { val ret = m.ret.fold("")(_ => "auto objcpp_result_ = ") val call = s"[djinni_private_get_proxied_objc_object() ${idObjc - .method(m.ident)}" + .method(m.ident)}" writeAlignedObjcCall( w, ret + call, @@ -341,7 +345,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { ) ) w.wl(";") - m.ret.fold()(ty => { + m.ret.fold(())(ty => { if ( spec.cppNnCheckExpression.nonEmpty && isInterface( ty.resolved @@ -394,7 +398,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { // C++ only. In this case we generate a class instead of a protocol, so // we don't have to do any casting at all, just access cppRef directly. w.wl("return " + nnCheck("objc->_cppRefHandle.get()") + ";") - //w.wl(s"return ${spec.cppNnCheckExpression.getOrElse("")}(objc->_cppRefHandle.get());") + // w.wl(s"return ${spec.cppNnCheckExpression.getOrElse("")}(objc->_cppRefHandle.get());") } else if (i.ext.cpp || i.ext.objc) { // ObjC only, or ObjC and C++. if (i.ext.cpp) { @@ -465,7 +469,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { val refs = new ObjcRefs() for (c <- r.consts) refs.find(c.ty) @@ -553,7 +557,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { w.wl( "(void)obj; // Suppress warnings in relase builds for empty records" ) - val call = "return CppType(" + writeAlignedCall( w, "return {", @@ -599,7 +603,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { origin: String, refs: Iterable[String], f: IndentWriter => Unit - ) { + ): Unit = { val folder = if (isHeader) spec.objcppHeaderOutFolder else spec.objcppOutFolder val fileName = @@ -613,7 +617,7 @@ class ObjcppGenerator(spec: Spec) extends BaseObjcGenerator(spec) { w.wl("// This file was generated by Djinni from " + origin) w.wl if (refs.nonEmpty) { - var included = mutable.TreeSet[String]() + val included = mutable.TreeSet[String]() for (s <- refs) { // Ignore the ! in front of each line; used to put own headers to the top // according to Objective-C style guide diff --git a/src/main/scala/djinni/ObjcppMarshal.scala b/src/main/scala/djinni/ObjcppMarshal.scala index 49b41ed2..90f953c6 100644 --- a/src/main/scala/djinni/ObjcppMarshal.scala +++ b/src/main/scala/djinni/ObjcppMarshal.scala @@ -13,16 +13,18 @@ class ObjcppMarshal(spec: Spec) extends Marshal(spec) { override def typename(tm: MExpr): String = throw new AssertionError( "not applicable" ) - def typename(name: String, ty: TypeDef): String = throw new AssertionError( - "not applicable" - ) + def typename(name: String, ty: TypeDef): String = { + val _ = (name, ty) // unused, TODO: remove + throw new AssertionError("not applicable") + } override def fqTypename(tm: MExpr): String = throw new AssertionError( "not applicable" ) - def fqTypename(name: String, ty: TypeDef): String = throw new AssertionError( - "not applicable" - ) + def fqTypename(name: String, ty: TypeDef): String = { + val _ = (name, ty) // unused, TODO: remove + throw new AssertionError("not applicable") + } override def paramType(tm: MExpr): String = throw new AssertionError( "not applicable" @@ -51,7 +53,7 @@ class ObjcppMarshal(spec: Spec) extends Marshal(spec) { } def references(m: Meta): Seq[SymbolReference] = m match { - case o: MOpaque => + case _: MOpaque => List(ImportRef(q(objcBaseLibIncludePrefix + "DJIMarshal+Private.h"))) case d: MDef => d.defType match { @@ -65,19 +67,19 @@ class ObjcppMarshal(spec: Spec) extends Marshal(spec) { ) } case e: MExtern => List(ImportRef(e.objcpp.header.get)) - case p: MParam => List() + case _: MParam => List() } - def include(m: Meta) = m match { + def include(m: Meta): String = m match { case d: MDef => q(spec.objcppIncludePrefix + privateHeaderName(d.name)) case _ => throw new AssertionError("not applicable") } - def helperClass(name: String) = idCpp.ty(name) + def helperClass(name: String): String = idCpp.ty(name) private def helperClass(tm: MExpr): String = helperName(tm) + helperTemplates(tm) - def helperClassWithNs(name: String) = + def helperClassWithNs(name: String): String = withNs(Some(spec.objcppNamespace), helperClass(name)) def privateHeaderName(ident: String): String = @@ -115,9 +117,9 @@ class ObjcppMarshal(spec: Spec) extends Marshal(spec) { case MList => "List" case MSet => "Set" case MMap => "Map" - case d: MDef => throw new AssertionError("unreachable") - case e: MExtern => throw new AssertionError("unreachable") - case p: MParam => throw new AssertionError("not applicable") + case _: MDef => throw new AssertionError("unreachable") + case _: MExtern => throw new AssertionError("unreachable") + case _: MParam => throw new AssertionError("not applicable") } ) } diff --git a/src/main/scala/djinni/PythonGenerator.scala b/src/main/scala/djinni/PythonGenerator.scala index b8015995..543df861 100644 --- a/src/main/scala/djinni/PythonGenerator.scala +++ b/src/main/scala/djinni/PythonGenerator.scala @@ -16,30 +16,30 @@ package djinni import djinni.ast.Record.DerivingType - -import scala.collection.mutable -import scala.math.pow import djinni.ast._ import djinni.generatorTools._ import djinni.meta._ import djinni.writer.IndentWriter +import scala.collection.mutable +import scala.math.pow + class PythonGenerator(spec: Spec) extends Generator(spec) { val lib = "lib" // internal library name (from PyCFFIlib_cffi import lib) val marshal = new PythonMarshal(spec) val cMarshal = new CWrapperMarshal(spec) - def getRecordArguments(r: Record, self: String) = { + def getRecordArguments(r: Record, self: String): Seq[String] = { if (self != "") Seq(self) ++ r.fields.map(f => idPython.local(f.ident.name)) else r.fields.map(f => idPython.local(f.ident.name)) } - def getRecordTypes(r: Record) = { + def getRecordTypes(r: Record): Seq[String] = { r.fields.map(f => cMarshal.cParamType(f.ty, forHeader = true)) } // Override since Python doesn't share the C-style comment syntax. - override def writeDoc(w: IndentWriter, doc: Doc) { + override def writeDoc(w: IndentWriter, doc: Doc): Unit = { doc.lines.foreach(l => w.wl(s"#$l")) } @@ -67,7 +67,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { w: IndentWriter, name: String, docItems: IndentWriter => Unit - ) { + ): Unit = { w.wl(name) w.nested { docItems(w) @@ -193,7 +193,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { extraAddCallback: String, extraCallBackImpl: IndentWriter => Unit ): Unit = { - + val _ = (tm, ident, elTyRef) // unused, TODO: remove // GET ELEMENT/ GET VALUE var ret = getRetType var defArgs = Seq("cself, " + elIndex).mkString("(", ", ", ")") @@ -329,7 +329,8 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { ident: Ident, origin: String, python: mutable.TreeSet[String] - ) = { + ): Unit = { + val _ = classAsMethodName // unused, TODO: remove val helperClass = idPython.className(fileName) + "Helper" val proxyName = idPython.className(fileName) + "Proxy" val next = @@ -382,7 +383,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { "el", elTy, "", - w => {} + _ => {} ) case MMap => val keyTyRef = getContainerElTyRef(tm, 0, ident) @@ -529,12 +530,12 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { // for map and set have proxy map and set that can hold on to metadata like iterator class PythonRefs(ident: Ident, origin: String) { - var python = mutable.TreeSet[String]() + var python: mutable.TreeSet[String] = mutable.TreeSet[String]() - def collect(ty: TypeRef, justCollect: Boolean) { + def collect(ty: TypeRef, justCollect: Boolean): Unit = { collect(ty.resolved, justCollect, isOpt = false) } - def collect(tm: MExpr, justCollect: Boolean, isOpt: Boolean) { + def collect(tm: MExpr, justCollect: Boolean, isOpt: Boolean): Unit = { tm.args.foreach(t => collect(t, justCollect, isOpt)) collect(tm.base, justCollect) @@ -589,7 +590,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { case _ => } } - def collect(m: Meta, justCollect: Boolean) = if (justCollect) + def collect(m: Meta, justCollect: Boolean): Unit = if (justCollect) for (r <- marshal references (m, ident.name)) r match { case ImportRef(arg) => python.add(arg) @@ -597,13 +598,13 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { } } - def getCArgTypes(m: Interface.Method, self: String) = { + def getCArgTypes(m: Interface.Method, self: String): String = { (Seq(self) ++ m.params.map(p => cMarshal.cParamType(p.ty, forHeader = true) )).mkString("(", ", ", ")") } - def getDefArgs(m: Interface.Method, self: String) = { + def getDefArgs(m: Interface.Method, self: String): String = { if (m.static) { m.params.map(p => idPython.local(p.ident.name)).mkString("(", ", ", ")") } else { @@ -612,7 +613,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { } } - def getLibArgsFrom(m: Interface.Method, pythonClass: String) = { + def getLibArgsFrom(m: Interface.Method, pythonClass: String): String = { if (m.static || pythonClass == "") { m.params .map(p => marshal.releaseRAII(marshal.pyName(p.ident.name, p.ty), p.ty)) @@ -624,7 +625,8 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { } } - def getLibArgsTo(m: Interface.Method, pythonClass: String) = { + def getLibArgsTo(m: Interface.Method, pythonClass: String): String = { + val _ = pythonClass // unused, TODO: remove m.params .map(p => marshal.convertTo(p.ident.name, p.ty)) .mkString("(", ", ", ")") @@ -636,7 +638,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { refs: Iterable[String], includeCffiLib: Boolean, f: IndentWriter => Unit - ) { + ): Unit = { createFileOnce( spec.pyOutFolder.get, idPython.ty(ident) + ".py", @@ -707,7 +709,9 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { } } - def writeWithStmts(withStmts: Seq[String], w: IndentWriter)(f: => Unit) { + def writeWithStmts(withStmts: Seq[String], w: IndentWriter)( + f: => Unit + ): Unit = { if (withStmts.nonEmpty) { val len = withStmts.length @@ -756,6 +760,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { libCall: String, w: IndentWriter ): Unit = { + val _ = self // unused, TODO: remove val returnStmt: String = ret.resolved.base match { case MString | MBinary => checkForExceptionFromPython( @@ -853,7 +858,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { ) } - def checkForExceptionFromCpp(ret: String, w: IndentWriter) { + def checkForExceptionFromCpp(ret: String, w: IndentWriter): Unit = { w.wl("CPyException.toPyCheckAndRaise" + p(ret)) } @@ -871,7 +876,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { val withStmts = mutable.ArrayBuffer[String]() processPackedArgs(m, withStmts) // check that if python promised to send as arguments non optionals then they are not None - //checkNonOptionals(m, w) + // checkNonOptionals(m, w) writeWithStmts(withStmts.toSeq, w) { val libArgs = getLibArgsFrom(m, pythonClass) val libCall = lib + "." + cMethodWrapper + "_" + m.ident.name + libArgs @@ -966,7 +971,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { ident: String, ext: Ext, w: IndentWriter - ) { + ): Unit = { val helperClass = idPython.className(ident) + "Helper" val proxyClass = idPython.className(ident) + "CppProxy" // Static method to wrap as object of this class @@ -1005,6 +1010,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { ext: Ext, w: IndentWriter ): Unit = { + val _ = ext // unused, TODO, check remove val proxyClass = pythonClass + "CallbacksHelper" val helperClass = pythonClass + "Helper" val classNameAsMethod = idPython.method(ident.name) @@ -1103,13 +1109,16 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { ty: TypeRef, v: Any, selfName: String - ): Unit = v match { - case l: Long => w.w(l.toString) - case d: Double => w.w(d.toString) - case b: Boolean => w.w(if (b) "True" else "False") - case s: String => w.w(s) - case e: EnumValue => throw new NotImplementedError() - case v: ConstRef => w.w(selfName + "." + idPython.const(v)) + ): Unit = { + val _ = ty // used, TODO, check remove + v match { + case l: Long => w.w(l.toString) + case d: Double => w.w(d.toString) + case b: Boolean => w.w(if (b) "True" else "False") + case s: String => w.w(s) + case _: EnumValue => throw new NotImplementedError() + case v: ConstRef => w.w(selfName + "." + idPython.const(v)) + } } def generateNonRecursiveConstants( @@ -1117,7 +1126,8 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { consts: Seq[Const], selfName: String, genRecord: Boolean - ) = { + ): Unit = { + val _ = genRecord // unused, TODO, check remove for (c <- consts) { if (!c.value.isInstanceOf[Map[_, _]]) { // is not a record w.w(idPython.const(c.ident) + " = ") @@ -1310,7 +1320,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { number: Int, callbackNames: mutable.Set[String], w: IndentWriter - ) = { + ): IndentWriter = { val recordAsMethod = idPython.method(ident.name) var field_number = number for (f <- r.fields) { @@ -1371,7 +1381,8 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { prefix: String, number: Int, w: IndentWriter - ) = { + ): IndentWriter = { + val _ = (prefix, number) // unused, TODO, check remove val recordClassName = idPython.className(ident.name) val skipFirst = SkipFirst() w.wl("py_rec = " + recordClassName + "(").nested { @@ -1391,7 +1402,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { fieldName: String, cmpOp: String, needsParens: Boolean - ) = { + ): String = { if (needsParens) { "self." + fieldName + cmpOp + p("other." + fieldName) } else { @@ -1497,7 +1508,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { // Record Definition w.wl("class " + recordClassName + (if (r.ext.py) "Base" else "") + ":") .nested { - var docLists = mutable.ArrayBuffer[IndentWriter => Unit]() + val docLists = mutable.ArrayBuffer[IndentWriter => Unit]() if (r.fields.exists(_.doc.lines.nonEmpty)) docLists += { w: IndentWriter => writeDocFieldsList(w, r.fields) } if (r.consts.exists(_.doc.lines.nonEmpty)) @@ -1637,7 +1648,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { ) } - def writeEnumOptionNone(w: IndentWriter, e: Enum) { + def writeEnumOptionNone(w: IndentWriter, e: Enum): Unit = { for ( o <- e.options.find(_.specialFlag.contains(Enum.SpecialFlag.NoFlags)) ) { @@ -1646,7 +1657,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { } } - def writeEnumOptions(w: IndentWriter, e: Enum) { + def writeEnumOptions(w: IndentWriter, e: Enum): Unit = { var shift = 0 for (o <- normalEnumOptions(e)) { writeDocString(w, o.doc) @@ -1657,7 +1668,7 @@ class PythonGenerator(spec: Spec) extends Generator(spec) { } } - def writeEnumOptionAll(w: IndentWriter, e: Enum) { + def writeEnumOptionAll(w: IndentWriter, e: Enum): Unit = { for ( o <- e.options.find(_.specialFlag.contains(Enum.SpecialFlag.AllFlags)) ) { diff --git a/src/main/scala/djinni/PythonMarshal.scala b/src/main/scala/djinni/PythonMarshal.scala index c68abd55..0a2206dc 100644 --- a/src/main/scala/djinni/PythonMarshal.scala +++ b/src/main/scala/djinni/PythonMarshal.scala @@ -28,12 +28,18 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { val dh = "dh__" override def typename(tm: MExpr): String = toPythonType(tm) - def typename(name: String, ty: TypeDef): String = - throw new NotImplementedError() //idPython.ty(name) + @SuppressWarnings(Array("unused")) + def typename(name: String, ty: TypeDef): String = { + val _ = (name, ty) // unused, TODO, check remove + throw new NotImplementedError() // idPython.ty(name) + } override def fqTypename(tm: MExpr): String = throw new NotImplementedError() - def fqTypename(name: String, ty: TypeDef): String = + @SuppressWarnings(Array("unused")) + def fqTypename(name: String, ty: TypeDef): String = { + val _ = (name, ty) // unused, TODO, check remove throw new NotImplementedError() + } override def paramType(tm: MExpr): String = typename(tm) override def fqParamType(tm: MExpr): String = throw new NotImplementedError() @@ -93,7 +99,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { } } else List() } - case mp: MPrimitive => + case _: MPrimitive => List(ImportRef("from djinni.pycffi_marshal import CPyPrimitive")) case MString => List(ImportRef("from djinni.pycffi_marshal import CPyString")) @@ -105,11 +111,11 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { List( ImportRef("from djinni.pycffi_marshal import CPyObject, CPyObjectProxy") ) - case e: MExtern => List() // TODO: implement e: MExtern + case _: MExtern => List() // TODO: implement e: MExtern case _ => List() } - def getExprIdlName(tm: MExpr) = toPythonType(tm) + def getExprIdlName(tm: MExpr): String = toPythonType(tm) def referencesForContainer( tm: MExpr, exclude: String @@ -179,7 +185,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { ) refs.add("from djinni.pycffi_marshal import CPyEnum") } - case mp: MPrimitive => + case _: MPrimitive => refs.add("from djinni.pycffi_marshal import CPyPrimitive") case MString => refs.add("from djinni.pycffi_marshal import CPyString") case MBinary => refs.add("from djinni.pycffi_marshal import CPyBinary") @@ -192,9 +198,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { return refs } - private def toPythonType(ty: TypeRef): String = toPythonType( - ty.resolved - ) // see if this works wutg getIdlName + // see if this works wutg getIdlName private def toPythonType(tm: MExpr): String = { def base(m: Meta): String = m match { case p: MPrimitive => p.cName @@ -215,7 +219,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { case DRecord => "record_" + d.name case DEnum => "enum_" + d.name } - case e: MExtern => "extern" // TODO: implement e: MExtern + case _: MExtern => "extern" // TODO: implement e: MExtern case _ => throw new NotImplementedError() } def expr(tm: MExpr): String = { @@ -245,8 +249,8 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { } def isPrimitive(ty: TypeRef): Boolean = ty.resolved.base match { - case mp: MPrimitive => true - case _ => false + case _: MPrimitive => true + case _ => false } // TODO: pyName, isPacked and getPacked have been removed on a different branch (keep them removed when rebasing) @@ -275,7 +279,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { case MString | MBinary => true case _ => false } - case e: MExtern => false // TODO: implement e: MExtern + case _: MExtern => false // TODO: implement e: MExtern case _ => isPacked(ty.resolved) } @@ -314,7 +318,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { ) } } - case e: MExtern => argName // TODO: implement e: MExtern + case _: MExtern => argName // TODO: implement e: MExtern case _ => getPacked(arg.ty.resolved, isOpt = false, argName, pyArgName) } } @@ -327,12 +331,12 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { } // from Python names - def fromRAII(name: String, ty: MExpr, isOpt: Boolean) = { + def fromRAII(name: String, ty: MExpr, isOpt: Boolean): String = { ty.base match { case MString => idPython.method(name + ".get_djinni_string()") case MBinary => idPython.method(name + ".get_djinni_binary()") case MOptional => convertFrom(name, ty, true) - case e: MExtern => name // TODO: implement e: MExtern + case _: MExtern => name // TODO: implement e: MExtern case _ => convertFrom(name, ty, isOpt) } } @@ -344,7 +348,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { case _ => fromRAII(name, ty.resolved.args.head, isOpt = true) } } - case e: MExtern => name // TODO: implement e: MExtern + case _: MExtern => name // TODO: implement e: MExtern case _ => fromRAII(name, ty.resolved, isOpt = false) } @@ -352,7 +356,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { ty.base match { case MString => idPython.method(name + ".release_djinni_string()") case MBinary => idPython.method(name + ".release_djinni_binary()") - case e: MExtern => name // TODO: implement e: MExtern + case _: MExtern => name // TODO: implement e: MExtern case _ => fromRAII( name, @@ -369,7 +373,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { idPython.method(name + ".release_djinni_boxed" + "()") case _ => releaseRAII(name, ty.resolved.args.head, isOpt = true) } - case e: MExtern => name // TODO: implement e: MExtern + case _: MExtern => name // TODO: implement e: MExtern case _ => releaseRAII(name, ty.resolved, isOpt = false) } @@ -382,7 +386,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { val opt_s = if (isOpt) "Opt" else "" ty.base match { - case mp: MPrimitive => "CPyPrimitive.toPy" + p(local) + case _: MPrimitive => "CPyPrimitive.toPy" + p(local) case MString | MBinary | MDate => "CPy" + idlName + ".toPy" + opt_s + p(local) case MList => @@ -412,7 +416,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { case _ => convertTo(name, ty.args.head, isOpt = true) } } - case e: MExtern => name // TODO: implement e: MExtern + case _: MExtern => name // TODO: implement e: MExtern case _ => name } } @@ -436,7 +440,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { case MString | MBinary => convertToRelease(name, ty.args.head) case _ => convertTo(name, ty, isOpt = false) } - case e: MExtern => name // TODO: implement e: MExtern + case _: MExtern => name // TODO: implement e: MExtern case _ => convertTo(name, ty, isOpt = false) } } @@ -449,7 +453,7 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { val opt_s = if (isOpt) "Opt" else "" ty.base match { - case mp: MPrimitive => "CPyPrimitive.fromPy" + p(local) + case _: MPrimitive => "CPyPrimitive.fromPy" + p(local) case MString | MBinary | MDate => "CPy" + idlName + ".fromPy" + opt_s + p(local) case MList => @@ -478,10 +482,10 @@ class PythonMarshal(spec: Spec) extends Marshal(spec) { case _ => convertFrom(name, ty.args.head, isOpt = true) } } - case e: MExtern => name // TODO: implement e: MExtern + case _: MExtern => name // TODO: implement e: MExtern case _ => name } } - def privateClassMember(s: String) = "_" + s // private class member + def privateClassMember(s: String): String = "_" + s // private class member } diff --git a/src/main/scala/djinni/SwiftBridgingHeaderGenerator.scala b/src/main/scala/djinni/SwiftBridgingHeaderGenerator.scala index 268baeea..c70d2f01 100644 --- a/src/main/scala/djinni/SwiftBridgingHeaderGenerator.scala +++ b/src/main/scala/djinni/SwiftBridgingHeaderGenerator.scala @@ -15,15 +15,20 @@ package djinni -import java.io._ - import djinni.ast._ import djinni.generatorTools._ +import java.io._ + class SwiftBridgingHeaderGenerator(spec: Spec) extends Generator(spec) { val marshal = new ObjcMarshal(spec) - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { spec.objcSwiftBridgingHeaderWriter.get.write( "#import \"" + marshal.headerName(ident) + "\"\n" ) @@ -35,7 +40,7 @@ class SwiftBridgingHeaderGenerator(spec: Spec) extends Generator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { spec.objcSwiftBridgingHeaderWriter.get.write( "#import \"" + marshal.headerName(ident) + "\"\n" ) @@ -47,7 +52,7 @@ class SwiftBridgingHeaderGenerator(spec: Spec) extends Generator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { spec.objcSwiftBridgingHeaderWriter.get.write( "#import \"" + marshal.headerName(ident) + "\"\n" ) @@ -56,10 +61,12 @@ class SwiftBridgingHeaderGenerator(spec: Spec) extends Generator(spec) { object SwiftBridgingHeaderGenerator { - val bridgingHeaderName = (s: String) => s.split('-').mkString("_") - val bridgingHeaderVariables = (s: String) => s.split('-').mkString("") + val bridgingHeaderName: String => String = (s: String) => + s.split('-').mkString("_") + val bridgingHeaderVariables: String => String = (s: String) => + s.split('-').mkString("") - def writeAutogenerationWarning(name: String, writer: Writer) { + def writeAutogenerationWarning(name: String, writer: Writer): Unit = { val bridgingHeaderVarName = bridgingHeaderName(name) writer.write("// AUTOGENERATED FILE - DO NOT MODIFY!\n") writer.write("// This file was generated by Djinni\n\n") @@ -67,7 +74,7 @@ object SwiftBridgingHeaderGenerator { writer.write("// " + bridgingHeaderVarName + "\n\n") } - def writeBridgingVars(name: String, writer: Writer) { + def writeBridgingVars(name: String, writer: Writer): Unit = { val bridgingHeaderVarName = bridgingHeaderVariables(name) writer.write("#import \n\n") writer.write( diff --git a/src/main/scala/djinni/YamlGenerator.scala b/src/main/scala/djinni/YamlGenerator.scala index 866a5e06..187f19b8 100644 --- a/src/main/scala/djinni/YamlGenerator.scala +++ b/src/main/scala/djinni/YamlGenerator.scala @@ -5,8 +5,10 @@ import djinni.generatorTools._ import djinni.meta._ import djinni.syntax._ import djinni.writer.IndentWriter -import collection.JavaConverters._ + import java.util.{Map => JMap} + +import collection.JavaConverters._ class YamlGenerator(spec: Spec) extends Generator(spec) { val cppMarshal = new CppMarshal(spec) @@ -66,7 +68,7 @@ class YamlGenerator(spec: Spec) extends Generator(spec) { } ) - private def write(w: IndentWriter, td: TypeDecl) { + private def write(w: IndentWriter, td: TypeDecl): Unit = { write(w, preamble(td)) w.wl("cpp:").nested { write(w, cpp(td)) } w.wl("objc:").nested { write(w, objc(td)) } @@ -76,7 +78,7 @@ class YamlGenerator(spec: Spec) extends Generator(spec) { w.wl("cs:").nested { write(w, cs(td)) } } - private def write(w: IndentWriter, m: Map[String, Any]) { + private def write(w: IndentWriter, m: Map[String, Any]): Unit = { for ((k, v) <- m) { w.w(k + ": ") v match { @@ -91,20 +93,20 @@ class YamlGenerator(spec: Spec) extends Generator(spec) { } } - private def write(w: IndentWriter, s: Seq[Any]) { + private def write(w: IndentWriter, s: Seq[Any]): Unit = { // The only arrays we have are small enough to use flow notation w.wl(s.mkString("[", ",", "]")) } - private def write(w: IndentWriter, b: Boolean) { + private def write(w: IndentWriter, b: Boolean): Unit = { w.wl(if (b) "true" else "false") } - private def write(w: IndentWriter, s: String) { + private def write(w: IndentWriter, s: String): Unit = { if (s.isEmpty) w.wl(q("")) else w.wl(s) } - private def write(w: IndentWriter, s: QuotedString) { + private def write(w: IndentWriter, s: QuotedString): Unit = { if (s.str.isEmpty) w.wl(q("")) else w.wl("'" + s.str.replaceAllLiterally("'", "''") + "'") } @@ -191,14 +193,14 @@ class YamlGenerator(spec: Spec) extends Generator(spec) { private def meta(td: TypeDecl) = { val defType = td.body match { - case i: Interface => DInterface - case r: Record => DRecord - case e: Enum => DEnum + case _: Interface => DInterface + case _: Record => DRecord + case _: Enum => DEnum } MDef(td.ident, 0, defType, td.body) } - override def generate(idl: Seq[TypeDecl]) { + override def generate(idl: Seq[TypeDecl]): Unit = { val internOnly = idl .collect { case itd: InternTypeDecl => itd } .sortWith(_.ident.name < _.ident.name) @@ -211,7 +213,12 @@ class YamlGenerator(spec: Spec) extends Generator(spec) { } } - override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) { + override def generateEnum( + origin: String, + ident: Ident, + doc: Doc, + e: Enum + ): Unit = { // unused } @@ -221,7 +228,7 @@ class YamlGenerator(spec: Spec) extends Generator(spec) { doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) { + ): Unit = { // unused } @@ -231,7 +238,7 @@ class YamlGenerator(spec: Spec) extends Generator(spec) { doc: Doc, params: Seq[TypeParam], r: Record - ) { + ): Unit = { // unused } } @@ -245,7 +252,7 @@ object YamlGenerator { javaOutRequired: Boolean, jniOutRequired: Boolean, cppCliOutRequired: Boolean - ) = MExtern( + ): MExtern = MExtern( td.ident.name.stripPrefix( td.properties("prefix").toString ), // Make sure the generator uses this type with its original name for all intents and purposes @@ -388,8 +395,8 @@ object YamlGenerator { } private def defType(td: ExternTypeDecl) = td.body match { - case i: Interface => DInterface - case r: Record => DRecord - case e: Enum => DEnum + case _: Interface => DInterface + case _: Record => DRecord + case _: Enum => DEnum } } diff --git a/src/main/scala/djinni/ast/ast.scala b/src/main/scala/djinni/ast/ast.scala index 955d2a1e..f5ae3c3e 100644 --- a/src/main/scala/djinni/ast/ast.scala +++ b/src/main/scala/djinni/ast/ast.scala @@ -15,11 +15,12 @@ package djinni.ast -import java.io.File import djinni.ast.Record.DerivingType.DerivingType import djinni.meta.MExpr import djinni.syntax.Loc +import java.io.File + case class IdlFile(imports: Seq[FileRef], typeDecls: Seq[TypeDecl]) abstract sealed class FileRef { diff --git a/src/main/scala/djinni/generator.scala b/src/main/scala/djinni/generator.scala index a81ed9ff..eed2053f 100644 --- a/src/main/scala/djinni/generator.scala +++ b/src/main/scala/djinni/generator.scala @@ -16,14 +16,13 @@ package djinni import djinni.ast._ -import java.io._ import djinni.generatorTools._ import djinni.writer.IndentWriter - -import scala.annotation.tailrec import org.apache.commons.io.FilenameUtils -import scala.language.{implicitConversions, postfixOps} + +import java.io._ import scala.collection.mutable +import scala.language.implicitConversions import scala.util.matching.Regex package object generatorTools { @@ -106,13 +105,13 @@ package object generatorTools { cppJsonSerialization: Option[String] ) - def preComma(s: String) = { + def preComma(s: String): String = { if (s.isEmpty) s else ", " + s } - def p(s: String) = "(" + s + ")" - def q(s: String) = '"' + s + '"' - def t(s: String) = "<" + s + ">" - def firstUpper(token: String) = + def p(s: String): String = "(" + s + ")" + def q(s: String): String = '"' + s + '"' + def t(s: String): String = "<" + s + ">" + def firstUpper(token: String): String = if (token.isEmpty()) token else token.charAt(0).toUpper + token.substring(1) type IdentConverter = String => String @@ -171,18 +170,21 @@ package object generatorTools { ) object IdentStyle { - val camelUpper = (s: String) => s.split('_').map(firstUpper).mkString - val camelLower = (s: String) => { + val camelUpper: String => String = (s: String) => + s.split('_').map(firstUpper).mkString + val camelLower: String => String = (s: String) => { val parts = s.split('_') parts.head + parts.tail.map(firstUpper).mkString } - val underLower = (s: String) => s - val underUpper = (s: String) => s.split('_').map(firstUpper).mkString("_") - val underCaps = (s: String) => s.toUpperCase - val prefix = (prefix: String, suffix: IdentConverter) => - (s: String) => prefix + suffix(s) - - val javaDefault = JavaIdentStyle( + val underLower: String => String = (s: String) => s + val underUpper: String => String = (s: String) => + s.split('_').map(firstUpper).mkString("_") + val underCaps: String => String = (s: String) => s.toUpperCase + val prefix: (String, IdentConverter) => String => String = + (prefix: String, suffix: IdentConverter) => + (s: String) => prefix + suffix(s) + + val javaDefault: JavaIdentStyle = JavaIdentStyle( ty = camelUpper, typeParam = camelUpper, method = camelLower, @@ -191,7 +193,7 @@ package object generatorTools { enum = underCaps, const = underCaps ) - val cppDefault = CppIdentStyle( + val cppDefault: CppIdentStyle = CppIdentStyle( ty = camelUpper, enumType = camelUpper, typeParam = camelUpper, @@ -201,7 +203,7 @@ package object generatorTools { enum = underCaps, const = underCaps ) - val objcDefault = ObjcIdentStyle( + val objcDefault: ObjcIdentStyle = ObjcIdentStyle( ty = camelUpper, typeParam = camelUpper, method = camelLower, @@ -210,7 +212,7 @@ package object generatorTools { enum = camelUpper, const = camelUpper ) - val pythonDefault = PythonIdentStyle( + val pythonDefault: PythonIdentStyle = PythonIdentStyle( ty = underLower, className = camelUpper, typeParam = underLower, @@ -221,7 +223,7 @@ package object generatorTools { const = underCaps ) - val csDefault = CppCliIdentStyle( + val csDefault: CppCliIdentStyle = CppCliIdentStyle( ty = camelUpper, typeParam = camelUpper, property = camelUpper, @@ -233,7 +235,7 @@ package object generatorTools { file = camelUpper ) - val styles = Map( + val styles: Map[String, String => String] = Map( "FooBar" -> camelUpper, "fooBar" -> camelLower, "foo_bar" -> underLower, @@ -259,8 +261,8 @@ package object generatorTools { } object JavaAccessModifier extends Enumeration { - val Public = Value("public") - val Package = Value("package") + val Public: Value = Value("public") + val Package: Value = Value("package") def getCodeGenerationString( javaAccessModifier: JavaAccessModifier.Value @@ -278,7 +280,7 @@ package object generatorTools { final case class SkipFirst() { private var first = true - def apply(f: => Unit) { + def apply(f: => Unit): Unit = { if (first) { first = false } else { @@ -290,7 +292,7 @@ package object generatorTools { case class GenerateException(message: String) extends java.lang.Exception(message) - def createFolder(name: String, folder: File) { + def createFolder(name: String, folder: File): Unit = { folder.mkdirs() if (folder.exists) { if (!folder.isDirectory) { @@ -415,7 +417,8 @@ package object generatorTools { } object Generator { - val writtenFiles = mutable.HashMap[String, String]() + val writtenFiles: mutable.HashMap[String, String] = + mutable.HashMap[String, String]() } abstract class Generator(spec: Spec) { @@ -488,12 +491,12 @@ abstract class Generator(spec: Spec) { folder: File, fileName: String, f: IndentWriter => Unit - ) { + ): Unit = { val file = new File(folder, fileName) val cp = file.getCanonicalPath Generator.writtenFiles.put(cp.toLowerCase, cp) match { - case Some(existing) => return - case _ => + case Some(_) => return + case _ => } if (spec.outFileListWriter.isDefined) { @@ -528,7 +531,11 @@ abstract class Generator(spec: Spec) { val idPython = spec.pyIdentStyle val idCs = spec.cppCliIdentStyle - def wrapNamespace(w: IndentWriter, ns: String, f: IndentWriter => Unit) { + def wrapNamespace( + w: IndentWriter, + ns: String, + f: IndentWriter => Unit + ): Unit = { ns match { case "" => f(w) case s => @@ -536,11 +543,11 @@ abstract class Generator(spec: Spec) { w.wl(parts.map("namespace " + _ + " {").mkString(" ")).wl f(w) w.wl - w.wl(parts.map(p => "}").mkString(" ") + s" // namespace $s") + w.wl(parts.map(_ => "}").mkString(" ") + s" // namespace $s") } } - def wrapAnonymousNamespace(w: IndentWriter, f: IndentWriter => Unit) { + def wrapAnonymousNamespace(w: IndentWriter, f: IndentWriter => Unit): Unit = { w.wl("namespace { // anonymous namespace") w.wl f(w) @@ -559,7 +566,7 @@ abstract class Generator(spec: Spec) { fwds: Iterable[String], f: IndentWriter => Unit, f2: IndentWriter => Unit - ) { + ): Unit = { createFile( folder, fileIdentStyle(name) + "." + spec.cppHeaderExt, @@ -599,7 +606,7 @@ abstract class Generator(spec: Spec) { origin: String, includes: Iterable[String], f: IndentWriter => Unit - ) { + ): Unit = { createFile( folder, fileIdentStyle(name) + "." + spec.cppExt, @@ -619,7 +626,7 @@ abstract class Generator(spec: Spec) { ) } - def generate(idl: Seq[TypeDecl]) { + def generate(idl: Seq[TypeDecl]): Unit = { for (td <- idl.collect { case itd: InternTypeDecl => itd }) td.body match { case e: Enum => assert(td.params.isEmpty) @@ -631,29 +638,29 @@ abstract class Generator(spec: Spec) { } } - def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) + def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum): Unit def generateRecord( origin: String, ident: Ident, doc: Doc, params: Seq[TypeParam], r: Record - ) + ): Unit def generateInterface( origin: String, ident: Ident, doc: Doc, typeParams: Seq[TypeParam], i: Interface - ) + ): Unit - def withNs(namespace: Option[String], t: String) = namespace match { + def withNs(namespace: Option[String], t: String): String = namespace match { case None => t case Some("") => "::" + t case Some(s) => "::" + s + "::" + t } - def withCppNs(t: String) = withNs(Some(spec.cppNamespace), t) + def withCppNs(t: String): String = withNs(Some(spec.cppNamespace), t) // -------------------------------------------------------------------------- // Render type expression @@ -690,7 +697,7 @@ abstract class Generator(spec: Spec) { params: Seq[Field], end: String, f: Field => (String, String) - ) = { + ): IndentWriter = { w.w(call) val skipFirst = new SkipFirst params.foreach(p => { @@ -703,9 +710,14 @@ abstract class Generator(spec: Spec) { w.w(end) } - def normalEnumOptions(e: Enum) = e.options.filter(_.specialFlag.isEmpty) + def normalEnumOptions(e: Enum): Seq[Enum.Option] = + e.options.filter(_.specialFlag.isEmpty) - def writeEnumOptionNone(w: IndentWriter, e: Enum, ident: IdentConverter) { + def writeEnumOptionNone( + w: IndentWriter, + e: Enum, + ident: IdentConverter + ): Unit = { for ( o <- e.options.find(_.specialFlag.contains(Enum.SpecialFlag.NoFlags)) ) { @@ -714,7 +726,11 @@ abstract class Generator(spec: Spec) { } } - def writeEnumOptions(w: IndentWriter, e: Enum, ident: IdentConverter) { + def writeEnumOptions( + w: IndentWriter, + e: Enum, + ident: IdentConverter + ): Unit = { var shift = 0 for (o <- normalEnumOptions(e)) { writeDoc(w, o.doc) @@ -725,7 +741,11 @@ abstract class Generator(spec: Spec) { } } - def writeEnumOptionAll(w: IndentWriter, e: Enum, ident: IdentConverter) { + def writeEnumOptionAll( + w: IndentWriter, + e: Enum, + ident: IdentConverter + ): Unit = { for ( o <- e.options.find(_.specialFlag.contains(Enum.SpecialFlag.AllFlags)) ) { @@ -746,7 +766,7 @@ abstract class Generator(spec: Spec) { w: IndentWriter, method: Interface.Method, ident: IdentConverter - ) { + ): Unit = { val paramReplacements = method.params.map(p => (s"\\b${Regex.quote(p.ident.name)}\\b", s"${ident(p.ident.name)}") ) @@ -758,7 +778,7 @@ abstract class Generator(spec: Spec) { writeDoc(w, newDoc) } - def writeDoc(w: IndentWriter, doc: Doc) { + def writeDoc(w: IndentWriter, doc: Doc): Unit = { doc.lines.length match { case 0 => case 1 => @@ -782,7 +802,7 @@ abstract class Generator(spec: Spec) { return None } - def writeDeprecated(w: IndentWriter, doc: Doc, annotation: String) { + def writeDeprecated(w: IndentWriter, doc: Doc, annotation: String): Unit = { deprecatedText(doc) match { case Some(message) => w.wl(annotation.replace("", message)) case None => diff --git a/src/main/scala/djinni/meta.scala b/src/main/scala/djinni/meta.scala index 8975d983..b8752d5c 100644 --- a/src/main/scala/djinni/meta.scala +++ b/src/main/scala/djinni/meta.scala @@ -16,6 +16,7 @@ package djinni import djinni.ast.TypeDef + import scala.collection.immutable package object meta { diff --git a/src/main/scala/djinni/parser.scala b/src/main/scala/djinni/parser.scala index 2e751565..d7fc5449 100644 --- a/src/main/scala/djinni/parser.scala +++ b/src/main/scala/djinni/parser.scala @@ -15,32 +15,34 @@ package djinni -import java.io.{ - File, - FileInputStream, - FileNotFoundException, - InputStreamReader, - Writer -} import djinni.ast.Interface.Method import djinni.ast.Record.DerivingType.DerivingType -import djinni.syntax._ import djinni.ast._ +import djinni.syntax._ import org.apache.commons.io.FilenameUtils import org.yaml.snakeyaml.Yaml + +import java.io.File +import java.io.FileInputStream +import java.io.FileNotFoundException +import java.io.InputStreamReader +import java.io.Writer import java.util.{Map => JMap} -import scala.jdk.CollectionConverters._ +import scala.collection.JavaConverters._ import scala.collection.mutable +import scala.collection.mutable.ArrayStack +import scala.util.matching.Regex import scala.util.parsing.combinator.RegexParsers -import scala.util.parsing.input.{Position, Positional} +import scala.util.parsing.input.Position +import scala.util.parsing.input.Positional case class Parser(includePaths: List[String]) { - val visitedFiles = mutable.Set[File]() - val fileStack = mutable.Stack[File]() + val visitedFiles: mutable.Set[File] = mutable.Set[File]() + val fileStack: ArrayStack[File] = ArrayStack[File]() private object IdlParser extends RegexParsers { - override protected val whiteSpace = """[ \t\n\r]+""".r + override protected val whiteSpace: Regex = """[ \t\n\r]+""".r def idlFile(origin: String): Parser[IdlFile] = rep(importFileRef) ~ rep(typeDecl(origin)) ^^ { case imp ~ types => @@ -51,13 +53,17 @@ case class Parser(includePaths: List[String]) { ("@" ~> directive) ~ ("\"" ~> filePath <~ "\"") ^^ { case "import" ~ x => IdlFileRef(importFile(x)) case "extern" ~ x => ExternFileRef(importFile(x)) + case unexpected => + throw new IllegalArgumentException( + s"Unexpected directive: $unexpected" + ) } } def importFile(fileName: String): File = { var file: Option[File] = None - val path = includePaths.find(path => { + includePaths.find(path => { val relPath = if (path.isEmpty) fileStack.top.getParent() else path val tmp = new File(relPath, fileName) val exists = tmp.exists @@ -73,11 +79,11 @@ case class Parser(includePaths: List[String]) { file.get } - def filePath = "[^\"]*".r + def filePath: Regex = "[^\"]*".r - def directive = importDirective | externDirective - def importDirective = "import".r - def externDirective = "extern".r + def directive: Parser[String] = importDirective | externDirective + def importDirective: Regex = "import".r + def externDirective: Regex = "extern".r def typeDecl(origin: String): Parser[TypeDecl] = doc ~ ident ~ typeList(ident ^^ TypeParam) ~ "=" ~ typeDef ^^ { @@ -85,11 +91,12 @@ case class Parser(includePaths: List[String]) { InternTypeDecl(ident, typeParams, body, doc, origin) } - def ext(default: Ext) = (rep1("+" ~> ident) >> checkExts) | success(default) - def extRecord = ext( + def ext(default: Ext): Parser[Ext] = + (rep1("+" ~> ident) >> checkExts) | success(default) + def extRecord: Parser[Ext] = ext( Ext(java = false, cpp = false, objc = false, py = false, cppcli = false) ) - def extInterface = ext( + def extInterface: Parser[Ext] = ext( Ext(java = true, cpp = true, objc = true, py = true, cppcli = true) ) @@ -129,7 +136,7 @@ case class Parser(includePaths: List[String]) { def typeDef: Parser[TypeDef] = record | enum | flags | interface - def recordHeader = "record" ~> extRecord + def recordHeader: Parser[Ext] = "record" ~> extRecord def record: Parser[Record] = recordHeader ~ bracesList(field | const) ~ opt(deriving) ^^ { case ext ~ items ~ deriving => { @@ -155,11 +162,11 @@ case class Parser(includePaths: List[String]) { ).toSet } - def flagsAll = "all".r - def flagsNone = "none".r + def flagsAll: Regex = "all".r + def flagsNone: Regex = "none".r - def enumHeader = "enum".r - def flagsHeader = "flags".r + def enumHeader: Regex = "enum".r + def flagsHeader: Regex = "flags".r def enum: Parser[Enum] = enumHeader ~> bracesList(enumOption) ^^ { case items => Enum(items, flags = false) } @@ -177,9 +184,10 @@ case class Parser(includePaths: List[String]) { Enum.Option(ident, doc, Some(Enum.SpecialFlag.AllFlags)) case doc ~ ident ~ Some("none") => Enum.Option(ident, doc, Some(Enum.SpecialFlag.NoFlags)) + case _ => throw new IllegalArgumentException("Unexpected flag value") } - def interfaceHeader = "interface" ~> extInterface + def interfaceHeader: Parser[Ext] = "interface" ~> extInterface def interface: Parser[Interface] = interfaceHeader ~ bracesList(method | const) ^^ { case ext ~ items => { @@ -245,7 +253,7 @@ case class Parser(includePaths: List[String]) { } // Integer before float for compatibility; ident for enum option - def value = + def value: Parser[Any] = floatValue | intValue | boolValue | stringValue | enumValue | constRef | compositeValue def const: Parser[Const] = @@ -299,7 +307,7 @@ case class Parser(includePaths: List[String]) { } } - def toLoc(file: File, pos: Position) = Loc(file, pos.line, pos.column) + def toLoc(file: File, pos: Position): Loc = Loc(file, pos.line, pos.column) def slurpReader(in: java.io.Reader): String = { var buf = new Array[Char](4 * 1024) @@ -308,7 +316,7 @@ case class Parser(includePaths: List[String]) { val space = buf.length - pos val read = in.read(buf, pos, space) if (read == -1) { - val r = new Array[Char](pos) + new Array[Char](pos) return new String(buf, 0, pos) } pos += read @@ -365,7 +373,7 @@ case class Parser(includePaths: List[String]) { ) match { case IdlParser.Success(ty: TypeDef, _) => tds += ExternTypeDecl(ident, params, ty, properties.toMap, origin) - case IdlParser.NoSuccess(msg, input) => + case IdlParser.NoSuccess(_, _) => return Left( Error( Loc(fileStack.top, 1, 1), @@ -439,9 +447,9 @@ case class Parser(includePaths: List[String]) { } if (!visitedFiles.contains(normalized)) { x match { - case IdlFileRef(file) => + case IdlFileRef(_) => types = parseFile(normalized, inFileListWriter) ++ types - case ExternFileRef(file) => + case ExternFileRef(_) => types = parseExternFile(normalized, inFileListWriter) ++ types } } diff --git a/src/main/scala/djinni/resolver.scala b/src/main/scala/djinni/resolver.scala index ec89c903..6eac5aad 100644 --- a/src/main/scala/djinni/resolver.scala +++ b/src/main/scala/djinni/resolver.scala @@ -17,9 +17,9 @@ package djinni import djinni.ast.Record.DerivingType import djinni.ast._ -import djinni.generatorTools._ import djinni.meta._ import djinni.syntax._ + import scala.collection.immutable import scala.collection.mutable import scala.collection.mutable.ArrayBuffer @@ -48,7 +48,7 @@ package object resolver { topLevelDupeChecker.check(typeDecl.ident) def defType = typeDecl.body match { - case e: Enum => + case _: Enum => if (!typeDecl.params.isEmpty) { throw Error( typeDecl.ident.loc, @@ -56,13 +56,13 @@ package object resolver { ).toException } DEnum - case r: Record => DRecord - case i: Interface => DInterface + case _: Record => DRecord + case _: Interface => DInterface } topScope = topScope.updated( typeDecl.ident.name, typeDecl match { - case td: InternTypeDecl => + case _: InternTypeDecl => MDef( typeDecl.ident.name, typeDecl.params.length, @@ -110,7 +110,7 @@ package object resolver { None } - private def resolve(scope: Scope, typeDef: TypeDef) { + private def resolve(scope: Scope, typeDef: TypeDef): Unit = { typeDef match { case e: Enum => resolveEnum(scope, e) case r: Record => resolveRecord(scope, r) @@ -118,14 +118,16 @@ package object resolver { } } - private def resolveEnum(scope: Scope, e: Enum) { + @SuppressWarnings(Array("unused")) // scope + private def resolveEnum(scope: Scope, e: Enum): Unit = { + val _ = scope // mark unused as used, TODO, check remove val dupeChecker = new DupeChecker("enum option") for (o <- e.options) { dupeChecker.check(o.ident) } } - private def resolveConst(typeDef: TypeDef) { + private def resolveConst(typeDef: TypeDef): Unit = { def f(consts: Seq[Const]): Unit = { val resolvedConsts = new ArrayBuffer[Const] for (c <- consts) { @@ -139,7 +141,7 @@ package object resolver { } } typeDef match { - case e: Enum => + case _: Enum => case r: Record => f(r.consts) case i: Interface => f(i.consts) } @@ -150,7 +152,7 @@ package object resolver { ty: MExpr, value: Any, resolvedConsts: Seq[Const] - ) { + ): Unit = { // Check existing consts if (value.isInstanceOf[ConstRef]) { val ref = value.asInstanceOf[ConstRef] @@ -216,7 +218,7 @@ package object resolver { value match { case i: Long => assert(i.toDouble == value, "Const value not a valid f64") - case f: Double => + case _: Double => case _ => throw new AssertionError("Const type mismatch: f64") } } @@ -255,13 +257,13 @@ package object resolver { ) } } - case e: MExtern => + case _: MExtern => throw new AssertionError("Extern type not allowed for constant") case _ => throw new AssertionError("Const type cannot be resolved") } } - private def resolveRecord(scope: Scope, r: Record) { + private def resolveRecord(scope: Scope, r: Record): Unit = { val dupeChecker = new DupeChecker("record field") for (f <- r.fields) { dupeChecker.check(f.ident) @@ -346,7 +348,7 @@ package object resolver { } } - private def resolveInterface(scope: Scope, i: Interface) { + private def resolveInterface(scope: Scope, i: Interface): Unit = { // Const and static methods are only allowed on +c (only) interfaces if (i.ext.java || i.ext.objc) { for (m <- i.methods) { @@ -391,7 +393,7 @@ package object resolver { } } - private def resolveRef(scope: Scope, r: TypeRef) { + private def resolveRef(scope: Scope, r: TypeRef): Unit = { if (r.resolved != null) throw new AssertionError("double-resolve?") r.resolved = buildMExpr(scope, r.expr) } @@ -427,7 +429,7 @@ package object resolver { private class DupeChecker(kind: String) { private val names = mutable.HashMap[String, Loc]() - def check(ident: Ident) { + def check(ident: Ident): Unit = { names.put(ident.name, ident.loc) match { case Some(existing) => throw Error( diff --git a/src/main/scala/djinni/syntax/syntax.scala b/src/main/scala/djinni/syntax/syntax.scala index 2b96c976..77a88dc1 100644 --- a/src/main/scala/djinni/syntax/syntax.scala +++ b/src/main/scala/djinni/syntax/syntax.scala @@ -18,12 +18,12 @@ package djinni.syntax import java.io.File case class Loc(file: File, line: Int, col: Int) { - override def toString() = + override def toString(): String = file.getAbsolutePath() + " (" + line + "." + col + ")" } case class Error(loc: Loc, msg: String) { - override def toString() = loc + ": " + msg + override def toString(): String = loc + ": " + msg def toException: Error.Exception = Error.Exception(this) } diff --git a/src/main/scala/djinni/writer.scala b/src/main/scala/djinni/writer.scala index 8de78f0b..5d98c4d2 100644 --- a/src/main/scala/djinni/writer.scala +++ b/src/main/scala/djinni/writer.scala @@ -55,11 +55,11 @@ package object writer { this } - def increase() { + def increase(): Unit = { currentIndent += indent } - def decrease() { + def decrease(): Unit = { assert(currentIndent.length > startIndent.length) currentIndent = currentIndent.substring(0, currentIndent.length - indent.length) @@ -69,13 +69,13 @@ package object writer { def nestedN(amount: Int): ((=> Unit) => Unit) = nested_(amount, _) - private def nested_(amount: Int, f: => Unit) { - for (i <- 0 until amount) increase() + private def nested_(amount: Int, f: => Unit): Unit = { + for (_ <- 0 until amount) increase() f - for (i <- 0 until amount) decrease() + for (_ <- 0 until amount) decrease() } - def bracedEnd(end: String)(f: => Unit) { + def bracedEnd(end: String)(f: => Unit): Unit = { if (startOfLine) { wl("{") } else { @@ -85,9 +85,9 @@ package object writer { wl(s"}$end") } - def braced = bracedEnd("")(_) + def braced: (=> Unit) => Unit = bracedEnd("")(_) - def bracedSemi = bracedEnd(";")(_) + def bracedSemi: (=> Unit) => Unit = bracedEnd(";")(_) } }