1#ifndef IMPULSE_CYPHER_HPP
2#define IMPULSE_CYPHER_HPP
71 explicit CypherLexer(std::string source) : src_(std::move(source)) {}
74 skip_whitespace_and_comments();
80 size_t start_pos = cursor_;
81 int start_line = line_;
133 return scan_parameter(start_pos, start_line, start_col);
136 return scan_backticked_identifier(start_pos, start_line, start_col);
140 return scan_string(c, start_pos, start_line, start_col);
143 if (std::isdigit(
static_cast<unsigned char>(c))) {
144 return scan_number(start_pos, start_line, start_col);
146 if (std::isalpha(
static_cast<unsigned char>(c)) || c ==
'_') {
147 return scan_identifier_or_keyword(start_pos, start_line, start_col);
159 CypherToken scan_parameter(
size_t start_pos,
int start_line,
int start_col) {
160 while (!is_at_end() && (std::isalnum(
static_cast<unsigned char>(peek())) || peek() ==
'_')) {
163 return {
CypherTokenType::PARAM, src_.substr(start_pos, cursor_ - start_pos), start_pos, start_line, start_col};
166 CypherToken scan_backticked_identifier(
size_t start_pos,
int start_line,
int start_col) {
167 size_t content_start = cursor_;
168 while (!is_at_end() && peek() !=
'`') {
169 if (peek() ==
'\n') { line_++; col_ = 1; }
175 std::string lexeme = src_.substr(content_start, cursor_ - content_start);
180 CypherToken scan_string(
char quote,
size_t start_pos,
int start_line,
int start_col) {
181 size_t content_start = cursor_;
182 while (!is_at_end() && peek() != quote) {
183 if (peek() ==
'\n') { line_++; col_ = 1; }
189 std::string content = src_.substr(content_start, cursor_ - content_start);
194 CypherToken scan_number(
size_t start_pos,
int start_line,
int start_col) {
195 while (!is_at_end() && std::isdigit(
static_cast<unsigned char>(peek()))) {
198 if (!is_at_end() && peek() ==
'.' && std::isdigit(
static_cast<unsigned char>(peek_next()))) {
200 while (!is_at_end() && std::isdigit(
static_cast<unsigned char>(peek()))) {
207 CypherToken scan_identifier_or_keyword(
size_t start_pos,
int start_line,
int start_col) {
208 while (!is_at_end() && (std::isalnum(
static_cast<unsigned char>(peek())) || peek() ==
'_' || peek() ==
'>')) {
211 std::string lexeme = src_.substr(start_pos, cursor_ - start_pos);
212 std::string upper = lexeme;
213 std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
232 return {type, lexeme, start_pos, start_line, start_col};
235 void skip_whitespace_and_comments() {
236 while (!is_at_end()) {
250 if (peek_next() ==
'/') {
251 while (!is_at_end() && peek() !=
'\n') {
264 bool is_at_end()
const {
return cursor_ >= src_.size(); }
265 char advance() { col_++;
return src_[cursor_++]; }
266 bool match(
char expected) {
267 if (is_at_end() || src_[cursor_] != expected)
return false;
272 char peek()
const {
return is_at_end() ?
'\0' : src_[cursor_]; }
273 char peek_next()
const {
return (cursor_ + 1 >= src_.size()) ?
'\0' : src_[cursor_ + 1]; }
352 std::vector<CypherWherePredicate> where_predicates;
354 where_predicates = parse_where_clause();
359 parse_with_clause(where_predicates);
367 order_by = parse_order_by_clause();
370 order_by.
limit = std::stoi(curr_.lexeme);
376 return {path, where_predicates, projection, order_by};
382 std::string count_alias_;
384 static std::string to_lower_str(std::string s) {
385 std::transform(s.begin(), s.end(), s.begin(),
386 [](
unsigned char c) { return static_cast<char>(std::tolower(c)); });
390 void parse_with_clause(std::vector<CypherWherePredicate>& where_predicates) {
399 count_alias_ = curr_.
lexeme;
408 auto extra = parse_where_clause();
409 for (
auto& p : extra) where_predicates.push_back(std::move(p));
413 CypherPathPattern parse_path_pattern() {
414 CypherNodePattern start_node = parse_node_pattern();
415 std::vector<CypherPathStep> steps;
418 bool is_forward =
true;
419 bool is_undirected =
false;
428 std::string edge_var;
434 consume(
CypherTokenType::COLON,
"Typed Edge Walk Mandate: Relationship type is mandatory (e.g. [:RelName])");
436 throw std::runtime_error(
"Expected relationship name after ':', got: " + curr_.lexeme);
438 std::string rel_name = curr_.lexeme;
439 std::vector<std::string> rel_names = {rel_name};
445 throw std::runtime_error(
"Expected relationship name after '|', got: " + curr_.lexeme);
447 rel_names.push_back(curr_.lexeme);
453 bool is_unbounded =
false;
456 min_hops = std::stoi(curr_.lexeme);
460 max_hops = std::stoi(curr_.lexeme);
463 throw std::runtime_error(
"Unbounded Traversal Mandate: Upper bound required (e.g. *1..4)");
470 max_hops = std::stoi(curr_.lexeme);
473 throw std::runtime_error(
"Unbounded Traversal Mandate: Upper bound required (e.g. *..4)");
483 throw std::runtime_error(
"Cypher min_hops must be >= 0");
486 if (max_hops < min_hops) {
487 throw std::runtime_error(
"Cypher max_hops cannot be less than min_hops");
490 throw std::runtime_error(
"Cypher variable-length path unrolling max_hops exceeds limit of 64");
499 is_undirected =
false;
501 is_undirected =
true;
506 CypherNodePattern target_node = parse_node_pattern();
507 steps.push_back({{edge_var, rel_name, is_forward, min_hops, max_hops, std::move(rel_names), is_undirected, is_unbounded}, target_node});
510 return {start_node, steps};
513 CypherNodePattern parse_node_pattern() {
526 label = curr_.lexeme;
535 std::string consume_comparison_op() {
536 std::string op = curr_.lexeme;
540 throw std::runtime_error(
"Unsupported operator in WHERE clause: " + curr_.lexeme);
545 std::vector<uint64_t> parse_u64_list() {
547 std::vector<uint64_t> vals;
550 vals.push_back(std::stoull(curr_.lexeme));
559 std::vector<float> parse_float_list_or_param(std::string& out_param) {
561 out_param = curr_.lexeme;
566 std::vector<float> vals;
570 float v = std::stof(curr_.lexeme);
571 vals.push_back(neg ? -v : v);
582 static constexpr size_t MAX_PARSE_DEPTH = 256;
584 std::vector<CypherWherePredicate> parse_where_clause() {
585 std::vector<CypherWherePredicate> preds;
586 size_t pred_count = 0;
588 if (++pred_count > MAX_PARSE_DEPTH) {
589 throw std::runtime_error(
"Cypher WHERE predicate count exceeded limit 256");
593 std::string var = curr_.lexeme;
596 std::string op = consume_comparison_op();
597 uint16_t k =
static_cast<uint16_t
>(std::stoul(curr_.lexeme));
599 preds.push_back({var,
"quorum", op, std::to_string(k), {k}, {}, k});
604 throw std::runtime_error(
"Expected identifier in WHERE clause, got: " + curr_.lexeme);
606 std::string var = curr_.lexeme;
608 std::string var_lower = to_lower_str(var);
611 std::string target_var = curr_.lexeme;
618 auto q_vec = parse_float_list_or_param(q_param);
621 k =
static_cast<uint16_t
>(std::stoul(curr_.lexeme));
625 preds.push_back({target_var,
"vector_ann",
"ANN", q_param.empty() ? std::to_string(k) : q_param, {}, std::move(q_vec), k});
629 if (var_lower ==
"quorum" || (!count_alias_.empty() && var == count_alias_)) {
630 std::string target_var = var;
632 target_var = curr_.
lexeme;
636 std::string op = consume_comparison_op();
637 uint16_t k =
static_cast<uint16_t
>(std::stoul(curr_.
lexeme));
639 preds.push_back({target_var,
"quorum", op, std::to_string(k), {k}, {}, k});
645 throw std::runtime_error(
"Expected property name after '.', got: " + curr_.
lexeme);
647 std::string prop = curr_.
lexeme;
651 auto in_vals = parse_u64_list();
652 preds.push_back({var, prop,
"IN",
"IN_LIST", std::move(in_vals), {}, 0});
656 std::string op = consume_comparison_op();
658 std::string val_or_param = curr_.
lexeme;
663 throw std::runtime_error(
"Expected parameter ($param) or literal in WHERE predicate, got: " + curr_.
lexeme);
666 if (to_lower_str(prop) ==
"quorum") {
667 uint16_t k =
static_cast<uint16_t
>(std::stoul(val_or_param));
668 preds.push_back({var,
"quorum", op, val_or_param, {k}, {}, k});
670 preds.push_back({var, prop, op, val_or_param, {}, {}, 0});
679 std::string fn_or_var = curr_.
lexeme;
683 clause.target_var = fn_or_var;
686 std::string fn_low = to_lower_str(fn_or_var);
687 if (fn_low.find(
"l2") != std::string::npos) clause.metric = 1;
688 else if (fn_low.find(
"cos") != std::string::npos) clause.metric = 2;
689 else if (fn_low.find(
"ham") != std::string::npos) clause.metric = 3;
690 else clause.metric = 0;
692 clause.target_var = curr_.
lexeme;
695 clause.attr_name = curr_.
lexeme;
699 clause.query_vector = parse_float_list_or_param(clause.query_param);
703 clause.attr_name = curr_.
lexeme;
711 clause.limit = std::stoi(curr_.
lexeme);
720 std::string var = curr_.
lexeme;
730 proj.attr_name = attr;
732 proj.is_count =
true;
736 std::string fn_name = curr_.
lexeme;
737 std::string fn_lower = to_lower_str(fn_name);
738 if (fn_lower ==
"sum" || fn_lower ==
"min" || fn_lower ==
"max" ||
739 fn_lower ==
"argmin" || fn_lower ==
"argmax") {
742 std::string var = curr_.
lexeme;
752 proj.attr_name = attr;
762 std::string var = curr_.
lexeme;
765 bool is_attr =
false;
773 proj.attr_name = attr;
774 proj.is_attr = is_attr;
778 throw std::runtime_error(
"Expected return target variable, attribute, or aggregate, got: " + curr_.
lexeme);
781 void advance() { curr_ = lexer_.
next_token(); }
783 if (curr_.
type == type) {
790 if (curr_.
type == type) {
794 throw std::runtime_error(error_msg +
" [Line " + std::to_string(curr_.
line) +
":" + std::to_string(curr_.
col) +
" at '" + curr_.
lexeme +
"']");
801 std::shared_ptr<ScmProgram>
ast;
815 throw std::runtime_error(
"Cypher query complexity exceeded limit 256");
817 std::vector<AstPtr> steps;
819 std::string seed_val_or_param;
820 std::vector<uint64_t> multi_seeds;
822 uint16_t quorum_k = 0;
825 if (pred.op ==
"IN" && !pred.in_values.empty() && (seed_var.empty() || pred.target_var == seed_var)) {
826 multi_seeds = pred.in_values;
827 seed_val_or_param = pred.value_or_param;
828 }
else if (pred.op ==
"ANN" && pred.field ==
"vector_ann") {
829 vector_ann_pred = &pred;
830 }
else if (pred.field ==
"quorum" && pred.top_k > 0) {
831 quorum_k = pred.top_k;
832 }
else if (pred.target_var == seed_var) {
833 seed_val_or_param = pred.value_or_param;
837 bool multi_lane_mode = !multi_seeds.empty() || (vector_ann_pred !=
nullptr && quorum_k > 0);
839 if (!multi_seeds.empty()) {
841 }
else if (vector_ann_pred !=
nullptr) {
842 steps.push_back(std::make_shared<ScmVectorAnnSearch>(
843 2, vector_ann_pred->
top_k, 0, multi_lane_mode));
846 for (
const auto& step : query.
path.
steps) {
847 const auto& edge = step.edge;
848 if (edge.max_hops > 64) {
849 throw std::runtime_error(
"Cypher variable-length path unrolling max_hops exceeds limit of 64");
851 std::vector<std::string> rels = edge.relation_names.empty()
852 ? std::vector<std::string>{edge.relation_name}
853 : edge.relation_names;
855 if (multi_lane_mode) {
856 bool fp = edge.is_unbounded;
857 int hops = fp ? 1 : std::max(1, edge.max_hops);
858 for (
int h = 0; h < hops; ++h) {
859 for (
const auto& r : rels) {
860 if (edge.is_undirected) {
863 }
else if (edge.is_forward) {
871 auto build_single_hop = [&]() ->
AstPtr {
872 std::vector<AstPtr> branches;
873 for (
const auto& r : rels) {
874 if (edge.is_undirected) {
877 }
else if (edge.is_forward) {
884 for (
size_t i = 1; i < branches.size(); ++i) {
890 if (edge.is_unbounded) {
891 steps.push_back(std::make_shared<ScmFixpoint>(
ScmProgram::of(build_single_hop())));
893 int hops = std::max(1, edge.max_hops);
894 for (
int h = 0; h < hops; ++h) {
895 steps.push_back(build_single_hop());
901 if (multi_lane_mode && quorum_k > 0) {
902 steps.push_back(std::make_shared<ScmLaneFilterQuorum>(quorum_k, 0xFF));
906 if (terminal_rerank) {
907 steps.push_back(std::make_shared<ScmVectorRerankDot>(2, 0, query.
order_by.
metric));
912 if (multi_lane_mode) {
913 uint8_t red_code = 0;
922 steps.push_back(std::make_shared<ScmLaneReduceAttr>(0, red_code));
933 steps.push_back(std::make_shared<ScmReduce>(rop));
938 }
else if (terminal_rerank) {
949 return {std::make_shared<ScmProgram>(steps), seed_var, seed_val_or_param};
Definition impulse_cypher.hpp:798
static constexpr size_t MAX_PARSE_DEPTH
Definition impulse_cypher.hpp:811
static CompilationResult compile(const CypherQuery &query)
Definition impulse_cypher.hpp:813
static CompilationResult compile(const std::string &cypher_query)
Definition impulse_cypher.hpp:806
Definition impulse_cypher.hpp:69
CypherToken next_token()
Definition impulse_cypher.hpp:73
CypherLexer(std::string source)
Definition impulse_cypher.hpp:71
static CypherQuery parse(const std::string &query)
Definition impulse_cypher.hpp:343
CypherQuery parse_query()
Definition impulse_cypher.hpp:348
CypherParser(std::string query)
Definition impulse_cypher.hpp:339
static std::shared_ptr< ScmCollect > bitset(uint16_t reg=0)
Definition impulse_scm_ast.hpp:654
static std::shared_ptr< ScmCollect > array(uint16_t reg=0)
Definition impulse_scm_ast.hpp:661
static std::shared_ptr< ScmCollect > count(uint16_t reg=0)
Definition impulse_scm_ast.hpp:668
static std::shared_ptr< ScmCollect > none(uint16_t reg=0)
Definition impulse_scm_ast.hpp:682
static std::shared_ptr< ScmLaneInitSeeds > from_inline_seeds(std::vector< uint64_t > seeds, uint16_t sreg=0, uint8_t wflag=0)
Definition impulse_scm_ast.hpp:399
static std::shared_ptr< ScmLaneWalk > reverse(std::string rel, bool fp=false, uint8_t flg=0)
Definition impulse_scm_ast.hpp:493
static std::shared_ptr< ScmLaneWalk > forward(std::string rel, bool fp=false, uint8_t flg=0)
Definition impulse_scm_ast.hpp:484
static std::shared_ptr< ScmProgram > of(Args &&... args)
Definition impulse_scm_ast.hpp:805
Op
Definition impulse_scm_ast.hpp:242
@ MAX
Definition impulse_scm_ast.hpp:242
@ SUM
Definition impulse_scm_ast.hpp:242
@ ARGMIN
Definition impulse_scm_ast.hpp:242
@ MIN
Definition impulse_scm_ast.hpp:242
@ ARGMAX
Definition impulse_scm_ast.hpp:242
static std::shared_ptr< ScmSetOp > union_op(AstPtr l, AstPtr r)
Definition impulse_scm_ast.hpp:779
static std::shared_ptr< ScmWalk > forward(std::string rel, AstPtr pred=nullptr)
Definition impulse_scm_ast.hpp:322
static std::shared_ptr< ScmWalk > reverse(std::string rel, AstPtr pred=nullptr)
Definition impulse_scm_ast.hpp:330
#define IMPULSE_ASSERT(cond)
Definition impulse_assert.h:168
#define IMPULSE_AUDIT_ASSERT(cond)
Definition impulse_assert.h:223
Zero-Dependency C++20 Optimizing Compiler Pipeline & ImpScheme IR for Impulse Graph.
Definition impulse_bytecode_emitter.hpp:16
CypherTokenType
Definition impulse_cypher.hpp:14
@ NUMBER_LITERAL
Definition impulse_cypher.hpp:55
@ KW_IN
Definition impulse_cypher.hpp:22
@ PARAM
Definition impulse_cypher.hpp:53
@ KW_WITH
Definition impulse_cypher.hpp:23
@ RBRACKET
Definition impulse_cypher.hpp:34
@ KW_OR
Definition impulse_cypher.hpp:19
@ EQ
Definition impulse_cypher.hpp:44
@ TOK_ERROR
Definition impulse_cypher.hpp:58
@ GTE
Definition impulse_cypher.hpp:50
@ KW_ASC
Definition impulse_cypher.hpp:28
@ NEQ
Definition impulse_cypher.hpp:46
@ KW_RETURN
Definition impulse_cypher.hpp:17
@ DOT
Definition impulse_cypher.hpp:37
@ LPAREN
Definition impulse_cypher.hpp:31
@ COMMA
Definition impulse_cypher.hpp:36
@ KW_MATCH
Definition impulse_cypher.hpp:15
@ STRING_LITERAL
Definition impulse_cypher.hpp:54
@ KW_LIMIT
Definition impulse_cypher.hpp:29
@ PIPE
Definition impulse_cypher.hpp:38
@ IDENTIFIER
Definition impulse_cypher.hpp:52
@ KW_AS
Definition impulse_cypher.hpp:24
@ STAR
Definition impulse_cypher.hpp:42
@ KW_ORDER
Definition impulse_cypher.hpp:25
@ DASH
Definition impulse_cypher.hpp:39
@ KW_WHERE
Definition impulse_cypher.hpp:16
@ EQ_EQ
Definition impulse_cypher.hpp:45
@ LT
Definition impulse_cypher.hpp:47
@ KW_NOT
Definition impulse_cypher.hpp:20
@ LTE
Definition impulse_cypher.hpp:48
@ GT
Definition impulse_cypher.hpp:49
@ LBRACKET
Definition impulse_cypher.hpp:33
@ KW_BY
Definition impulse_cypher.hpp:26
@ ARROW_RIGHT
Definition impulse_cypher.hpp:40
@ TOK_EOF
Definition impulse_cypher.hpp:57
@ KW_AND
Definition impulse_cypher.hpp:18
@ ARROW_LEFT
Definition impulse_cypher.hpp:41
@ COLON
Definition impulse_cypher.hpp:35
@ KW_COUNT
Definition impulse_cypher.hpp:21
@ KW_DESC
Definition impulse_cypher.hpp:27
@ RPAREN
Definition impulse_cypher.hpp:32
std::shared_ptr< ImpScmNode > AstPtr
Definition impulse_scm_ast.hpp:159
@ COLLECT
Definition impulse_scm_ast.hpp:95
Definition impulse_cypher.hpp:800
std::string seed_param_or_value
Definition impulse_cypher.hpp:803
std::shared_ptr< ScmProgram > ast
Definition impulse_cypher.hpp:801
std::string seed_variable
Definition impulse_cypher.hpp:802
Definition impulse_cypher.hpp:281
std::string relation_name
Definition impulse_cypher.hpp:283
std::vector< std::string > relation_names
Definition impulse_cypher.hpp:287
std::string variable
Definition impulse_cypher.hpp:282
bool is_undirected
Definition impulse_cypher.hpp:288
bool is_unbounded
Definition impulse_cypher.hpp:289
int min_hops
Definition impulse_cypher.hpp:285
bool is_forward
Definition impulse_cypher.hpp:284
int max_hops
Definition impulse_cypher.hpp:286
Definition impulse_cypher.hpp:276
std::string variable
Definition impulse_cypher.hpp:277
std::string label
Definition impulse_cypher.hpp:278
Definition impulse_cypher.hpp:320
std::vector< float > query_vector
Definition impulse_cypher.hpp:323
std::string attr_name
Definition impulse_cypher.hpp:322
std::string query_param
Definition impulse_cypher.hpp:324
uint8_t metric
Definition impulse_cypher.hpp:325
bool active
Definition impulse_cypher.hpp:327
int limit
Definition impulse_cypher.hpp:326
std::string target_var
Definition impulse_cypher.hpp:321
Definition impulse_cypher.hpp:297
CypherNodePattern start_node
Definition impulse_cypher.hpp:298
std::vector< CypherPathStep > steps
Definition impulse_cypher.hpp:299
Definition impulse_cypher.hpp:292
CypherEdgePattern edge
Definition impulse_cypher.hpp:293
CypherNodePattern target_node
Definition impulse_cypher.hpp:294
Definition impulse_cypher.hpp:330
std::vector< CypherWherePredicate > where_predicates
Definition impulse_cypher.hpp:332
CypherReturnProjection projection
Definition impulse_cypher.hpp:333
CypherPathPattern path
Definition impulse_cypher.hpp:331
CypherOrderByClause order_by
Definition impulse_cypher.hpp:334
Definition impulse_cypher.hpp:312
std::string variable
Definition impulse_cypher.hpp:313
std::string attr_name
Definition impulse_cypher.hpp:314
AggOp
Definition impulse_cypher.hpp:315
@ MAX
Definition impulse_cypher.hpp:315
@ COUNT
Definition impulse_cypher.hpp:315
@ SUM
Definition impulse_cypher.hpp:315
@ ARGMIN
Definition impulse_cypher.hpp:315
@ NONE
Definition impulse_cypher.hpp:315
@ MIN
Definition impulse_cypher.hpp:315
@ ARGMAX
Definition impulse_cypher.hpp:315
enum impulse::compiler::CypherReturnProjection::AggOp NONE
bool is_count
Definition impulse_cypher.hpp:316
bool is_attr
Definition impulse_cypher.hpp:317
Definition impulse_cypher.hpp:61
std::string lexeme
Definition impulse_cypher.hpp:63
int line
Definition impulse_cypher.hpp:65
CypherTokenType type
Definition impulse_cypher.hpp:62
int col
Definition impulse_cypher.hpp:66
size_t start_pos
Definition impulse_cypher.hpp:64
Definition impulse_cypher.hpp:302
std::string field
Definition impulse_cypher.hpp:304
std::vector< uint64_t > in_values
Definition impulse_cypher.hpp:307
std::vector< float > vector_arg
Definition impulse_cypher.hpp:308
std::string target_var
Definition impulse_cypher.hpp:303
std::string op
Definition impulse_cypher.hpp:305
std::string value_or_param
Definition impulse_cypher.hpp:306
uint16_t top_k
Definition impulse_cypher.hpp:309