Code

frontend: Improved parser error reporting.
[sysdb.git] / src / frontend / scanner.l
1 /*
2  * SysDB - src/frontend/scanner.l
3  * Copyright (C) 2013 Sebastian 'tokkee' Harl <sh@tokkee.org>
4  * 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
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
28 %{
30 #if HAVE_CONFIG_H
31 #       include "config.h"
32 #endif /* HAVE_CONFIG_H */
34 #include "core/data.h"
35 #include "frontend/connection.h"
36 #include "frontend/parser.h"
37 #include "frontend/grammar.h"
38 #include "utils/error.h"
40 #include <assert.h>
41 #include <errno.h>
43 #include <string.h>
44 #include <stdlib.h>
46 #include <time.h>
48 #define YY_EXTRA_TYPE sdb_fe_yyextra_t *
50 static struct {
51         const char *name;
52         int id;
53 } reserved_words[] = {
54         { "ALL",         ALL },
55         { "AND",         AND },
56         { "ANY",         ANY },
57         { "END",         END },
58         { "FETCH",       FETCH },
59         { "FILTER",      FILTER },
60         { "IN",          IN },
61         { "IS",          IS },
62         { "LIST",        LIST },
63         { "LOOKUP",      LOOKUP },
64         { "MATCHING",    MATCHING },
65         { "NOT",         NOT },
66         { "NULL",        NULL_T },
67         { "OR",          OR },
68         { "START",       START },
69         { "TIMESERIES",  TIMESERIES },
71         /* object types */
72         { "host",        HOST_T },
73         { "hosts",       HOSTS_T },
74         { "service",     SERVICE_T },
75         { "services",    SERVICES_T },
76         { "metric",      METRIC_T },
77         { "metrics",     METRICS_T },
78         { "attribute",   ATTRIBUTE_T },
79         { "attributes",  ATTRIBUTES_T },
80         /* queryable fields */
81         { "name",        NAME_T },
82         { "last_update", LAST_UPDATE_T },
83         { "age",         AGE_T },
84         { "interval",    INTERVAL_T },
85         { "backend",     BACKEND_T },
86 };
88 void
89 sdb_fe_yyerror(YYLTYPE *lval, sdb_fe_yyscan_t scanner, const char *msg);
91 %}
93 %option never-interactive
94 %option reentrant
95 %option bison-bridge
96 %option bison-locations
97 %option 8bit
98 %option yylineno
99 %option nodefault
100 %option noinput
101 %option nounput
102 %option noyywrap
103 %option verbose
104 %option warn
105 %option prefix="sdb_fe_yy" outfile="lex.yy.c"
107 %x CSC
109 whitespace              ([ \t\n\r\f]+)
110 simple_comment  ("--"[^\n\r]*)
112 /*
113  * C style comments
114  */
115 csc_start       \/\*
116 csc_inside      ([^*/]+|[^*]\/|\*[^/])
117 csc_end         \*\/
119 /*
120  * Strings and identifiers.
121  */
122 identifier      ([A-Za-z_][A-Za-z_0-9$]*)
123 /* TODO: fully support SQL strings */
124 string          ('([^']|'')*')
126 /*
127  * Numeric constants.
128  */
129 dec                     ([\+\-]?[0-9]+)
130 exp                     ([\+\-]?[0-9]+[Ee]\+?[0-9]+)
131 integer         ({dec}|{exp})
132 float1          ([\+\-]?[0-9]+\.[0-9]*([Ee][\+\-]?[0-9]+)?)
133 float2          ([\+\-]?[0-9]*\.[0-9]+([Ee][\+\-]?[0-9]+)?)
134 float3          ([\+\-]?[0-9]+[Ee]\-[0-9]+)
135 float4          ([\+\-]?[Ii][Nn][Ff]([Ii][Nn][Ii][Tt][Yy])?)
136 float5          ([Nn][Aa][Nn])
137 float           ({float1}|{float2}|{float3}|{float4}|{float5})
139 /*
140  * Time constants.
141  */
142 date            ([0-9]{4}-[0-9]{2}-[0-9]{2})
143 time            ([0-9]{1,2}:[0-9]{1,2}(:[0-9]{1,2}(\.[0-9]{1,9})?)?)
145 %%
147 {whitespace} |
148 {simple_comment}        { /* ignore */ }
150 {csc_start}                     { BEGIN(CSC); }
151 <CSC>{csc_inside}       { /* ignore */ }
152 <CSC>{csc_end}          { BEGIN(INITIAL); }
153 <CSC><<EOF>> {
154                 sdb_fe_yyerror(yylloc, yyscanner, "unterminated C-style comment");
155                 return SCANNER_ERROR;
156         }
158 {identifier} {
159                 size_t i;
160                 for (i = 0; i < SDB_STATIC_ARRAY_LEN(reserved_words); ++i)
161                         if (! strcasecmp(reserved_words[i].name, yytext))
162                                 return reserved_words[i].id;
164                 yylval->str = strdup(yytext);
165                 return IDENTIFIER;
166         }
167 {string} {
168                 char *quot;
169                 size_t len;
171                 /* remove the leading and trailing quote */
172                 yytext[yyleng - 1] = '\0';
173                 yylval->str = strdup(yytext + 1);
175                 quot = yylval->str;
176                 len = yyleng - 2;
177                 while ((quot = strstr(quot, "''")) != NULL) {
178                         memmove(quot, quot + 1, len - (quot - yylval->str) - 1);
179                         yylval->str[len - 1] = '\0';
180                         --len;
181                         ++quot;
182                 }
183                 return STRING;
184         }
185 {integer} {
186                 yylval->data.data.integer = (int64_t)strtoll(yytext, NULL, 10);
187                 yylval->data.type = SDB_TYPE_INTEGER;
188                 return INTEGER;
189         }
190 {float} {
191                 yylval->data.data.decimal = strtod(yytext, NULL);
192                 yylval->data.type = SDB_TYPE_DECIMAL;
193                 return FLOAT;
194         }
196 {date} {
197                 struct tm tm;
198                 memset(&tm, 0, sizeof(tm));
199                 if (! strptime(yytext, "%Y-%m-%d", &tm)) {
200                         char errmsg[1024];
201                         snprintf(errmsg, sizeof(errmsg),
202                                 "Failed to parse '%s' as date", yytext);
203                         sdb_fe_yyerror(yylloc, yyscanner, errmsg);
204                         return SCANNER_ERROR;
205                 }
206                 yylval->datetime = SECS_TO_SDB_TIME(mktime(&tm));
207                 return DATE;
208         }
209 {time} {
210                 struct tm tm;
211                 char time[9], ns[10];
212                 char *tmp;
214                 memset(&tm, 0, sizeof(tm));
215                 memset(time, '\0', sizeof(time));
216                 memset(ns, '0', sizeof(ns));
217                 ns[sizeof(ns) - 1] = '\0';
219                 tmp = strchr(yytext, '.');
220                 if (tmp) {
221                         size_t i;
222                         *tmp = '\0';
223                         ++tmp;
224                         strncpy(ns, tmp, sizeof(ns));
225                         for (i = strlen(ns); i < 9; ++i)
226                                 ns[i] = '0';
227                 }
228                 strncpy(time, yytext, sizeof(time));
229                 if (tmp) {
230                         /* reset for better error messages */
231                         --tmp;
232                         *tmp = '.';
233                 }
235                 tmp = strchr(time, ':');
236                 assert(tmp);
237                 tmp = strchr(tmp + 1, ':');
238                 if (! tmp)
239                         strncat(time, ":00", sizeof(time));
241                 if (! strptime(time, "%H:%M:%S", &tm)) {
242                         char errmsg[1024];
243                         snprintf(errmsg, sizeof(errmsg),
244                                 "Failed to parse '%s' as time", yytext);
245                         sdb_fe_yyerror(yylloc, yyscanner, errmsg);
246                         return SCANNER_ERROR;
247                 }
249                 yylval->datetime = SECS_TO_SDB_TIME(mktime(&tm));
250                 yylval->datetime += (sdb_time_t)strtoll(ns, NULL, 10);
251                 return TIME;
252         }
254 =       { return CMP_EQUAL; }
255 !=      { return CMP_NEQUAL; }
256 =~      { return CMP_REGEX; }
257 !~      { return CMP_NREGEX; }
258 \<      { return CMP_LT; }
259 \<=     { return CMP_LE; }
260 \>=     { return CMP_GE; }
261 \>      { return CMP_GT; }
262 \|\|    { return CONCAT; }
264 .       { /* XXX: */ return yytext[0]; }
266 %%
268 sdb_fe_yyscan_t
269 sdb_fe_scanner_init(const char *str, int len, sdb_fe_yyextra_t *yyext)
271         yyscan_t scanner;
273         if (! str)
274                 return NULL;
276         if (sdb_fe_yylex_init(&scanner)) {
277                 char errbuf[1024];
278                 sdb_strbuf_sprintf(yyext->errbuf, "yylex_init_failed: %s",
279                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
280                 return NULL;
281         }
283         sdb_fe_yyset_extra(yyext, scanner);
285         if (len < 0)
286                 len = strlen(str);
288         /* the newly allocated buffer state (YY_BUFFER_STATE) is stored inside the
289          * scanner and, thus, will be freed by yylex_destroy */
290         sdb_fe_yy_scan_bytes(str, len, scanner);
291         return scanner;
292 } /* sdb_fe_scanner_init */
294 void
295 sdb_fe_scanner_destroy(sdb_fe_yyscan_t scanner)
297         sdb_fe_yylex_destroy(scanner);
298 } /* sdb_fe_scanner_destroy */
300 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */