harper-core 2.4.0

The language checker for developers.
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! Weir is a programming language for finding errors in natural language.
//! See our [main documentation](https://writewithharper.com/docs/weir) for more details.

mod ast;
mod error;
mod optimize;
mod parsing;

use std::collections::VecDeque;
use std::str::FromStr;
use std::sync::Arc;

pub use error::Error;
use hashbrown::{HashMap, HashSet};
use is_macro::Is;
use parsing::{parse_expr_str, parse_str};
use strum_macros::{AsRefStr, EnumString};

use crate::expr::{Expr, ExprExt};
use crate::linting::{Chunk, ExprLinter, Lint, LintKind, Linter, Sentence, Suggestion};
use crate::parsers::Markdown;
use crate::spell::FstDictionary;
use crate::{Document, Lrc, Token, TokenStringExt};

use self::ast::{Ast, AstVariable};

pub(crate) fn weir_expr_to_expr(weir_code: &str) -> Result<Box<dyn Expr>, Error> {
    let ast = parse_expr_str(weir_code, true)?;
    ast.to_expr(&HashMap::new())
}

#[derive(Debug, Is, EnumString, AsRefStr)]
enum ReplacementStrategy {
    MatchCase,
    Exact,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString)]
enum WeirScope {
    Chunk,
    Sentence,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestResult {
    pub expected: String,
    pub got: String,
}

pub struct WeirLinter {
    expr: Lrc<Box<dyn Expr>>,
    description: String,
    message: String,
    strategy: ReplacementStrategy,
    replacements: Vec<String>,
    lint_kind: LintKind,
    scope: WeirScope,
    ast: Arc<Ast>,
}

struct ChunkWeirLinter(WeirLinter);

struct SentenceWeirLinter(WeirLinter);

impl WeirLinter {
    pub fn new(weir_code: &str) -> Result<WeirLinter, Error> {
        let ast = parse_str(weir_code, true)?;

        let main_expr_name = "main";
        let description_name = "description";
        let message_name = "message";
        let lint_kind_name = "kind";
        let replacement_name = "becomes";
        let replacement_strat_name = "strategy";
        let scope_name = "scope";

        let resolved = resolve_exprs(&ast)?;

        let expr = resolved
            .get(main_expr_name)
            .ok_or(Error::ExpectedVariableUndefined)?;

        let description = ast
            .get_variable_value(description_name)
            .ok_or(Error::ExpectedVariableUndefined)?
            .as_string()
            .ok_or(Error::ExpectedDifferentVariableType)?
            .to_owned();

        let message = ast
            .get_variable_value(message_name)
            .ok_or(Error::ExpectedVariableUndefined)?
            .as_string()
            .ok_or(Error::ExpectedDifferentVariableType)?
            .to_owned();

        let replacement_val = ast
            .get_variable_value(replacement_name)
            .ok_or(Error::ExpectedVariableUndefined)?;

        let replacements = match replacement_val {
            AstVariable::String(s) => vec![s.to_owned()],
            AstVariable::Array(arr) => {
                let mut out = Vec::with_capacity(arr.len());
                for item in arr.iter().map(|v| {
                    v.as_string()
                        .cloned()
                        .ok_or(Error::ExpectedDifferentVariableType)
                }) {
                    let item = item?;
                    out.push(item);
                }
                out
            }
        };

        let replacement_strat_var = ast.get_variable_value(replacement_strat_name);
        let replacement_strat = if let Some(replacement_strat) = replacement_strat_var {
            let str = replacement_strat
                .as_string()
                .ok_or(Error::ExpectedDifferentVariableType)?;
            ReplacementStrategy::from_str(str)
                .ok()
                .ok_or(Error::InvalidReplacementStrategy)?
        } else {
            ReplacementStrategy::MatchCase
        };

        let lint_kind_var = ast.get_variable_value(lint_kind_name);
        let lint_kind = if let Some(lint_kind) = lint_kind_var {
            let str = lint_kind
                .as_string()
                .ok_or(Error::ExpectedDifferentVariableType)?;
            LintKind::from_string_key(str).ok_or(Error::InvalidLintKind)?
        } else {
            LintKind::Miscellaneous
        };

        let scope_var = ast.get_variable_value(scope_name);
        let scope = if let Some(scope) = scope_var {
            let str = scope
                .as_string()
                .ok_or(Error::ExpectedDifferentVariableType)?;
            WeirScope::from_str(str).ok().ok_or(Error::InvalidScope)?
        } else {
            WeirScope::Chunk
        };

        let linter = WeirLinter {
            strategy: replacement_strat,
            ast,
            expr: expr.clone(),
            lint_kind,
            scope,
            description,
            message,
            replacements,
        };

        Ok(linter)
    }

    pub fn into_chunk_linter(self) -> Result<impl ExprLinter<Unit = Chunk>, Self> {
        if self.scope == WeirScope::Chunk {
            Ok(ChunkWeirLinter(self))
        } else {
            Err(self)
        }
    }

    pub fn into_sentence_linter(self) -> Result<impl ExprLinter<Unit = Sentence>, Self> {
        if self.scope == WeirScope::Sentence {
            Ok(SentenceWeirLinter(self))
        } else {
            Err(self)
        }
    }

    fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
        let span = matched_tokens.span()?;
        let orig = span.get_content(source);

        let suggestions = match self.strategy {
            ReplacementStrategy::MatchCase => self
                .replacements
                .iter()
                .map(|s| Suggestion::replace_with_match_case(s.chars().collect(), orig))
                .collect(),
            ReplacementStrategy::Exact => self
                .replacements
                .iter()
                .map(|r| Suggestion::ReplaceWith(r.chars().collect()))
                .collect(),
        };

        Some(Lint {
            span,
            lint_kind: self.lint_kind,
            suggestions,
            message: self.message.to_owned(),
            priority: 31,
        })
    }

    /// Counts the total number of tests defined.
    pub fn count_tests(&self) -> usize {
        self.ast.iter_tests().count()
    }

    /// Runs the tests defined in the source code, returning any failing results.
    pub fn run_tests(&mut self) -> Vec<TestResult> {
        fn apply_nth_suggestion(text: &str, lint: &Lint, n: usize) -> Option<String> {
            let suggestion = lint.suggestions.get(n)?;
            let mut text_chars: Vec<char> = text.chars().collect();
            suggestion.apply(lint.span, &mut text_chars);
            Some(text_chars.iter().collect())
        }

        fn transform_to_expected(
            text: &str,
            expected: &str,
            linter: &mut impl Linter,
        ) -> Option<String> {
            let mut queue: VecDeque<(String, usize)> = VecDeque::new();
            let mut seen: HashSet<String> = HashSet::new();

            queue.push_back((text.to_string(), 0));
            seen.insert(text.to_string());

            while let Some((current, depth)) = queue.pop_front() {
                if current == expected {
                    return Some(current);
                }

                if depth >= 100 {
                    continue;
                }

                let doc = Document::new_from_chars(
                    current.chars().collect::<Vec<_>>().into(),
                    &Markdown::default(),
                    &FstDictionary::curated(),
                );
                let lints = linter.lint(&doc);

                if let Some(lint) = lints.first() {
                    for i in 0..lint.suggestions.len() {
                        if let Some(next) = apply_nth_suggestion(&current, lint, i)
                            && seen.insert(next.clone())
                        {
                            queue.push_back((next, depth + 1));
                        }
                    }
                }
            }

            None
        }

        fn transform_nth_str(text: &str, linter: &mut impl Linter, n: usize) -> String {
            let mut text_chars: Vec<char> = text.chars().collect();
            let mut iter_count = 0;

            loop {
                let test = Document::new_from_chars(
                    text_chars.clone().into(),
                    &Markdown::default(),
                    &FstDictionary::curated(),
                );
                let lints = linter.lint(&test);

                if let Some(lint) = lints.first() {
                    if let Some(suggestion) = lint.suggestions.get(n) {
                        suggestion.apply(lint.span, &mut text_chars);
                    } else {
                        break;
                    }
                } else {
                    break;
                }

                iter_count += 1;
                if iter_count == 100 {
                    break;
                }
            }

            text_chars.iter().collect()
        }

        fn lint_count(text: &str, linter: &mut impl Linter) -> usize {
            let document = Document::new_from_chars(
                text.chars().collect::<Vec<_>>().into(),
                &Markdown::default(),
                &FstDictionary::curated(),
            );

            linter.lint(&document).len()
        }

        let mut results = Vec::new();
        let tests: Vec<(String, String)> = self
            .ast
            .iter_tests()
            .map(|(text, expected)| (text.to_string(), expected.to_string()))
            .collect();

        for (text, expected) in tests {
            let matched = transform_to_expected(&text, &expected, self);

            match matched {
                Some(result) => {
                    let remaining_lints = lint_count(&result, self);

                    if remaining_lints != 0 {
                        results.push(TestResult {
                            expected: expected.to_string(),
                            got: result,
                        });
                    }
                }
                None => results.push(TestResult {
                    expected: expected.to_string(),
                    got: transform_nth_str(&text, self, 0),
                }),
            }
        }

        results
    }
}

impl Linter for WeirLinter {
    fn lint(&mut self, document: &Document) -> Vec<Lint> {
        let source = document.get_source();
        let mut lints = Vec::new();
        let units: Box<dyn Iterator<Item = &[Token]> + '_> = match self.scope {
            WeirScope::Chunk => Box::new(document.iter_chunks()),
            WeirScope::Sentence => Box::new(document.iter_sentences()),
        };

        for unit in units {
            lints.extend(
                self.expr
                    .iter_matches(unit, source)
                    .filter_map(|match_span| {
                        self.match_to_lint(&unit[match_span.start..match_span.end], source)
                    }),
            );
        }

        lints
    }

    fn description(&self) -> &str {
        &self.description
    }
}

impl ExprLinter for ChunkWeirLinter {
    type Unit = Chunk;

    fn expr(&self) -> &dyn Expr {
        &self.0.expr
    }

    fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
        self.0.match_to_lint(matched_tokens, source)
    }

    fn description(&self) -> &str {
        &self.0.description
    }
}

impl ExprLinter for SentenceWeirLinter {
    type Unit = Sentence;

    fn expr(&self) -> &dyn Expr {
        &self.0.expr
    }

    fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
        self.0.match_to_lint(matched_tokens, source)
    }

    fn description(&self) -> &str {
        &self.0.description
    }
}

fn resolve_exprs(ast: &Ast) -> Result<HashMap<String, Lrc<Box<dyn Expr>>>, Error> {
    let mut resolved_exprs = HashMap::new();

    for (name, val) in ast.iter_exprs() {
        let expr = val.to_expr(&resolved_exprs)?;
        resolved_exprs.insert(name.to_owned(), Lrc::new(expr));
    }

    Ok(resolved_exprs)
}

#[cfg(test)]
pub mod tests {
    use quickcheck_macros::quickcheck;

    use crate::weir::Error;

    use super::{TestResult, WeirLinter};

    #[track_caller]
    pub fn assert_passes_all(linter: &mut WeirLinter) {
        assert_eq!(Vec::<TestResult>::new(), linter.run_tests());
    }

    #[test]
    fn simple_right_click_linter() {
        let source = r#"
            expr main <([right, middle, left] $click), ( )>
            let message "Hyphenate this mouse command"
            let description "Hyphenates right-click style mouse commands."
            let kind "Punctuation"
            let becomes "-"

            test "Right click the icon." "Right-click the icon."
            test "Please right click on the link." "Please right-click on the link."
            test "They right clicked the submit button." "They right-clicked the submit button."
            test "Right clicking the item highlights it." "Right-clicking the item highlights it."
            test "Right clicks are tracked in the log." "Right-clicks are tracked in the log."
            test "He RIGHT CLICKED the file." "He RIGHT-CLICKED the file."
            test "Left click the checkbox." "Left-click the checkbox."
            test "Middle click to open in a new tab." "Middle-click to open in a new tab."

            allows "This test contains the correct version of right-click and therefore shouldn't error."
            "#;

        let mut linter = WeirLinter::new(source).unwrap();
        assert_passes_all(&mut linter);
        assert_eq!(9, linter.count_tests());
    }

    #[test]
    fn g_suite() {
        let source = r#"
            expr main [(G [Suite, Suit]), (Google Apps for Work)]
            let message "Use the updated brand."
            let description "`G Suite` or `Google Apps for Work` is now called `Google Workspace`"
            let kind "Miscellaneous"
            let becomes "Google Workspace"
            let strategy "Exact"

            test "We migrated from G Suite last year." "We migrated from Google Workspace last year."
            test "This account is still labeled as Google Apps for Work." "This account is still labeled as Google Workspace."
            test "The pricing page mentions G Suit for legacy plans." "The pricing page mentions Google Workspace for legacy plans."
            test "New customers sign up for Google Workspace." "New customers sign up for Google Workspace."

            allows "This test contains the correct version of Google Workspace and therefore shouldn't error."
            "#;

        let mut linter = WeirLinter::new(source).unwrap();

        assert_passes_all(&mut linter);
        assert_eq!(5, linter.count_tests());
    }

    #[test]
    fn array_prefers_longest_match_over_first_match() {
        for main in [
            "[(capitalized off of), (capitalized off)]",
            "[(capitalized off), (capitalized off of)]",
        ] {
            let source = format!(
                r#"
            expr main {main}
            let message "Use the replacement."
            let description "Regression test for overlapping Weir array options."
            let kind "Miscellaneous"
            let becomes "replacement"
            let strategy "Exact"

            test "capitalized off of" "replacement"
            "#
            );

            let mut linter = WeirLinter::new(&source).unwrap();
            assert_passes_all(&mut linter);
        }
    }

    #[test]
    fn g_suite_with_refs() {
        let source = r#"
            expr a (G [Suite, Suit])
            expr b (Google Apps For Work)
            expr incorrect [@a, @b]

            expr main @incorrect
            let message "Use the updated brand."
            let description "`G Suite` or `Google Apps for Work` is now called `Google Workspace`"
            let kind "Miscellaneous"
            let becomes "Google Workspace"
            let strategy "Exact"

            test "We migrated from G Suite last year." "We migrated from Google Workspace last year."
            test "This account is still labeled as Google Apps for Work." "This account is still labeled as Google Workspace."
            test "The pricing page mentions G Suit for legacy plans." "The pricing page mentions Google Workspace for legacy plans."
            test "New customers sign up for Google Workspace." "New customers sign up for Google Workspace."
            "#;

        let mut linter = WeirLinter::new(source).unwrap();

        assert_passes_all(&mut linter);
        assert_eq!(4, linter.count_tests());
    }

    #[test]
    fn scope_defaults_to_chunk() {
        let source = r#"
            expr main one**two
            let message "Use three."
            let description "Test chunk-scoped Weir."
            let kind "Miscellaneous"
            let becomes "three"
            let strategy "Exact"

            allows "one, two."
        "#;

        let mut linter = WeirLinter::new(source).unwrap();

        assert_passes_all(&mut linter);

        let linter = WeirLinter::new(source).unwrap();
        let linter = match linter.into_sentence_linter() {
            Ok(_) => panic!("default-scoped Weir rule should not convert to sentence linter"),
            Err(linter) => linter,
        };
        assert!(linter.into_chunk_linter().is_ok());
    }

    #[test]
    fn sentence_scope_can_match_across_chunks() {
        let source = r#"
            expr main one**two
            let message "Use three."
            let description "Test sentence-scoped Weir."
            let kind "Miscellaneous"
            let becomes "three"
            let strategy "Exact"
            let scope "Sentence"

            test "one, two." "three."
        "#;

        let mut linter = WeirLinter::new(source).unwrap();

        assert_passes_all(&mut linter);

        assert!(
            WeirLinter::new(source)
                .unwrap()
                .into_sentence_linter()
                .is_ok()
        );
    }

    #[test]
    fn invalid_scope_errors() {
        let source = r#"
            expr main one
            let message ""
            let description ""
            let kind "Miscellaneous"
            let becomes ""
            let scope "Paragraph"
        "#;

        let res = WeirLinter::new(source);

        assert_eq!(res.err(), Some(Error::InvalidScope));
    }

    #[test]
    fn fails_on_unresolved_expr() {
        let source = r#"
            expr main @missing
            let message ""
            let description ""
            let kind "Miscellaneous"
            let becomes ""
            let strategy "Exact"
        "#;

        let res = WeirLinter::new(source);

        assert_eq!(
            res.err().unwrap(),
            Error::UnableToResolveExpr("missing".to_string())
        )
    }

    #[test]
    fn wildcard() {
        let source = r#"
            expr main <(NOUN * NOUN), (* NOUN), *>
            let message ""
            let description ""
            let kind "Miscellaneous"
            let becomes ""
            let strategy "Exact"

            test "I like trees and plants of all kinds" "I like trees  plants of all kinds"
            test "homework tempts teachers" "homework  teachers"
            "#;

        let mut linter = WeirLinter::new(source).unwrap();

        assert_passes_all(&mut linter);
        assert_eq!(2, linter.count_tests());
    }

    #[test]
    fn dashes() {
        let source = r#"
            expr main --
            let message ""
            let description ""
            let kind "Miscellaneous"
            let becomes "-"
            let strategy "Exact"

            test "This--and--that" "This-and-that"

            allows "this-and-that"
            "#;

        let mut linter = WeirLinter::new(source).unwrap();

        assert_passes_all(&mut linter);
        assert_eq!(2, linter.count_tests());
    }

    #[test]
    fn fails_on_ignore_test() {
        let source = r#"
            expr main test
            let message ""
            let description ""
            let kind "Miscellaneous"
            let becomes "-"
            let strategy "Exact"

            allows "test"
            "#;

        let mut linter = WeirLinter::new(source).unwrap();

        assert_eq!(linter.run_tests().len(), 1)
    }

    #[test]
    fn errors_properly_with_missing_expr() {
        let source = "expr main";
        let res = WeirLinter::new(source);
        assert_eq!(res.err(), Some(Error::ExpectedVariableUndefined))
    }

    #[test]
    fn becomes_array_with_many_alternatives() {
        let source = r#"
 expr main (the fact)
 let message "Consider alternative phrasing"
 let description "Test that all 'becomes' alternatives can be reached"
 let kind "Miscellaneous"
 let becomes ["the allegation", "the idea", "the claim", "the story", "the rumor"]
 let strategy "Exact"

 test "There is truth to the fact that people like images." "There is truth to the allegation that people like images."
 test "There is truth to the fact that people like images." "There is truth to the idea that people like images."
 test "There is truth to the fact that people like images." "There is truth to the claim that people like images."
 test "There is truth to the fact that people like images." "There is truth to the story that people like images."
 test "There is truth to the fact that people like images." "There is truth to the rumor that people like images."

 allows "There is truth to the story that people like images."
 "#;

        let mut linter = WeirLinter::new(source).unwrap();
        assert_passes_all(&mut linter);
        assert_eq!(6, linter.count_tests());
    }

    #[quickcheck]
    fn does_not_panic(s: String) {
        let _ = WeirLinter::new(s.as_str());
    }
}