1use crate::desc::{Kind, Node};
38
39#[derive(Debug, Clone, PartialEq)]
41enum Token {
42 Name(String),
43 Number(f64),
44 Str(String),
45 Sym(&'static str),
47}
48
49fn lex(text: &str) -> Option<Vec<Token>> {
50 let b: Vec<char> = text.chars().collect();
51 let mut out = Vec::new();
52 let mut i = 0;
53 while i < b.len() {
54 let c = b[i];
55 if c.is_whitespace() {
56 i += 1;
57 continue;
58 }
59 if c == '\'' || c == '"' {
60 let quote = c;
61 i += 1;
62 let start = i;
63 while i < b.len() && b[i] != quote {
64 i += 1;
65 }
66 if i >= b.len() {
67 return None;
68 }
69 out.push(Token::Str(b[start..i].iter().collect()));
70 i += 1;
71 continue;
72 }
73 if c.is_ascii_digit() || (c == '.' && i + 1 < b.len() && b[i + 1].is_ascii_digit()) {
74 let start = i;
75 while i < b.len() && (b[i].is_ascii_digit() || b[i] == '.') {
76 i += 1;
77 }
78 let text: String = b[start..i].iter().collect();
79 out.push(Token::Number(text.parse().ok()?));
80 continue;
81 }
82 if c.is_alphabetic() || c == '_' {
83 let start = i;
84 while i < b.len() && (b[i].is_alphanumeric() || b[i] == '_' || b[i] == '.') {
85 i += 1;
86 if i < b.len() && b[i] == '-' {
90 if i + 1 < b.len() && (b[i + 1].is_alphabetic() || b[i + 1] == '_') {
91 i += 1;
92 } else {
93 break;
94 }
95 }
96 }
97 out.push(Token::Name(b[start..i].iter().collect()));
98 continue;
99 }
100 let two: String = b[i..(i + 2).min(b.len())].iter().collect();
101 let sym = match two.as_str() {
102 "//" => Some("//"),
103 "!=" => Some("!="),
104 "<=" => Some("<="),
105 ">=" => Some(">="),
106 _ => None,
107 };
108 if let Some(s) = sym {
109 out.push(Token::Sym(s));
110 i += 2;
111 continue;
112 }
113 let one = match c {
114 '(' => "(",
115 ')' => ")",
116 ',' => ",",
117 '/' => "/",
118 '=' => "=",
119 '<' => "<",
120 '>' => ">",
121 '+' => "+",
122 '-' => "-",
123 '*' => "*",
124 _ => return None,
125 };
126 out.push(Token::Sym(one));
127 i += 1;
128 }
129 Some(out)
130}
131
132#[derive(Debug, Clone)]
133enum Expr {
134 Number(f64),
135 Str(String),
136 Path {
138 descendant: bool,
139 steps: Vec<String>,
140 },
141 Binary(&'static str, Box<Expr>, Box<Expr>),
142 Negate(Box<Expr>),
143 Call(String, Vec<Expr>),
144}
145
146struct Parser {
147 tokens: Vec<Token>,
148 at: usize,
149}
150
151impl Parser {
152 fn peek(&self) -> Option<&Token> {
153 self.tokens.get(self.at)
154 }
155
156 fn eat_sym(&mut self, s: &str) -> bool {
157 if matches!(self.peek(), Some(Token::Sym(x)) if *x == s) {
158 self.at += 1;
159 return true;
160 }
161 false
162 }
163
164 fn eat_word(&mut self, w: &str) -> bool {
165 if matches!(self.peek(), Some(Token::Name(x)) if x == w) {
166 self.at += 1;
167 return true;
168 }
169 false
170 }
171
172 fn or(&mut self) -> Option<Expr> {
173 let mut left = self.and()?;
174 while self.eat_word("or") {
175 let right = self.and()?;
176 left = Expr::Binary("or", Box::new(left), Box::new(right));
177 }
178 Some(left)
179 }
180
181 fn and(&mut self) -> Option<Expr> {
182 let mut left = self.equality()?;
183 while self.eat_word("and") {
184 let right = self.equality()?;
185 left = Expr::Binary("and", Box::new(left), Box::new(right));
186 }
187 Some(left)
188 }
189
190 fn equality(&mut self) -> Option<Expr> {
191 let mut left = self.relational()?;
192 loop {
193 let op = if self.eat_sym("=") {
194 "="
195 } else if self.eat_sym("!=") {
196 "!="
197 } else {
198 return Some(left);
199 };
200 let right = self.relational()?;
201 left = Expr::Binary(op, Box::new(left), Box::new(right));
202 }
203 }
204
205 fn relational(&mut self) -> Option<Expr> {
206 let mut left = self.additive()?;
207 loop {
208 let op = if self.eat_sym("<=") {
210 "<="
211 } else if self.eat_sym(">=") {
212 ">="
213 } else if self.eat_sym("<") {
214 "<"
215 } else if self.eat_sym(">") {
216 ">"
217 } else {
218 return Some(left);
219 };
220 let right = self.additive()?;
221 left = Expr::Binary(op, Box::new(left), Box::new(right));
222 }
223 }
224
225 fn additive(&mut self) -> Option<Expr> {
226 let mut left = self.multiplicative()?;
227 loop {
228 let op = if self.eat_sym("+") {
229 "+"
230 } else if self.eat_sym("-") {
231 "-"
232 } else {
233 return Some(left);
234 };
235 let right = self.multiplicative()?;
236 left = Expr::Binary(op, Box::new(left), Box::new(right));
237 }
238 }
239
240 fn multiplicative(&mut self) -> Option<Expr> {
241 let mut left = self.unary()?;
242 loop {
243 let op = if self.eat_sym("*") {
244 "*"
245 } else if self.eat_word("div") {
246 "div"
247 } else if self.eat_word("mod") {
248 "mod"
249 } else {
250 return Some(left);
251 };
252 let right = self.unary()?;
253 left = Expr::Binary(op, Box::new(left), Box::new(right));
254 }
255 }
256
257 fn unary(&mut self) -> Option<Expr> {
258 if self.eat_sym("-") {
259 return Some(Expr::Negate(Box::new(self.unary()?)));
260 }
261 self.primary()
262 }
263
264 fn primary(&mut self) -> Option<Expr> {
265 if self.eat_sym("(") {
266 let inner = self.or()?;
267 if !self.eat_sym(")") {
268 return None;
269 }
270 return Some(inner);
271 }
272 match self.peek().cloned() {
273 Some(Token::Number(n)) => {
274 self.at += 1;
275 Some(Expr::Number(n))
276 }
277 Some(Token::Str(s)) => {
278 self.at += 1;
279 Some(Expr::Str(s))
280 }
281 Some(Token::Sym("//")) => {
282 self.at += 1;
283 let steps = self.steps()?;
284 Some(Expr::Path {
285 descendant: true,
286 steps,
287 })
288 }
289 Some(Token::Sym("/")) => {
290 self.at += 1;
291 let steps = self.steps()?;
292 Some(Expr::Path {
293 descendant: false,
294 steps,
295 })
296 }
297 Some(Token::Name(word)) => {
298 if matches!(self.tokens.get(self.at + 1), Some(Token::Sym("("))) {
300 self.at += 2;
301 let mut args = Vec::new();
302 if !self.eat_sym(")") {
303 loop {
304 args.push(self.or()?);
305 if self.eat_sym(",") {
306 continue;
307 }
308 if self.eat_sym(")") {
309 break;
310 }
311 return None;
312 }
313 }
314 return Some(Expr::Call(word, args));
315 }
316 let steps = self.steps()?;
317 Some(Expr::Path {
318 descendant: false,
319 steps,
320 })
321 }
322 _ => None,
323 }
324 }
325
326 fn steps(&mut self) -> Option<Vec<String>> {
328 let mut out = Vec::new();
329 loop {
330 match self.peek().cloned() {
331 Some(Token::Name(w)) => {
332 self.at += 1;
333 out.push(w);
334 }
335 Some(Token::Sym("*")) => {
336 self.at += 1;
337 out.push("*".to_string());
338 }
339 _ => return None,
340 }
341 if !self.eat_sym("/") {
342 return Some(out);
343 }
344 }
345 }
346}
347
348#[derive(Debug, Clone)]
354enum Value {
355 Bool(bool),
356 Num(f64),
357 Str(String),
358 Nodes(Vec<String>),
359}
360
361fn text_of(node: &Node) -> String {
363 if node.kind != Kind::Element {
364 return node.value.clone();
365 }
366 let mut out = String::new();
367 for c in &node.children {
368 out.push_str(&text_of(c));
369 }
370 out
371}
372
373impl Value {
374 fn boolean(&self) -> bool {
375 match self {
376 Value::Bool(b) => *b,
377 Value::Num(n) => *n != 0.0 && !n.is_nan(),
378 Value::Str(s) => !s.is_empty(),
379 Value::Nodes(n) => !n.is_empty(),
380 }
381 }
382
383 fn string(&self) -> String {
384 match self {
385 Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
386 Value::Num(n) => number_to_string(*n),
387 Value::Str(s) => s.clone(),
388 Value::Nodes(n) => n.first().cloned().unwrap_or_default(),
390 }
391 }
392
393 fn number(&self) -> f64 {
394 match self {
395 Value::Bool(b) => {
396 if *b {
397 1.0
398 } else {
399 0.0
400 }
401 }
402 Value::Num(n) => *n,
403 _ => self.string().trim().parse().unwrap_or(f64::NAN),
404 }
405 }
406}
407
408fn number_to_string(n: f64) -> String {
410 if n.is_nan() {
411 return "NaN".to_string();
412 }
413 if n.is_infinite() {
414 return if n < 0.0 { "-Infinity" } else { "Infinity" }.to_string();
415 }
416 if n == n.trunc() && n.abs() < 1e18 {
417 return format!("{}", n as i64);
418 }
419 let mut s = format!("{n}");
420 if s.contains('e') {
421 s = format!("{n:.10}");
422 while s.ends_with('0') {
423 s.pop();
424 }
425 if s.ends_with('.') {
426 s.pop();
427 }
428 }
429 s
430}
431
432fn walk(context: &Node, descendant: bool, steps: &[String]) -> Vec<String> {
434 let mut current: Vec<&Node> = vec![context];
437 if descendant {
438 let mut all = Vec::new();
439 collect(context, &mut all);
440 current = all;
441 }
442 for (depth, step) in steps.iter().enumerate() {
443 let mut next: Vec<&Node> = Vec::new();
444 for node in ¤t {
445 for child in &node.children {
446 if child.kind == Kind::Element && (step == "*" || &child.name == step) {
447 next.push(child);
448 }
449 }
450 }
451 current = next;
452 if current.is_empty() && depth + 1 < steps.len() {
453 break;
454 }
455 }
456 current.into_iter().map(text_of).collect()
457}
458
459fn collect<'a>(node: &'a Node, out: &mut Vec<&'a Node>) {
460 out.push(node);
461 for c in &node.children {
462 if c.kind == Kind::Element {
463 collect(c, out);
464 }
465 }
466}
467
468fn compare(op: &str, left: &Value, right: &Value) -> bool {
469 let relational = matches!(op, "<" | ">" | "<=" | ">=");
472 let numbers = |v: &Value| -> Vec<f64> {
473 match v {
474 Value::Nodes(n) => n
475 .iter()
476 .map(|s| s.trim().parse().unwrap_or(f64::NAN))
477 .collect(),
478 other => vec![other.number()],
479 }
480 };
481 if relational {
482 for a in numbers(left) {
483 for b in numbers(right) {
484 let ok = match op {
485 "<" => a < b,
486 ">" => a > b,
487 "<=" => a <= b,
488 _ => a >= b,
489 };
490 if ok {
491 return true;
492 }
493 }
494 }
495 return false;
496 }
497
498 let equal = |a: bool| if op == "=" { a } else { !a };
499 match (left, right) {
500 (Value::Nodes(a), Value::Nodes(b)) => {
501 for x in a {
502 for y in b {
503 if equal(x == y) {
504 return true;
505 }
506 }
507 }
508 false
509 }
510 (Value::Nodes(a), other) | (other, Value::Nodes(a)) => match other {
511 Value::Bool(_) => equal(Value::Nodes(a.clone()).boolean() == other.boolean()),
512 Value::Num(n) => a
513 .iter()
514 .any(|s| equal(s.trim().parse::<f64>().map(|v| v == *n).unwrap_or(false))),
515 _ => {
516 let want = other.string();
517 a.iter().any(|s| equal(*s == want))
518 }
519 },
520 (Value::Bool(_), _) | (_, Value::Bool(_)) => equal(left.boolean() == right.boolean()),
521 (Value::Num(_), _) | (_, Value::Num(_)) => equal(left.number() == right.number()),
522 _ => equal(left.string() == right.string()),
523 }
524}
525
526fn eval(expr: &Expr, context: &Node) -> Option<Value> {
527 Some(match expr {
528 Expr::Number(n) => Value::Num(*n),
529 Expr::Str(s) => Value::Str(s.clone()),
530 Expr::Path { descendant, steps } => Value::Nodes(walk(context, *descendant, steps)),
531 Expr::Negate(inner) => Value::Num(-eval(inner, context)?.number()),
532 Expr::Binary(op, a, b) => {
533 if *op == "and" {
535 return Some(Value::Bool(
536 eval(a, context)?.boolean() && eval(b, context)?.boolean(),
537 ));
538 }
539 if *op == "or" {
540 return Some(Value::Bool(
541 eval(a, context)?.boolean() || eval(b, context)?.boolean(),
542 ));
543 }
544 let left = eval(a, context)?;
545 let right = eval(b, context)?;
546 match *op {
547 "=" | "!=" | "<" | ">" | "<=" | ">=" => Value::Bool(compare(op, &left, &right)),
548 "+" => Value::Num(left.number() + right.number()),
549 "-" => Value::Num(left.number() - right.number()),
550 "*" => Value::Num(left.number() * right.number()),
551 "div" => Value::Num(left.number() / right.number()),
552 "mod" => Value::Num(left.number() % right.number()),
553 _ => return None,
554 }
555 }
556 Expr::Call(name, args) => {
557 let arg = |k: usize| -> Option<Value> { args.get(k).and_then(|e| eval(e, context)) };
558 match name.as_str() {
559 "true" if args.is_empty() => Value::Bool(true),
560 "false" if args.is_empty() => Value::Bool(false),
561 "not" if args.len() == 1 => Value::Bool(!arg(0)?.boolean()),
562 "count" if args.len() == 1 => match arg(0)? {
563 Value::Nodes(n) => Value::Num(n.len() as f64),
564 _ => return None,
565 },
566 "string" if args.len() == 1 => Value::Str(arg(0)?.string()),
567 "number" if args.len() == 1 => Value::Num(arg(0)?.number()),
568 "floor" if args.len() == 1 => Value::Num(arg(0)?.number().floor()),
569 "ceiling" if args.len() == 1 => Value::Num(arg(0)?.number().ceil()),
570 "round" if args.len() == 1 => Value::Num((arg(0)?.number() + 0.5).floor()),
573 "string-length" if args.len() == 1 => {
574 Value::Num(arg(0)?.string().chars().count() as f64)
575 }
576 "concat" if args.len() >= 2 => {
577 let mut out = String::new();
578 for k in 0..args.len() {
579 out.push_str(&arg(k)?.string());
580 }
581 Value::Str(out)
582 }
583 "contains" if args.len() == 2 => {
584 Value::Bool(arg(0)?.string().contains(&arg(1)?.string()))
585 }
586 "starts-with" if args.len() == 2 => {
587 Value::Bool(arg(0)?.string().starts_with(&arg(1)?.string()))
588 }
589 "normalize-space" if args.len() == 1 => Value::Str(
590 arg(0)?
591 .string()
592 .split_whitespace()
593 .collect::<Vec<_>>()
594 .join(" "),
595 ),
596 "translate" if args.len() == 3 => {
597 let from: Vec<char> = arg(1)?.string().chars().collect();
598 let to: Vec<char> = arg(2)?.string().chars().collect();
599 let mut out = String::new();
600 for c in arg(0)?.string().chars() {
601 match from.iter().position(|x| *x == c) {
602 Some(k) => {
604 if let Some(r) = to.get(k) {
605 out.push(*r);
606 }
607 }
608 None => out.push(c),
609 }
610 }
611 Value::Str(out)
612 }
613 "substring" if args.len() == 2 || args.len() == 3 => {
615 let s: Vec<char> = arg(0)?.string().chars().collect();
616 let start = (arg(1)?.number() + 0.5).floor();
617 let end = match args.len() {
618 3 => start + (arg(2)?.number() + 0.5).floor(),
619 _ => f64::INFINITY,
620 };
621 let mut out = String::new();
622 for (k, c) in s.iter().enumerate() {
623 let pos = (k + 1) as f64;
624 if pos >= start && pos < end {
625 out.push(*c);
626 }
627 }
628 Value::Str(out)
629 }
630 _ => return None,
631 }
632 }
633 })
634}
635
636pub fn matches(query: &str, document: &Node) -> bool {
642 let q = query.trim();
643 if q.is_empty() {
644 return true;
645 }
646 let tokens = match lex(q) {
647 Some(t) => t,
648 None => return false,
649 };
650 let mut parser = Parser { tokens, at: 0 };
651 let expr = match parser.or() {
652 Some(e) => e,
653 None => return false,
654 };
655 if parser.at != parser.tokens.len() {
657 return false;
658 }
659 match eval(&expr, document) {
660 Some(v) => v.boolean(),
661 None => false,
662 }
663}
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668
669 fn document() -> Node {
671 let mut info = Node::element("info");
672 info.append_child_value("name", "XpTest");
673 info.append_child_value("type", "EEG");
674 info.append_child_value("channel_count", "8");
675 info.append_child_value("channel_format", "float32");
676 info.append_child_value("source_id", "xp_src");
677 info.append_child_value("nominal_srate", "100.0000000000000");
678 info.append_child_value("session_id", "default");
679 info.append_child_value("v4data_port", "16572");
680 info.append_child("desc");
681 info
682 }
683
684 fn hit(q: &str) -> bool {
685 matches(q, &document())
686 }
687
688 #[test]
689 fn the_queries_that_a_resolver_builds() {
690 assert!(hit(""));
691 assert!(hit("session_id='default'"));
692 assert!(hit("session_id='default' and name='XpTest'"));
693 assert!(!hit("session_id='default' and name='Other'"));
694 assert!(hit("name='XpTest'"));
695 assert!(hit("type='EEG'"));
696 assert!(hit("source_id='xp_src'"));
697 }
698
699 #[test]
700 fn the_boolean_operators() {
701 assert!(hit("name='XpTest' or name='Nothing'"));
702 assert!(!hit("name='Nothing' or name='AlsoNothing'"));
703 assert!(hit("not(name='Nothing')"));
704 assert!(!hit("not(name='XpTest')"));
705 assert!(hit("name='XpTest' and type='EEG' and source_id='xp_src'"));
706 assert!(hit("(name='XpTest' or name='X') and type='EEG'"));
707 assert!(hit("true()"));
708 assert!(!hit("false()"));
709 }
710
711 #[test]
712 fn the_string_functions() {
713 assert!(hit("contains(name,'XpT')"));
714 assert!(!hit("contains(name,'zzz')"));
715 assert!(hit("starts-with(name,'Xp')"));
716 assert!(!hit("starts-with(name,'zz')"));
717 assert!(hit("string-length(name)>3"));
718 assert!(hit("substring(name,1,2)='Xp'"));
719 assert!(hit("translate(name,'X','x')='xpTest'"));
720 assert!(hit("concat(name,type)='XpTestEEG'"));
721 assert!(hit("normalize-space(name)='XpTest'"));
722 }
723
724 #[test]
725 fn the_numbers() {
726 assert!(hit("channel_count=8"));
727 assert!(hit("channel_count>4"));
728 assert!(!hit("channel_count<4"));
729 assert!(hit("channel_count>=8"));
730 assert!(hit("nominal_srate=100"));
731 assert!(hit("number(channel_count)+1=9"));
732 assert!(hit("floor(nominal_srate div 3)=33"));
733 }
734
735 #[test]
736 fn the_paths() {
737 assert!(!hit("info/name='XpTest'"));
740 assert!(hit("//name='XpTest'"));
741 assert!(hit("name"));
742 assert!(!hit("missing_field"));
743 assert!(hit("count(//name)=1"));
744 assert!(hit("//v4data_port>0"));
745 }
746
747 #[test]
748 fn a_query_that_cannot_be_read_matches_nothing() {
749 assert!(!hit("in'va'lid"));
750 assert!(!hit("name="));
751 assert!(!hit("and and and"));
752 assert!(!hit("name='XpTest'))"));
753 assert!(!hit("!!!"));
754 }
755}