Scala Combinator定义出现错误,无法理解原因

Scala Combinator定义出现错误,无法理解原因,scala,Scala,我试图编写一个简单的解析器,以便能够为RDBMS生成DDL,但在定义组合器时遇到了困难 import scala.util.parsing.combinator._ object DocumentParser extends RegexParsers { override protected val whiteSpace = """(\s|//.*)+""".r //To include comments in what is regarded as white space, to be i

我试图编写一个简单的解析器,以便能够为RDBMS生成DDL,但在定义组合器时遇到了困难

import scala.util.parsing.combinator._
object DocumentParser extends RegexParsers {
  override protected val whiteSpace = """(\s|//.*)+""".r //To include comments in what is regarded as white space, to be ignored
  case class DocumentAttribute(attributeName : String, attributeType : String)
  case class Document(documentName : String, documentAttributeList : List[DocumentAttribute])
  def document : Parser[Document]= "document" ~> documentName <~ "{" ~> attributeList <~ "}" ^^ {case n ~ l => Document(n, l)} //Here is where I get an error
  def documentName  : Parser[String] = """[a-zA-Z_][a-zA-Z0-9_]*""".r ^^ {_.toString}
  def attributeList : Parser[List[DocumentAttribute]] = repsep(attribute, ",")
  def attribute : Parser[DocumentAttribute] = attributeName ~ attributeType ^^ {case n ~ t => DocumentAttribute(n, t)}
  def attributeName : Parser[String] = """[a-zA-Z_][a-zA-Z0-9_]*""".r ^^ {_.toString}
  def attributeType : Parser[String] = """[a-zA-Z_][a-zA-Z0-9_]*""".r ^^ {_.toString}
}
导入scala.util.parsing.combinator_
对象DocumentParser扩展RegexParsers{
重写受保护的val whiteSpace=“”(\s |/.*)+“”。”。r//将注释包含在被视为空白的内容中,将被忽略
案例类DocumentAttribute(attributeName:String,attributeType:String)
案例类文档(文档名称:字符串,文档属性列表:列表[文档属性])
def document:Parser[document]=“document”~>documentName attributeList document(n,l)}//这里是我得到错误的地方
def documentName:Parser[String]=“a-zA-Z][a-zA-Z0-9\]*”“”.r^^{u.toString}
def attributeList:Parser[List[DocumentAttribute]]=repsep(属性,“”)
def属性:解析器[DocumentAttribute]=attributeName~attributeType^{case n~t=>DocumentAttribute(n,t)}
def attributeName:Parser[String]=“a-zA-Z][a-zA-Z0-9\]*”“”.r^^{.toString}
def attributeType:Parser[String]=“a-zA-Z][a-zA-Z0-9\]*”“”.r^^{.toString}
}

看来我对它的定义是正确的。是否有一些明显的我遗漏的东西,或者关于组合子的一些基本的东西我不明白?谢谢

对于
文档
,您必须使用以下代码:

def document : Parser[Document]= "document" ~> documentName ~ ("{" ~> attributeList <~ "}") ^^ {case n ~ l => Document(n, l)}
通过此更改,您的代码可以正常工作:

scala> DocumentParser.document(new CharSequenceReader(
  """ document foo {bar baz, // comment 
    | qaz wsx}""".stripMargin))
res4: DocumentParser.ParseResult[DocumentParser.Document] = [2.10] parsed: Document(foo,List(DocumentAttribute(bar,baz), DocumentAttribute(qaz,wsx)))

谢谢这就解释了为什么括号是必要的。现在一切都好了。实际上,我的代码稍微复杂一些;我需要直接定义属性,或者将其指向另一个文档的属性(基本上是外键)。但在发布任何问题之前,我会先自己尝试一下。再次感谢!
scala> DocumentParser.document(new CharSequenceReader(
  """ document foo {bar baz, // comment 
    | qaz wsx}""".stripMargin))
res4: DocumentParser.ParseResult[DocumentParser.Document] = [2.10] parsed: Document(foo,List(DocumentAttribute(bar,baz), DocumentAttribute(qaz,wsx)))