summaryrefslogtreecommitdiff
path: root/lib/parser/parser.cc
blob: 8b5d8c84688733d34e52d712a407af1a60dd068f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
**  Copyright (C) 2017 Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public License
**  as published by the Free Software Foundation; either version 2.1
**  of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free
**  Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
**  02110-1301, USA.
*/
#include "parser.hh"
#include "tokenizer.hh"
#include "utils.hh"

using namespace Mux;

// 3 precedence levels: units (NOT,()) > factors (OR) > terms (AND)

// query	->      <term-1> | ε
// <term-1>	->	<factor-1> <term-2> | ε
// <term-2>	->	OR|XOR <term-1> | ε
// <factor-1>	->	<unit> <factor-2> | ε
// <factor-2>	->	[AND]|AND NOT <factor-1> | ε
// <unit>	->	[NOT] <term-1> | ( <term-1> ) | <data>
// <data>       ->      <value> | <range> | <regex>
// <value>      ->      [field:]value
// <range>      ->      [field:][lower]..[upper]
// <regex>      ->      [field:]/regex/


#define BUG(...) std::runtime_error (format("%u: BUG: ",__LINE__)	\
				     + format(__VA_ARGS__))

static Token
look_ahead (const Mux::Tokens& tokens)
{
	return tokens.front();
}

static Mux::Tree
empty()
{
	return {{Node::Type::Empty}};
}

static Mux::Tree term_1 (Mux::Tokens& tokens, ProcPtr proc, WarningVec& warnings);


static Mux::Tree
value (const ProcIface::FieldInfoVec& fields, const std::string& v,
       size_t pos, ProcPtr proc, WarningVec& warnings)
{
	auto val = utf8_flatten(v);

	if (fields.empty())
		throw BUG("expected one or more fields");

	if (fields.size() == 1) {
		const auto item = fields.front();
		return Tree({Node::Type::Value,
			     std::make_unique<Value>(
				     item.field, item.prefix, item.id,
				     proc->process_value(item.field, val),
				     item.supports_phrase)});
	}

	// a 'multi-field' such as "recip:"
	Tree tree(Node{Node::Type::OpOr});
	for (const auto& item: fields)
		tree.add_child (Tree({Node::Type::Value,
				      std::make_unique<Value>(
					      item.field, item.prefix, item.id,
					      proc->process_value(item.field, val),
					      item.supports_phrase)}));
	return tree;
}

static Mux::Tree
regex (const ProcIface::FieldInfoVec& fields, const std::string& v,
       size_t pos, ProcPtr proc, WarningVec& warnings)
{
	if (v.length() < 2)
		throw BUG("expected regexp, got '%s'", v.c_str());

	const auto rxstr = utf8_flatten(v.substr(1, v.length()-2));

 	try {
		Tree tree(Node{Node::Type::OpOr});
		const auto rx = std::regex (rxstr);
		for (const auto& field: fields) {
			const auto terms = proc->process_regex (field.field, rx);
			for (const auto& term: terms) {
				tree.add_child (Tree(
					{Node::Type::Value,
					 std::make_unique<Value>(field.field, "",
								 field.id, term)}));
			}
		}

		if (tree.children.empty())
			return empty();
		else
			return tree;

	} catch (...) {
		// fallback
		warnings.push_back ({pos, "invalid regexp"});
		return value (fields, v, pos, proc, warnings);
	}
}



static Mux::Tree
range (const ProcIface::FieldInfoVec& fields, const std::string& lower,
       const std::string& upper, size_t pos, ProcPtr proc,
       WarningVec& warnings)
{
	if (fields.empty())
		throw BUG("expected field");

	const auto& field = fields.front();
	if (!proc->is_range_field(field.field))
		return value (fields, lower + ".." + upper, pos, proc, warnings);

	auto prange = proc->process_range (field.field, lower, upper);
	if (prange.lower > prange.upper)
		prange = proc->process_range (field.field, upper, lower);

	return Tree({Node::Type::Range,
			     std::make_unique<Range>(field.field, field.prefix, field.id,
						     prange.lower, prange.upper)});
}


static Mux::Tree
data (Mux::Tokens& tokens, ProcPtr proc, WarningVec& warnings)
{
	const auto token = look_ahead(tokens);
	if (token.type != Token::Type::Data)
		warnings.push_back ({token.pos, "expected: value"});

	tokens.pop_front();

	std::string field, val;
	const auto col = token.str.find (":");
	if (col != 0 && col != std::string::npos && col != token.str.length()-1) {
		field = token.str.substr(0, col);
		val = token.str.substr(col + 1);
	} else
		val = token.str;

	auto fields = proc->process_field (field);
	if (fields.empty()) {// not valid field...
		warnings.push_back ({token.pos, format ("invalid field '%s'", field.c_str())});
		fields = proc->process_field ("");
		// fallback, treat the whole of foo:bar as a value
		return value (fields, field + ":" + val, token.pos, proc, warnings);
	}

	// does it look like a regexp?
	if (val.length() >=2 )
		if (val[0] == '/' && val[val.length()-1] == '/')
			return regex (fields, val, token.pos, proc, warnings);

	// does it look like a range?
	const auto dotdot = val.find("..");
	if (dotdot != std::string::npos)
		return range(fields, val.substr(0, dotdot), val.substr(dotdot + 2),
			     token.pos, proc, warnings);
	else if (proc->is_range_field(fields.front().field)) {
		// range field without a range - treat as field:val..val
		return range (fields, val, val, token.pos, proc, warnings);
	}

	// if nothing else, it's a value.
	return value (fields, val, token.pos, proc, warnings);
}

static Mux::Tree
unit (Mux::Tokens& tokens, ProcPtr proc, WarningVec& warnings)
{
	if (tokens.empty()) {
		warnings.push_back ({0, "expected: unit"});
		return empty();
	}

	const auto token = look_ahead (tokens);

	if (token.type == Token::Type::Not) {
		tokens.pop_front();
		Tree tree{{Node::Type::OpNot}};
		tree.add_child(unit (tokens, proc, warnings));
		return tree;
	}

	if (token.type == Token::Type::Open) {
		tokens.pop_front();
		auto tree = term_1 (tokens, proc, warnings);
		if (tokens.empty())
			warnings.push_back({token.pos, "expected: ')'"});
		else {
			const auto token2 = look_ahead(tokens);
			if (token2.type == Token::Type::Close)
				tokens.pop_front();
			else {
				warnings.push_back(
				{token2.pos,
				 std::string("expected: ')' but got ") +
				 token2.str});
			}

		}
		return tree;
	}

	return data (tokens, proc, warnings);
}

static Mux::Tree factor_1 (Mux::Tokens& tokens, ProcPtr proc,
			   WarningVec& warnings);

static Mux::Tree
factor_2 (Mux::Tokens& tokens, Node::Type& op, ProcPtr proc,
	  WarningVec& warnings)
{
	if (tokens.empty())
		return empty();

	const auto token = look_ahead(tokens);

	switch (token.type) {
	case Token::Type::And: {
		tokens.pop_front();
		op = Node::Type::OpAnd;
	} break;

	case Token::Type::Open:
	case Token::Type::Data:
	case Token::Type::Not:
		op = Node::Type::OpAnd; // implicit AND
		break;

	default:
		return empty();
	}

	return factor_1 (tokens, proc, warnings);
}

static Mux::Tree
factor_1 (Mux::Tokens& tokens, ProcPtr proc, WarningVec& warnings)
{
	Node::Type op { Node::Type::Invalid };

	auto t  = unit (tokens, proc, warnings);
	auto a2 = factor_2 (tokens, op, proc, warnings);

	if (a2.empty())
		return t;

	Tree tree {{op}};
	tree.add_child(std::move(t));
	tree.add_child(std::move(a2));

	return tree;
}


static Mux::Tree
term_2 (Mux::Tokens& tokens, Node::Type& op, ProcPtr proc,
	WarningVec& warnings)
{
	if (tokens.empty())
		return empty();

	const auto token = look_ahead (tokens);

	switch (token.type) {
	case Token::Type::Or:
		op = Node::Type::OpOr;
		break;
	case Token::Type::Xor:
		op = Node::Type::OpXor;
		break;
	default:
		if (token.type != Token::Type::Close)
			warnings.push_back({token.pos, "expected OR|XOR"});
		return empty();
	}

	tokens.pop_front();

	return term_1 (tokens, proc, warnings);
}

static Mux::Tree
term_1 (Mux::Tokens& tokens, ProcPtr proc, WarningVec& warnings)
{
	Node::Type op { Node::Type::Invalid };

	auto t  = factor_1 (tokens, proc, warnings);
	auto o2 = term_2 (tokens, op, proc, warnings);

	if (o2.empty())
		return t;
	else {
		Tree tree {{op}};
		tree.add_child(std::move(t));
		tree.add_child(std::move(o2));
		return tree;
	}
}

static Mux::Tree
query (Mux::Tokens& tokens, ProcPtr proc, WarningVec& warnings)
{
	if (tokens.empty())
		return empty ();
	else
		return term_1 (tokens, proc, warnings);
}

Mux::Tree
Mux::parse (const std::string& expr, WarningVec& warnings, ProcPtr proc)
{
	try {
		auto tokens = tokenize (expr);
		return query (tokens, proc, warnings);

	} catch (const std::runtime_error& ex) {
		std::cerr << ex.what() << std::endl;
		return empty();
	}
}