use crate::ast::*;
use crate::error::{ParseError, ParseResult, SUPPORTED_CYPHER_VERSION};
use crate::lexer::tokenize_with_options;
use crate::token::{is_clause_boundary, is_contextual_clause_keyword, Token, TokenType};
use relate_names::SmallName;
use interp::parse_interp_body;
use is_predicate::{IsLabelPolicy, Suffix};
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())
}
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)
}
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,
expression_labels: LabelMixFlags,
label_saw_paren_group: bool,
quantifiers: QuantifierForms,
comprehension_quantifiers: QuantifierForms,
}
#[derive(Default, Clone, Copy)]
struct QuantifierForms {
legacy_bracket: bool,
gpm_form: bool,
}
impl QuantifierForms {
fn mixed(self) -> bool {
self.legacy_bracket && self.gpm_form
}
fn absorb(&mut self, other: Self) {
self.legacy_bracket |= other.legacy_bracket;
self.gpm_form |= other.gpm_form;
}
}
#[derive(Default, Clone, Copy)]
struct LabelMixFlags {
legacy_conjunction: bool,
gql_symbol: bool,
is_introducer: bool,
}
impl LabelMixFlags {
fn within_expression_mixing(&self) -> bool {
self.legacy_conjunction && self.gql_symbol
}
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.expected_token_error(ty, &tok));
}
Ok(tok)
}
fn expected_token_error(&self, ty: TokenType, tok: &Token) -> ParseError {
self.error_at_token(
tok,
format!("expected {:?}, got {:?} ({:?})", ty, tok.literal, tok.ty),
)
}
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.expected_token_error(ty, &tok).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))
}
}
mod case;
mod clauses;
mod definitions;
mod expressions;
mod interp;
mod is_predicate;
mod labels;
mod literals;
mod names;
mod patterns;
pub use patterns::selector_is_selective;
mod schema;
mod search;
mod show;
mod statement;
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) };
}