move control socket handling to separate file
[mizunara.git] / libidav / davqlparser.h
1 /*
2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3  *
4  * Copyright 2018 Olaf Wintermann. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  *   1. Redistributions of source code must retain the above copyright
10  *      notice, this list of conditions and the following disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above copyright
13  *      notice, this list of conditions and the following disclaimer in the
14  *      documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #ifndef DAVQLPARSER_H
30 #define DAVQLPARSER_H
31
32 #ifdef  __cplusplus
33 extern "C" {
34 #endif
35
36 #include <stdint.h>
37 #include "ucx/string.h"
38 #include "ucx/list.h"
39
40 /**
41  * Enumeration of possible statement types.
42  */
43 typedef enum {DAVQL_ERROR, DAVQL_SELECT, DAVQL_SET} davqltype_t;
44
45 /**
46  * Enumeration of possible token classes.
47  */
48 typedef enum {
49     DAVQL_TOKEN_INVALID, DAVQL_TOKEN_KEYWORD,
50     DAVQL_TOKEN_IDENTIFIER, DAVQL_TOKEN_FMTSPEC,
51     DAVQL_TOKEN_STRING, DAVQL_TOKEN_NUMBER, DAVQL_TOKEN_TIMESTAMP,
52     DAVQL_TOKEN_COMMA, DAVQL_TOKEN_OPENP, DAVQL_TOKEN_CLOSEP,
53     DAVQL_TOKEN_OPERATOR, DAVQL_TOKEN_END
54 } davqltokenclass_t;
55
56 /**
57  * Enumeration of possible expression types.
58  */
59 typedef enum {
60     DAVQL_UNDEFINED_TYPE,
61     DAVQL_NUMBER, DAVQL_STRING, DAVQL_TIMESTAMP, DAVQL_IDENTIFIER,
62     DAVQL_UNARY, DAVQL_BINARY, DAVQL_LOGICAL, DAVQL_FUNCCALL
63 } davqlexprtype_t;
64
65 /**
66  * Enumeration of possible expression operators.
67  */
68 typedef enum {
69     DAVQL_NOOP, DAVQL_CALL, DAVQL_ARGLIST, // internal representations
70     DAVQL_ADD, DAVQL_SUB, DAVQL_MUL, DAVQL_DIV,
71     DAVQL_AND, DAVQL_OR, DAVQL_XOR, DAVQL_NEG,  // airthmetic
72     DAVQL_NOT, DAVQL_LAND, DAVQL_LOR, DAVQL_LXOR, // logical
73     DAVQL_EQ, DAVQL_NEQ, DAVQL_LT, DAVQL_GT, DAVQL_LE, DAVQL_GE,
74     DAVQL_LIKE, DAVQL_UNLIKE // comparisons
75 } davqloperator_t;
76
77 typedef struct {
78     davqltokenclass_t tokenclass;
79     sstr_t value;
80 } DavQLToken;
81
82 /**
83  * An expression within a DAVQL query.
84  */
85 typedef struct _davqlexpr DavQLExpression;
86
87 /**
88  * The structure for type DavQLExpression.
89  */
90 struct _davqlexpr {
91     /**
92      * The original expression text.
93      * Contains the literal value, if type is LITERAL.
94      */
95     sstr_t srctext;
96     /**
97      * The expression type.
98      */
99     davqlexprtype_t type;
100     /**
101      * Operator.
102      */
103     davqloperator_t op;
104     /**
105      * Left or single operand.
106      * <code>NULL</code> for literals or identifiers.
107      */
108     DavQLExpression *left;
109     /**
110      * Right operand.
111      * <code>NULL</code> for literals, identifiers or unary expressions.
112      */
113     DavQLExpression *right;
114 };
115
116 /**
117  * A tuple representing an order criterion.
118  */
119 typedef struct {
120     /**
121      * The column.
122      */
123     DavQLExpression *column;
124     /**
125      * True, if the result shall be sorted descending, false otherwise.
126      * Default is false (ascending).
127      */
128     _Bool descending;
129 } DavQLOrderCriterion;
130
131 /**
132  * A tuple representing a field.
133  */
134 typedef struct {
135     /**
136      * The field name.
137      * <ul>
138      * <li>SELECT: the identifier or an alias name</li>
139      * <li>SET: the identifier</li>
140      * </ul>
141      */
142     sstr_t name;
143     /**
144      * The field expression.
145      * <ul>
146      * <li>SELECT: the queried property (identifier) or an expression</li>
147      * <li>SET: the expression for the value to be set</li>
148      * </ul>
149      */
150     DavQLExpression *expr;
151 } DavQLField;
152
153 /**
154  * Query statement object.
155  * Contains the binary information about the parsed query.
156  * 
157  * The grammar for a DavQLStatement is:
158  * 
159  * <pre>
160  * Keyword = "select" | "set" | "from" | "at" | "as"
161  *         | "where" | "anywhere" | "like" | "unlike"
162  *         | "and" | "or" | "not" | "xor" | "with" | "infinity"
163  *         | "order" | "by" | "asc" | "desc";
164  * 
165  * Expression        = AddExpression;
166  * AddExpression     = MultExpression, [AddOperator, AddExpression];
167  * MultExpression    = BitwiseExpression, [MultOperator, MultExpression];
168  * BitwiseExpression = UnaryExpression, [BitwiseOperator, BitwiseExpression];
169  * UnaryExpression   = [UnaryOperator], (ParExpression | AtomicExpression);
170  * AtomicExpression  = FunctionCall | Identifier | Literal;
171  * ParExpression     = "(", Expression, ")";
172  * 
173  * BitwiseOperator = "&" | "|" | "^";
174  * MultOperator    = "*" | "/";
175  * AddOperator     = "+" | "-";
176  * UnaryOperator   = "+" | "-" | "~";
177  * 
178  * FunctionCall    = Identifier, "(", [ArgumentList], ")";
179  * ArgumentList    = Expression, {",", Expression};
180  * Identifier      = IdentifierChar - ?Digit?, {IdentifierChar}
181  *                 | "`", ?Character? - "`", {?Character? - "`"}, "`";
182  * IdentifierChar  = ?Character? - (" "|",");
183  * Literal         = Number | String | Timestamp;
184  * Number          = ?Digit?, {?Digit?} | "%d";
185  * String          = "'", {?Character? - "'" | "'''"} , "'" | "%s";
186  * Timestamp       = "%t"; // TODO: maybe introduce a real literal 
187  * 
188  * LogicalExpression = BooleanExpression, [LogicalOperator, LogicalExpression];
189  * BooleanExpression = "not ", BooleanExpression
190  *                   | "(", LogicalExpression, ")"
191  *                   | BooleanPrimary;
192  * BooleanPrimary    = Expression, (" like " | " unlike "), String
193  *                   | Expression, Comparison, Expression
194  *                   | FunctionCall | Identifier;
195  * 
196  * LogicalOperator = " and " | " or " | " xor ";
197  * Comparison      = | "=" | "<" | ">" | "<=" | ">=" | "!=";
198  * 
199  * FieldExpressions = "-"
200  *                  | "*", {",", NamedField}
201  *                  | FieldExpression, {",", FieldExpression};
202  * FieldExpression  = NamedField | Identifier;
203  * NamedField       = Expression, " as ", Identifier;
204  * 
205  * Assignments   = Assignment, {",", Assignment};
206  * Assignment    = Identifier, "=", Expression;
207  * 
208  * Path     = String
209  *          | "/", [PathNode, {"/", PathNode}], ["/"];
210  * PathNode = {{?Character? - "/"} - Keyword};
211  * 
212  * WithClause = "depth", "=", (Number | "infinity");
213  * 
214  * OrderByClause    = OrderByCriterion, {",", OrderByCriterion};
215  * OrderByCriterion = (Identifier | Number), [" asc"|" desc"];
216  * 
217  * </pre>
218  * 
219  * Note: mandatory spaces are part of the grammar. But you may also insert an
220  * arbitrary amount of optional spaces between two symbols if they are not part
221  * of an literal, identifier or the path.
222  * 
223  * <b>SELECT:</b>
224  * <pre>
225  * SelectStatement = "select ", FieldExpressions,
226  * " from ", Path,
227  * [" with ", WithClause],
228  * [(" where ", LogicalExpression) | " anywhere"],
229  * [" order by ", OrderByClause];
230   * </pre>
231  * 
232  * <b>SET:</b>
233  * <pre>
234  * SetStatement = "set ",Assignments,
235  * " at ", Path,
236  * [" with ", WithClause],
237  * (" where ", LogicalExpression) | " anywhere";
238  * </pre>
239  * 
240  */
241 typedef struct {
242     /**
243      * The original query text.
244      */
245     sstr_t srctext;
246     /**
247      * The statement type.
248      */
249     davqltype_t type;
250     /**
251      * Error code, if any error occurred. Zero otherwise.
252      */
253     int errorcode;
254     /**
255      * Error message, if any error occurred.
256      */
257     char* errormessage;
258     /**
259      * The list of DavQLFields.
260      */
261     UcxList* fields;
262     /**
263      * A string that denotes the queried path.
264      */
265     sstr_t path;
266     /**
267      * Logical expression for selection.
268      * <code>NULL</code>, if there is no where clause.
269      */
270     DavQLExpression* where;
271     /**
272      * The list of DavQLOrderCriterions.
273      * This is <code>NULL</code> for SET queries and may be <code>NULL</code>
274      * if the result doesn't need to be sorted.
275      */
276     UcxList* orderby;
277     /**
278      * The recursion depth for the statement.
279      * Defaults to 1.
280      * Magic numbers are DAV_DEPTH_INFINITY for infinity and
281      * DAV_DEPTH_PLACEHOLDER for a placeholder.
282      */
283     int depth;
284     /**
285      * A list of all required arguments
286      */
287     UcxList* args;
288 } DavQLStatement;
289
290 /** Infinity recursion depth for a DavQLStatement. */
291 #define DAV_DEPTH_INFINITY -1
292
293 /** Depth needs to be specified at runtime. */
294 #define DAV_DEPTH_PLACEHOLDER -2
295
296 /** Unexpected token. */
297 #define DAVQL_ERROR_UNEXPECTED_TOKEN 1
298
299 /** A token has been found, for which no token class is applicable. */
300 #define DAVQL_ERROR_INVALID_TOKEN 2
301
302 /** A token that has been expected was not found. */
303 #define DAVQL_ERROR_MISSING_TOKEN 11
304
305 /** An expression has been expected, but was not found. */
306 #define DAVQL_ERROR_MISSING_EXPR 12
307
308 /** A closed parenthesis ')' is missing. */
309 #define DAVQL_ERROR_MISSING_PAR 13
310
311 /** An assignment operator '=' is missing. */
312 #define DAVQL_ERROR_MISSING_ASSIGN 14
313
314 /** The type of the expression could not be determined. */
315 #define DAVQL_ERROR_INVALID_EXPR 21
316
317 /** An operator has been found for an unary expression, but it is invalid. */
318 #define DAVQL_ERROR_INVALID_UNARY_OP 22
319
320 /** An operator has been found for a logical expression, but it is invalid. */
321 #define DAVQL_ERROR_INVALID_LOGICAL_OP 23
322
323 /** Invalid format specifier. */
324 #define DAVQL_ERROR_INVALID_FMTSPEC 24
325
326 /** A string has been expected. */
327 #define DAVQL_ERROR_INVALID_STRING 25
328
329 /** The order criterion is invalid (must be an identifier or field index). */
330 #define DAVQL_ERROR_INVALID_ORDER_CRITERION 26
331
332 /** The depth is invalid. */
333 #define DAVQL_ERROR_INVALID_DEPTH 101
334
335 /** Nothing about the statement seems legit. */
336 #define DAVQL_ERROR_INVALID -1
337
338 /** A call to malloc or calloc failed. */
339 #define DAVQL_ERROR_OUT_OF_MEMORY -2
340
341 /**
342  * Starts an interactive debugger for a DavQLStatement.
343  * 
344  * @param stmt the statement to debug
345  */
346 void dav_debug_statement(DavQLStatement *stmt);
347
348 /**
349  * Parses a statement.
350  * @param stmt the sstr_t containing the statement
351  * @return a DavQLStatement object
352  */
353 DavQLStatement* dav_parse_statement(sstr_t stmt);
354
355 /**
356  * Implicitly converts a cstr to a sstr_t and calls dav_parse_statement.
357  */
358 #define dav_parse_cstr_statement(stmt) dav_parse_statement(S(stmt))
359
360 /**
361  * Frees a DavQLStatement.
362  * @param stmt the statement object to free
363  */
364 void dav_free_statement(DavQLStatement *stmt);
365
366 #ifdef  __cplusplus
367 }
368 #endif
369
370 #endif  /* DAVQLPARSER_H */
371