Trovo che la funzione di registrazione sia estremamente difficile da digitare. Mi piace perché devo fare log(parser)("string")
? Perché non avere qualcosa di semplice come parser.log("string")
? In ogni modo, di superare quella, ho fatto questo, invece:
trait Logging { self: Parsers =>
// Used to turn logging on or off
val debug: Boolean
// Much easier than having to wrap a parser with a log function and type a message
// i.e. log(someParser)("Message") vs someParser.log("Message")
implicit class Logged[+A](parser: Parser[A]) {
def log(msg: String): Parser[A] =
if (debug) self.log(parser)(msg) else parser
}
}
Ora nel tuo parser, si può mescolare in questo tratto in questo modo:
import scala.util.parsing.combinator.Parsers
import scala.util.parsing.input.CharSequenceReader
object CombinatorParserTest extends App with Parsers with Logging {
type Elem = Char
override val debug: Boolean = true
def notComma: Parser[Char] = elem("not comma", _ != ',')
def notEndLine: Parser[Char] = elem("not end line", x => x != '\r' && x != '\n')
def text: Parser[List[Char]] = rep(notComma.log("notComma") | notEndLine.log("notEndLine"))
val r = text(new CharSequenceReader(","))
println(r)
}
È inoltre possibile eseguire l'override del campo debug
per spegnere la registrazione se lo si desidera.
L'esecuzione di questo dimostra anche il secondo parser correttamente analizzato la virgola:
trying notComma at [email protected]
notComma --> [1.1] failure: not comma expected
,
^
trying notEndLine at [email protected]
notEndLine --> [1.2] parsed: ,
trying notComma at [email protected]
notComma --> [1.2] failure: end of input
,
^
trying notEndLine at [email protected]
notEndLine --> [1.2] failure: end of input
,
^
The result is List(,)
Process finished with exit code 0
Penso che EOF è artificialmente introdotta, ma hai ragione nel dire che è più volte analizzato al sembra ripetutamente fornito al momento della richiesta un carattere aggiuntivo quando l'input è già alla fine della sequenza. – huynhjl