Created
March 28, 2025 09:01
-
-
Save dacr/4a9d693167458f7043e0f64c1ef3ba92 to your computer and use it in GitHub Desktop.
com-lihaoyi fastparse basic usage examples - new line issue ? / published by https://github.com/dacr/code-examples-manager #ec19b756-24fa-49b6-8654-1113b9e2fd6b/f4e34ffc37cad4b80adec8d6c115828e4387619c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : com-lihaoyi fastparse basic usage examples - new line issue ? | |
// keywords : scala, lihaoyi, fastparse, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : ec19b756-24fa-49b6-8654-1113b9e2fd6b | |
// created-on : 2025-03-12T13:45:14+01:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.6.4" | |
//> using dep "com.lihaoyi::fastparse:3.1.1" | |
//> using dep "com.lihaoyi::pprint:0.9.0" | |
// --------------------- | |
// https://github.com/com-lihaoyi/fastparse/issues/327 | |
// IN FACT NOT A BUG => Use ~~ instead of ~ non-whitespace-consuming | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment