Scala js `#JSGlobal` object reference error - scala

I had this small snippet of code: -
import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal
object Main2 extends App {
val js: Option[JS1] = for {
jsTest <- JSTest.js1.toOption
} yield jsTest
println(js)
}
#js.native
#JSGlobal
object JSTest extends js.Object {
def js1: js.UndefOr[JS1] = js.native
}
#js.native
trait JS1 extends js.Object {
def js1: js.UndefOr[JS2] = js.native
}
#js.native
trait JS2 extends js.Object {
def js2: js.UndefOr[Int] = js.native
}
When I try to run this I am getting this error: -
const value = JSTest.js1;
^
ReferenceError: JSTest is not defined
at $c_LMain2$.delayedEndpoint$Main2$1__V (D:\experiment\target\scala-2.13\file:\D:\experiment\src\main\scala\Main2.scala:8:15)
at $c_LMain2$delayedInit$body.apply__O (D:\experiment\target\scala-2.13\file:\D:\experiment\src\main\scala\Main2.scala:5:14)
at $f_s_App__main__AT__V (D:\experiment\target\scala-2.13\https:\raw.githubusercontent.com\scala\scala\v2.13.2\src\library\scala\Function0.scala:39:7)
at $s_LMain2__main__AT__V (D:\experiment\target\scala-2.13\file:\D:\experiment\src\main\scala\Main2.scala:5:8)
at D:\experiment\target\scala-2.13\experiment-fastopt.js:9360:1
at D:\experiment\target\scala-2.13\experiment-fastopt.js:9361:4
at Script.runInThisContext (vm.js:132:18)
at Object.runInThisContext (vm.js:315:38)
at [stdin]:8:25
at Script.runInThisContext (vm.js:132:18)
[error] org.scalajs.jsenv.ExternalJSRun$NonZeroExitException: exited with code 1
[error] at org.scalajs.jsenv.ExternalJSRun$$anon$1.run(ExternalJSRun.scala:186)
[error] stack trace is suppressed; run last Compile / run for the full output
[error] (Compile / run) org.scalajs.jsenv.ExternalJSRun$NonZeroExitException: exited with code 1
[error] Total time: 7 s, completed 20-Aug-2020, 5:47:54 pm
According to scala-js doc: - https://www.scala-js.org/doc/interoperability/global-scope.html
It should run but throwing this error can anybody let me know what the issue here?
build.sbt
name := "experiment"
version := "0.1"
scalaVersion := "2.13.3"
enablePlugins(ScalaJSPlugin)
scalaJSUseMainModuleInitializer := true
configuration:-
Scala -> 2.13.3, SBT -> 1.3.13, JVM -> Java 14, scala-js -> 1.1.1

This question was asked because of porting issue from scala 0.6.33 to scala 1.1.1 and The solution for this is answered on this: -
scala-js "#JSGlobalScope" error when migrating to scala-js 1.1.1

Related

How to run Scala test in Scala native application?

I have hello world scala native app and wanted to run small scala test to this app I use the usual test command but it's throw an exception :
NativeMain.scala
object NativeMain {
val p = new Person("xxxx")
def main(args: Array[String]): Unit = {
println("Hello world")
}
}
class Person(var name: String)
}
NativeTest.scala
import org.scalatest.{FlatSpec, Matchers}
class NativeTest extends FlatSpec with Matchers {
"name" should "the name is set correctly in constructor" in {
assert(NativeMain.p.name == "xxxx")
}
}
I run test command in the sbt shell and got this error
[IJ]> test
[info] Compiling 1 Scala source to /home/****/Documents/ScalaNativeFresh/target/scala-2.11/classes...
[info] Compiling 1 Scala source to /home/****/Documents/ScalaNativeFresh/target/scala-2.11/test-classes...
[info] Compiling 1 Scala source to /home/****/Documents/ScalaNativeFresh/target/scala-2.11/test-classes...
[info] Linking (28516 ms)
[error] cannot link: #java.lang.Thread::getStackTrace_scala.scalanative.runtime.ObjectArray
[error] unable to link
[error] (nativetest:nativeLink) unable to link
[error] Total time: 117 s, completed Apr 2, 2019 3:04:24 PM
Any help or suggestions thank you :) ?
There is an open issue to add Add support for Scala Native #1112 and according to cheeseng:
3.1.0-SNAP6 and 3.2.0-SNAP10 are the only 2 versions (as of the time of writing) that supports scala-native
Try importing scalatest_native0.3_2.11 like so
libraryDependencies += "org.scalatest" % "scalatest_native0.3_2.11" % "3.2.0-SNAP10"
scalatest-native-example is a working example showing how to use scalatest with scala-native.

how to create vertx in scala

The build.sbt is as follows:
name := "ScalaVertxTest"
version := "0.1"
scalaVersion := "2.12.8"
libraryDependencies += "io.vertx" %% "vertx-lang-scala" % "3.6.3"
In Scala file, just trying to create vertx instance as follows:
package com.example
import io.vertx.scala.core._
object Main {
def main (args: Array[String]): Unit = {
println("Hello Vertx Scala")
var vertx = Vertx.vertx()
}
sbt compile command generates following error message:
com/example/Main.scala:3:11: object vertx is not a member of package io
[error] import io.vertx.scala.core._
[error] ^
[error] com/example/Main.scala:12:17: not found: value Vertx
[error] var vertx = Vertx.vertx()
[error] ^
[error] two errors found
}
How to create Vertx instance in Scala?
I was having problem building in Intellij IDE.
Compiled using sbt in console, program builds correctly.

Codec for ADT do not compile

I'm using the scala driver to make IO operations with mongodb. My scala version is 2.11.11 and the mongo db driver is 2.2.0.
I take the example in documentation about ADT :
sealed class Tree
case class Branch(b1: Tree, b2: Tree, value: Int) extends Tree
case class Leaf(value: Int) extends Tree
val codecRegistry = fromRegistries( fromProviders(classOf[Tree]), DEFAULT_CODEC_REGISTRY )
This code didn't compile.
No known subclasses of the sealed class
[error] val codecRegistry = fromRegistries( fromProviders(classOf[Tree]), DEFAULT_CODEC_REGISTRY )
[error] ^
[error] knownDirectSubclasses of Tree observed before subclass Branch registered
[error] knownDirectSubclasses of Tree observed before subclass Leaf registered
Did I miss something ?
Update
Below a complete example of what I'm tring to do.
build.sbt
name := "mongodb-driver-test"
version := "1.0"
scalaVersion := "2.11.11"
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "2.2.0"
file Models.scala
import org.mongodb.scala.bson.codecs.{DEFAULT_CODEC_REGISTRY, Macros}
import org.bson.codecs.configuration.CodecRegistries.{fromProviders, fromRegistries}
/**
* Created by alifirat on 02/01/18.
*/
object Models {
sealed class Tree
case class Branch(b1: Tree, b2: Tree, value: Int) extends Tree
case class Leaf(value: Int) extends Tree
val treeCodec = Macros.createCodecProvider[Tree]()
val treeCodecRegistry = fromRegistries( fromProviders(treeCodec), DEFAULT_CODEC_REGISTRY )
}
Then, just do :
sbt compile
You will get :
[error] val treeCodec = Macros.createCodecProvider[Tree]()
[error] ^
[error] knownDirectSubclasses of Tree observed before subclass Branch registered
[error] knownDirectSubclasses of Tree observed before subclass Leaf registered
[error] three errors found
[error] (compile:compileIncremental) Compilation failed
If I change the scala version to 2.12.0, I didn't have any errors at compile time ...
I'm using driver version 2.6.0 and Scala version 2.12.8 and still get the same problem.
My workaround is to remove the keyword sealed in front of that sealed class, compile, put it back, and then compile again. But it's very cumbersome.

SBT cannot resolve class declared in src/main/scala in a src/test/scala test class

I am trying to make my own custom CSV reader. I am using IntelliJ IDEA 14 with sbt and specs2 test framework.
The class I declared in src/main is as follows:
import java.io.FileInputStream
import scala.io.Source
class CSVStream(filePath:String) {
val csvStream = Source.fromInputStream(new FileInputStream(filePath)).getLines()
val headers = csvStream.next().split("\\,", -1)
}
The content of the test file in src/test is as follows:
import org.specs2.mutable._
object CSVStreamSpec {
val csvSourcePath = getClass.getResource("/csv_source.csv").getPath
}
class CSVStreamSpec extends Specification {
import CSVStreamLib.CSVStreamSpec._
"The CSV Stream reader" should {
"Extract the header" in {
val csvSource = CSVStream(csvSourcePath)
}
}
}
The build.sbt file contains the following:
name := "csvStreamLib"
version := "1.0"
scalaVersion := "2.11.4"
libraryDependencies ++= Seq("org.specs2" %% "specs2-core" % "2.4.15" % "test")
parallelExecution in Test := false
The error I am getting when I type test is as follows:
[error] /Users/raiyan/IdeaProjects/csvStreamLib/src/test/scala/csvStreamSpec.scala:18: not found: value CSVStream
[error] val csvSource = CSVStream(csvSourcePath)
[error] ^
[error] one error found
[error] (test:compile) Compilation failed
[error] Total time: 23 s, completed 30-Dec-2014 07:44:46
How do I make the CSVStream class accessible to the CSVStreamSpec class in the test file?
Update:
I tried it with sbt in the command line. The result is the same.
You forgot the new keyword. Without it, the compiler looks for the companion object named CSVStream, not the class. Since there is none, it complains. Add new and it'll work.

combining input task with dynamic task in sbt

I'd like to make an input task that proceed user input and generate bunch of subtasks to run. Here is the example:
import sbt._
import Keys._
import Def.Initialize
import complete.DefaultParsers._
object TestBuild extends Build {
val sampleInput = inputKey[Seq[String]]("sample dynamic input task")
val sampleDynamic = taskKey[Seq[String]]("sample dynamic task")
override lazy val settings = super.settings ++ Seq(
sampleDynamic := Def.taskDyn {
val sources = Seq("ab", "csd", "efda")
sources.map(sampleTaskFor _).joinWith(_.join)
}.value,
sampleInput := Def.inputTaskDyn {
val sources = spaceDelimited("<arg>").parsed
sources.map(sampleTaskFor _).joinWith(_.join)
}.value
)
private def sampleTaskFor(source : String) : Initialize[Task[String]] = Def.task {
source + " : " + source
}
}
There are two samples. The first works and shows simple taskDyn with predefined input. The second is intended dynamic task with user input that refuses to compile with error that I can not interpret
[error] home/project/build.scala:15: Illegal dynamic reference: Def
[error] sampleInput := Def.inputTaskDyn {
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
How can I avoid it?
Trial and error log
There I would append my question with different proposed changes that still can not solve the issue
replace InputTask.value with InputTask.evaluated
sources.map(sampleTaskFor _).joinWith(_.join)
- }.value
+ }.evaluated
)
If I would able to define correct InputTask it should be accessed via evaluated method, as I've found both in documentation and in practice after trying to play with different InputTasks that compiles.
Still that would not fix the issue that sbt macro engine refuses provided inputTaskDyn.
waiting for other suggestions
Trial and error method gave me the answer but non a single bit of understanding. Here it is:
import sbt._
import Keys._
import Def.Initialize
import complete.DefaultParsers._
object TestBuild extends Build {
val sampleInput = inputKey[Seq[String]]("sample dynamic input task")
val sampleDynamic = taskKey[Seq[String]]("sample dynamic task")
override lazy val settings = super.settings ++ Seq(
sampleDynamic := Def.taskDyn {
val sources = Seq("ab", "csd", "efda")
sources.map(sampleTaskFor _).joinWith(_.join)
}.value,
sampleInput := Def.inputTaskDyn {
val sources = spaceDelimited("<arg>").parsed
sampleTaskAll(sources)
}.evaluated
)
private def sampleTaskFor(source : String) : Initialize[Task[String]] = Def.task {
source + " : " + source
}
private def sampleTaskAll(sources : Seq[String]) : Initialize[Task[Seq[String]]] = Def.taskDyn {
sources.map(sampleTaskFor _).joinWith(_.join)
}
}
For a reason I can not comprehend you should isolate creating multitask out of sequence of single tasks in a separate method.