aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-09-29 14:39:52 +0200
committerOnur Gündüz <ogunduz@gmail.com>2026-09-29 14:39:52 +0200
commitcf5358473839638940dcf43f83fe3afe298cf112 (patch)
treed73788adf3f2d54e93168697e90f34a97f8749ba
parente725f63eee5bdb5854aa24b75139951efebb3191 (diff)
downloadele-cf5358473839638940dcf43f83fe3afe298cf112.tar.gz
ele-cf5358473839638940dcf43f83fe3afe298cf112.zip
Apply standard Rust formatting for release checks
-rw-r--r--src/ast.rs5
-rw-r--r--src/display.rs12
-rw-r--r--src/eval.rs99
-rw-r--r--src/lex.rs300
-rw-r--r--src/main.rs48
-rw-r--r--src/parser.rs55
6 files changed, 385 insertions, 134 deletions
diff --git a/src/ast.rs b/src/ast.rs
index 7612c35..9c3c3cf 100644
--- a/src/ast.rs
+++ b/src/ast.rs
@@ -99,10 +99,7 @@ pub enum Expr {
},
/// A function call expression: `fn(args...)`.
- Function {
- func: Box<Expr>,
- args: Vec<Expr>,
- },
+ Function { func: Box<Expr>, args: Vec<Expr> },
}
impl Expr {
diff --git a/src/display.rs b/src/display.rs
index f89f284..4fb7c58 100644
--- a/src/display.rs
+++ b/src/display.rs
@@ -10,7 +10,9 @@ impl fmt::Display for Expr {
impl Expr {
fn print(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
match self {
- Expr::Binary { op, left, right, .. } => {
+ Expr::Binary {
+ op, left, right, ..
+ } => {
let label = match op {
BinaryOp::And => "conjunction",
BinaryOp::Or => "disjunction",
@@ -29,13 +31,17 @@ impl Expr {
expr.print(f, indent + 2)
}
- Expr::Comparison { op, left, right, .. } => {
+ Expr::Comparison {
+ op, left, right, ..
+ } => {
writeln!(f, "{:indent$}compare {}", "", op.as_str(), indent = indent)?;
left.print(f, indent + 2)?;
right.print(f, indent + 2)
}
- Expr::Name { name, is_string, .. } => {
+ Expr::Name {
+ name, is_string, ..
+ } => {
if *is_string {
writeln!(f, "{:indent$}{:?}", "", name, indent = indent)
} else {
diff --git a/src/eval.rs b/src/eval.rs
index 517409f..46a599a 100644
--- a/src/eval.rs
+++ b/src/eval.rs
@@ -182,7 +182,10 @@ fn native_number(number: &serde_json::Number) -> Option<Value<'static>> {
} else if let Some(value) = number.as_u64() {
Some(Value::Uint(value))
} else {
- number.as_f64().filter(|value| value.is_finite()).map(Value::Float)
+ number
+ .as_f64()
+ .filter(|value| value.is_finite())
+ .map(Value::Float)
}
}
@@ -261,14 +264,19 @@ impl<'a> Literal<'a> {
Cow::Borrowed(_) => None,
Cow::Owned(text) => Some(text),
};
- let word_prefix = if op == CompareOp::Has
- && !text.starts_with('*') && !text.ends_with('*')
+ let word_prefix = if op == CompareOp::Has && !text.starts_with('*') && !text.ends_with('*')
{
prefix_lengths(folded.as_deref().unwrap_or(&text).as_bytes())
} else {
Vec::new()
};
- Self { text, folded, number, boolean, word_prefix }
+ Self {
+ text,
+ folded,
+ number,
+ boolean,
+ word_prefix,
+ }
}
pub(crate) fn is_presence(&self) -> bool {
@@ -284,11 +292,26 @@ pub(crate) fn eval_literal(op: CompareOp, value: &Value<'_>, literal: &Literal<'
if op == CompareOp::Has && literal.text == "*" {
return !value.is_zero();
}
- if matches!(op, CompareOp::Equals | CompareOp::NotEquals | CompareOp::Has) {
- let element_op = if op == CompareOp::NotEquals { CompareOp::Equals } else { op };
+ if matches!(
+ op,
+ CompareOp::Equals | CompareOp::NotEquals | CompareOp::Has
+ ) {
+ let element_op = if op == CompareOp::NotEquals {
+ CompareOp::Equals
+ } else {
+ op
+ };
let found = match value {
- Value::List(items) => Some(items.iter().any(|item| value_matches_literal(item, literal, element_op))),
- Value::JsonArray(items) => Some(items.iter().any(|item| value_matches_literal(&Value::from(item), literal, element_op))),
+ Value::List(items) => Some(
+ items
+ .iter()
+ .any(|item| value_matches_literal(item, literal, element_op)),
+ ),
+ Value::JsonArray(items) => Some(
+ items
+ .iter()
+ .any(|item| value_matches_literal(&Value::from(item), literal, element_op)),
+ ),
_ => None,
};
if let Some(found) = found {
@@ -297,8 +320,16 @@ pub(crate) fn eval_literal(op: CompareOp, value: &Value<'_>, literal: &Literal<'
}
if op == CompareOp::Has {
match value {
- Value::Map(entries) => return entries.iter().any(|(key, _)| key.eq_ignore_ascii_case(&literal.text)),
- Value::JsonObject(entries) => return entries.keys().any(|key| key.eq_ignore_ascii_case(&literal.text)),
+ Value::Map(entries) => {
+ return entries
+ .iter()
+ .any(|(key, _)| key.eq_ignore_ascii_case(&literal.text));
+ }
+ Value::JsonObject(entries) => {
+ return entries
+ .keys()
+ .any(|key| key.eq_ignore_ascii_case(&literal.text));
+ }
_ => {}
}
}
@@ -307,10 +338,18 @@ pub(crate) fn eval_literal(op: CompareOp, value: &Value<'_>, literal: &Literal<'
fn value_matches_literal(value: &Value<'_>, literal: &Literal<'_>, op: CompareOp) -> bool {
match value {
- Value::List(items) => items.iter().any(|item| value_matches_literal(item, literal, op)),
- Value::Map(entries) => entries.iter().any(|(_, value)| value_matches_literal(value, literal, op)),
- Value::JsonArray(items) => items.iter().any(|value| value_matches_literal(&Value::from(value), literal, op)),
- Value::JsonObject(entries) => entries.values().any(|value| value_matches_literal(&Value::from(value), literal, op)),
+ Value::List(items) => items
+ .iter()
+ .any(|item| value_matches_literal(item, literal, op)),
+ Value::Map(entries) => entries
+ .iter()
+ .any(|(_, value)| value_matches_literal(value, literal, op)),
+ Value::JsonArray(items) => items
+ .iter()
+ .any(|value| value_matches_literal(&Value::from(value), literal, op)),
+ Value::JsonObject(entries) => entries
+ .values()
+ .any(|value| value_matches_literal(&Value::from(value), literal, op)),
_ => compare_literal(op, value, literal),
}
}
@@ -342,13 +381,15 @@ fn string_match(haystack: &str, literal: &Literal<'_>, op: CompareOp) -> bool {
let needle = literal.text.as_ref();
if matches!(op, CompareOp::Equals | CompareOp::Has) {
if let Some(suffix) = needle.strip_prefix('*') {
- return haystack.len()
+ return haystack
+ .len()
.checked_sub(suffix.len())
.and_then(|start| haystack.get(start..))
.is_some_and(|tail| tail.eq_ignore_ascii_case(suffix));
}
if let Some(prefix) = needle.strip_suffix('*') {
- return haystack.get(..prefix.len())
+ return haystack
+ .get(..prefix.len())
.is_some_and(|head| head.eq_ignore_ascii_case(prefix));
}
}
@@ -360,9 +401,8 @@ fn string_match(haystack: &str, literal: &Literal<'_>, op: CompareOp) -> bool {
if needle.is_empty() {
return true;
}
- let boundary = |c: char| {
- c.is_whitespace() || (c.is_ascii() && !c.is_ascii_alphanumeric())
- };
+ let boundary =
+ |c: char| c.is_whitespace() || (c.is_ascii() && !c.is_ascii_alphanumeric());
let bytes = needle.as_bytes();
let mut matched = 0;
for (index, byte) in haystack.bytes().enumerate() {
@@ -436,8 +476,12 @@ fn value_contains_str(val: &Value<'_>, search: &str) -> bool {
}
Value::List(items) => items.iter().any(|item| value_contains_str(item, search)),
Value::Map(entries) => entries.iter().any(|(_, v)| value_contains_str(v, search)),
- Value::JsonArray(items) => items.iter().any(|value| Value::from(value).matches_global(search)),
- Value::JsonObject(entries) => entries.values().any(|value| Value::from(value).matches_global(search)),
+ Value::JsonArray(items) => items
+ .iter()
+ .any(|value| Value::from(value).matches_global(search)),
+ Value::JsonObject(entries) => entries
+ .values()
+ .any(|value| Value::from(value).matches_global(search)),
Value::Null => false,
}
}
@@ -476,7 +520,10 @@ mod tests {
"score" => Some(Value::Float(self.score)),
"active" => Some(Value::Bool(self.active)),
"labels" => Some(Value::List(
- self.labels.iter().map(|l| Value::String(l.as_str())).collect(),
+ self.labels
+ .iter()
+ .map(|l| Value::String(l.as_str()))
+ .collect(),
)),
"name" => Some(Value::String(&self.name)),
_ => None,
@@ -543,7 +590,9 @@ mod tests {
#[test]
fn test_and() {
- let expr = parse(r#"state = "open" AND priority > 3"#).unwrap().unwrap();
+ let expr = parse(r#"state = "open" AND priority > 3"#)
+ .unwrap()
+ .unwrap();
assert!(expr.evaluate(&item()));
let expr = parse(r#"state = "closed" AND priority > 3"#)
@@ -658,9 +707,7 @@ mod tests {
impl Filterable for Outer {
fn field(&self, name: &str) -> Option<Value<'_>> {
match name {
- "inner" => Some(Value::Map(vec![
- ("value", Value::Int(self.inner.value)),
- ])),
+ "inner" => Some(Value::Map(vec![("value", Value::Int(self.inner.value))])),
_ => None,
}
}
diff --git a/src/lex.rs b/src/lex.rs
index 883e7c7..b7ebc4e 100644
--- a/src/lex.rs
+++ b/src/lex.rs
@@ -5,30 +5,30 @@ use super::ast::Position;
pub(crate) enum TokenKind {
InvalidInput,
Eof,
- Wsc, // whitespace or comment
- Dot, // .
- Has, // :
- Or, // OR
- And, // AND
- Not, // NOT
- Lparen, // (
- Rparen, // )
- Comma, // ,
- LessThan, // <
- GreaterThan, // >
- GreaterThanEquals, // >=
- LessThanEquals, // <=
- NotEquals, // !=
- MatchesRegexp, // =~
- NotMatchesRegexp, // !~
- Equals, // =
- Minus, // -
- Plus, // +
- Tilde, // ~
+ Wsc, // whitespace or comment
+ Dot, // .
+ Has, // :
+ Or, // OR
+ And, // AND
+ Not, // NOT
+ Lparen, // (
+ Rparen, // )
+ Comma, // ,
+ LessThan, // <
+ GreaterThan, // >
+ GreaterThanEquals, // >=
+ LessThanEquals, // <=
+ NotEquals, // !=
+ MatchesRegexp, // =~
+ NotMatchesRegexp, // !~
+ Equals, // =
+ Minus, // -
+ Plus, // +
+ Tilde, // ~
#[allow(dead_code)]
- Backslash, // backslash
- StringLit, // quoted string
- Text, // unquoted text/name
+ Backslash, // backslash
+ StringLit, // quoted string
+ Text, // unquoted text/name
}
/// A lexical token.
@@ -67,7 +67,11 @@ impl Lexer {
self.prev_text = false;
let Some(r) = self.peek() else {
- return Token { kind: TokenKind::Eof, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::Eof,
+ pos,
+ val: String::new(),
+ };
};
self.advance();
@@ -75,7 +79,11 @@ impl Lexer {
match r {
_ if is_white(r) => {
self.skip_white();
- Token { kind: TokenKind::Wsc, pos, val: String::new() }
+ Token {
+ kind: TokenKind::Wsc,
+ pos,
+ val: String::new(),
+ }
}
'-' => {
if let Some(rn) = self.peek() {
@@ -83,39 +91,67 @@ impl Lexer {
self.advance();
self.skip_comment();
self.skip_white();
- return Token { kind: TokenKind::Wsc, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::Wsc,
+ pos,
+ val: String::new(),
+ };
}
if is_digit(rn) {
return self.text(r, prev_dot);
}
- if !prev_text && rn == '.'
+ if !prev_text
+ && rn == '.'
&& let Some(&next_after) = self.input.get(self.cursor + 1)
- && is_digit(next_after) {
- return self.text(r, prev_dot);
- }
+ && is_digit(next_after)
+ {
+ return self.text(r, prev_dot);
+ }
+ }
+ Token {
+ kind: TokenKind::Minus,
+ pos,
+ val: String::new(),
}
- Token { kind: TokenKind::Minus, pos, val: String::new() }
}
'.' => {
if self.peek().is_none() {
self.prev_dot = true;
- return Token { kind: TokenKind::Dot, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::Dot,
+ pos,
+ val: String::new(),
+ };
}
if !prev_text
&& let Some(rn) = self.peek()
- && is_digit(rn) {
- return self.text(r, prev_dot);
- }
+ && is_digit(rn)
+ {
+ return self.text(r, prev_dot);
+ }
self.prev_dot = true;
- Token { kind: TokenKind::Dot, pos, val: String::new() }
+ Token {
+ kind: TokenKind::Dot,
+ pos,
+ val: String::new(),
+ }
}
- ':' => Token { kind: TokenKind::Has, pos, val: String::new() },
+ ':' => Token {
+ kind: TokenKind::Has,
+ pos,
+ val: String::new(),
+ },
'O' => {
- if self.remaining() > 0 && self.input[self.cursor] == 'R'
+ if self.remaining() > 0
+ && self.input[self.cursor] == 'R'
&& (self.remaining() < 2 || is_white(self.input[self.cursor + 1]))
{
self.advance();
- return Token { kind: TokenKind::Or, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::Or,
+ pos,
+ val: String::new(),
+ };
}
self.text(r, prev_dot)
}
@@ -127,7 +163,11 @@ impl Lexer {
{
self.advance();
self.advance();
- return Token { kind: TokenKind::And, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::And,
+ pos,
+ val: String::new(),
+ };
}
self.text(r, prev_dot)
}
@@ -139,38 +179,78 @@ impl Lexer {
{
self.advance();
self.advance();
- return Token { kind: TokenKind::Not, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::Not,
+ pos,
+ val: String::new(),
+ };
}
self.text(r, prev_dot)
}
- '(' => Token { kind: TokenKind::Lparen, pos, val: String::new() },
- ')' => Token { kind: TokenKind::Rparen, pos, val: String::new() },
- ',' => Token { kind: TokenKind::Comma, pos, val: String::new() },
+ '(' => Token {
+ kind: TokenKind::Lparen,
+ pos,
+ val: String::new(),
+ },
+ ')' => Token {
+ kind: TokenKind::Rparen,
+ pos,
+ val: String::new(),
+ },
+ ',' => Token {
+ kind: TokenKind::Comma,
+ pos,
+ val: String::new(),
+ },
'<' => {
if self.peek() == Some('=') {
self.advance();
- Token { kind: TokenKind::LessThanEquals, pos, val: String::new() }
+ Token {
+ kind: TokenKind::LessThanEquals,
+ pos,
+ val: String::new(),
+ }
} else {
- Token { kind: TokenKind::LessThan, pos, val: String::new() }
+ Token {
+ kind: TokenKind::LessThan,
+ pos,
+ val: String::new(),
+ }
}
}
'>' => {
if self.peek() == Some('=') {
self.advance();
- Token { kind: TokenKind::GreaterThanEquals, pos, val: String::new() }
+ Token {
+ kind: TokenKind::GreaterThanEquals,
+ pos,
+ val: String::new(),
+ }
} else {
- Token { kind: TokenKind::GreaterThan, pos, val: String::new() }
+ Token {
+ kind: TokenKind::GreaterThan,
+ pos,
+ val: String::new(),
+ }
}
}
'!' => {
if let Some(rn) = self.peek() {
if rn == '=' {
self.advance();
- return Token { kind: TokenKind::NotEquals, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::NotEquals,
+ pos,
+ val: String::new(),
+ };
}
if rn == '~' {
self.advance();
- return Token { kind: TokenKind::NotMatchesRegexp, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::NotMatchesRegexp,
+ pos,
+ val: String::new(),
+ };
}
}
// bare ! is part of a name
@@ -179,16 +259,36 @@ impl Lexer {
'=' => {
if self.peek() == Some('~') {
self.advance();
- Token { kind: TokenKind::MatchesRegexp, pos, val: String::new() }
+ Token {
+ kind: TokenKind::MatchesRegexp,
+ pos,
+ val: String::new(),
+ }
} else {
- Token { kind: TokenKind::Equals, pos, val: String::new() }
+ Token {
+ kind: TokenKind::Equals,
+ pos,
+ val: String::new(),
+ }
}
}
- '+' => Token { kind: TokenKind::Plus, pos, val: String::new() },
- '~' => Token { kind: TokenKind::Tilde, pos, val: String::new() },
+ '+' => Token {
+ kind: TokenKind::Plus,
+ pos,
+ val: String::new(),
+ },
+ '~' => Token {
+ kind: TokenKind::Tilde,
+ pos,
+ val: String::new(),
+ },
'"' => self.collect_string(),
_ if is_text_start(r) || is_digit(r) => self.text(r, prev_dot),
- _ => Token { kind: TokenKind::InvalidInput, pos, val: String::new() },
+ _ => Token {
+ kind: TokenKind::InvalidInput,
+ pos,
+ val: String::new(),
+ },
}
}
@@ -220,7 +320,9 @@ impl Lexer {
fn skip_white(&mut self) {
loop {
match self.peek() {
- Some(r) if is_white(r) => { self.advance(); }
+ Some(r) if is_white(r) => {
+ self.advance();
+ }
Some('-') => {
if self.input.get(self.cursor + 1) == Some(&'-') {
self.advance();
@@ -253,7 +355,11 @@ impl Lexer {
if first != '\\' {
sb.push(first);
} else if !self.text_esc(&mut sb) {
- return Token { kind: TokenKind::InvalidInput, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::InvalidInput,
+ pos,
+ val: String::new(),
+ };
}
// Number prefix handling
@@ -283,7 +389,11 @@ impl Lexer {
if rn == '\\' {
self.advance();
if !self.text_esc(&mut sb) {
- return Token { kind: TokenKind::InvalidInput, pos, val: String::new() };
+ return Token {
+ kind: TokenKind::InvalidInput,
+ pos,
+ val: String::new(),
+ };
}
} else if is_text_start(rn) || is_digit(rn) || rn == '+' || rn == '-' {
sb.push(rn);
@@ -291,9 +401,10 @@ impl Lexer {
} else if rn == '!' {
// ! is part of a name unless followed by = or ~
if let Some(&next) = self.input.get(self.cursor + 1)
- && (next == '=' || next == '~') {
- break;
- }
+ && (next == '=' || next == '~')
+ {
+ break;
+ }
sb.push(rn);
self.advance();
} else {
@@ -302,7 +413,11 @@ impl Lexer {
}
self.prev_text = true;
- Token { kind: TokenKind::Text, pos, val: sb }
+ Token {
+ kind: TokenKind::Text,
+ pos,
+ val: sb,
+ }
}
fn text_esc(&mut self, sb: &mut String) -> bool {
@@ -328,9 +443,8 @@ impl Lexer {
self.advance(); // skip r
self.advance(); // skip n1
self.advance(); // skip n2
- let val = (d0 << 6)
- + ((n1 as u32 - '0' as u32) << 3)
- + (n2 as u32 - '0' as u32);
+ let val =
+ (d0 << 6) + ((n1 as u32 - '0' as u32) << 3) + (n2 as u32 - '0' as u32);
if let Some(c) = char::from_u32(val) {
sb.push(c);
} else {
@@ -417,21 +531,52 @@ impl Lexer {
while let Some(r) = self.peek() {
self.advance();
match r {
- '"' => return Token { kind: TokenKind::StringLit, pos: start_pos, val: sb },
+ '"' => {
+ return Token {
+ kind: TokenKind::StringLit,
+ pos: start_pos,
+ val: sb,
+ };
+ }
'\\' => {
let Some(rn) = self.peek() else {
- return Token { kind: TokenKind::InvalidInput, pos: start_pos, val: String::new() };
+ return Token {
+ kind: TokenKind::InvalidInput,
+ pos: start_pos,
+ val: String::new(),
+ };
};
if !self.handle_text_esc(rn, &mut sb) {
// String-only single-char escape sequences not handled by handle_text_esc
match rn {
- 'a' => { self.advance(); sb.push('\x07'); }
- 'b' => { self.advance(); sb.push('\x08'); }
- 'f' => { self.advance(); sb.push('\x0c'); }
- 'n' => { self.advance(); sb.push('\n'); }
- 'r' => { self.advance(); sb.push('\r'); }
- 't' => { self.advance(); sb.push('\t'); }
- 'v' => { self.advance(); sb.push('\x0b'); }
+ 'a' => {
+ self.advance();
+ sb.push('\x07');
+ }
+ 'b' => {
+ self.advance();
+ sb.push('\x08');
+ }
+ 'f' => {
+ self.advance();
+ sb.push('\x0c');
+ }
+ 'n' => {
+ self.advance();
+ sb.push('\n');
+ }
+ 'r' => {
+ self.advance();
+ sb.push('\r');
+ }
+ 't' => {
+ self.advance();
+ sb.push('\t');
+ }
+ 'v' => {
+ self.advance();
+ sb.push('\x0b');
+ }
// Unrecognised escape: keep the backslash
_ => sb.push('\\'),
}
@@ -441,7 +586,11 @@ impl Lexer {
}
}
// Unterminated string
- Token { kind: TokenKind::InvalidInput, pos: start_pos, val: String::new() }
+ Token {
+ kind: TokenKind::InvalidInput,
+ pos: start_pos,
+ val: String::new(),
+ }
}
}
@@ -549,5 +698,4 @@ mod tests {
let t = lex.next_token();
assert_eq!(t.kind, TokenKind::Equals);
}
-
}
diff --git a/src/main.rs b/src/main.rs
index 900ff88..d2fe848 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,4 +1,4 @@
-use aip_filter::{parse, CompiledFilter};
+use aip_filter::{CompiledFilter, parse};
use serde_json::Value as Json;
use std::{
fs::File,
@@ -41,8 +41,10 @@ fn filter_lines(
let mut lineno = 0;
let mut valid = true;
- while (&mut reader).take(max_record_bytes as u64 + 1)
- .read_until(b'\n', &mut line_buffer)? > 0
+ while (&mut reader)
+ .take(max_record_bytes as u64 + 1)
+ .read_until(b'\n', &mut line_buffer)?
+ > 0
{
lineno += 1;
if line_buffer.len() > max_record_bytes {
@@ -93,21 +95,25 @@ fn main() {
match arg.as_str() {
"-p" | "--print" => print_only = true,
"--max-record-bytes" => {
- max_record_bytes = args.next()
+ max_record_bytes = args
+ .next()
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0 && value.checked_add(1).is_some())
.unwrap_or_else(|| usage(&program));
}
"--" => break args.next().unwrap_or_else(|| usage(&program)),
"-h" | "--help" => {
- return print_info(&program, &format!(
- "usage: {program} {USAGE}\n\n\
+ return print_info(
+ &program,
+ &format!(
+ "usage: {program} {USAGE}\n\n\
-p, --print Print the parsed expression.\n\
--max-record-bytes N Limit each record, including its newline (default: {DEFAULT_MAX_RECORD_BYTES}).\n\
-h, --help Print help without reading input.\n\
-V, --version Print the version without reading input.\n\
-- End option parsing."
- ));
+ ),
+ );
}
"-V" | "--version" => {
return print_info(&program, concat!("aip-filter ", env!("CARGO_PKG_VERSION")));
@@ -136,18 +142,36 @@ fn main() {
}
return Ok(true);
}
- let filter = expr.as_ref().map(|expr| expr.compile()).transpose()
+ let filter = expr
+ .as_ref()
+ .map(|expr| expr.compile())
+ .transpose()
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
- let mut records = RecordOutput { writer: &mut out, needs_separator: false };
+ let mut records = RecordOutput {
+ writer: &mut out,
+ needs_separator: false,
+ };
if paths.peek().is_none() {
- return filter_lines(filter.as_ref(), io::stdin().lock(), &mut records, "<stdin>", max_record_bytes);
+ return filter_lines(
+ filter.as_ref(),
+ io::stdin().lock(),
+ &mut records,
+ "<stdin>",
+ max_record_bytes,
+ );
}
let mut valid = true;
for path in paths {
let file = File::open(Path::new(&path))
.map_err(|e| io::Error::new(e.kind(), format!("{path}: {e}")))?;
- valid &= filter_lines(filter.as_ref(), BufReader::new(file), &mut records, &path, max_record_bytes)
- .map_err(|e| io::Error::new(e.kind(), format!("{path}: {e}")))?;
+ valid &= filter_lines(
+ filter.as_ref(),
+ BufReader::new(file),
+ &mut records,
+ &path,
+ max_record_bytes,
+ )
+ .map_err(|e| io::Error::new(e.kind(), format!("{path}: {e}")))?;
}
Ok(valid)
})();
diff --git a/src/parser.rs b/src/parser.rs
index d979334..9014c2f 100644
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -33,7 +33,10 @@ impl Parser {
if token.kind != TokenKind::Wsc {
count += 1;
if count > MAX_FILTER_TOKENS {
- return Err(format!("{}: filter exceeds {MAX_FILTER_TOKENS} tokens", token.pos));
+ return Err(format!(
+ "{}: filter exceeds {MAX_FILTER_TOKENS} tokens",
+ token.pos
+ ));
}
}
tokens.push(token);
@@ -52,9 +55,14 @@ impl Parser {
self.pushed = Some(token);
}
- fn nested<T>(&mut self, parse: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
+ fn nested<T>(
+ &mut self,
+ parse: impl FnOnce(&mut Self) -> Result<T, String>,
+ ) -> Result<T, String> {
if self.depth >= MAX_PARSE_DEPTH {
- return Err(format!("filter exceeds parser nesting limit of {MAX_PARSE_DEPTH}"));
+ return Err(format!(
+ "filter exceeds parser nesting limit of {MAX_PARSE_DEPTH}"
+ ));
}
self.depth += 1;
let result = parse(self);
@@ -86,7 +94,10 @@ pub fn parse_filter(filter: &str) -> Result<Option<Expr>, String> {
tok = lex.next_token();
}
if tok.kind != TokenKind::Eof {
- return Err(format!("{}: unexpected tokens after filter expression", tok.pos));
+ return Err(format!(
+ "{}: unexpected tokens after filter expression",
+ tok.pos
+ ));
}
expr.check_limits()?;
@@ -292,9 +303,17 @@ fn validate_regex(expr: &Expr) -> Result<(), String> {
validate_regex(right)
}
Expr::Unary { expr, .. } => validate_regex(expr),
- Expr::Name { is_string, pos, name, .. } => {
+ Expr::Name {
+ is_string,
+ pos,
+ name,
+ ..
+ } => {
if !is_string {
- return Err(format!("{}: regular expression is not a quoted string", pos));
+ return Err(format!(
+ "{}: regular expression is not a quoted string",
+ pos
+ ));
}
// Validate the regex syntax
if let Err(e) = crate::compiled::compile_regex(name) {
@@ -302,13 +321,17 @@ fn validate_regex(expr: &Expr) -> Result<(), String> {
}
Ok(())
}
- Expr::Comparison { pos, .. } | Expr::Member { pos, .. } => {
- Err(format!("{}: regular expression is not a quoted string", pos))
- }
+ Expr::Comparison { pos, .. } | Expr::Member { pos, .. } => Err(format!(
+ "{}: regular expression is not a quoted string",
+ pos
+ )),
Expr::Function { func, .. } => {
// Use the function name position
let pos = func_pos(func);
- Err(format!("{}: regular expression is not a quoted string", pos))
+ Err(format!(
+ "{}: regular expression is not a quoted string",
+ pos
+ ))
}
}
}
@@ -556,7 +579,9 @@ mod tests {
fn test_basic_comparison() {
let expr = parse_filter("x = 42").unwrap().unwrap();
match expr {
- Expr::Comparison { op, left, right, .. } => {
+ Expr::Comparison {
+ op, left, right, ..
+ } => {
assert_eq!(op, CompareOp::Equals);
match *left {
Expr::Name { ref name, .. } => assert_eq!(name, "x"),
@@ -575,7 +600,9 @@ mod tests {
fn test_conjunction() {
let expr = parse_filter("a : b c = 17").unwrap().unwrap();
match expr {
- Expr::Binary { op: BinaryOp::And, .. } => {}
+ Expr::Binary {
+ op: BinaryOp::And, ..
+ } => {}
_ => panic!("expected conjunction"),
}
}
@@ -584,7 +611,9 @@ mod tests {
fn test_negation() {
let expr = parse_filter("-a < 1").unwrap().unwrap();
match expr {
- Expr::Unary { op: UnaryOp::Minus, .. } => {}
+ Expr::Unary {
+ op: UnaryOp::Minus, ..
+ } => {}
_ => panic!("expected unary minus"),
}
}