Impulse Graph C++ Engine 2.4.0
High-Performance Zero-Copy C-ABI Kernel and C++20 Fluent VM Engine
Loading...
Searching...
No Matches
impulse_cypher.hpp
Go to the documentation of this file.
1#ifndef IMPULSE_CYPHER_HPP
2#define IMPULSE_CYPHER_HPP
3
5#include <string>
6#include <vector>
7#include <memory>
8#include <stdexcept>
9#include <cctype>
10#include <algorithm>
11
12namespace impulse::compiler {
13
60
63 std::string lexeme;
64 size_t start_pos;
65 int line;
66 int col;
67};
68
70public:
71 explicit CypherLexer(std::string source) : src_(std::move(source)) {}
72
74 skip_whitespace_and_comments();
75
76 if (is_at_end()) {
77 return {CypherTokenType::TOK_EOF, "", cursor_, line_, col_};
78 }
79
80 size_t start_pos = cursor_;
81 int start_line = line_;
82 int start_col = col_;
83 char c = advance();
84
85 switch (c) {
86 case '(': return {CypherTokenType::LPAREN, "(", start_pos, start_line, start_col};
87 case ')': return {CypherTokenType::RPAREN, ")", start_pos, start_line, start_col};
88 case '[': return {CypherTokenType::LBRACKET, "[", start_pos, start_line, start_col};
89 case ']': return {CypherTokenType::RBRACKET, "]", start_pos, start_line, start_col};
90 case ':': return {CypherTokenType::COLON, ":", start_pos, start_line, start_col};
91 case ',': return {CypherTokenType::COMMA, ",", start_pos, start_line, start_col};
92 case '.': return {CypherTokenType::DOT, ".", start_pos, start_line, start_col};
93 case '|': return {CypherTokenType::PIPE, "|", start_pos, start_line, start_col};
94 case '*': return {CypherTokenType::STAR, "*", start_pos, start_line, start_col};
95
96 case '-':
97 if (match('>')) {
98 return {CypherTokenType::ARROW_RIGHT, "->", start_pos, start_line, start_col};
99 }
100 return {CypherTokenType::DASH, "-", start_pos, start_line, start_col};
101
102 case '<':
103 if (match('-')) {
104 return {CypherTokenType::ARROW_LEFT, "<-", start_pos, start_line, start_col};
105 }
106 if (match('>')) {
107 return {CypherTokenType::NEQ, "<>", start_pos, start_line, start_col};
108 }
109 if (match('=')) {
110 return {CypherTokenType::LTE, "<=", start_pos, start_line, start_col};
111 }
112 return {CypherTokenType::LT, "<", start_pos, start_line, start_col};
113
114 case '>':
115 if (match('=')) {
116 return {CypherTokenType::GTE, ">=", start_pos, start_line, start_col};
117 }
118 return {CypherTokenType::GT, ">", start_pos, start_line, start_col};
119
120 case '=':
121 if (match('=')) {
122 return {CypherTokenType::EQ_EQ, "==", start_pos, start_line, start_col};
123 }
124 return {CypherTokenType::EQ, "=", start_pos, start_line, start_col};
125
126 case '!':
127 if (match('=')) {
128 return {CypherTokenType::NEQ, "!=", start_pos, start_line, start_col};
129 }
130 return {CypherTokenType::TOK_ERROR, "Unexpected '!'", start_pos, start_line, start_col};
131
132 case '$':
133 return scan_parameter(start_pos, start_line, start_col);
134
135 case '`':
136 return scan_backticked_identifier(start_pos, start_line, start_col);
137
138 case '\'':
139 case '"':
140 return scan_string(c, start_pos, start_line, start_col);
141
142 default:
143 if (std::isdigit(static_cast<unsigned char>(c))) {
144 return scan_number(start_pos, start_line, start_col);
145 }
146 if (std::isalpha(static_cast<unsigned char>(c)) || c == '_') {
147 return scan_identifier_or_keyword(start_pos, start_line, start_col);
148 }
149 return {CypherTokenType::TOK_ERROR, std::string("Unexpected char: ") + c, start_pos, start_line, start_col};
150 }
151 }
152
153private:
154 std::string src_;
155 size_t cursor_ = 0;
156 int line_ = 1;
157 int col_ = 1;
158
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() == '_')) {
161 advance();
162 }
163 return {CypherTokenType::PARAM, src_.substr(start_pos, cursor_ - start_pos), start_pos, start_line, start_col};
164 }
165
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; }
170 advance();
171 }
172 if (is_at_end()) {
173 return {CypherTokenType::TOK_ERROR, "Unterminated backtick identifier", start_pos, start_line, start_col};
174 }
175 std::string lexeme = src_.substr(content_start, cursor_ - content_start);
176 advance(); // consume closing `
177 return {CypherTokenType::IDENTIFIER, lexeme, start_pos, start_line, start_col};
178 }
179
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; }
184 advance();
185 }
186 if (is_at_end()) {
187 return {CypherTokenType::TOK_ERROR, "Unterminated string literal", start_pos, start_line, start_col};
188 }
189 std::string content = src_.substr(content_start, cursor_ - content_start);
190 advance(); // consume closing quote
191 return {CypherTokenType::STRING_LITERAL, content, start_pos, start_line, start_col};
192 }
193
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()))) {
196 advance();
197 }
198 if (!is_at_end() && peek() == '.' && std::isdigit(static_cast<unsigned char>(peek_next()))) {
199 advance();
200 while (!is_at_end() && std::isdigit(static_cast<unsigned char>(peek()))) {
201 advance();
202 }
203 }
204 return {CypherTokenType::NUMBER_LITERAL, src_.substr(start_pos, cursor_ - start_pos), start_pos, start_line, start_col};
205 }
206
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() == '>')) {
209 advance();
210 }
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);
214
216 if (upper == "MATCH") type = CypherTokenType::KW_MATCH;
217 else if (upper == "WHERE") type = CypherTokenType::KW_WHERE;
218 else if (upper == "RETURN") type = CypherTokenType::KW_RETURN;
219 else if (upper == "AND") type = CypherTokenType::KW_AND;
220 else if (upper == "OR") type = CypherTokenType::KW_OR;
221 else if (upper == "NOT") type = CypherTokenType::KW_NOT;
222 else if (upper == "COUNT") type = CypherTokenType::KW_COUNT;
223 else if (upper == "IN") type = CypherTokenType::KW_IN;
224 else if (upper == "WITH") type = CypherTokenType::KW_WITH;
225 else if (upper == "AS") type = CypherTokenType::KW_AS;
226 else if (upper == "ORDER") type = CypherTokenType::KW_ORDER;
227 else if (upper == "BY") type = CypherTokenType::KW_BY;
228 else if (upper == "DESC") type = CypherTokenType::KW_DESC;
229 else if (upper == "ASC") type = CypherTokenType::KW_ASC;
230 else if (upper == "LIMIT") type = CypherTokenType::KW_LIMIT;
231
232 return {type, lexeme, start_pos, start_line, start_col};
233 }
234
235 void skip_whitespace_and_comments() {
236 while (!is_at_end()) {
237 char c = peek();
238 switch (c) {
239 case ' ':
240 case '\r':
241 case '\t':
242 advance();
243 break;
244 case '\n':
245 line_++;
246 col_ = 1;
247 advance();
248 break;
249 case '/':
250 if (peek_next() == '/') {
251 while (!is_at_end() && peek() != '\n') {
252 advance();
253 }
254 } else {
255 return;
256 }
257 break;
258 default:
259 return;
260 }
261 }
262 }
263
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;
268 cursor_++;
269 col_++;
270 return true;
271 }
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]; }
274};
275
277 std::string variable;
278 std::string label;
279};
280
282 std::string variable;
283 std::string relation_name;
284 bool is_forward{true};
285 int min_hops{1};
286 int max_hops{1};
287 std::vector<std::string> relation_names;
288 bool is_undirected{false};
289 bool is_unbounded{false};
290};
291
296
299 std::vector<CypherPathStep> steps;
300};
301
303 std::string target_var;
304 std::string field;
305 std::string op;
306 std::string value_or_param;
307 std::vector<uint64_t> in_values{};
308 std::vector<float> vector_arg{};
309 uint16_t top_k{0};
310};
311
313 std::string variable;
314 std::string attr_name;
315 enum class AggOp { NONE, COUNT, SUM, MIN, MAX, ARGMIN, ARGMAX } agg_op{AggOp::NONE};
316 bool is_count{false};
317 bool is_attr{false};
318};
319
321 std::string target_var;
322 std::string attr_name;
323 std::vector<float> query_vector{};
324 std::string query_param;
325 uint8_t metric{0};
326 int limit{0};
327 bool active{false};
328};
329
336
338public:
339 explicit CypherParser(std::string query) : lexer_(std::move(query)) {
340 advance();
341 }
342
343 static CypherQuery parse(const std::string& query) {
344 CypherParser parser(query);
345 return parser.parse_query();
346 }
347
349 consume(CypherTokenType::KW_MATCH, "Expected 'MATCH' at query start");
350 CypherPathPattern path = parse_path_pattern();
351
352 std::vector<CypherWherePredicate> where_predicates;
353 if (match(CypherTokenType::KW_WHERE)) {
354 where_predicates = parse_where_clause();
355 }
356
357 // Optional WITH clause (e.g. WITH b, count(a) AS c WHERE c >= 2)
358 if (match(CypherTokenType::KW_WITH)) {
359 parse_with_clause(where_predicates);
360 }
361
362 consume(CypherTokenType::KW_RETURN, "Expected 'RETURN' clause");
363 CypherReturnProjection projection = parse_return_clause();
364
365 CypherOrderByClause order_by{};
366 if (match(CypherTokenType::KW_ORDER)) {
367 order_by = parse_order_by_clause();
368 } else if (match(CypherTokenType::KW_LIMIT)) {
369 if (curr_.type == CypherTokenType::NUMBER_LITERAL) {
370 order_by.limit = std::stoi(curr_.lexeme);
371 order_by.active = true;
372 advance();
373 }
374 }
375
376 return {path, where_predicates, projection, order_by};
377 }
378
379private:
380 CypherLexer lexer_;
381 CypherToken curr_;
382 std::string count_alias_;
383
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)); });
387 return s;
388 }
389
390 void parse_with_clause(std::vector<CypherWherePredicate>& where_predicates) {
391 while (curr_.type != CypherTokenType::KW_WHERE &&
394 if (match(CypherTokenType::KW_COUNT)) {
395 consume(CypherTokenType::LPAREN, "Expected '(' after count in WITH");
396 if (curr_.type == CypherTokenType::IDENTIFIER) advance();
397 consume(CypherTokenType::RPAREN, "Expected ')' after count(...) in WITH");
399 count_alias_ = curr_.lexeme;
400 advance();
401 }
402 } else {
403 advance();
404 }
406 }
407 if (match(CypherTokenType::KW_WHERE)) {
408 auto extra = parse_where_clause();
409 for (auto& p : extra) where_predicates.push_back(std::move(p));
410 }
411 }
412
413 CypherPathPattern parse_path_pattern() {
414 CypherNodePattern start_node = parse_node_pattern();
415 std::vector<CypherPathStep> steps;
416
417 while (curr_.type == CypherTokenType::DASH || curr_.type == CypherTokenType::ARROW_LEFT) {
418 bool is_forward = true;
419 bool is_undirected = false;
420 if (match(CypherTokenType::ARROW_LEFT)) {
421 is_forward = false;
422 consume(CypherTokenType::LBRACKET, "Expected '[' after '<-'");
423 } else {
424 consume(CypherTokenType::DASH, "Expected '-'");
425 consume(CypherTokenType::LBRACKET, "Expected '[' after '-'");
426 }
427
428 std::string edge_var;
429 if (curr_.type == CypherTokenType::IDENTIFIER) {
430 // Could be edge variable before ':'
431 // Check if next is COLON by only consuming if curr_ is followed by ':'
432 }
433
434 consume(CypherTokenType::COLON, "Typed Edge Walk Mandate: Relationship type is mandatory (e.g. [:RelName])");
435 if (curr_.type != CypherTokenType::IDENTIFIER) {
436 throw std::runtime_error("Expected relationship name after ':', got: " + curr_.lexeme);
437 }
438 std::string rel_name = curr_.lexeme;
439 std::vector<std::string> rel_names = {rel_name};
440 advance();
441
442 while (match(CypherTokenType::PIPE)) {
444 if (curr_.type != CypherTokenType::IDENTIFIER) {
445 throw std::runtime_error("Expected relationship name after '|', got: " + curr_.lexeme);
446 }
447 rel_names.push_back(curr_.lexeme);
448 advance();
449 }
450
451 int min_hops = 1;
452 int max_hops = 1;
453 bool is_unbounded = false;
454 if (match(CypherTokenType::STAR)) {
455 if (curr_.type == CypherTokenType::NUMBER_LITERAL) {
456 min_hops = std::stoi(curr_.lexeme);
457 advance();
458 if (match(CypherTokenType::DOT) && match(CypherTokenType::DOT)) {
459 if (curr_.type == CypherTokenType::NUMBER_LITERAL) {
460 max_hops = std::stoi(curr_.lexeme);
461 advance();
462 } else {
463 throw std::runtime_error("Unbounded Traversal Mandate: Upper bound required (e.g. *1..4)");
464 }
465 } else {
466 max_hops = min_hops;
467 }
468 } else if (match(CypherTokenType::DOT) && match(CypherTokenType::DOT)) {
469 if (curr_.type == CypherTokenType::NUMBER_LITERAL) {
470 max_hops = std::stoi(curr_.lexeme);
471 advance();
472 } else {
473 throw std::runtime_error("Unbounded Traversal Mandate: Upper bound required (e.g. *..4)");
474 }
475 } else {
476 is_unbounded = true;
477 min_hops = 1;
478 max_hops = -1;
479 }
480 }
481
482 if (min_hops < 0) {
483 throw std::runtime_error("Cypher min_hops must be >= 0");
484 }
485 if (!is_unbounded) {
486 if (max_hops < min_hops) {
487 throw std::runtime_error("Cypher max_hops cannot be less than min_hops");
488 }
489 if (max_hops > 64) {
490 throw std::runtime_error("Cypher variable-length path unrolling max_hops exceeds limit of 64");
491 }
492 }
493
494 consume(CypherTokenType::RBRACKET, "Expected ']' at end of relationship pattern");
495
496 if (!is_forward) {
497 consume(CypherTokenType::DASH, "Expected '-' after ']' in incoming relationship '<-[:Rel]-'");
498 } else if (match(CypherTokenType::ARROW_RIGHT)) {
499 is_undirected = false;
500 } else if (match(CypherTokenType::DASH)) {
501 is_undirected = true;
502 } else {
503 consume(CypherTokenType::ARROW_RIGHT, "Expected '->' after ']' in outgoing relationship '-[:Rel]->'");
504 }
505
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});
508 }
509
510 return {start_node, steps};
511 }
512
513 CypherNodePattern parse_node_pattern() {
514 consume(CypherTokenType::LPAREN, "Expected '(' at start of node pattern");
515 std::string var;
516 std::string label;
517
518 if (curr_.type == CypherTokenType::IDENTIFIER) {
519 var = curr_.lexeme;
520 advance();
521 }
522
523 if (match(CypherTokenType::COLON)) {
524 if (curr_.type == CypherTokenType::IDENTIFIER ||
525 (curr_.type >= CypherTokenType::KW_MATCH && curr_.type <= CypherTokenType::KW_LIMIT)) {
526 label = curr_.lexeme;
527 advance();
528 }
529 }
530
531 consume(CypherTokenType::RPAREN, "Expected ')' at end of node pattern");
532 return {var, label};
533 }
534
535 std::string consume_comparison_op() {
536 std::string op = curr_.lexeme;
537 if (!match(CypherTokenType::EQ) && !match(CypherTokenType::EQ_EQ) && !match(CypherTokenType::GT)
538 && !match(CypherTokenType::GTE) && !match(CypherTokenType::LT) && !match(CypherTokenType::LTE)
539 && !match(CypherTokenType::NEQ)) {
540 throw std::runtime_error("Unsupported operator in WHERE clause: " + curr_.lexeme);
541 }
542 return op;
543 }
544
545 std::vector<uint64_t> parse_u64_list() {
546 consume(CypherTokenType::LBRACKET, "Expected '[' at start of IN list");
547 std::vector<uint64_t> vals;
548 while (curr_.type != CypherTokenType::RBRACKET && curr_.type != CypherTokenType::TOK_EOF) {
549 if (curr_.type == CypherTokenType::NUMBER_LITERAL) {
550 vals.push_back(std::stoull(curr_.lexeme));
551 }
552 advance();
554 }
555 consume(CypherTokenType::RBRACKET, "Expected ']' at end of IN list");
556 return vals;
557 }
558
559 std::vector<float> parse_float_list_or_param(std::string& out_param) {
560 if (curr_.type == CypherTokenType::PARAM || curr_.type == CypherTokenType::IDENTIFIER) {
561 out_param = curr_.lexeme;
562 advance();
563 return {};
564 }
565 consume(CypherTokenType::LBRACKET, "Expected '[' or $param for vector argument");
566 std::vector<float> vals;
567 while (curr_.type != CypherTokenType::RBRACKET && curr_.type != CypherTokenType::TOK_EOF) {
568 bool neg = match(CypherTokenType::DASH);
569 if (curr_.type == CypherTokenType::NUMBER_LITERAL) {
570 float v = std::stof(curr_.lexeme);
571 vals.push_back(neg ? -v : v);
572 advance();
573 } else {
574 advance();
575 }
577 }
578 consume(CypherTokenType::RBRACKET, "Expected ']' at end of vector literal");
579 return vals;
580 }
581
582 static constexpr size_t MAX_PARSE_DEPTH = 256;
583
584 std::vector<CypherWherePredicate> parse_where_clause() {
585 std::vector<CypherWherePredicate> preds;
586 size_t pred_count = 0;
587 do {
588 if (++pred_count > MAX_PARSE_DEPTH) {
589 throw std::runtime_error("Cypher WHERE predicate count exceeded limit 256");
590 }
591 if (match(CypherTokenType::KW_COUNT)) {
592 consume(CypherTokenType::LPAREN, "Expected '(' after count");
593 std::string var = curr_.lexeme;
594 consume(CypherTokenType::IDENTIFIER, "Expected variable inside count(...)");
595 consume(CypherTokenType::RPAREN, "Expected ')' after count(...)");
596 std::string op = consume_comparison_op();
597 uint16_t k = static_cast<uint16_t>(std::stoul(curr_.lexeme));
598 consume(CypherTokenType::NUMBER_LITERAL, "Expected integer quorum threshold");
599 preds.push_back({var, "quorum", op, std::to_string(k), {k}, {}, k});
600 continue;
601 }
602
603 if (curr_.type != CypherTokenType::IDENTIFIER) {
604 throw std::runtime_error("Expected identifier in WHERE clause, got: " + curr_.lexeme);
605 }
606 std::string var = curr_.lexeme;
607 advance();
608 std::string var_lower = to_lower_str(var);
609
610 if (var_lower == "vector_ann" && match(CypherTokenType::LPAREN)) {
611 std::string target_var = curr_.lexeme;
612 consume(CypherTokenType::IDENTIFIER, "Expected node variable in vector_ann(...)");
613 if (match(CypherTokenType::DOT)) {
614 consume(CypherTokenType::IDENTIFIER, "Expected attribute name after '.' in vector_ann");
615 }
616 consume(CypherTokenType::COMMA, "Expected ',' after target in vector_ann");
617 std::string q_param;
618 auto q_vec = parse_float_list_or_param(q_param);
619 uint16_t k = 10;
620 if (match(CypherTokenType::COMMA)) {
621 k = static_cast<uint16_t>(std::stoul(curr_.lexeme));
622 consume(CypherTokenType::NUMBER_LITERAL, "Expected top_k integer in vector_ann");
623 }
624 consume(CypherTokenType::RPAREN, "Expected ')' at end of vector_ann(...)");
625 preds.push_back({target_var, "vector_ann", "ANN", q_param.empty() ? std::to_string(k) : q_param, {}, std::move(q_vec), k});
626 continue;
627 }
628
629 if (var_lower == "quorum" || (!count_alias_.empty() && var == count_alias_)) {
630 std::string target_var = var;
631 if (match(CypherTokenType::LPAREN)) {
632 target_var = curr_.lexeme;
633 consume(CypherTokenType::IDENTIFIER, "Expected variable inside quorum(...)");
634 consume(CypherTokenType::RPAREN, "Expected ')' after quorum(...)");
635 }
636 std::string op = consume_comparison_op();
637 uint16_t k = static_cast<uint16_t>(std::stoul(curr_.lexeme));
638 consume(CypherTokenType::NUMBER_LITERAL, "Expected integer quorum threshold");
639 preds.push_back({target_var, "quorum", op, std::to_string(k), {k}, {}, k});
640 continue;
641 }
642
643 consume(CypherTokenType::DOT, "Expected '.' after variable in WHERE predicate");
644 if (curr_.type != CypherTokenType::IDENTIFIER) {
645 throw std::runtime_error("Expected property name after '.', got: " + curr_.lexeme);
646 }
647 std::string prop = curr_.lexeme;
648 advance();
649
650 if (match(CypherTokenType::KW_IN)) {
651 auto in_vals = parse_u64_list();
652 preds.push_back({var, prop, "IN", "IN_LIST", std::move(in_vals), {}, 0});
653 continue;
654 }
655
656 std::string op = consume_comparison_op();
657
658 std::string val_or_param = curr_.lexeme;
661 advance();
662 } else {
663 throw std::runtime_error("Expected parameter ($param) or literal in WHERE predicate, got: " + curr_.lexeme);
664 }
665
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});
669 } else {
670 preds.push_back({var, prop, op, val_or_param, {}, {}, 0});
671 }
672 } while (match(CypherTokenType::KW_AND));
673
674 return preds;
675 }
676
677 CypherOrderByClause parse_order_by_clause() {
678 consume(CypherTokenType::KW_BY, "Expected 'BY' after 'ORDER'");
679 std::string fn_or_var = curr_.lexeme;
680 consume(CypherTokenType::IDENTIFIER, "Expected identifier in ORDER BY");
681 CypherOrderByClause clause{};
682 clause.active = true;
683 clause.target_var = fn_or_var;
684
685 if (match(CypherTokenType::LPAREN)) {
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;
691
692 clause.target_var = curr_.lexeme;
693 consume(CypherTokenType::IDENTIFIER, "Expected variable in ORDER BY function");
694 if (match(CypherTokenType::DOT)) {
695 clause.attr_name = curr_.lexeme;
696 consume(CypherTokenType::IDENTIFIER, "Expected attribute name after '.' in ORDER BY");
697 }
698 if (match(CypherTokenType::COMMA)) {
699 clause.query_vector = parse_float_list_or_param(clause.query_param);
700 }
701 consume(CypherTokenType::RPAREN, "Expected ')' after ORDER BY function");
702 } else if (match(CypherTokenType::DOT)) {
703 clause.attr_name = curr_.lexeme;
704 consume(CypherTokenType::IDENTIFIER, "Expected attribute name after '.' in ORDER BY");
705 }
706
707 if (!match(CypherTokenType::KW_DESC)) {
709 }
711 clause.limit = std::stoi(curr_.lexeme);
712 advance();
713 }
714 return clause;
715 }
716
717 CypherReturnProjection parse_return_clause() {
718 if (match(CypherTokenType::KW_COUNT)) {
719 consume(CypherTokenType::LPAREN, "Expected '(' after 'count'");
720 std::string var = curr_.lexeme;
721 consume(CypherTokenType::IDENTIFIER, "Expected variable name inside count(...)");
722 std::string attr;
723 if (match(CypherTokenType::DOT)) {
724 attr = curr_.lexeme;
725 consume(CypherTokenType::IDENTIFIER, "Expected attribute name after '.'");
726 }
727 consume(CypherTokenType::RPAREN, "Expected ')' after variable inside count(...)");
729 proj.variable = var;
730 proj.attr_name = attr;
732 proj.is_count = true;
733 return proj;
734 }
735
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") {
740 advance();
741 consume(CypherTokenType::LPAREN, "Expected '(' after aggregate function");
742 std::string var = curr_.lexeme;
743 consume(CypherTokenType::IDENTIFIER, "Expected variable name in aggregate function");
744 std::string attr;
745 if (match(CypherTokenType::DOT)) {
746 attr = curr_.lexeme;
747 consume(CypherTokenType::IDENTIFIER, "Expected attribute name after '.'");
748 }
749 consume(CypherTokenType::RPAREN, "Expected ')' after aggregate argument");
751 proj.variable = var;
752 proj.attr_name = attr;
753 if (fn_lower == "sum") proj.agg_op = CypherReturnProjection::AggOp::SUM;
754 else if (fn_lower == "min") proj.agg_op = CypherReturnProjection::AggOp::MIN;
755 else if (fn_lower == "max") proj.agg_op = CypherReturnProjection::AggOp::MAX;
756 else if (fn_lower == "argmin") proj.agg_op = CypherReturnProjection::AggOp::ARGMIN;
757 else if (fn_lower == "argmax") proj.agg_op = CypherReturnProjection::AggOp::ARGMAX;
758 return proj;
759 }
760
761 if (curr_.type == CypherTokenType::IDENTIFIER) {
762 std::string var = curr_.lexeme;
763 advance();
764 std::string attr;
765 bool is_attr = false;
766 if (match(CypherTokenType::DOT)) {
767 attr = curr_.lexeme;
768 consume(CypherTokenType::IDENTIFIER, "Expected attribute name after '.'");
769 is_attr = true;
770 }
772 proj.variable = var;
773 proj.attr_name = attr;
774 proj.is_attr = is_attr;
775 return proj;
776 }
777
778 throw std::runtime_error("Expected return target variable, attribute, or aggregate, got: " + curr_.lexeme);
779 }
780
781 void advance() { curr_ = lexer_.next_token(); }
782 bool match(CypherTokenType type) {
783 if (curr_.type == type) {
784 advance();
785 return true;
786 }
787 return false;
788 }
789 void consume(CypherTokenType type, const std::string& error_msg) {
790 if (curr_.type == type) {
791 advance();
792 return;
793 }
794 throw std::runtime_error(error_msg + " [Line " + std::to_string(curr_.line) + ":" + std::to_string(curr_.col) + " at '" + curr_.lexeme + "']");
795 }
796};
797
799public:
801 std::shared_ptr<ScmProgram> ast;
802 std::string seed_variable;
804 };
805
806 static CompilationResult compile(const std::string& cypher_query) {
807 CypherQuery query = CypherParser::parse(cypher_query);
808 return compile(query);
809 }
810
811 static constexpr size_t MAX_PARSE_DEPTH = 256;
812
813 static CompilationResult compile(const CypherQuery& query) {
814 if (query.where_predicates.size() > MAX_PARSE_DEPTH || query.path.steps.size() > MAX_PARSE_DEPTH) {
815 throw std::runtime_error("Cypher query complexity exceeded limit 256");
816 }
817 std::vector<AstPtr> steps;
818 std::string seed_var = query.path.start_node.variable;
819 std::string seed_val_or_param;
820 std::vector<uint64_t> multi_seeds;
821 const CypherWherePredicate* vector_ann_pred = nullptr;
822 uint16_t quorum_k = 0;
823
824 for (const auto& pred : query.where_predicates) {
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;
834 }
835 }
836
837 bool multi_lane_mode = !multi_seeds.empty() || (vector_ann_pred != nullptr && quorum_k > 0);
838
839 if (!multi_seeds.empty()) {
840 steps.push_back(ScmLaneInitSeeds::from_inline_seeds(multi_seeds, 0, 0));
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));
844 }
845
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");
850 }
851 std::vector<std::string> rels = edge.relation_names.empty()
852 ? std::vector<std::string>{edge.relation_name}
853 : edge.relation_names;
854
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) {
861 steps.push_back(ScmLaneWalk::forward(r, fp, fp ? 0x04 : 0x00));
862 steps.push_back(ScmLaneWalk::reverse(r, fp, fp ? 0x04 : 0x00));
863 } else if (edge.is_forward) {
864 steps.push_back(ScmLaneWalk::forward(r, fp, fp ? 0x04 : 0x00));
865 } else {
866 steps.push_back(ScmLaneWalk::reverse(r, fp, fp ? 0x04 : 0x00));
867 }
868 }
869 }
870 } else {
871 auto build_single_hop = [&]() -> AstPtr {
872 std::vector<AstPtr> branches;
873 for (const auto& r : rels) {
874 if (edge.is_undirected) {
875 branches.push_back(ScmWalk::forward(r));
876 branches.push_back(ScmWalk::reverse(r));
877 } else if (edge.is_forward) {
878 branches.push_back(ScmWalk::forward(r));
879 } else {
880 branches.push_back(ScmWalk::reverse(r));
881 }
882 }
883 AstPtr acc = branches[0];
884 for (size_t i = 1; i < branches.size(); ++i) {
885 acc = ScmSetOp::union_op(acc, branches[i]);
886 }
887 return acc;
888 };
889
890 if (edge.is_unbounded) {
891 steps.push_back(std::make_shared<ScmFixpoint>(ScmProgram::of(build_single_hop())));
892 } else {
893 int hops = std::max(1, edge.max_hops);
894 for (int h = 0; h < hops; ++h) {
895 steps.push_back(build_single_hop());
896 }
897 }
898 }
899 }
900
901 if (multi_lane_mode && quorum_k > 0) {
902 steps.push_back(std::make_shared<ScmLaneFilterQuorum>(quorum_k, 0xFF));
903 }
904
905 bool terminal_rerank = query.order_by.active && (!query.order_by.query_vector.empty() || !query.order_by.query_param.empty());
906 if (terminal_rerank) {
907 steps.push_back(std::make_shared<ScmVectorRerankDot>(2, 0, query.order_by.metric));
908 }
909
912 if (multi_lane_mode) {
913 uint8_t red_code = 0;
914 switch (query.projection.agg_op) {
915 case CypherReturnProjection::AggOp::SUM: red_code = 0; break;
916 case CypherReturnProjection::AggOp::MIN: red_code = 2; break;
917 case CypherReturnProjection::AggOp::MAX: red_code = 3; break;
918 case CypherReturnProjection::AggOp::ARGMIN: red_code = 6; break;
919 case CypherReturnProjection::AggOp::ARGMAX: red_code = 7; break;
920 default: break;
921 }
922 steps.push_back(std::make_shared<ScmLaneReduceAttr>(0, red_code));
923 } else {
925 switch (query.projection.agg_op) {
931 default: break;
932 }
933 steps.push_back(std::make_shared<ScmReduce>(rop));
934 }
935 steps.push_back(ScmCollect::none());
936 } else if (query.projection.is_count) {
937 steps.push_back(ScmCollect::count());
938 } else if (terminal_rerank) {
939 steps.push_back(ScmCollect::none());
940 } else if (query.projection.is_attr) {
941 steps.push_back(ScmCollect::array());
942 } else {
943 steps.push_back(ScmCollect::bitset());
944 }
945
946 IMPULSE_ASSERT(!steps.empty());
947 IMPULSE_AUDIT_ASSERT(steps.back()->kind() == NodeKind::COLLECT);
948
949 return {std::make_shared<ScmProgram>(steps), seed_var, seed_val_or_param};
950 }
951};
952
953} // namespace impulse::compiler
954
955#endif // IMPULSE_CYPHER_HPP
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
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