use crate::ast::*;
use crate::error::{ParseError, ParseResult};
use crate::lexer::tokenize_with_options;
use crate::token::{is_clause_boundary, is_contextual_clause_keyword, Token, TokenType};
use relate_names::SmallName;
pub(crate) use literals::parse_int_literal;
use literals::{IntLiteralError, IntLiteralSite};
struct ConstraintForTarget {
entity_type: SchemaEntityType,
labels: Vec<SmallName>,
variable: SmallName,
source_alias: Option<SmallName>,
target_alias: Option<SmallName>,
}
struct GraphTypeConstraintVerbSpec {
kind: GraphTypeConstraintVerb,
property_type: Option<TypeExpr>,
options: OptionsForm,
}
pub const MAX_QUERY_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_NESTING_DEPTH: u32 = 500;
pub const UNSUPPORTED_ADMINISTRATION_DETAIL: &str = "UnsupportedAdministrationCommand";
pub const UNDEFINED_VARIABLE_DETAIL: &str = "UndefinedVariable";
pub fn parse(input: &str) -> ParseResult<Statement> {
parse_with_options(input, crate::lexer::ParseOptions::default())
}
pub fn parse_with_options(
input: &str,
options: crate::lexer::ParseOptions,
) -> ParseResult<Statement> {
let mut parser = Parser::new(input, "query text", options)?;
parser.parse()
}
pub(crate) fn parse_expression_str_with_options(
input: &str,
options: crate::lexer::ParseOptions,
) -> ParseResult<Expr> {
let mut parser = Parser::new(input, "expression text", options)?;
let expr = parser.parse_expression()?;
if parser.peek().ty != TokenType::EOF {
return Err(parser
.error_at_token(parser.peek(), "unexpected trailing input in expression")
.with_detail("UnexpectedSyntax"));
}
Ok(expr)
}
pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
parse_expression_str_with_options(input, crate::lexer::ParseOptions::default())
}
fn parse_interp_body(
body: &str,
options: crate::lexer::ParseOptions,
) -> Result<Vec<crate::ast::InterpPart>, String> {
use crate::ast::InterpPart;
let chars: Vec<char> = body.chars().collect();
let mut parts: Vec<InterpPart> = Vec::new();
let mut text = String::new();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c == '\\' && i + 1 < chars.len() {
i += push_interp_escape(&mut text, &chars, i)?;
continue;
}
if c != '{' {
text.push(c);
i += 1;
continue;
}
let mut depth = 1usize;
let mut inner_quote: Option<char> = None;
let mut in_backtick = false;
let mut j = i + 1;
while j < chars.len() {
let d = chars[j];
if let Some(q) = inner_quote {
if d == '\\' {
j += 2;
continue;
}
if d == q {
inner_quote = None;
}
} else if in_backtick {
if d == '`' {
in_backtick = false;
}
} else {
match d {
'\\' => j += 1,
'`' => in_backtick = true,
'{' | '[' | '(' => depth += 1,
'}' | ']' | ')' => {
if depth == 0 {
break;
}
depth -= 1;
if d == '}' && depth == 0 {
break;
}
}
'\'' | '"' => inner_quote = Some(d),
_ => {}
}
}
j += 1;
}
if depth != 0 {
return Err("unterminated { expression } in interpolated string".into());
}
let expr_src: String = chars[i + 1..j].iter().collect();
let expr = parse_expression_str_with_options(&expr_src, options)
.map_err(|e| format!("invalid expression in interpolated string: {e}"))?;
if !text.is_empty() {
parts.push(InterpPart::Text(std::mem::take(&mut text)));
}
parts.push(InterpPart::Interp(Box::new(expr)));
i = j + 1;
}
if !text.is_empty() {
parts.push(InterpPart::Text(text));
}
Ok(parts)
}
fn push_interp_escape(text: &mut String, chars: &[char], i: usize) -> Result<usize, String> {
let next = chars[i + 1]; match next {
'\\' => {
text.push('\\');
Ok(2)
}
'{' => {
text.push('{');
Ok(2)
}
'}' => {
text.push('}');
Ok(2)
}
'n' => {
text.push('\n');
Ok(2)
}
't' => {
text.push('\t');
Ok(2)
}
'\'' => {
text.push('\'');
Ok(2)
}
'"' => {
text.push('"');
Ok(2)
}
'u' => {
if i + 6 > chars.len() {
return Err("invalid unicode escape sequence".into());
}
let hex: String = chars[i + 2..i + 6].iter().collect();
match u32::from_str_radix(&hex, 16) {
Ok(cp) => {
if let Some(pair) = interp_surrogate_pair(cp, chars, i) {
text.push(pair.0);
return Ok(pair.1);
}
if let Some(ch) = char::from_u32(cp) {
text.push(ch);
}
Ok(6)
}
Err(_) => Err(format!("invalid unicode escape sequence: \\u{hex}")),
}
}
other => {
text.push('\\');
text.push(other);
Ok(2)
}
}
}
fn interp_surrogate_pair(cp: u32, chars: &[char], i: usize) -> Option<(char, usize)> {
if !(0xD800..=0xDBFF).contains(&cp) || i + 12 > chars.len() {
return None;
}
if chars[i + 6] != '\\' || chars[i + 7] != 'u' {
return None;
}
let hex: String = chars[i + 8..i + 12].iter().collect();
let lo = u32::from_str_radix(&hex, 16).ok()?;
if !(0xDC00..=0xDFFF).contains(&lo) {
return None;
}
char::from_u32(0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00)).map(|ch| (ch, 12))
}
pub fn parse_graph_type_body(canonical: &str) -> ParseResult<GraphTypeBody> {
let wrapped = format!("{{{canonical}}}");
let mut parser = Parser::new(
&wrapped,
"graph type body",
crate::lexer::ParseOptions::default(),
)?;
let (open, body) = parser.parse_graph_type_spec_body()?;
parser.reject_bare_constraint_drops(&open, &body)?;
Ok(body)
}
struct Preamble {
version: Option<u32>,
explain: bool,
profile: bool,
}
const CYPHER_OPTION_KEYS: &[&str] = &[
"planner",
"runtime",
"updatestrategy",
"expressionengine",
"replan",
"connectcomponentsplanner",
"debug",
"operatorengine",
];
const CYPHER_OPTION_VALUES: &[(&str, &[&str])] =
&[("runtime", &["slotted", "pipelined", "parallel"])];
struct Parser<'a> {
source: &'a str,
tokens: Vec<Token<'a>>,
pos: usize,
line_starts: Vec<usize>,
side_effects: PatternSideEffectFlags,
in_when_branch_body: u32,
statement_depth: u32,
block_depth: u32,
expr_depth: u32,
clause_depth: u32,
comprehension_where_ambiguous_pipe: bool,
comprehension_where_map_required: bool,
exists_subquery_depth: u32,
pattern_comprehension_probe_memo: std::collections::HashMap<usize, bool>,
label_group_extent_memo: std::collections::HashMap<(usize, u32), Option<usize>>,
options: crate::lexer::ParseOptions,
label_mix_target: LabelMixTarget,
}
#[derive(Default, Clone, Copy)]
struct PatternSideEffectFlags {
clause_labels: LabelMixFlags,
read_labels: LabelMixFlags,
write_labels: LabelMixFlags,
label_expr_saw_legacy_conjunction: bool,
label_expr_saw_gql_symbol: bool,
label_saw_paren_group: bool,
quantifier_saw_legacy_bracket: bool,
quantifier_saw_gpm_form: bool,
quantifier_comprehension_saw_legacy_bracket: bool,
quantifier_comprehension_saw_gpm_form: bool,
}
#[derive(Default, Clone, Copy)]
struct LabelMixFlags {
legacy_conjunction: bool,
gql_symbol: bool,
is_introducer: bool,
}
impl LabelMixFlags {
fn mixing(&self) -> Option<&'static str> {
if self.legacy_conjunction && self.gql_symbol {
return Some(
"InvalidLabelExpression: mixing label expression symbols (|, &, !, and %) with colon (:) between labels is not allowed",
);
}
if self.legacy_conjunction && self.is_introducer {
return Some(
"MixedIsAndColonConjunction: cannot mix the IS introducer with colon-conjunction within the same clause",
);
}
None
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum LabelMixTarget {
#[default]
None,
Read,
Write,
Both,
}
enum PropertyTargetAccessor {
Static(SmallName),
Dynamic(Expr),
}
macro_rules! depth_guard_family {
(
field = $field:ident,
enter = $enter:ident,
exit = $exit:ident,
with = $with:ident,
enter_doc = $enter_doc:expr,
exit_doc = $exit_doc:expr,
with_doc = $with_doc:expr $(,)?
) => {
#[doc = $enter_doc]
fn $enter(&mut self) -> ParseResult<()> {
if self.$field >= MAX_NESTING_DEPTH {
return Err(self.error(format!(
"maximum nesting depth of {MAX_NESTING_DEPTH} exceeded"
)));
}
self.$field += 1;
Ok(())
}
#[doc = $exit_doc]
fn $exit(&mut self) {
self.$field = self.$field.saturating_sub(1);
}
#[doc = $with_doc]
fn $with<T>(&mut self, f: impl FnOnce(&mut Self) -> ParseResult<T>) -> ParseResult<T> {
self.$enter()?;
let result = f(self);
self.$exit();
result
}
};
}
enum PostfixBase {
Built(Expr, Option<String>),
NsPath(String),
}
impl<'a> Parser<'a> {
fn new(
source: &'a str,
subject: &str,
options: crate::lexer::ParseOptions,
) -> Result<Self, ParseError> {
if source.len() > MAX_QUERY_BYTES {
return Err(ParseError::new(
format!(
"{subject} of {} bytes exceeds the maximum query size of {MAX_QUERY_BYTES} bytes",
source.len()
),
1,
1,
));
}
let tokens = tokenize_with_options(source, options);
Ok(Parser {
source,
line_starts: crate::token::line_starts_of(source),
tokens,
pos: 0,
side_effects: PatternSideEffectFlags::default(),
label_mix_target: LabelMixTarget::None,
in_when_branch_body: 0,
statement_depth: 0,
block_depth: 0,
expr_depth: 0,
clause_depth: 0,
comprehension_where_ambiguous_pipe: false,
comprehension_where_map_required: false,
exists_subquery_depth: 0,
pattern_comprehension_probe_memo: std::collections::HashMap::new(),
label_group_extent_memo: std::collections::HashMap::new(),
options,
})
}
fn eof_token() -> &'static Token<'static> {
static EOF: std::sync::OnceLock<Token<'static>> = std::sync::OnceLock::new();
EOF.get_or_init(|| Token::new(TokenType::EOF, "", 0, 0))
}
fn peek(&self) -> &Token<'a> {
self.peek_at(0)
}
fn peek_type(&self) -> TokenType {
self.peek().ty
}
fn peek_at(&self, offset: usize) -> &Token<'a> {
let idx = self.pos + offset;
if idx >= self.tokens.len() {
Self::eof_token()
} else {
&self.tokens[idx]
}
}
pub(super) fn peek_is_ident(&self, word: &str) -> bool {
self.peek_at_is_ident(0, word)
}
pub(super) fn peek_at_is_ident(&self, offset: usize, word: &str) -> bool {
Self::token_is_ident(self.peek_at(offset), word)
}
pub(super) fn token_is_ident(tok: &Token, word: &str) -> bool {
tok.ty == TokenType::Identifier && tok.literal.eq_ignore_ascii_case(word)
}
pub(super) fn all_is_set_quantifier(&self) -> bool {
self.peek_type() == TokenType::ALL && self.peek_at(1).ty != TokenType::LeftParen
}
fn next_token(&mut self) -> Token<'a> {
if self.pos >= self.tokens.len() {
Self::eof_token().clone()
} else {
let tok = self.tokens[self.pos].clone();
self.pos += 1;
tok
}
}
fn backup(&mut self) {
if self.pos > 0 {
self.pos -= 1;
}
}
fn save_pos(&self) -> usize {
self.pos
}
fn restore_pos(&mut self, pos: usize) {
self.pos = pos;
}
fn extract_namespace(expr: &Expr) -> Option<String> {
match expr {
Expr::Variable(name) => Some(name.with_str(str::to_owned)),
Expr::Property(prop) => {
Self::extract_namespace(&prop.expr).map(|ns| format!("{}.{}", ns, prop.property))
}
_ => None,
}
}
fn expect(&mut self, ty: TokenType) -> ParseResult<Token<'a>> {
let tok = self.next_token();
if tok.ty != ty {
return Err(self.error_at_token(
&tok,
format!("expected {:?}, got {:?} ({:?})", ty, tok.literal, tok.ty),
));
}
Ok(tok)
}
fn expect_detail(&mut self, ty: TokenType, detail: &'static str) -> ParseResult<Token<'a>> {
let tok = self.next_token();
if tok.ty != ty {
return Err(self
.error_at_token(
&tok,
format!("expected {:?}, got {:?} ({:?})", ty, tok.literal, tok.ty),
)
.with_detail(detail));
}
Ok(tok)
}
fn error(&self, msg: impl Into<String>) -> ParseError {
let tok = self.peek();
self.error_at_token(tok, msg)
}
fn error_at_token(&self, tok: &Token, msg: impl Into<String>) -> ParseError {
let err = ParseError::new(msg, tok.line, tok.col).with_source(self.source);
match tok.detail {
Some(detail) => err.with_detail(detail),
None => err,
}
}
fn internal_error(&self, msg: impl Into<String>) -> ParseError {
self.error(format!("internal parser error: {}", msg.into()))
}
depth_guard_family! {
field = expr_depth,
enter = enter_expr_depth,
exit = exit_expr_depth,
with = with_expr_depth,
enter_doc = "ADR-0257: enter one level of expression nesting. \
Returns a typed error naming the limit once [`MAX_NESTING_DEPTH`] \
levels are already active, instead of recursing until the process \
aborts (LABS-69). On error the counter is left unchanged, so a \
speculative re-parse at a shallower position is not poisoned.",
exit_doc = "Pairs with [`Parser::enter_expr_depth`]; must run on \
every exit path (including error propagation) so \
backtracking/speculative parses keep the counter balanced.",
with_doc = "Runs `f` one expression-nesting level deep: the only \
sanctioned way to guard a recursive expression-shaped parse with \
`expr_depth`. The enter/exit pair is balanced by construction -- \
`f`'s result (including error propagation) is captured, the \
counter is decremented, and only then is the result returned, so \
no `?` can ever sit between enter and exit.",
}
depth_guard_family! {
field = clause_depth,
enter = enter_clause_depth,
exit = exit_clause_depth,
with = with_clause_depth,
enter_doc = "ADR-0257: enter one level of clause nesting. Returns a \
typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
are already active, instead of recursing until the process aborts \
(LABS-69: nested FOREACH bodies recurse through `parse_clause` \
without passing through `parse_statement`). On error the counter \
is left unchanged, so a speculative re-parse at a shallower \
position is not poisoned.",
exit_doc = "Pairs with [`Parser::enter_clause_depth`]; must run on \
every exit path (including error propagation) so sequential \
clauses in one statement/FOREACH body do not accumulate.",
with_doc = "[`Parser::with_expr_depth`] for `clause_depth`.",
}
depth_guard_family! {
field = statement_depth,
enter = enter_statement_depth,
exit = exit_statement_depth,
with = with_statement_depth,
enter_doc = "ADR-0257: enter one level of statement nesting. Returns \
a typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
are already active, instead of recursing until the process aborts \
(LABS-69). On error the counter is left unchanged, so a \
speculative re-parse at a shallower position is not poisoned.",
exit_doc = "Pairs with [`Parser::enter_statement_depth`]; must run on \
every exit path (including error propagation) so \
backtracking/speculative parses keep the counter balanced.",
with_doc = "[`Parser::with_expr_depth`] for `statement_depth`.",
}
depth_guard_family! {
field = block_depth,
enter = enter_block_depth,
exit = exit_block_depth,
with = with_block_depth,
enter_doc = "ADR-0257: enter one level of statement-block nesting. \
Returns a typed error naming the limit once \
[`MAX_NESTING_DEPTH`] levels are already active, instead of \
recursing until the process aborts (LABS-69: braced single \
queries and WHEN/ELSE bodies recurse through \
`parse_statement_block` without passing through \
`parse_statement`, `parse_clause`, or `parse_expression`). On \
error the counter is left unchanged, so a speculative re-parse \
at a shallower position is not poisoned.",
exit_doc = "Pairs with [`Parser::enter_block_depth`]; must run on \
every exit path (including error propagation) so sequential NEXT \
stages in one block and backtracking/speculative parses keep the \
counter balanced.",
with_doc = "[`Parser::with_expr_depth`] for `block_depth`.",
}
fn parse_u32_bound(&self, tok: &Token, what: &str) -> ParseResult<u32> {
let site = IntLiteralSite::Bounded {
what,
max: u64::from(u32::MAX),
};
let value = parse_int_literal(&tok.literal)
.map_err(|error| self.int_literal_error(tok, error, site))?;
u32::try_from(value)
.map_err(|_| self.int_literal_error(tok, IntLiteralError::Overflow, site))
}
fn parse(&mut self) -> ParseResult<Statement> {
let preamble = self.parse_preamble()?;
let mut stmt = self.parse_statement_block()?;
stmt.explain = preamble.explain;
stmt.profile = preamble.profile;
stmt.cypher_version = preamble.version;
if self.peek_type() == TokenType::Semicolon {
self.next_token();
}
if self.peek_type() != TokenType::EOF {
return Err(self.error(format!("unexpected token {:?}", self.peek().literal)));
}
Ok(stmt)
}
fn parse_preamble(&mut self) -> ParseResult<Preamble> {
let mut version: Option<u32> = None;
let mut options: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
let mut explain = false;
let mut profile = false;
loop {
match self.peek_type() {
TokenType::EXPLAIN if !explain && !profile => {
self.next_token();
explain = true;
}
TokenType::PROFILE if !explain && !profile => {
self.next_token();
profile = true;
}
TokenType::Identifier if self.peek().literal.eq_ignore_ascii_case("cypher") => {
self.next_token();
if matches!(self.peek_type(), TokenType::Integer | TokenType::Float) {
let tok = self.next_token();
if tok.ty != TokenType::Integer
|| (tok.literal != "5" && tok.literal != "25")
{
return Err(self.error_at_token(
&tok,
format!(
"SyntaxError: 22N10 invalid pre-parser option value: {:?} is not a valid cypher version",
tok.literal
),
));
}
let v: u32 = tok.literal.parse().unwrap();
match version {
Some(existing) if existing != v => {
return Err(self.error_at_token(
&tok,
"SyntaxError: 22N09 conflicting pre-parser combination: multiple values for 'cypher version'",
));
}
_ => version = Some(v),
}
}
while self.peek_type() == TokenType::Identifier
&& self.peek_at(1).ty == TokenType::Equals
{
let key_tok = self.next_token();
self.next_token(); let value_tok = self.next_token();
let key_lower = key_tok.literal.to_ascii_lowercase();
if !CYPHER_OPTION_KEYS.contains(&key_lower.as_str()) {
return Err(self.error_at_token(
&key_tok,
format!(
"SyntaxError: 22N07 invalid pre-parser option key: {:?}",
key_tok.literal
),
));
}
if let Some((_, values)) = CYPHER_OPTION_VALUES
.iter()
.find(|(key, _)| *key == key_lower)
{
if !values.contains(&value_tok.literal.to_ascii_lowercase().as_str()) {
return Err(self.error_at_token(
&value_tok,
format!(
"SyntaxError: 22N10 invalid pre-parser option value: {:?} is not a valid {} value (valid values: {})",
value_tok.literal,
key_tok.literal,
values.join(", ")
),
));
}
}
match options.get(&key_lower) {
Some(existing) if existing != &value_tok.literal => {
return Err(self.error_at_token(
&value_tok,
format!(
"SyntaxError: 22N09 conflicting pre-parser combination: multiple values for {:?}",
key_tok.literal
),
));
}
_ => {
options.insert(key_lower, value_tok.literal.into_owned());
}
}
}
}
_ => break,
}
}
Ok(Preamble {
version,
explain,
profile,
})
}
fn parse_regular_query(&mut self) -> ParseResult<Statement> {
if self.peek_type() == TokenType::WHEN {
return self.parse_when_query();
}
let mut stmt = self.parse_single_query()?;
if self.peek_type() != TokenType::UNION {
return Ok(stmt);
}
stmt = Self::maybe_wrap_composite_union_arm(stmt);
while self.peek_type() == TokenType::UNION {
self.next_token();
let all = if self.peek_type() == TokenType::ALL {
self.next_token();
true
} else {
if self.peek_type() == TokenType::DISTINCT {
self.next_token();
}
false
};
let next_stmt = self.parse_single_query()?;
let next_stmt = Self::maybe_wrap_composite_union_arm(next_stmt);
let mut current = &mut stmt;
while current.union.is_some() {
current = &mut current.union.as_mut().unwrap().statement;
}
current.union = Some(Box::new(UnionPart {
all,
statement: next_stmt,
}));
}
Ok(stmt)
}
fn at_next_keyword(&self) -> bool {
self.peek_type() == TokenType::Identifier
&& self.peek().literal.eq_ignore_ascii_case("next")
}
fn parse_statement_block(&mut self) -> ParseResult<Statement> {
self.with_block_depth(Self::parse_statement_block_at_current_depth)
}
fn parse_statement_block_at_current_depth(&mut self) -> ParseResult<Statement> {
if self.at_next_keyword() {
return Err(
self.error("InvalidNextStatement: NEXT must follow a statement, not begin one")
);
}
let saved_in_when_branch_body = std::mem::take(&mut self.in_when_branch_body);
let definitions = self.parse_local_definitions()?;
let result = self.parse_statement_block_inner();
self.in_when_branch_body = saved_in_when_branch_body;
let mut result = result?;
result.definitions.splice(0..0, definitions);
Ok(result)
}
fn parse_statement_block_inner(&mut self) -> ParseResult<Statement> {
let mut stmt = self.parse_regular_query()?;
let mut tail = &mut stmt;
while tail.next.is_some() {
tail = tail.next.as_mut().unwrap();
}
while self.at_next_keyword() {
self.next_token(); if self.at_next_keyword() {
return Err(self.error(
"InvalidNextStatement: NEXT cannot be immediately followed by another NEXT",
));
}
if matches!(
self.peek_type(),
TokenType::EOF | TokenType::Semicolon | TokenType::RightBrace | TokenType::UNION
) {
return Err(
self.error("InvalidNextStatement: NEXT must be followed by a statement")
);
}
let next_stmt = self.parse_regular_query()?;
tail.next = Some(Box::new(next_stmt));
tail = tail.next.as_mut().unwrap();
}
Ok(stmt)
}
fn maybe_wrap_composite_union_arm(arm: Statement) -> Statement {
if arm.union.is_none() && arm.next.is_none() {
return arm;
}
let mut tail = &arm;
while let Some(next_stmt) = &tail.next {
tail = next_stmt;
}
let tabular = tail.clauses.iter().any(|c| matches!(c, Clause::Return(_)));
let trailer = if tabular {
Clause::Return(ReturnClause {
group_by: None,
distinct: false,
items: vec![ReturnItem {
expr: Expr::Star,
alias: None,
all: true,
source_text: None,
}],
order_by: Vec::new(),
skip: None,
limit: None,
})
} else {
Clause::Finish
};
Statement {
clauses: vec![
Clause::CallSubquery(CallSubqueryClause {
statement: arm,
scope: CallScope::Wildcard,
optional: false,
in_transactions: None,
}),
trailer,
],
union: None,
explain: false,
profile: false,
next: None,
cypher_version: None,
brace_wrapped: false,
definitions: Vec::new(),
}
}
fn parse_single_query(&mut self) -> ParseResult<Statement> {
if self.peek_type() == TokenType::LeftBrace {
return self.parse_braced_single_query(None);
}
if self.peek_type() == TokenType::Identifier
&& self.peek().literal.eq_ignore_ascii_case("use")
{
let save = self.save_pos();
let use_clause = self.parse_use()?;
if self.peek_type() == TokenType::LeftBrace {
return self.parse_braced_single_query(Some(use_clause.graph_expr));
}
self.restore_pos(save);
}
self.parse_statement()
}
fn parse_braced_single_query(&mut self, use_prefix: Option<Expr>) -> ParseResult<Statement> {
let brace_tok = self.next_token(); if self.peek_type() == TokenType::RightBrace {
return Err(self.error_at_token(
&brace_tok,
"InvalidInput: empty braces `{ }` are not a valid query body",
));
}
let mut inner = self.parse_statement_block()?;
self.expect(TokenType::RightBrace)?;
inner.brace_wrapped = true;
if let Some(graph_expr) = use_prefix {
let mut cur = &mut inner;
loop {
cur.clauses.insert(
0,
Clause::Use(UseClause {
graph_expr: graph_expr.clone(),
}),
);
if cur.union.is_some() {
cur = &mut cur.union.as_mut().unwrap().statement;
} else {
break;
}
}
}
Ok(inner)
}
fn parse_when_query(&mut self) -> ParseResult<Statement> {
let mut branches = Vec::new();
loop {
self.expect(TokenType::WHEN)?;
let predicate = self.parse_expression()?;
self.expect(TokenType::THEN)?;
let body = self.parse_when_branch_body()?;
branches.push(WhenBranch { predicate, body });
if self.peek_type() != TokenType::WHEN {
break;
}
}
let else_body = if self.peek_type() == TokenType::ELSE {
self.next_token();
Some(self.parse_when_branch_body()?)
} else {
None
};
Ok(Statement {
clauses: vec![Clause::Conditional(ConditionalClause {
branches,
else_body,
})],
..Statement::default()
})
}
fn parse_when_branch_body(&mut self) -> ParseResult<Statement> {
self.in_when_branch_body += 1;
let body = self.parse_single_query();
self.in_when_branch_body -= 1;
body
}
fn parse_statement(&mut self) -> ParseResult<Statement> {
self.with_statement_depth(Self::parse_statement_at_current_depth)
}
fn parse_statement_at_current_depth(&mut self) -> ParseResult<Statement> {
let mut stmt = Statement {
clauses: Vec::new(),
..Statement::default()
};
loop {
match self.peek_type() {
TokenType::EOF
| TokenType::Semicolon
| TokenType::UNION
| TokenType::RightBrace
| TokenType::ELSE => {
if self.peek_type() == TokenType::Semicolon {
self.next_token();
}
break;
}
TokenType::WHEN if self.in_when_branch_body > 0 => break,
_ if self.at_next_keyword() => break,
_ => {
let clause = self.parse_clause()?;
stmt.clauses.push(clause);
}
}
}
self.check_label_set_mixing(&stmt.clauses)?;
Ok(stmt)
}
fn check_label_set_mixing(&self, clauses: &[Clause]) -> ParseResult<()> {
for clause in clauses {
let items: Vec<(bool, usize)> = match clause {
Clause::Set(sc) => sc
.items
.iter()
.filter(|i| !i.labels.is_empty())
.map(|i| (i.is_keyword, i.labels.len()))
.collect(),
Clause::Remove(rc) => rc
.items
.iter()
.filter(|i| !i.labels.is_empty())
.map(|i| (i.is_keyword, i.labels.len()))
.collect(),
_ => continue,
};
let mut saw_is = false;
let mut saw_colon_conjunction = false;
for (is_keyword, len) in items {
if is_keyword {
saw_is = true;
} else if len > 1 {
saw_colon_conjunction = true;
}
}
if saw_is && saw_colon_conjunction {
return Err(self.error(
"MixedIsAndColonConjunction: cannot mix IS and colon-conjunction across SET/REMOVE label items in the same clause",
));
}
}
Ok(())
}
}
mod case;
mod clauses;
mod definitions;
mod expressions;
mod labels;
mod literals;
mod names;
mod patterns;
pub use patterns::selector_is_selective;
mod schema;
mod search;
mod show;
mod types;
#[cfg(test)]
mod tests;
fn contains_quantification(elements: &[PatternElement]) -> bool {
elements.iter().any(|e| match e {
PatternElement::Quantified(_) => true,
PatternElement::Relationship(rp) => rp.is_variable_length(),
PatternElement::Node(_) => false,
})
}
fn contains_gpm_quantification(elements: &[PatternElement]) -> bool {
elements.iter().any(|e| match e {
PatternElement::Quantified(_) => true,
PatternElement::Relationship(rp) => rp.quantified,
PatternElement::Node(_) => false,
})
}
fn comparison_op(ty: TokenType) -> Option<&'static str> {
match ty {
TokenType::Equals => Some(EQUALS),
TokenType::NotEquals => Some("<>"),
TokenType::LessThan => Some("<"),
TokenType::GreaterThan => Some(">"),
TokenType::LessEqual => Some("<="),
TokenType::GreaterEqual => Some(">="),
TokenType::RegexMatch => Some("=~"),
_ => None,
}
}
const EQUALS: &str = "=";
const OR: &str = "OR";
const XOR: &str = "XOR";
const AND: &str = "AND";
const NOT: &str = "NOT";
const PLUS: &str = "+";
const MINUS: &str = "-";
const CONCAT: &str = "||";
const MUL: &str = "*";
const DIV: &str = "/";
const MOD: &str = "%";
const POW: &str = "^";
const STARTS_WITH: &str = "STARTS WITH";
const ENDS_WITH: &str = "ENDS WITH";
const CONTAINS: &str = "CONTAINS";
#[cfg(test)]
std::thread_local! {
static SPECULATIVE_COMPREHENSION_PARSES: std::cell::Cell<usize> =
const { std::cell::Cell::new(0) };
}