harper-core 2.0.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
//! 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;
use crate::linting::{Chunk, ExprLinter, Lint, LintKind, Linter, 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, 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,
    ast: Arc<Ast>,
}

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 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 linter = WeirLinter {
            strategy: replacement_strat,
            ast,
            expr: expr.clone(),
            lint_kind,
            description,
            message,
            replacements,
        };

        Ok(linter)
    }

    /// 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_top3_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..3 {
                        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_top3_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 ExprLinter for WeirLinter {
    type Unit = Chunk;

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

    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,
        })
    }

    fn description(&self) -> &str {
        &self.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 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 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))
    }

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