Search code examples
scalafastparse

No implicit view available from fastparse.P[Any] => fastparse.P[Unit]


I am working through the tutorial/explanation of fastparse and am getting the error message

error: No implicit view available from fastparse.P[Any] => fastparse.P[Unit]

for the sequence example.

I am using sbt 1.3.8 and scala 2.13.1. The defined version for fastparse is 2.2.2.

scala> import fastparse._
import fastparse._

scala> def ab[_:P] = P("a" ~ "b")
                           ^
       error: No implicit view available from fastparse.P[Any] => fastparse.P[Unit].

scala> def a[_:P] = P("a")
a: [_](implicit evidence$1: fastparse.P[Any])fastparse.package.P[Unit]

scala> def b[_:P] = P("b")
b: [_](implicit evidence$1: fastparse.P[Any])fastparse.package.P[Unit]

scala> def ab[_:P] = P(a ~ b)
                         ^
       error: No implicit view available from fastparse.package.P[Any] => fastparse.package.P[Unit].

scala> def ab[_:P] = P("a" | "b")
ab: [_](implicit evidence$1: fastparse.P[Any])fastparse.package.P[Unit]

scala> fastparse.parse("a", ab(_))
res2: fastparse.Parsed[Unit] = Parsed.Success((), 1)

What does this error mean and what did I do wrong/how can I conclude this tutorial step without error?


Solution

  • You need to specify how to handle whitespace, for example the following fails

    import fastparse._
    import fastparse.NoWhitespace._
    
    def ab[_:P] = P("a" ~ "b")
    assert(parse("a      b", ab(_)).isSuccess)
    

    because "a b" contains spaces, whilst the following passes

    import fastparse._
    import fastparse.SingleLineWhitespace._
    
    def ab[_:P] = P("a" ~ "b")
    assert(parse("a      b", ab(_)).isSuccess)
    

    becase import fastparse.SingleLineWhitespace._ provides whitespace consumer. If we look at the definition of ~

    def ~[V, R](other:  P[V])
               (implicit s: Implicits.Sequencer[T, V, R],
                whitespace: P[Any] => P[Unit],
                ctx: P[_]): P[R] = macro MacroImpls.parsedSequence[T, V, R]
    

    we see implicit whitespace: P[Any] => P[Unit] requirement which explains No implicit view available error. The whitespace imports provide this capability, for example

    object NoWhitespace {
      implicit object noWhitespaceImplicit extends (ParsingRun[_] => ParsingRun[Unit]){
        def apply(ctx: ParsingRun[_]) = ctx.freshSuccessUnit()
      }
    }
    

    where we see ParsingRun[_] => ParsingRun[Unit] implicit function.