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
mod ast;
mod normalize;
pub mod operators;
lalrpop_mod!(parser, "/annis/db/aql/parser.rs");
use annis::db::aql::operators::edge_op::PartOfSubCorpusSpec;
use annis::db::aql::operators::identical_node::IdenticalNodeSpec;
use annis::errors::*;
use annis::db::exec::nodesearch::NodeSearchSpec;
use annis::operator::OperatorSpec;
use annis::db::query::conjunction::Conjunction;
use annis::db::query::disjunction::Disjunction;
use annis::types::{LineColumn, LineColumnRange};
use lalrpop_util::ParseError;
use std::collections::BTreeMap;
use std::collections::HashMap;
pub fn parse<'a>(query_as_aql: &str) -> Result<Disjunction<'a>> {
let ast = parser::DisjunctionParser::new().parse(query_as_aql);
match ast {
Ok(mut ast) => {
let offsets = get_line_offsets(query_as_aql);
// make sure AST is in DNF
normalize::to_disjunctive_normal_form(&mut ast);
// map all conjunctions and its literals
let mut alternatives: Vec<Conjunction> = Vec::new();
for c in ast.into_iter() {
let mut q = Conjunction::new();
// collect and sort all node searches according to their start position in the text
let mut pos_to_node: BTreeMap<
usize,
(NodeSearchSpec, Option<String>),
> = BTreeMap::default();
let mut pos_to_endpos: BTreeMap<usize, usize> = BTreeMap::default();
let mut legacy_meta_search: Vec<(NodeSearchSpec, ast::Pos)> = Vec::new();
for f in c.iter() {
if let ast::Factor::Literal(literal) = f {
match literal {
ast::Literal::NodeSearch {
spec,
pos,
variable,
} => {
if let Some(pos) = pos {
pos_to_node.insert(pos.start, (spec.clone(), variable.clone()));
pos_to_endpos.insert(pos.start, pos.end.clone());
}
}
ast::Literal::BinaryOp { lhs, rhs, .. } => {
if let ast::Operand::Literal {
spec,
pos,
variable,
} = lhs
{
pos_to_node.entry(pos.start).or_insert_with(|| {
(spec.as_ref().clone(), variable.clone())
});
pos_to_endpos
.entry(pos.start)
.or_insert_with(|| pos.end.clone());
}
if let ast::Operand::Literal {
spec,
pos,
variable,
} = rhs
{
pos_to_node.entry(pos.start).or_insert_with(|| {
(spec.as_ref().clone(), variable.clone())
});
pos_to_endpos
.entry(pos.start)
.or_insert_with(|| pos.end.clone());
}
}
ast::Literal::LegacyMetaSearch { spec, pos } => {
legacy_meta_search.push((spec.clone(), pos.clone()));
}
};
}
}
// add all nodes specs in order of their start position
let mut first_node_pos: Option<String> = None;
let mut pos_to_node_id: HashMap<usize, String> = HashMap::default();
for (start_pos, (node_spec, variable)) in pos_to_node.into_iter() {
let variable = variable.as_ref().map(|s| &**s);
let start = get_line_and_column_for_pos(start_pos, &offsets);
let end = if let Some(end_pos) = pos_to_endpos.get(&start_pos) {
Some(get_line_and_column_for_pos(*end_pos, &offsets))
} else {
None
};
let idx = q.add_node_from_query(
node_spec,
variable,
Some(LineColumnRange { start, end }),
);
pos_to_node_id.insert(start_pos, idx.clone());
if first_node_pos.is_none() {
first_node_pos = Some(idx);
}
}
// add all legacy meta searches
{
let mut first_meta_idx: Option<String> = None;
// TODO: add warning to the user not to use this construct anymore
for (spec, _pos) in legacy_meta_search.into_iter() {
// add an artificial node that describes the document/corpus node
let meta_node_idx = q.add_node(spec, None);
if let Some(first_meta_idx) = first_meta_idx.clone() {
// avoid nested loops by joining additional meta nodes with a "identical node"
q.add_operator(
Box::new(IdenticalNodeSpec {}),
&first_meta_idx,
&meta_node_idx,
)?;
} else if let Some(first_node_pos) = first_node_pos.clone() {
first_meta_idx = Some(meta_node_idx.clone());
// add a special join to the first node of the query
q.add_operator(
Box::new(PartOfSubCorpusSpec {
min_dist: 1,
max_dist: usize::max_value(),
}),
&first_node_pos,
&meta_node_idx,
)?;
// Also make sure the matched node is actually a document
// (the @* could match anything in the hierarchy, including the toplevel corpus)
let doc_anno_idx = q.add_node(
NodeSearchSpec::ExactValue {
ns: Some("annis".to_string()),
name: "doc".to_string(),
val: None,
is_meta: true,
},
None,
);
q.add_operator(
Box::new(IdenticalNodeSpec {}),
&meta_node_idx,
&doc_anno_idx,
)?;
}
}
}
// finally add all operators
for f in c.into_iter() {
if let ast::Factor::Literal(literal) = f {
if let ast::Literal::BinaryOp { lhs, op, rhs, pos } = literal {
let idx_left = match lhs {
ast::Operand::Literal { spec, pos, .. } => pos_to_node_id
.entry(pos.start)
.or_insert_with(|| q.add_node(spec.as_ref().clone(), None))
.clone(),
ast::Operand::NodeRef(node_ref) => match node_ref {
ast::NodeRef::ID(id) => id.to_string(),
ast::NodeRef::Name(name) => name,
},
};
let idx_right = match rhs {
ast::Operand::Literal { spec, pos, .. } => pos_to_node_id
.entry(pos.start)
.or_insert_with(|| q.add_node(spec.as_ref().clone(), None))
.clone(),
ast::Operand::NodeRef(node_ref) => match node_ref {
ast::NodeRef::ID(id) => id.to_string(),
ast::NodeRef::Name(name) => name,
},
};
let op_pos: Option<LineColumnRange> = if let Some(pos) = pos {
Some(LineColumnRange {
start: get_line_and_column_for_pos(pos.start, &offsets),
end: Some(get_line_and_column_for_pos(pos.end, &offsets)),
})
} else {
None
};
q.add_operator_from_query(
make_operator_spec(op),
&idx_left,
&idx_right,
op_pos,
)?;
}
}
}
// add the conjunction to the disjunction
alternatives.push(q);
}
return Ok(Disjunction::new(alternatives));
}
Err(e) => {
let mut desc = match e {
ParseError::InvalidToken { .. } => "Invalid token detected.",
ParseError::ExtraToken { .. } => "Extra token at end of query.",
ParseError::UnrecognizedToken { .. } => "Unexpected token in query.",
ParseError::User { error } => error,
}.to_string();
let location = extract_location(&e, query_as_aql);
match e {
ParseError::UnrecognizedToken { expected, .. } => {
if !expected.is_empty() {
//TODO: map token regular expressions and IDs (like IDENT_NODE) to human readable descriptions
desc.push_str("Expected one of: ");
desc.push_str(&expected.join(","));
}
}
_ => {}
};
return Err(ErrorKind::AQLSyntaxError(desc, location).into());
}
};
}
fn make_operator_spec(op: ast::BinaryOpSpec) -> Box<OperatorSpec> {
match op {
ast::BinaryOpSpec::Dominance(spec) => Box::new(spec),
ast::BinaryOpSpec::Pointing(spec) => Box::new(spec),
ast::BinaryOpSpec::Precedence(spec) => Box::new(spec),
ast::BinaryOpSpec::Overlap(spec) => Box::new(spec),
ast::BinaryOpSpec::IdenticalCoverage(spec) => Box::new(spec),
ast::BinaryOpSpec::PartOfSubCorpus(spec) => Box::new(spec),
ast::BinaryOpSpec::Inclusion(spec) => Box::new(spec),
ast::BinaryOpSpec::IdenticalNode(spec) => Box::new(spec),
}
}
fn get_line_offsets(input: &str) -> BTreeMap<usize, usize> {
let mut offsets = BTreeMap::default();
let mut o = 0;
let mut l = 1;
for line in input.split("\n") {
offsets.insert(o, l);
o += line.len() + 1;
l += 1;
}
return offsets;
}
pub fn get_line_and_column_for_pos(
pos: usize,
offset_to_line: &BTreeMap<usize, usize>,
) -> LineColumn {
// get the offset for the position by searching for all offsets smaller than the position and taking the last one
for (offset, line) in offset_to_line.range(..pos + 1).rev() {
// column starts with 1 at line offset
let column: usize = pos - offset + 1;
return LineColumn {
line: *line,
column,
};
}
return LineColumn { line: 0, column: 0 };
}
fn extract_location<'a>(
e: &ParseError<usize, parser::Token<'a>, &'static str>,
input: &'a str,
) -> Option<LineColumnRange> {
let offsets = get_line_offsets(input);
let from_to: Option<LineColumnRange> = match e {
ParseError::InvalidToken { location } => Some(LineColumnRange {
start: get_line_and_column_for_pos(*location, &offsets),
end: None,
}),
ParseError::ExtraToken { token } => {
let start = get_line_and_column_for_pos(token.0, &offsets);
let end = get_line_and_column_for_pos(token.2 - 1, &offsets);
Some(LineColumnRange {
start,
end: Some(end),
})
}
ParseError::UnrecognizedToken { token, .. } => {
if let Some(token) = token {
let start = get_line_and_column_for_pos(token.0, &offsets);
let end = get_line_and_column_for_pos(token.2 - 1, &offsets);
Some(LineColumnRange {
start,
end: Some(end),
})
} else {
// set to end of query
let start = get_line_and_column_for_pos(input.len() - 1, &offsets);
Some(LineColumnRange { start, end: None })
}
}
ParseError::User { .. } => None,
};
from_to
}