Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

strange behavior, last newline is being captured although MultiLineWhitespace is used #327

Closed
dacr opened this issue Mar 12, 2025 · 3 comments

Comments

@dacr
Copy link

dacr commented Mar 12, 2025

Using this script :

//> using scala "3.6.4"
//> using dep "com.lihaoyi::fastparse:3.1.1"
//> using dep "com.lihaoyi::pprint:0.9.0"

import fastparse.*, MultiLineWhitespace.*, pprint.pprintln

case class MatchNode(variableName: Option[String], labels: Seq[String])
case class MatchSection(matchNode: MatchNode)
case class ReturnSection(returnExpressions: String)
case class Statement(matchSection: MatchSection, returnSection: ReturnSection)

def pVariableName[$: P]: P[String] =
  P((CharIn("_a-zA-Z") ~ CharsWhileIn("_a-zA-Z0-9", 0)).!)

def pLabel[$: P]: P[String] =
  P((CharIn("_a-zA-Z") ~ CharsWhileIn("_a-zA-Z0-9", 0)).!)

def pMatchExpression[$: P]: P[MatchNode] =
  P("(" ~ pVariableName.!.? ~ (":" ~ pLabel.!).rep ~ ")")
    .map((variableName, labels) => MatchNode(variableName, labels))

def pMatchSection[$: P]: P[MatchSection] =
  P("MATCH" ~ pMatchExpression)
    .map(expression => MatchSection(expression))

def pReturnSection[$: P]: P[ReturnSection] =
  P("RETURN" ~ pVariableName.!)
    .map(v => ReturnSection(v))

def pStatement[$: P]: P[Statement] =
  P(pMatchSection ~ pReturnSection ~ End)
    .map((ms, rs) => Statement(ms, rs))


val input =
  """MATCH (n)
    |RETURN n
    |""".stripMargin

val result = parse(input, p => pStatement(using p))
pprintln(result)
pprintln(result.get.value.returnSection.returnExpressions)

I get "n\n" as response for the RETURN n part :

Image

@dacr
Copy link
Author

dacr commented Mar 12, 2025

(Of course going to do .stripMargin.trim as workaround)

@dacr
Copy link
Author

dacr commented Mar 12, 2025

sorry found the issue, it is the way I've written my parser

@dacr dacr closed this as completed Mar 12, 2025
@dacr
Copy link
Author

dacr commented Mar 12, 2025

for the posterity, the fix is to use ~~ (non-whitespace-consuming):

def pVariableName[$: P]: P[String] =
  P((CharIn("_a-zA-Z") ~~ CharsWhileIn("_a-zA-Z0-9", 0)).!)

def pLabel[$: P]: P[String] =
  P((CharIn("_a-zA-Z") ~~ CharsWhileIn("_a-zA-Z0-9", 0)).!)

@dacr dacr changed the title strange behavior, last new line is being captured although MultiLineWhitespace is used strange behavior, last newline is being captured although MultiLineWhitespace is used Mar 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant