I have a piece of code:
case class ColumnChange private(field: String, old: Option[JsValue], `new`: Option[JsValue])
#typeclass
trait CreateColumnChanges[-New] {
def fieldChanges(newValue: New): Vector[ColumnChange]
}
trait LowLevelFieldChangesImplicits {
import com.github.ghik.silencer.silent
#silent
implicit object NothingColumnChanges extends CreateColumnChanges[Nothing] {
override def columnChanges(newValue: Nothing): Vector[ColumnChange] = Vector.empty
}
}
I have enabled "-Xfatal-warnings" in my build.sbt.
When I am compiling my project its throwing this error:
dead code following this construct
[error] implicit object NothingCreateFieldChanges extends CreateFieldChanges[Nothing] {
I tried changing type to CreateColumnChanges[Any], but somehow many tests are failing, which over-complicates my problem, maybe because -New is in contravariant position. I tried putting this scalacOptions "-Ywarn-dead-code" in build file too, but its not having any effect and again I am getting the same exception. I am compiling with scala 2.12.10.Also #silent annotation is not having effect on it. How can I change my code to avoid this error.
Finally this worked,
I changed type from Nothing to Unit
Related
Macro sample code:
package macros
import scala.reflect.macros.whitebox.Context
import scala.language.experimental.macros
import scala.annotation.StaticAnnotation
class Ant extends StaticAnnotation {
def macroTransform(annottees: Any*): Unit = macro Ant.impl
}
object Ant {
def impl(c: Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
c.internal.enclosingOwner.asType.toType // this line is Ok
// ! Any commented line below causes the same compilation error
// c.internal.enclosingOwner.asType.toType.decls
// c.mirror.staticClass(c.internal.enclosingOwner.fullName + ".A".toString)
// c.typecheck(annottees.head)
q"""implicit class A(val v: Int) extends AnyVal { def ask() = println("ok") }"""
}
}
Changing whitebox.Context to macros.Context or blackbox.Context does not help.
Changing arguments withImplicitViewsDisabled=true, or withMacrosDisabled=true has no effect.
Exec sample code:
package test
import macros.Ant
object Test extends App {
val a = new A(42)
a.ask() // Output should be "ok" (not 42)
// ! removing [implicit] lets code be compiled
#Ant implicit class A(v: Int) { def ask() = println(v)}
}
So, removing line c.typecheck(annottees.head) and / or word implicit in line #Ant implicit class A(v: Int) lets code be compiled.
Otherwise compilation crashes with error:
Error:scalac:
no progress in completing object Test: <?>
while compiling: D:\Projects\_Schemee\TestMacro1\src\test\Test.scala
during phase: globalPhase=typer, enteringPhase=namer
library version: version 2.11.6
compiler version: version 2.11.6
reconstructed args: -nobootcp -classpath ...
last tree to typer: Ident(v)
tree position: <unknown>
tree tpe: Int
symbol: value v
symbol definition: v: Int (a TermSymbol)
symbol package: test
symbol owners: value v -> method A -> object Test
call site: method A in object Test in package test
<Cannot read source file>
Compiled under latest IntelliJ. With and without Sbt.
The question is: how to use typecheck in macro annotation with implicit classes? (or am i missing something?)
EDITED:
Besides that that error is caused when trying to access enclosingOwner declarations or mirror class A "manually".
Github link
Issue link
It looks like an sbt bug or interaction with compiler behavior.
The original exception:
java.lang.NullPointerException
at xsbt.Dependency$ExtractDependenciesByMemberRefTraverser$$anonfun$1.isDefinedAt(Dependency.scala:142)
That location:
val typeSymbolCollector = new CollectTypeTraverser({
case tpe if !tpe.typeSymbol.isPackage => tpe.typeSymbol
})
The traverser has a comment suggesting similar issues:
/*
* Some macros appear to contain themselves as original tree.
* We must check that we don't inspect the same tree over and over.
* See https://issues.scala-lang.org/browse/SI-8486
* https://github.com/sbt/sbt/issues/1237
* https://github.com/sbt/sbt/issues/1544
*/
I'm using spray and I have the following code:
import spray.json.DefaultJsonProtocol
import spray.routing.Directives
import spray.httpx.SprayJsonSupport.sprayJsonMarshaller
import spray.httpx.SprayJsonSupport.sprayJsonUnmarshaller
case class SomeResult(id: String, color: String)
trait Protocols extends DefaultJsonProtocol {
implicit val someResultFormat = jsonFormat2(SomeResult)
}
trait Api extends Directives with Protocols {
val route =
path("order" / IntNumber) { id =>
get {
complete {
val result: List[SomeResult] = List(SomeResult("foo", "green"+id), SomeResult("bar", "red"+id))
result
} // ERROR HERE
}
}
}
This compiles and runs fine, however, inside IntelliJ IDEA editor it complains about an error. Namely, it says that Expression of type List[SomeResult] doesn't conform to expected type ToResponseMarshallable. How can I avoid the IDE complaining about such things? is there any fix for this? is it a well-known error? I already invalidated cache files and restarted but the error persist.
FWIW, I'm using:
Scala 2.11.1
Spray 1.3.1
IDEA 14.0.3
Scala plugin 1.3.2
JDK 1.7.0_71
I'm working on a simple test spec using spray and I can't get it to compile correctly, don't know if I'm doing anything wrong. My version of scala is 2.9.3 and spray 1.0.1 (Updating either of them is not a suitable option). Here's my test spec's code:
import org.specs2.mutable.Specification
import spray.testkit.Specs2RouteTest
import spray.http._
import akka.util.Duration
import java.util.concurrent.TimeUnit
import service.MyProxy
abstract class MyTestSpec extends Specification with Specs2RouteTest with MyProxy{
val duration = Duration(30, TimeUnit.SECONDS)
implicit val routeTestTimeout = RouteTestTimeout(duration)
"MyProxy" should {
"return a json for GET requests to the /api/getclass/classCode path for a regular request" in {
Get("/api/getclass/123/") ~> myRoutes~> check {
responseAs[String] must contain("classCode")
contentType === ContentTypes.`application/json`
}
}
} // end should...
} //end class
I'm getting this error when I run the test.
[error] C:\Users\Desktop\Project\MyTestSpec.scala:23: could not find implicit value for parameter ta: MyProxySpec.this.TildeArrow[spray.routing.RequestContext,Unit]
[error] Get("/api/getclass/123/") ~> myRoutes~> check {
[error] ^
[error] one error found
[error] (test:compile) Compilation failed
I've tried different solutions seen on another questions and nothing seems to work so far.
Spray.io: Can't compile test spec
how to make scalatest work with spraytestkit and HttpServiceActor
Basic Spray-Testkit usage to test a route does not work
https://groups.google.com/forum/#!topic/spray-user/H5hkXuDGWYQ
https://groups.google.com/forum/#!topic/spray-user/zFUJSVBPM5c
NOTE: Just for the record, I'm not using scalatest or scalacheck on this. Is purely a [spray] route test.And MyProxy extends Actor
I just struggled with this problem. To figure it out, I waded through the Akka HTTP codebase, which is a jungle of implicits.
My problem seemed to be that without the right secondary implicit in place, the correct TildeArrow instance wasn't being found. If you look at the code, the TildeArrow instance, which is required in the error message, is defined as an implicit def injectIntoRoute in the companion object and it requires a whole host of other implicits.
I suggest writing out your code without any of the implicit sugar. This should better help the compiler give you a proper error message:
"MyProxy" should {
"return a json for GET requests to the /api/getclass/classCode path for a regular request" in {
val request = Get("/api/getclass/123/")
val requestWithRoutes = request.~>(myRoutes)(TildeArrow.injectIntoRoute)
requestWithRoutes.~>(check {
responseAs[String] must contain("classCode")
contentType === ContentTypes.`application/json`
})
}
}
I think the reason is that since there's no concrete instance of the implicit available, the compiler is trying to satisfy the implicit resolution with the abstract class TildeArrow, and the completely unspecified abstract type, ta.Out, doesn't have a ~> defined.
In my specific case, I was missing an implicit ExecutionContextExecutor, whatever that means.
UPDATE
Actually, I looked into it further and the problem was that I had an implicit def ec: ExecutionContextExecutor declared in my route trait, but trait RouteTest defines its name as executor, and so when I defined my own to fulfill the missing implicit, I ended up with two of the same implicit.
It's a cute API, but the implicit magic is way out of control, IMO, especially given how cryptic the error messages tend to be.
The ScalatestRouteTest already provides an implicit ActorySystem. Remove the "implicit" modifier from your actorRefFactory method and the test should get executed.
Spray.io: Can't compile test spec
for akka http:
in my case which refer to akka-http-microservice
the implicit modifier of executionContext and also need to be removed
and should reorder the trait like this : class ServiceSpec extends FlatSpec with Matchers with Service with ScalatestRouteTest
In my case, the not found implicit error appeared when in my TestCase I also imported import monix.execution.Scheduler.Implicits.global (which is probably having some sort of ExecutionContext).
I fixed it adding the monix scheduler import just in the method where I needed it, not on the top imports.
I can reproduce the precise same error message with Scala 2.10 if myRoutes is not actually a route but a Directive[HNil].
I am therefore guessing that in your unshown service.MyProxy class your route does not complete.
ie
trait MyProxy extends HttpService {
val myRoutes = path("foo")
}
Gives this error
trait MyProxy extends HttpService {
val myRoutes = path("foo") {
complete(StatusCodes.Accepted)
}
}
Does not.
To expand a bit on previous answers given, there are some implicits which shouldn't be declared by any other Trait or class that is extends by your Test Class :
the ActorSystem
the ExecutionContext
the DefaultHostInfo (package akka.http.scaladsl.testkit)
the ActorMaterializer
if any of these is declared elsewhere than in ScalatestRouteTest, you'll have the following error thrown :
could not find implicit value for parameter ...TildeArrow[RequestContext, SomethingHereOther]
your build.sbt should have dependencies for akka-stream test along with akka test.
then it should get the whatever dependencies.
refer to this doc:-
scala route test doc
Can someone help me to understand what is wrong with the code below? The problem is inside the "join" method - I am not able to set "state" field. Error message is -
No implicit view available from code.model.Membership.MembershipState.Val => _14.MembershipState.Value.
[error] create.member(user).group(group).state(MembershipState.Accepted).save
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
What does _14 mean? I tried similar thing with MappedGender and it works as expected, so why MappedEnum fails?
scala 2.10
lift 2.5
Thanks
package code
package model
import net.liftweb.mapper._
import net.liftweb.util._
import net.liftweb.common._
class Membership extends LongKeyedMapper[Membership] with IdPK {
def getSingleton = Membership
object MembershipState extends Enumeration {
val Requested = new Val(1, "Requested")
val Accepted = new Val(2, "Accepted")
val Denied = new Val(3, "Denied")
}
object state extends MappedEnum(this, MembershipState)
{
override def defaultValue = MembershipState.Requested
}
object member extends MappedLongForeignKey(this, User) {
override def dbIndexed_? = true
}
object group extends MappedLongForeignKey(this, Group) {
override def dbIndexed_? = true
}
}
object Membership extends Membership with LongKeyedMetaMapper[Membership] {
def join (user : User, group : Group) = {
create.member(user).group(group).state(MembershipState.Accepted).save
}
}
Try moving your MembershipState enum outside of the MembershipClass. I was getting the same error as you until I tried this. Not sure why, but the code compiled after I did that.
_14 means a compiler-generated intermediate anonymous value. In other words, the compiler doesn't know how to express the type it's looking in a better way.
But if you look past that, you see the compiler is looking for a conversion from [...].Val to [...].Value. I would guess that changing
val Requested = new Val(1, "Requested")
to
val Requested = Value(1, "Requested")
would fix the error.
(I'm curious where you picked up the "new Val" style?)
What's strange is that Val actually extends Value. So if the outer type was known correctly (not inferred to the odd _14) Val vs. Value wouldn't be a problem. The issue here is that Lift from some reason defines the setters to take the now-deprecated view bound syntax. Perhaps this causes the compiler, rather than going in a straight line and trying to fit the input type into the expected type, instead to start from both ends, defining the starting type and the required type, and then start searching for an implicit view function that can reconcile the two.
I've got the above odd error message that I don't understand "value Parsers is not a member of package scala.util.parsing.combinator".
I'm trying to learn Parser combinators by writing a C parser step by step. I started at token, so I have the classes:
import util.parsing.combinator.JavaTokenParsers
object CeeParser extends JavaTokenParsers {
def token: Parser[CeeExpr] = ident ^^ (x => Token(x))
}
abstract class CeeExpr
case class Token(name: String) extends CeeExpr
This is as simple as I could make it.
The code below works fine, but if I uncomment the commented line I get the error message given above:
object Play {
def main(args: Array[String]) {
//val parser: _root_.scala.util.parsing.combinator.Parsers.Parser[CeeExpr] CeeParser.token
val x = CeeParser.token
print(x)
}
}
In case it is a problem with my setup, I'm using scala 2.7.6 via the scala-plugin for intellij. Can anyone shed any light on this? The message is wrong, Parsers is a member of scala.util.parsing.combinator.
--- Follow-up
This person http://www.scala-lang.org/node/5475 seems to have the same problem, but I don't understand the answer he was given. Can anyone explain it?
The problem is that Parser is a subclass of Parsers, so the proper way to refer to it is from an instance of Parser. That is, CeeParser.Parser is different from any other x.Parser.
The correct way to refer to the type of CeeParser.token is CeeParser.Parser.
The issue is that Parsers is not a package or class, is is a trait, so its members can't be imported. You need to import from the specific class extending the trait.
In this case the specific class is CeeParser so the type of val should be CeeParser.Parser[CeeExpr]:
val parser : CeeParser.Parser[CeeExpr]