smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
parser.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <cctype>
5#include <charconv>
6#include <cstddef>
7#include <cstdint>
8#include <iterator>
9#include <string>
10#include <utility>
11#include <vector>
12
13#include "absl/status/status.h"
14#include "absl/status/statusor.h"
15#include "absl/strings/str_cat.h"
16#include "smollergraph/lexer.h"
17
18namespace smollergraph {
19namespace {
20
21// The most hops one relationship in a pattern can stand for.
22constexpr int kMaxHops = 10;
23// The operators a comparison in WHERE can have.
24constexpr std::string_view kOperators[] = {"=", "<>", "<", "<=", ">", ">="};
25
26bool EqualsIgnoringCase(std::string_view a, std::string_view b) {
27 if (a.size() != b.size()) return false;
28 for (size_t i = 0; i < a.size(); ++i) {
29 if (std::toupper(static_cast<unsigned char>(a[i])) !=
30 std::toupper(static_cast<unsigned char>(b[i]))) {
31 return false;
32 }
33 }
34 return true;
35}
36
37// A recursive descent parser: a function for each part of the query, which
38// reads that part's tokens, and calls the functions for the parts inside it.
39// Each returns false, with the parser's status filled in, when the tokens
40// don't fit.
41class Parser {
42 public:
43 explicit Parser(std::vector<Token> tokens) : tokens_(std::move(tokens)) {}
44
45 // What's wrong with the query, once a part has failed.
46 const absl::Status& status() const { return status_; }
47
48 // query := [EXPLAIN] MATCH [variable =] (pattern | shortestPath(pattern))
49 // [WHERE comparison (AND comparison)*]
50 // RETURN [DISTINCT] item (, item)*
51 // pattern := node (relationship node)*
52 bool ParseQuery(Query& query) {
53 query.explain = Keyword("EXPLAIN");
54 if (!ExpectKeyword("MATCH")) return false;
55 // A word and an equals sign name the path that follows.
56 if (Peek().kind == TokenKind::kWord && IsSymbolAt(1, "=")) {
57 query.path = Next().text;
58 Next();
59 query.shortest = Keyword("shortestPath");
60 if (query.shortest && !ExpectSymbol("(")) return false;
61 }
62 NodePattern node;
63 if (!ParseNode(node)) return false;
64 query.nodes.push_back(node);
65 while (IsSymbol("-") || IsSymbol("<")) {
66 RelationshipPattern relationship;
67 if (!ParseRelationship(relationship) || !ParseNode(node)) return false;
68 query.relationships.push_back(relationship);
69 query.nodes.push_back(node);
70 }
71 if (query.shortest && !ExpectSymbol(")")) return false;
72 if (Keyword("WHERE")) {
73 do {
74 Comparison comparison;
75 if (!ParseComparison(comparison)) return false;
76 query.where.push_back(std::move(comparison));
77 } while (Keyword("AND"));
78 }
79 if (!ExpectKeyword("RETURN")) return false;
80 query.distinct = Keyword("DISTINCT");
81 do {
82 ReturnItem item;
83 if (!ParseReturnItem(item)) return false;
84 query.returns.push_back(std::move(item));
85 } while (Symbol(","));
86 if (Peek().kind != TokenKind::kEnd) return Fail("the end of the query");
87 return true;
88 }
89
90 // Properties on their own, as the facts we load have them.
91 bool ParsePropertiesAlone(std::vector<Property>& properties) {
92 if (!ParseProperties(properties)) return false;
93 if (Peek().kind != TokenKind::kEnd) {
94 return Fail("the end of the properties");
95 }
96 return true;
97 }
98
99 private:
100 // node := ( [variable] [: label] [properties] )
101 bool ParseNode(NodePattern& node) {
102 node = {};
103 if (!ExpectSymbol("(")) return false;
104 if (Peek().kind == TokenKind::kWord) node.variable = Next().text;
105 if (Symbol(":")) {
106 if (Peek().kind != TokenKind::kWord) return Fail("a label");
107 node.label = Next().text;
108 }
109 if (IsSymbol("{") && !ParseProperties(node.properties)) return false;
110 return ExpectSymbol(")");
111 }
112
113 // relationship := - [ : types [* [hops | WSHORTEST(key)]] ] - [>]
114 // | < - [ : types [* [hops | WSHORTEST(key)]] ] -
115 // types := type (| type)*
116 bool ParseRelationship(RelationshipPattern& relationship) {
117 if (Symbol("<")) relationship.direction = Direction::kIn;
118 if (!ExpectSymbol("-") || !ExpectSymbol("[") || !ExpectSymbol(":")) {
119 return false;
120 }
121 // A bar between two types, as in -[:MemberOf|AdminTo]->, matches a
122 // relationship of either.
123 do {
124 if (Peek().kind != TokenKind::kWord) return Fail("a relationship type");
125 relationship.types.push_back(Next().text);
126 } while (Symbol("|"));
127 if (Symbol("*")) {
128 const std::string& text = Peek().text;
129 auto [end, failed] = std::from_chars(
130 text.data(), text.data() + text.size(), relationship.hops);
131 // A star with no number after it stands for any number of hops, and
132 // WSHORTEST after it names the weight a cheapest path adds up.
133 if (Peek().kind != TokenKind::kNumber) {
134 relationship.hops = kAnyHops;
135 if (Keyword("WSHORTEST")) {
136 if (!ExpectSymbol("(")) return false;
137 if (Peek().kind != TokenKind::kWord) return Fail("a key");
138 relationship.weight = Next().text;
139 if (!ExpectSymbol(")")) return false;
140 }
141 } else if (failed != std::errc() || relationship.hops < 1 ||
142 relationship.hops > kMaxHops) {
143 return Fail("a number of hops from 1 to " + std::to_string(kMaxHops));
144 } else {
145 Next();
146 }
147 }
148 if (!ExpectSymbol("]") || !ExpectSymbol("-")) return false;
149 // An arrow on the left needs none on the right, and a relationship with
150 // no arrow at all goes either way.
151 if (relationship.direction == Direction::kOut && !Symbol(">")) {
152 relationship.direction = Direction::kBoth;
153 }
154 return true;
155 }
156
157 // properties := { key : value (, key : value)* }
158 bool ParseProperties(std::vector<Property>& properties) {
159 if (!ExpectSymbol("{")) return false;
160 do {
161 Property property;
162 if (Peek().kind != TokenKind::kWord) return Fail("a key");
163 property.key = Next().text;
164 if (!ExpectSymbol(":") || !ParseValue(property.value)) return false;
165 properties.push_back(std::move(property));
166 } while (Symbol(","));
167 return ExpectSymbol("}");
168 }
169
170 // value := string | number
171 bool ParseValue(Value& value) {
172 if (Peek().kind == TokenKind::kString) {
173 value = Next().text;
174 return true;
175 }
176 const std::string& text = Peek().text;
177 int64_t number = 0;
178 auto [end, failed] =
179 std::from_chars(text.data(), text.data() + text.size(), number);
180 if (Peek().kind != TokenKind::kNumber || failed != std::errc()) {
181 return Fail("a string or a whole number");
182 }
183 Next();
184 value = number;
185 return true;
186 }
187
188 // comparison := lookup operator value
189 bool ParseComparison(Comparison& comparison) {
190 if (!ParseLookup(comparison.property)) return false;
191 if (Peek().kind != TokenKind::kSymbol ||
192 std::find(std::begin(kOperators), std::end(kOperators), Peek().text) ==
193 std::end(kOperators)) {
194 return Fail("a comparison");
195 }
196 comparison.op = Next().text;
197 return ParseValue(comparison.value);
198 }
199
200 // lookup := variable . key
201 bool ParseLookup(PropertyLookup& lookup) {
202 if (Peek().kind != TokenKind::kWord) return Fail("a variable");
203 lookup.variable = Next().text;
204 if (!ExpectSymbol(".")) return false;
205 if (Peek().kind != TokenKind::kWord) return Fail("a key");
206 lookup.key = Next().text;
207 return true;
208 }
209
210 // item := variable [. key] | (length | cost) ( variable )
211 bool ParseReturnItem(ReturnItem& item) {
212 if (Peek().kind == TokenKind::kWord && IsSymbolAt(1, "(")) {
213 if (Keyword("length")) {
214 item.function = "length";
215 } else if (Keyword("cost")) {
216 item.function = "cost";
217 } else {
218 return Fail("length or cost");
219 }
220 if (!ExpectSymbol("(")) return false;
221 if (Peek().kind != TokenKind::kWord) return Fail("a variable");
222 item.variable = Next().text;
223 return ExpectSymbol(")");
224 }
225 if (Peek().kind != TokenKind::kWord) return Fail("a variable");
226 item.variable = Next().text;
227 // A variable on its own returns all of it, which our subset allows for a
228 // path, as a path has no properties.
229 if (!Symbol(".")) return true;
230 if (Peek().kind != TokenKind::kWord) return Fail("a key");
231 item.key = Next().text;
232 return true;
233 }
234
235 const Token& Peek() const { return tokens_[next_]; }
236 const Token& Next() { return tokens_[next_++]; }
237
238 bool IsSymbol(std::string_view symbol) const { return IsSymbolAt(0, symbol); }
239 // Whether the token `ahead` of the next one is this symbol. The last token
240 // is the end, so looking past it finds the end.
241 bool IsSymbolAt(size_t ahead, std::string_view symbol) const {
242 const Token& token = tokens_[std::min(next_ + ahead, tokens_.size() - 1)];
243 return token.kind == TokenKind::kSymbol && token.text == symbol;
244 }
245 // Reads a symbol, if it's the next token.
246 bool Symbol(std::string_view symbol) {
247 if (!IsSymbol(symbol)) return false;
248 ++next_;
249 return true;
250 }
251 // Reads a keyword, if it's the next token. Cypher's keywords can be written
252 // in any case, so match is MATCH.
253 bool Keyword(std::string_view keyword) {
254 if (Peek().kind != TokenKind::kWord ||
255 !EqualsIgnoringCase(Peek().text, keyword)) {
256 return false;
257 }
258 ++next_;
259 return true;
260 }
261 bool ExpectSymbol(std::string_view symbol) {
262 return Symbol(symbol) || Fail(std::string(symbol));
263 }
264 bool ExpectKeyword(std::string_view keyword) {
265 return Keyword(keyword) || Fail(std::string(keyword));
266 }
267
268 // Says what was expected, where, and what was there.
269 bool Fail(const std::string& expected) {
270 const Token& token = Peek();
271 status_ = absl::InvalidArgumentError(
272 absl::StrCat("expected ", expected, " at ", token.at, ", not ",
273 token.kind == TokenKind::kEnd ? "the end" : token.text));
274 return false;
275 }
276
277 std::vector<Token> tokens_;
278 size_t next_ = 0;
279 absl::Status status_;
280};
281
282} // namespace
283
284absl::StatusOr<Query> Parse(std::string_view text) {
285 absl::StatusOr<std::vector<Token>> tokens = Lex(text);
286 if (!tokens.ok()) return tokens.status();
287 Parser parser(*std::move(tokens));
288 Query query;
289 if (!parser.ParseQuery(query)) return parser.status();
290 return query;
291}
292
293absl::StatusOr<std::vector<Property>> ParseProperties(std::string_view text) {
294 absl::StatusOr<std::vector<Token>> tokens = Lex(text);
295 if (!tokens.ok()) return tokens.status();
296 Parser parser(*std::move(tokens));
297 std::vector<Property> properties;
298 if (!parser.ParsePropertiesAlone(properties)) return parser.status();
299 return properties;
300}
301
302} // namespace smollergraph
std::vector< Property > properties
Definition facts.cc:19
std::string_view text
Definition facts.cc:17
std::variant< int64_t, std::string > Value
A property's value, as the graph hands it out: a whole number or a string.
Definition graph.h:100
absl::StatusOr< Query > Parse(std::string_view text)
Reads a query.
Definition parser.cc:284
absl::StatusOr< std::vector< Property > > ParseProperties(std::string_view text)
Reads properties as Cypher writes them, in braces, such as {legs: 4, diet: 'omnivore'},...
Definition parser.cc:293
absl::StatusOr< std::vector< Token > > Lex(std::string_view query)
Splits a query into tokens, ending with a kEnd token.
Definition lexer.cc:25
constexpr int kAnyHops
The hops of a relationship written with a star and no number, such as -[:KNOWS*]-,...
Definition parser.h:24
A query in our subset of Cypher, such as MATCH (a {name: 'Red fox'})-[:EATS]->(b) WHERE b....
Definition parser.h:71