liwe 0.13.0

IWE core library
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use regex::Regex;
use serde_yaml::{Mapping, Value};

use crate::model::Key;
use crate::query::builder::ParseError;

#[derive(Debug, Clone)]
pub struct BlockRegex {
    pattern: String,
    regex: Regex,
}

impl BlockRegex {
    pub fn compile(pattern: &str) -> Result<Self, ParseError> {
        Regex::new(pattern)
            .map(|regex| BlockRegex {
                pattern: pattern.to_string(),
                regex,
            })
            .map_err(|e| ParseError::InvalidRegex {
                pattern: pattern.to_string(),
                message: e.to_string(),
            })
    }

    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    pub fn is_match(&self, text: &str) -> bool {
        self.regex.is_match(text)
    }
}

impl PartialEq for BlockRegex {
    fn eq(&self, other: &Self) -> bool {
        self.pattern == other.pattern
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum TextMatch {
    Substring(String),
    Exact(String),
}

impl TextMatch {
    pub fn matches(&self, text: &str) -> bool {
        match self {
            TextMatch::Substring(s) => text.to_lowercase().contains(&s.to_lowercase()),
            TextMatch::Exact(s) => text.to_lowercase() == s.to_lowercase(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockType {
    Header,
    Paragraph,
    Item,
    Code,
    Table,
    Ref,
    Hr,
}

#[derive(Debug, Clone, PartialEq)]
pub enum BlockOp {
    Text(TextMatch),
    Matches(BlockRegex),
    Within(Box<BlockPredicate>),
    Contains(Box<BlockPredicate>),
    Section(Box<BlockPredicate>),
    Quote(Box<BlockPredicate>),
    List(Box<BlockPredicate>),
    Type(BlockType, Box<BlockPredicate>),
    References(Key),
    And(Vec<BlockPredicate>),
    Or(Vec<BlockPredicate>),
    Nor(Vec<BlockPredicate>),
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct BlockPredicate(pub Vec<BlockOp>);

pub trait IntoBlockPredicate {
    fn into_block_predicate(self) -> BlockPredicate;
}

impl IntoBlockPredicate for BlockPredicate {
    fn into_block_predicate(self) -> BlockPredicate {
        self
    }
}

impl IntoBlockPredicate for &str {
    fn into_block_predicate(self) -> BlockPredicate {
        BlockPredicate::text_exact(self)
    }
}

impl BlockPredicate {
    pub fn empty() -> Self {
        BlockPredicate(Vec::new())
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    fn text_exact(text: &str) -> Self {
        BlockPredicate(vec![BlockOp::Text(TextMatch::Exact(text.to_string()))])
    }

    fn has_direct_text_op(&self) -> bool {
        self.0
            .iter()
            .any(|op| matches!(op, BlockOp::Text(_) | BlockOp::Matches(_)))
    }

    fn carries_contents(&self) -> bool {
        self.is_empty()
            || self.0.iter().any(|op| match op {
                BlockOp::Section(_) | BlockOp::Quote(_) | BlockOp::List(_) => true,
                BlockOp::And(preds) => preds.iter().any(BlockPredicate::carries_contents),
                BlockOp::Or(preds) => preds.iter().all(BlockPredicate::carries_contents),
                _ => false,
            })
    }

    fn with(mut self, op: BlockOp) -> Self {
        self.0.push(op);
        self
    }

    fn typed(self, block_type: BlockType, arg: impl IntoBlockPredicate) -> Self {
        self.with(BlockOp::Type(
            block_type,
            Box::new(arg.into_block_predicate()),
        ))
    }

    pub fn text(self, text: &str) -> Self {
        self.with(BlockOp::Text(TextMatch::Substring(text.to_string())))
    }

    pub fn text_eq(self, text: &str) -> Self {
        self.with(BlockOp::Text(TextMatch::Exact(text.to_string())))
    }

    pub fn matches(self, pattern: &str) -> Self {
        self.with(BlockOp::Matches(
            BlockRegex::compile(pattern).expect("valid regex"),
        ))
    }

    pub fn within(self, scope: BlockPredicate) -> Self {
        assert!(
            scope.carries_contents(),
            "$within argument must carry contents: {{}}, or a predicate containing $section, $quote, or $list"
        );
        self.with(BlockOp::Within(Box::new(scope)))
    }

    pub fn within_section(self, title: &str) -> Self {
        self.within(BlockPredicate::empty().section(title))
    }

    pub fn contains(self, pred: BlockPredicate) -> Self {
        self.with(BlockOp::Contains(Box::new(pred)))
    }

    pub fn section(self, root: impl IntoBlockPredicate) -> Self {
        self.with(BlockOp::Section(Box::new(root.into_block_predicate())))
    }

    pub fn quote(self, inner: BlockPredicate) -> Self {
        self.with(BlockOp::Quote(Box::new(inner)))
    }

    pub fn list(self, inner: BlockPredicate) -> Self {
        self.with(BlockOp::List(Box::new(inner)))
    }

    pub fn header(self, arg: impl IntoBlockPredicate) -> Self {
        self.typed(BlockType::Header, arg)
    }

    pub fn paragraph(self, arg: impl IntoBlockPredicate) -> Self {
        self.typed(BlockType::Paragraph, arg)
    }

    pub fn item(self, arg: impl IntoBlockPredicate) -> Self {
        self.typed(BlockType::Item, arg)
    }

    pub fn code(self, arg: impl IntoBlockPredicate) -> Self {
        self.typed(BlockType::Code, arg)
    }

    pub fn table(self, arg: impl IntoBlockPredicate) -> Self {
        self.typed(BlockType::Table, arg)
    }

    pub fn reference(self, inner: BlockPredicate) -> Self {
        self.typed(BlockType::Ref, inner)
    }

    pub fn hr(self, inner: BlockPredicate) -> Self {
        self.typed(BlockType::Hr, inner)
    }

    pub fn references(self, key: &str) -> Self {
        self.with(BlockOp::References(Key::name(key)))
    }

    pub fn and(self, preds: Vec<BlockPredicate>) -> Self {
        self.with(BlockOp::And(preds))
    }

    pub fn or(self, preds: Vec<BlockPredicate>) -> Self {
        self.with(BlockOp::Or(preds))
    }

    pub fn nor(self, preds: Vec<BlockPredicate>) -> Self {
        self.with(BlockOp::Nor(preds))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct MatchesSource {
    pub pattern: BlockRegex,
    pub scope: BlockPredicate,
}

pub fn parse_block_predicate(
    value: &Value,
    op: &'static str,
) -> Result<BlockPredicate, ParseError> {
    match value {
        Value::Mapping(m) => parse_mapping(m),
        _ => Err(ParseError::OperatorExpectedMapping { op }),
    }
}

fn parse_mapping(map: &Mapping) -> Result<BlockPredicate, ParseError> {
    let mut ops = Vec::new();
    for (k, v) in map {
        let key = k.as_str().ok_or(ParseError::NonStringKey)?;
        if !key.starts_with('$') {
            return Err(ParseError::BareKeyInBlockPredicate {
                key: key.to_string(),
            });
        }
        ops.push(parse_entry(key, v)?);
    }
    Ok(BlockPredicate(ops))
}

fn parse_entry(key: &str, value: &Value) -> Result<BlockOp, ParseError> {
    match key {
        "$text" => parse_text(value),
        "$matches" => parse_regex(value).map(BlockOp::Matches),
        "$within" => parse_within(value),
        "$contains" => {
            parse_block_predicate(value, "$contains").map(|p| BlockOp::Contains(Box::new(p)))
        }
        "$section" => parse_root_arg(value, "$section").map(|p| BlockOp::Section(Box::new(p))),
        "$quote" => parse_empty_head(value, "$quote").map(|p| BlockOp::Quote(Box::new(p))),
        "$list" => parse_empty_head(value, "$list").map(|p| BlockOp::List(Box::new(p))),
        "$header" => parse_type_arg(value, "$header", BlockType::Header),
        "$paragraph" => parse_type_arg(value, "$paragraph", BlockType::Paragraph),
        "$item" => parse_type_arg(value, "$item", BlockType::Item),
        "$code" => parse_type_arg(value, "$code", BlockType::Code),
        "$table" => parse_type_arg(value, "$table", BlockType::Table),
        "$ref" => match value {
            Value::Mapping(_) => parse_block_predicate(value, "$ref")
                .map(|p| BlockOp::Type(BlockType::Ref, Box::new(p))),
            _ => Err(ParseError::BlockScalarNotAllowed { op: "$ref" }),
        },
        "$hr" => parse_empty_head(value, "$hr").map(|p| BlockOp::Type(BlockType::Hr, Box::new(p))),
        "$references" => match value {
            Value::String(s) => Ok(BlockOp::References(Key::name(s))),
            _ => Err(ParseError::OperatorExpectedString { op: "$references" }),
        },
        "$and" => parse_list(value, "$and").map(BlockOp::And),
        "$or" => parse_list(value, "$or").map(BlockOp::Or),
        "$nor" => parse_list(value, "$nor").map(BlockOp::Nor),
        other => Err(ParseError::UnknownBlockOperator {
            op: other.to_string(),
        }),
    }
}

fn parse_text(value: &Value) -> Result<BlockOp, ParseError> {
    match value {
        Value::String(s) => Ok(BlockOp::Text(TextMatch::Substring(s.clone()))),
        Value::Mapping(m) => {
            if m.len() == 1 {
                if let Some(Value::String(s)) = m.get(Value::String("$eq".to_string())) {
                    return Ok(BlockOp::Text(TextMatch::Exact(s.clone())));
                }
            }
            Err(ParseError::OperatorExpectedString { op: "$text" })
        }
        _ => Err(ParseError::OperatorExpectedString { op: "$text" }),
    }
}

pub fn parse_regex(value: &Value) -> Result<BlockRegex, ParseError> {
    match value {
        Value::String(s) => BlockRegex::compile(s),
        _ => Err(ParseError::OperatorExpectedString { op: "$matches" }),
    }
}

fn parse_within(value: &Value) -> Result<BlockOp, ParseError> {
    match value {
        Value::String(s) => Ok(BlockOp::Within(Box::new(BlockPredicate(vec![
            BlockOp::Section(Box::new(BlockPredicate::text_exact(s))),
        ])))),
        Value::Mapping(_) => {
            let scope = parse_block_predicate(value, "$within")?;
            if !scope.carries_contents() {
                return Err(ParseError::WithinArgumentWithoutContents);
            }
            Ok(BlockOp::Within(Box::new(scope)))
        }
        _ => Err(ParseError::GraphOpExpectedScalarOrMapping { op: "$within" }),
    }
}

fn parse_root_arg(value: &Value, op: &'static str) -> Result<BlockPredicate, ParseError> {
    match value {
        Value::String(s) => Ok(BlockPredicate::text_exact(s)),
        Value::Mapping(_) => parse_block_predicate(value, op),
        _ => Err(ParseError::GraphOpExpectedScalarOrMapping { op }),
    }
}

fn parse_type_arg(value: &Value, op: &'static str, t: BlockType) -> Result<BlockOp, ParseError> {
    let arg = match value {
        Value::String(s) => BlockPredicate::text_exact(s),
        Value::Mapping(_) => parse_block_predicate(value, op)?,
        _ => return Err(ParseError::GraphOpExpectedScalarOrMapping { op }),
    };
    Ok(BlockOp::Type(t, Box::new(arg)))
}

fn parse_empty_head(value: &Value, op: &'static str) -> Result<BlockPredicate, ParseError> {
    match value {
        Value::Mapping(_) => {
            let pred = parse_block_predicate(value, op)?;
            if pred.has_direct_text_op() {
                return Err(ParseError::BlockTextPredicateNotAllowed { op });
            }
            Ok(pred)
        }
        _ => Err(ParseError::BlockScalarNotAllowed { op }),
    }
}

fn parse_list(value: &Value, op: &'static str) -> Result<Vec<BlockPredicate>, ParseError> {
    match value {
        Value::Sequence(items) => {
            if items.is_empty() {
                return Err(ParseError::EmptyOperatorList { op });
            }
            items
                .iter()
                .map(|item| parse_block_predicate(item, op))
                .collect()
        }
        _ => Err(ParseError::OperatorExpectedList { op }),
    }
}

pub fn parse_matches_source(value: &Value) -> Result<MatchesSource, ParseError> {
    match value {
        Value::String(_) => Ok(MatchesSource {
            pattern: parse_regex(value)?,
            scope: BlockPredicate::empty(),
        }),
        Value::Mapping(m) => {
            let mut pattern = None;
            let mut scope_map = Mapping::new();
            for (k, v) in m {
                let key = k.as_str().ok_or(ParseError::NonStringKey)?;
                if key == "pattern" {
                    pattern = Some(parse_regex(v)?);
                } else if key.starts_with('$') {
                    scope_map.insert(k.clone(), v.clone());
                } else {
                    return Err(ParseError::BareKeyInBlockPredicate {
                        key: key.to_string(),
                    });
                }
            }
            let pattern = pattern.ok_or(ParseError::MatchesPatternMissing)?;
            let scope = parse_mapping(&scope_map)?;
            Ok(MatchesSource { pattern, scope })
        }
        _ => Err(ParseError::OperatorExpectedString { op: "$matches" }),
    }
}