Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

Linters are now allowed to have their own state

Elijah Potter55ef7b4b5506
diff --git a/Cargo.lock b/Cargo.lock
index fbd66b9de..68bfca673 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -35,27 +35,12 @@ dependencies = [
"zerocopy",
]
-[[package]]
-name = "aho-corasick"
-version = "1.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
-dependencies = [
- "memchr",
-]
-
[[package]]
name = "allocator-api2"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
-[[package]]
-name = "anes"
-version = "0.1.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
-
[[package]]
name = "anstream"
version = "0.6.11"
@@ -141,7 +126,7 @@ checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf"
dependencies = [
"async-trait",
"axum-core",
- "bitflags 1.3.2",
+ "bitflags",
"bytes",
"futures-util",
"http",
@@ -203,12 +188,6 @@ version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
-[[package]]
-name = "bitflags"
-version = "2.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
-
[[package]]
name = "bumpalo"
version = "3.14.0"
@@ -221,45 +200,6 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
-[[package]]
-name = "cached"
-version = "0.47.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "69b0116662497bc24e4b177c90eaf8870e39e2714c3fcfa296327a93f593fc21"
-dependencies = [
- "ahash",
- "cached_proc_macro",
- "cached_proc_macro_types",
- "hashbrown",
- "instant",
- "once_cell",
- "thiserror",
-]
-
-[[package]]
-name = "cached_proc_macro"
-version = "0.18.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c878c71c2821aa2058722038a59a67583a4240524687c6028571c9b395ded61f"
-dependencies = [
- "darling",
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
-[[package]]
-name = "cached_proc_macro_types"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a4f925191b4367301851c6d99b09890311d74b0d43f274c0b34c86d308a3663"
-
-[[package]]
-name = "cast"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
-
[[package]]
name = "cc"
version = "1.0.83"
@@ -275,33 +215,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
-[[package]]
-name = "ciborium"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "effd91f6c78e5a4ace8a5d3c0b6bfaec9e2baaef55f3efc00e45fb2e477ee926"
-dependencies = [
- "ciborium-io",
- "ciborium-ll",
- "serde",
-]
-
-[[package]]
-name = "ciborium-io"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cdf919175532b369853f5d5e20b26b43112613fd6fe7aee757e35f7a44642656"
-
-[[package]]
-name = "ciborium-ll"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "defaa24ecc093c77630e6c15e17c51f5e187bf35ee514f4e2d67baaa96dae22b"
-dependencies = [
- "ciborium-io",
- "half",
-]
-
[[package]]
name = "clap"
version = "4.4.18"
@@ -358,102 +271,6 @@ dependencies = [
"wasm-bindgen",
]
-[[package]]
-name = "criterion"
-version = "0.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
-dependencies = [
- "anes",
- "cast",
- "ciborium",
- "clap",
- "criterion-plot",
- "is-terminal",
- "itertools 0.10.5",
- "num-traits",
- "once_cell",
- "oorandom",
- "plotters",
- "rayon",
- "regex",
- "serde",
- "serde_derive",
- "serde_json",
- "tinytemplate",
- "walkdir",
-]
-
-[[package]]
-name = "criterion-plot"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
-dependencies = [
- "cast",
- "itertools 0.10.5",
-]
-
-[[package]]
-name = "crossbeam-deque"
-version = "0.8.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d"
-dependencies = [
- "crossbeam-epoch",
- "crossbeam-utils",
-]
-
-[[package]]
-name = "crossbeam-epoch"
-version = "0.9.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
-dependencies = [
- "crossbeam-utils",
-]
-
-[[package]]
-name = "crossbeam-utils"
-version = "0.8.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345"
-
-[[package]]
-name = "darling"
-version = "0.14.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850"
-dependencies = [
- "darling_core",
- "darling_macro",
-]
-
-[[package]]
-name = "darling_core"
-version = "0.14.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0"
-dependencies = [
- "fnv",
- "ident_case",
- "proc-macro2",
- "quote",
- "strsim",
- "syn 1.0.109",
-]
-
-[[package]]
-name = "darling_macro"
-version = "0.14.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e"
-dependencies = [
- "darling_core",
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "dashmap"
version = "5.5.3"
@@ -473,16 +290,6 @@ version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
-[[package]]
-name = "errno"
-version = "0.3.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245"
-dependencies = [
- "libc",
- "windows-sys 0.52.0",
-]
-
[[package]]
name = "fnv"
version = "1.0.7"
@@ -603,20 +410,13 @@ version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
-[[package]]
-name = "half"
-version = "1.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7"
-
[[package]]
name = "harper-core"
version = "0.1.0"
dependencies = [
- "criterion",
"hashbrown",
"is-macro",
- "itertools 0.11.0",
+ "itertools",
"once_cell",
"paste",
"pulldown-cmark",
@@ -629,9 +429,9 @@ dependencies = [
name = "harper-ls"
version = "0.1.0"
dependencies = [
- "cached",
"clap",
"harper-core",
+ "once_cell",
"tokio",
"tower-lsp",
]
@@ -742,12 +542,6 @@ dependencies = [
"want",
]
-[[package]]
-name = "ident_case"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
-
[[package]]
name = "idna"
version = "0.5.0"
@@ -758,15 +552,6 @@ dependencies = [
"unicode-normalization",
]
-[[package]]
-name = "instant"
-version = "0.1.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
-dependencies = [
- "cfg-if",
-]
-
[[package]]
name = "is-macro"
version = "0.3.5"
@@ -779,26 +564,6 @@ dependencies = [
"syn 2.0.48",
]
-[[package]]
-name = "is-terminal"
-version = "0.4.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bad00257d07be169d870ab665980b06cdb366d792ad690bf2e76876dc503455"
-dependencies = [
- "hermit-abi",
- "rustix",
- "windows-sys 0.52.0",
-]
-
-[[package]]
-name = "itertools"
-version = "0.10.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
-dependencies = [
- "either",
-]
-
[[package]]
name = "itertools"
version = "0.11.0"
@@ -835,12 +600,6 @@ version = "0.2.152"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13e3bf6590cbc649f4d1a3eefc9d5d6eb746f5200ffb04e5e142700b8faa56e7"
-[[package]]
-name = "linux-raw-sys"
-version = "0.4.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456"
-
[[package]]
name = "lock_api"
version = "0.4.11"
@@ -863,7 +622,7 @@ version = "0.94.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c66bfd44a06ae10647fe3f8214762e9369fd4248df1350924b4ef9e770a85ea1"
dependencies = [
- "bitflags 1.3.2",
+ "bitflags",
"serde",
"serde_json",
"serde_repr",
@@ -918,15 +677,6 @@ dependencies = [
"winapi",
]
-[[package]]
-name = "num-traits"
-version = "0.2.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c"
-dependencies = [
- "autocfg",
-]
-
[[package]]
name = "num_cpus"
version = "1.16.0"
@@ -952,12 +702,6 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
-[[package]]
-name = "oorandom"
-version = "11.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
-
[[package]]
name = "overload"
version = "0.1.1"
@@ -1031,34 +775,6 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
-[[package]]
-name = "plotters"
-version = "0.3.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45"
-dependencies = [
- "num-traits",
- "plotters-backend",
- "plotters-svg",
- "wasm-bindgen",
- "web-sys",
-]
-
-[[package]]
-name = "plotters-backend"
-version = "0.3.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609"
-
-[[package]]
-name = "plotters-svg"
-version = "0.3.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab"
-dependencies = [
- "plotters-backend",
-]
-
[[package]]
name = "proc-macro-error"
version = "1.0.4"
@@ -1098,7 +814,7 @@ version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a1a2f1f0a7ecff9c31abbe177637be0e97a0aef46cf8738ece09327985d998"
dependencies = [
- "bitflags 1.3.2",
+ "bitflags",
"getopts",
"memchr",
"unicase",
@@ -1113,83 +829,21 @@ dependencies = [
"proc-macro2",
]
-[[package]]
-name = "rayon"
-version = "1.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1"
-dependencies = [
- "either",
- "rayon-core",
-]
-
-[[package]]
-name = "rayon-core"
-version = "1.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed"
-dependencies = [
- "crossbeam-deque",
- "crossbeam-utils",
-]
-
[[package]]
name = "redox_syscall"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
dependencies = [
- "bitflags 1.3.2",
+ "bitflags",
]
-[[package]]
-name = "regex"
-version = "1.10.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343"
-dependencies = [
- "aho-corasick",
- "memchr",
- "regex-automata",
- "regex-syntax",
-]
-
-[[package]]
-name = "regex-automata"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f"
-dependencies = [
- "aho-corasick",
- "memchr",
- "regex-syntax",
-]
-
-[[package]]
-name = "regex-syntax"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
-
[[package]]
name = "rustc-demangle"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
-[[package]]
-name = "rustix"
-version = "0.38.30"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "322394588aaf33c24007e8bb3238ee3e4c5c09c084ab32bc73890b99ff326bca"
-dependencies = [
- "bitflags 2.4.1",
- "errno",
- "libc",
- "linux-raw-sys",
- "windows-sys 0.52.0",
-]
-
[[package]]
name = "rustversion"
version = "1.0.14"
@@ -1202,15 +856,6 @@ version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c"
-[[package]]
-name = "same-file"
-version = "1.0.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
-dependencies = [
- "winapi-util",
-]
-
[[package]]
name = "scopeguard"
version = "1.2.0"
@@ -1399,16 +1044,6 @@ dependencies = [
"once_cell",
]
-[[package]]
-name = "tinytemplate"
-version = "1.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
-dependencies = [
- "serde",
- "serde_json",
-]
-
[[package]]
name = "tinyvec"
version = "1.6.0"
@@ -1671,16 +1306,6 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
-[[package]]
-name = "walkdir"
-version = "2.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee"
-dependencies = [
- "same-file",
- "winapi-util",
-]
-
[[package]]
name = "want"
version = "0.3.1"
@@ -1750,16 +1375,6 @@ version = "0.2.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d91413b1c31d7539ba5ef2451af3f0b833a005eb27a631cec32bc0635a8602b"
-[[package]]
-name = "web-sys"
-version = "0.3.67"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "58cd2333b6e0be7a39605f0e255892fd7418a682d8da8fe042fe25128794d2ed"
-dependencies = [
- "js-sys",
- "wasm-bindgen",
-]
-
[[package]]
name = "winapi"
version = "0.3.9"
@@ -1776,15 +1391,6 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
-[[package]]
-name = "winapi-util"
-version = "0.1.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
-dependencies = [
- "winapi",
-]
-
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
diff --git a/harper-core/Cargo.toml b/harper-core/Cargo.toml
index 13025fcd8..07d895312 100644
--- a/harper-core/Cargo.toml
+++ b/harper-core/Cargo.toml
@@ -16,9 +16,3 @@ serde = { version = "1.0.190", features = ["derive"] }
smallvec = "1.12.0"
thiserror = "1.0.56"
-[dev-dependencies]
-criterion = { version = "0.5.1" }
-
-[[bench]]
-name = "spellcheck"
-harness = false
diff --git a/harper-core/benches/spellcheck.rs b/harper-core/benches/spellcheck.rs
deleted file mode 100644
index eb4fd7194..000000000
--- a/harper-core/benches/spellcheck.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use criterion::{criterion_group, criterion_main, Criterion};
-use harper_core::{suggest_correct_spelling_str, Dictionary};
-
-fn criterion_benchmark(c: &mut Criterion) {
- let mut group = c.benchmark_group("spellcheck");
-
- let dictionary = Dictionary::new();
-
- group.bench_function("dict create", |b| b.iter(Dictionary::new));
-
- group.bench_function("hellw 5", |b| {
- b.iter(|| {
- suggest_correct_spelling_str("hellw", 5, 3, dictionary);
- })
- });
-
- group.bench_function("thw 5", |b| {
- b.iter(|| {
- suggest_correct_spelling_str("thw", 5, 3, dictionary);
- })
- });
-
- group.bench_function("thw 10", |b| {
- b.iter(|| {
- suggest_correct_spelling_str("thw", 10, 3, dictionary);
- })
- });
-
- group.bench_function("hecatoncheires 10", |b| {
- b.iter(|| {
- suggest_correct_spelling_str("hecatoncheires", 10, 3, dictionary);
- })
- });
-}
-
-criterion_group!(benches, criterion_benchmark);
-criterion_main!(benches);
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index a1a797ed8..222403196 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -3,11 +3,10 @@ use std::fmt::Display;
use itertools::Itertools;
use crate::{
- linting::{LintSet, Suggestion},
+ linting::Suggestion,
parsing::{lex_to_end, lex_to_end_md},
- run_lint_set,
span::Span,
- Dictionary, FatToken, Lint,
+ FatToken,
Punctuation::{self},
Token, TokenKind,
};
@@ -48,10 +47,6 @@ impl Document {
self.match_quotes();
}
- pub fn run_lint_set(&self, lint_set: &LintSet, dictionary: &Dictionary) -> Vec<Lint> {
- run_lint_set(lint_set, self, dictionary)
- }
-
pub fn iter_quote_indices(&self) -> impl Iterator<Item = usize> + '_ {
self.tokens.iter().enumerate().filter_map(|(idx, token)| {
if let TokenKind::Punctuation(Punctuation::Quote(_)) = &token.kind {
diff --git a/harper-core/src/lib.rs b/harper-core/src/lib.rs
index ab2674a1d..08ec5fa9e 100644
--- a/harper-core/src/lib.rs
+++ b/harper-core/src/lib.rs
@@ -7,10 +7,8 @@ mod span;
mod spell;
pub use document::Document;
-pub use linting::run_lint_set;
pub use linting::LintSet;
-pub use linting::{Lint, LintKind, Suggestion};
+pub use linting::{Lint, LintKind, Linter, Suggestion};
pub use parsing::{FatToken, Punctuation, Token, TokenKind};
pub use span::Span;
pub use spell::Dictionary;
-pub use spell::{suggest_correct_spelling, suggest_correct_spelling_str};
diff --git a/harper-core/src/linting/lint.rs b/harper-core/src/linting/lint.rs
index 0ef363a59..3bc89178f 100644
--- a/harper-core/src/linting/lint.rs
+++ b/harper-core/src/linting/lint.rs
@@ -3,7 +3,7 @@ use std::fmt::Display;
use is_macro::Is;
use serde::{Deserialize, Serialize};
-use crate::{document::Document, span::Span, Dictionary};
+use crate::{document::Document, span::Span};
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Lint {
@@ -39,5 +39,3 @@ impl Display for Suggestion {
}
}
}
-
-pub type Linter = fn(document: &Document, dictionary: &Dictionary) -> Vec<Lint>;
diff --git a/harper-core/src/linting/lint_set.rs b/harper-core/src/linting/lint_set.rs
index 30db430d0..e3d31c39f 100644
--- a/harper-core/src/linting/lint_set.rs
+++ b/harper-core/src/linting/lint_set.rs
@@ -1,15 +1,30 @@
-use super::lint::Linter;
+use crate::{Dictionary, Lint};
+
+use super::Linter;
use paste::paste;
use super::{
- long_sentences::long_sentences, repeated_words::repeated_words,
- sentence_capitalization::sentence_capitalization, spell_check::spell_check,
- unclosed_quotes::unclosed_quotes, wrong_quotes::wrong_quotes,
+ long_sentences::LongSentences, repeated_words::RepeatedWords,
+ sentence_capitalization::SentenceCapitalization, spell_check::SpellCheck,
+ unclosed_quotes::UnclosedQuotes, wrong_quotes::WrongQuotes,
};
-#[derive(Debug, Clone)]
pub struct LintSet {
- pub(super) linters: Vec<Linter>,
+ pub(super) linters: Vec<Box<dyn Linter>>,
+}
+
+impl Linter for LintSet {
+ fn lint(&mut self, document: &crate::Document) -> Vec<Lint> {
+ let mut lints = Vec::new();
+
+ for linter in &mut self.linters {
+ lints.append(&mut linter.lint(document));
+ }
+
+ lints.sort_by_key(|lint| lint.span.start);
+
+ lints
+ }
}
impl LintSet {
@@ -18,37 +33,41 @@ impl LintSet {
linters: Vec::new(),
}
}
-}
-impl Default for LintSet {
- fn default() -> Self {
- Self::new()
- .with_spell_check()
- .with_repeated_words()
- .with_long_sentences()
- .with_unclosed_quotes()
- .with_sentence_capitalization()
+ pub fn add_standard(&mut self, dictionary: Dictionary) -> &mut Self {
+ self.add_repeated_words()
+ .add_long_sentences()
+ .add_unclosed_quotes()
+ .add_sentence_capitalization()
+ .add_spell_check(dictionary);
+ self
+ }
+
+ pub fn with_standard(mut self, dictionary: Dictionary) -> Self {
+ self.add_standard(dictionary);
+ self
+ }
+
+ pub fn add_spell_check(&mut self, dictionary: Dictionary) -> &mut Self {
+ self.linters.push(Box::new(SpellCheck::new(dictionary)));
+ self
+ }
+
+ pub fn with_spell_check(mut self, dictionary: Dictionary) -> Self {
+ self.add_spell_check(dictionary);
+ self
}
}
-macro_rules! create_builder {
+/// Create builder methods for the linters that do not take any arguments.
+macro_rules! create_simple_builder_methods {
($($linter:ident),*) => {
impl LintSet {
- pub fn add_all(&mut self) -> &mut Self {
- self.linters.extend_from_slice(&[
- $(
- $linter
- ),*
- ]);
-
- self
- }
-
paste! {
$(
#[doc = "Modifies self, adding the `" $linter "` linter to the set."]
- pub fn [<add_$linter>](&mut self) -> &mut Self{
- self.linters.push($linter);
+ pub fn [<add_$linter:snake>](&mut self) -> &mut Self{
+ self.linters.push(Box::new($linter::default()));
self
}
)*
@@ -57,8 +76,8 @@ macro_rules! create_builder {
paste! {
$(
#[doc = "Consumes self, adding the `" $linter "` linter to the set."]
- pub fn [<with_$linter>](mut self) -> Self{
- self.linters.push($linter);
+ pub fn [<with_$linter:snake>](mut self) -> Self{
+ self.[<add_$linter:snake>]();
self
}
)*
@@ -67,11 +86,10 @@ macro_rules! create_builder {
};
}
-create_builder!(
- spell_check,
- sentence_capitalization,
- unclosed_quotes,
- wrong_quotes,
- repeated_words,
- long_sentences
+create_simple_builder_methods!(
+ SentenceCapitalization,
+ UnclosedQuotes,
+ WrongQuotes,
+ LongSentences,
+ RepeatedWords
);
diff --git a/harper-core/src/linting/long_sentences.rs b/harper-core/src/linting/long_sentences.rs
index aaf332455..901e69072 100644
--- a/harper-core/src/linting/long_sentences.rs
+++ b/harper-core/src/linting/long_sentences.rs
@@ -1,21 +1,27 @@
-use crate::{parsing::TokenStringExt, Dictionary, Document, Lint, LintKind, Span};
+use super::{Lint, LintKind, Linter};
+use crate::{parsing::TokenStringExt, Document, Span};
/// Detect and warn that the sentence is too long.
-pub fn long_sentences(document: &Document, _dictionary: &Dictionary) -> Vec<Lint> {
- let mut output = Vec::new();
+#[derive(Debug, Clone, Copy, Default)]
+pub struct LongSentences;
- for sentence in document.sentences() {
- let word_count = sentence.iter_words().count();
+impl Linter for LongSentences {
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ let mut output = Vec::new();
- if word_count > 40 {
- output.push(Lint {
- span: Span::new(sentence[0].span.start, sentence.last().unwrap().span.end),
- lint_kind: LintKind::Readability,
- message: format!("This sentence is {} words long.", word_count),
- ..Default::default()
- })
+ for sentence in document.sentences() {
+ let word_count = sentence.iter_words().count();
+
+ if word_count > 40 {
+ output.push(Lint {
+ span: Span::new(sentence[0].span.start, sentence.last().unwrap().span.end),
+ lint_kind: LintKind::Readability,
+ message: format!("This sentence is {} words long.", word_count),
+ ..Default::default()
+ })
+ }
}
- }
- output
+ output
+ }
}
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index 2fce127b5..8c89ee144 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -10,16 +10,8 @@ mod wrong_quotes;
pub use lint::{Lint, LintKind, Suggestion};
pub use lint_set::LintSet;
-use crate::{Dictionary, Document};
+use crate::Document;
-pub fn run_lint_set(lint_set: &LintSet, document: &Document, dictionary: &Dictionary) -> Vec<Lint> {
- let mut lints = Vec::new();
-
- for linter in &lint_set.linters {
- lints.append(&mut linter(document, dictionary));
- }
-
- lints.sort_by_key(|lint| lint.span.start);
-
- lints
+pub trait Linter: Send + Sync {
+ fn lint(&mut self, document: &Document) -> Vec<Lint>;
}
diff --git a/harper-core/src/linting/repeated_words.rs b/harper-core/src/linting/repeated_words.rs
index aebc8a840..329e62f41 100644
--- a/harper-core/src/linting/repeated_words.rs
+++ b/harper-core/src/linting/repeated_words.rs
@@ -1,97 +1,108 @@
use hashbrown::HashSet;
use crate::{
- parsing::TokenStringExt, Dictionary, Document, Lint, LintKind, Span, Suggestion, Token,
- TokenKind,
+ parsing::{Token, TokenKind, TokenStringExt},
+ Document, Span, Suggestion,
};
-/// A linter that checks to make sure the first word of each sentence is capitalized.
-pub fn repeated_words(document: &Document, _dictionary: &Dictionary) -> Vec<Lint> {
- let mut lints = Vec::new();
- let set = create_match_set();
-
- for sentence in document.sentences() {
- let mut iter = sentence
- .iter_word_indices()
- .zip(sentence.iter_words())
- .peekable();
-
- while let (Some((idx_a, tok_a)), Some((idx_b, tok_b))) = (iter.next(), iter.peek()) {
- let word_a = document.get_span_content(tok_a.span);
- let word_b = document.get_span_content(tok_b.span);
-
- if set.contains(word_a) && word_a == word_b {
- let intervening_tokens = &sentence[idx_a + 1..*idx_b];
-
- // Detect and remove the whitespace between the repetitions.
- let remove_end = tok_b.span.end;
-
- let remove_start = if let Some(Token {
- span,
- kind: TokenKind::Space(_),
- }) = intervening_tokens.last()
- {
- span.start
- } else {
- tok_b.span.start
- };
-
- lints.push(Lint {
- span: Span::new(remove_start, remove_end),
- lint_kind: LintKind::Repetition,
- suggestions: vec![Suggestion::ReplaceWith(Vec::new())],
- message: "Did you mean to repeat this word?".to_string(),
- })
- }
- }
- }
+use super::{Lint, LintKind, Linter};
- lints
+#[derive(Debug, Clone, Default)]
+pub struct RepeatedWords {
+ /// The set of words that can be considered for repetition checking.
+ set: HashSet<Vec<char>>,
}
-/// The set of words that can be considered for repetition checking.
-fn create_match_set() -> HashSet<Vec<char>> {
- let mut output = HashSet::new();
-
- output.insert(vec!['t', 'h', 'e']);
- output.insert(vec!['T', 'h', 'e']);
- output.insert(vec!['a']);
- output.insert(vec!['A']);
- output.insert(vec!['a', 'n']);
- output.insert(vec!['A', 'n']);
- output.insert(vec!['i', 's']);
- output.insert(vec!['I', 's']);
- output.insert(vec!['w', 'i', 'l', 'l']);
- output.insert(vec!['W', 'i', 'l', 'l']);
- output.insert(vec!['l', 'i', 'k', 'e']);
- output.insert(vec!['L', 'i', 'k', 'e']);
- output.insert(vec!['t', 'h', 'a', 't']);
- output.insert(vec!['T', 'h', 'a', 't']);
- output.insert(vec!['w', 'h', 'a', 't']);
- output.insert(vec!['W', 'h', 'a', 't']);
- output.insert(vec!['w', 'h', 'i', 'c', 'h']);
- output.insert(vec!['W', 'h', 'i', 'c', 'h']);
- output.insert(vec!['b', 'e']);
- output.insert(vec!['B', 'e']);
- output.insert(vec!['a', 'n', 'd']);
- output.insert(vec!['A', 'n', 'd']);
- output.insert(vec!['I']);
- output.insert(vec!['a', 't']);
- output.insert(vec!['A', 't']);
-
- output
+impl RepeatedWords {
+ pub fn new() -> Self {
+ let mut set = HashSet::new();
+
+ set.insert(vec!['t', 'h', 'e']);
+ set.insert(vec!['T', 'h', 'e']);
+ set.insert(vec!['a']);
+ set.insert(vec!['A']);
+ set.insert(vec!['a', 'n']);
+ set.insert(vec!['A', 'n']);
+ set.insert(vec!['i', 's']);
+ set.insert(vec!['I', 's']);
+ set.insert(vec!['w', 'i', 'l', 'l']);
+ set.insert(vec!['W', 'i', 'l', 'l']);
+ set.insert(vec!['l', 'i', 'k', 'e']);
+ set.insert(vec!['L', 'i', 'k', 'e']);
+ set.insert(vec!['t', 'h', 'a', 't']);
+ set.insert(vec!['T', 'h', 'a', 't']);
+ set.insert(vec!['w', 'h', 'a', 't']);
+ set.insert(vec!['W', 'h', 'a', 't']);
+ set.insert(vec!['w', 'h', 'i', 'c', 'h']);
+ set.insert(vec!['W', 'h', 'i', 'c', 'h']);
+ set.insert(vec!['b', 'e']);
+ set.insert(vec!['B', 'e']);
+ set.insert(vec!['a', 'n', 'd']);
+ set.insert(vec!['A', 'n', 'd']);
+ set.insert(vec!['I']);
+ set.insert(vec!['a', 't']);
+ set.insert(vec!['A', 't']);
+
+ Self { set }
+ }
+}
+
+impl Linter for RepeatedWords {
+ /// A linter that checks to make sure the first word of each sentence is capitalized.
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ let mut lints = Vec::new();
+
+ for sentence in document.sentences() {
+ let mut iter = sentence
+ .iter_word_indices()
+ .zip(sentence.iter_words())
+ .peekable();
+
+ while let (Some((idx_a, tok_a)), Some((idx_b, tok_b))) = (iter.next(), iter.peek()) {
+ let word_a = document.get_span_content(tok_a.span);
+ let word_b = document.get_span_content(tok_b.span);
+
+ if self.set.contains(word_a) && word_a == word_b {
+ let intervening_tokens = &sentence[idx_a + 1..*idx_b];
+
+ // Detect and remove the whitespace between the repetitions.
+ let remove_end = tok_b.span.end;
+
+ let remove_start = if let Some(Token {
+ span,
+ kind: TokenKind::Space(_),
+ }) = intervening_tokens.last()
+ {
+ span.start
+ } else {
+ tok_b.span.start
+ };
+
+ lints.push(Lint {
+ span: Span::new(remove_start, remove_end),
+ lint_kind: LintKind::Repetition,
+ suggestions: vec![Suggestion::ReplaceWith(Vec::new())],
+ message: "Did you mean to repeat this word?".to_string(),
+ })
+ }
+ }
+ }
+
+ lints
+ }
}
#[cfg(test)]
mod tests {
- use super::repeated_words;
- use crate::{Dictionary, Document};
+ use super::super::Linter;
+ use super::RepeatedWords;
+ use crate::Document;
#[test]
fn catches_basic() {
- let dictionary = Dictionary::new();
let test = Document::new("I wanted the the banana.", false);
- let lints = repeated_words(&test, dictionary);
+ let mut linter = RepeatedWords::new();
+ let lints = linter.lint(&test);
assert!(lints.len() == 1);
}
}
diff --git a/harper-core/src/linting/sentence_capitalization.rs b/harper-core/src/linting/sentence_capitalization.rs
index c13c3dfa9..c60049090 100644
--- a/harper-core/src/linting/sentence_capitalization.rs
+++ b/harper-core/src/linting/sentence_capitalization.rs
@@ -1,31 +1,38 @@
use itertools::Itertools;
-use crate::{document::Document, parsing::TokenStringExt, Dictionary, Lint, LintKind};
+use crate::{document::Document, parsing::TokenStringExt, Dictionary};
use super::lint::Suggestion;
+use super::{Lint, LintKind, Linter};
-/// A linter that checks to make sure the first word of each sentence is capitalized.
-pub fn sentence_capitalization(document: &Document, _dictionary: &Dictionary) -> Vec<Lint> {
- let mut lints = Vec::new();
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SentenceCapitalization;
- for sentence in document.sentences() {
- if let Some(first_word) = sentence.first_word() {
- let letters = document.get_span_content(first_word.span);
+impl Linter for SentenceCapitalization {
+ /// A linter that checks to make sure the first word of each sentence is capitalized.
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ let mut lints = Vec::new();
- if let Some(first_letter) = letters.first() {
- if first_letter.is_alphabetic() && !first_letter.is_uppercase() {
- lints.push(Lint {
- span: first_word.span.with_len(1),
- lint_kind: LintKind::Capitalization,
- suggestions: vec![Suggestion::ReplaceWith(
- first_letter.to_uppercase().collect_vec(),
- )],
- message: "This sentance does not start with a capital letter".to_string(),
- })
+ for sentence in document.sentences() {
+ if let Some(first_word) = sentence.first_word() {
+ let letters = document.get_span_content(first_word.span);
+
+ if let Some(first_letter) = letters.first() {
+ if first_letter.is_alphabetic() && !first_letter.is_uppercase() {
+ lints.push(Lint {
+ span: first_word.span.with_len(1),
+ lint_kind: LintKind::Capitalization,
+ suggestions: vec![Suggestion::ReplaceWith(
+ first_letter.to_uppercase().collect_vec(),
+ )],
+ message: "This sentance does not start with a capital letter"
+ .to_string(),
+ })
+ }
}
}
}
- }
- lints
+ lints
+ }
}
diff --git a/harper-core/src/linting/spell_check.rs b/harper-core/src/linting/spell_check.rs
index 85dee2308..63baaa03c 100644
--- a/harper-core/src/linting/spell_check.rs
+++ b/harper-core/src/linting/spell_check.rs
@@ -1,34 +1,48 @@
-use crate::{document::Document, suggest_correct_spelling, Dictionary, Lint, LintKind};
+use super::{Lint, LintKind, Linter};
+use crate::{
+ document::Document,
+ spell::{suggest_correct_spelling, Dictionary},
+};
use super::lint::Suggestion;
-pub fn spell_check(document: &Document, _dictionary: &Dictionary) -> Vec<Lint> {
- let mut lints = Vec::new();
+pub struct SpellCheck {
+ dictionary: Dictionary,
+}
- let dictionary = Dictionary::new();
+impl SpellCheck {
+ pub fn new(dictionary: Dictionary) -> Self {
+ Self { dictionary }
+ }
+}
- for word in document.words() {
- let word_chars = document.get_span_content(word.span);
- if dictionary.contains_word(word_chars) {
- continue;
+impl Linter for SpellCheck {
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ let mut lints = Vec::new();
+
+ for word in document.words() {
+ let word_chars = document.get_span_content(word.span);
+ if self.dictionary.contains_word(word_chars) {
+ continue;
+ }
+
+ let possibilities = suggest_correct_spelling(word_chars, 3, 3, &self.dictionary);
+
+ let suggestions = possibilities
+ .into_iter()
+ .map(|word| Suggestion::ReplaceWith(word.to_vec()));
+
+ lints.push(Lint {
+ span: word.span,
+ lint_kind: LintKind::Spelling,
+ suggestions: suggestions.collect(),
+ message: format!(
+ "Did you mean to spell “{}” this way?",
+ document.get_span_content_str(word.span)
+ ),
+ })
}
- let possibilities = suggest_correct_spelling(word_chars, 3, 3, dictionary);
-
- let suggestions = possibilities
- .into_iter()
- .map(|word| Suggestion::ReplaceWith(word.to_vec()));
-
- lints.push(Lint {
- span: word.span,
- lint_kind: LintKind::Spelling,
- suggestions: suggestions.collect(),
- message: format!(
- "Did you mean to spell “{}” this way?",
- document.get_span_content_str(word.span)
- ),
- })
+ lints
}
-
- lints
}
diff --git a/harper-core/src/linting/unclosed_quotes.rs b/harper-core/src/linting/unclosed_quotes.rs
index 9bffe7c7b..67653aba1 100644
--- a/harper-core/src/linting/unclosed_quotes.rs
+++ b/harper-core/src/linting/unclosed_quotes.rs
@@ -1,21 +1,27 @@
-use crate::{
- document::Document, parsing::Quote, Dictionary, Lint, LintKind, Punctuation, TokenKind,
-};
+use crate::{document::Document, parsing::Quote, Punctuation, TokenKind};
-pub fn unclosed_quotes(document: &Document, _dictionary: &Dictionary) -> Vec<Lint> {
- let mut lints = Vec::new();
+use super::{Lint, LintKind, Linter};
- // TODO: Try zipping quote positions
- for token in document.tokens() {
- if let TokenKind::Punctuation(Punctuation::Quote(Quote { twin_loc: None })) = token.kind {
- lints.push(Lint {
- span: token.span,
- lint_kind: LintKind::UnmatchedQuote,
- suggestions: vec![],
- message: "This quote has no termination.".to_string(),
- })
+#[derive(Debug, Clone, Copy, Default)]
+pub struct UnclosedQuotes;
+
+impl Linter for UnclosedQuotes {
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ let mut lints = Vec::new();
+
+ // TODO: Try zipping quote positions
+ for token in document.tokens() {
+ if let TokenKind::Punctuation(Punctuation::Quote(Quote { twin_loc: None })) = token.kind
+ {
+ lints.push(Lint {
+ span: token.span,
+ lint_kind: LintKind::UnmatchedQuote,
+ suggestions: vec![],
+ message: "This quote has no termination.".to_string(),
+ })
+ }
}
- }
- lints
+ lints
+ }
}
diff --git a/harper-core/src/linting/wrong_quotes.rs b/harper-core/src/linting/wrong_quotes.rs
index 65d73181a..b7a9eb12c 100644
--- a/harper-core/src/linting/wrong_quotes.rs
+++ b/harper-core/src/linting/wrong_quotes.rs
@@ -1,11 +1,18 @@
-use crate::{document::Document, Dictionary, Lint, LintKind, Suggestion, Token};
-
-pub fn wrong_quotes(document: &Document, _dictionary: &Dictionary) -> Vec<Lint> {
- document
- .iter_quote_indices()
- .zip(document.iter_quotes())
- .filter_map(|(quote_idx, quote_token)| lint_quote(document, quote_idx, quote_token))
- .collect()
+use crate::{document::Document, Suggestion, Token};
+
+use super::{Lint, LintKind, Linter};
+
+#[derive(Debug, Clone, Copy, Default)]
+pub struct WrongQuotes;
+
+impl Linter for WrongQuotes {
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ document
+ .iter_quote_indices()
+ .zip(document.iter_quotes())
+ .filter_map(|(quote_idx, quote_token)| lint_quote(document, quote_idx, quote_token))
+ .collect()
+ }
}
fn lint_quote(document: &Document, quote_idx: usize, quote_token: Token) -> Option<Lint> {
diff --git a/harper-core/src/parsing/lexer.rs b/harper-core/src/parsing/lexer.rs
index 99002cdb4..95e13997b 100644
--- a/harper-core/src/parsing/lexer.rs
+++ b/harper-core/src/parsing/lexer.rs
@@ -26,17 +26,20 @@ pub fn lex_to_end_md(source: &[char]) -> Vec<Token> {
// NOTE: the range spits out __byte__ indices, not char indices.
// This is why we keep track above.
for (event, range) in md_parser.into_offset_iter() {
- if let pulldown_cmark::Event::Text(text) = event {
- traversed_chars += source_str[traversed_bytes..range.start].chars().count();
- traversed_bytes = range.start;
+ match event {
+ pulldown_cmark::Event::Text(text) => {
+ traversed_chars += source_str[traversed_bytes..range.start].chars().count();
+ traversed_bytes = range.start;
- let mut new_tokens = lex_to_end_str(text);
+ let mut new_tokens = lex_to_end_str(text);
- new_tokens
- .iter_mut()
- .for_each(|token| token.span.offset(traversed_chars));
+ new_tokens
+ .iter_mut()
+ .for_each(|token| token.span.offset(traversed_chars));
- tokens.append(&mut new_tokens);
+ tokens.append(&mut new_tokens);
+ }
+ _ => (),
}
}
diff --git a/harper-core/src/spell/dictionary.rs b/harper-core/src/spell/dictionary.rs
index 018ec83ec..d5bb630ad 100644
--- a/harper-core/src/spell/dictionary.rs
+++ b/harper-core/src/spell/dictionary.rs
@@ -50,8 +50,8 @@ fn uncached_inner_new() -> Dictionary {
static DICT: Lazy<Dictionary> = Lazy::new(uncached_inner_new);
impl Dictionary {
- pub fn new() -> &'static Self {
- &DICT
+ pub fn new() -> Self {
+ DICT.clone()
}
/// Iterate over all the words in the dicitonary of a given length
diff --git a/harper-ls/Cargo.toml b/harper-ls/Cargo.toml
index b5b5e17a1..7cd3c80f2 100644
--- a/harper-ls/Cargo.toml
+++ b/harper-ls/Cargo.toml
@@ -10,4 +10,4 @@ harper-core = { path = "../harper-core", version = "0.1.0" }
tower-lsp = "0.20.0"
tokio = { version = "1.35.1", features = ["full"] }
clap = { version = "4.4.18", features = ["derive"] }
-cached = "0.47.0"
+once_cell = "1.19.0"
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index b54a0b35b..1d052e96c 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -1,4 +1,7 @@
-use tokio::time::Instant;
+use std::{borrow::BorrowMut, ops::DerefMut};
+
+use harper_core::{Dictionary, LintSet};
+use tokio::{sync::Mutex, time::Instant};
use tower_lsp::{
jsonrpc::Result,
lsp_types::{
@@ -15,16 +18,22 @@ use crate::diagnostics::{generate_code_actions, generate_diagnostics};
pub struct Backend {
client: Client,
+ linter: Mutex<LintSet>,
}
impl Backend {
pub fn new(client: Client) -> Self {
- Self { client }
+ let dictionary = Dictionary::new();
+ let linter = Mutex::new(LintSet::new().with_standard(dictionary));
+
+ Self { client, linter }
}
async fn publish_diagnostics(&self, url: &Url) {
let start_time = Instant::now();
- let diagnostics = generate_diagnostics(url).unwrap();
+ let mut linter = self.linter.lock().await;
+
+ let diagnostics = generate_diagnostics(url, linter.deref_mut()).unwrap();
let result = PublishDiagnosticsParams {
uri: url.clone(),
@@ -105,7 +114,9 @@ impl LanguageServer for Backend {
}
async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
- let actions = generate_code_actions(&params.text_document.uri, params.range)?;
+ let mut linter = self.linter.lock().await;
+ let actions =
+ generate_code_actions(&params.text_document.uri, params.range, linter.deref_mut())?;
self.client
.log_message(MessageType::INFO, format!("{:?}", actions))
diff --git a/harper-ls/src/diagnostics.rs b/harper-ls/src/diagnostics.rs
index cf7954faa..9932c5903 100644
--- a/harper-ls/src/diagnostics.rs
+++ b/harper-ls/src/diagnostics.rs
@@ -1,5 +1,4 @@
-use cached::proc_macro::cached;
-use harper_core::{Dictionary, Document, Lint, LintSet, Span, Suggestion};
+use harper_core::{Document, Lint, LintSet, Linter, Span, Suggestion};
use std::collections::HashMap;
use std::fs::read;
use tower_lsp::jsonrpc::{ErrorCode, Result};
@@ -7,10 +6,15 @@ use tower_lsp::lsp_types::{
CodeAction, CodeActionKind, Diagnostic, Position, Range, TextEdit, Url, WorkspaceEdit,
};
-pub fn generate_diagnostics(file_url: &Url) -> Result<Vec<Diagnostic>> {
+fn lint_file(file_url: &Url, linter: &mut impl Linter) -> Result<(Vec<Lint>, Vec<char>)> {
let file_str = open_url(file_url)?;
let source_chars: Vec<_> = file_str.chars().collect();
- let lints = lint_string(file_str);
+ let document = Document::new(&file_str, true);
+ Ok((linter.lint(&document), source_chars))
+}
+
+pub fn generate_diagnostics(file_url: &Url, linter: &mut impl Linter) -> Result<Vec<Diagnostic>> {
+ let (lints, source_chars) = lint_file(file_url, linter)?;
let diagnostics = lints
.into_iter()
@@ -20,10 +24,12 @@ pub fn generate_diagnostics(file_url: &Url) -> Result<Vec<Diagnostic>> {
Ok(diagnostics)
}
-pub fn generate_code_actions(url: &Url, range: Range) -> Result<Vec<CodeAction>> {
- let file_str = open_url(url)?;
- let source_chars: Vec<_> = file_str.chars().collect();
- let lints = lint_string(file_str);
+pub fn generate_code_actions(
+ url: &Url,
+ range: Range,
+ linter: &mut impl Linter,
+) -> Result<Vec<CodeAction>> {
+ let (lints, source_chars) = lint_file(url, linter)?;
// Find lints whose span overlaps with range
let span = range_to_span(&source_chars, range);
@@ -76,13 +82,6 @@ fn open_url(url: &Url) -> Result<String> {
Ok(String::from_utf8(file).unwrap())
}
-#[cached]
-fn lint_string(text: String) -> Vec<Lint> {
- let document = Document::new(&text, true);
- let dictionary = Dictionary::new();
- document.run_lint_set(&LintSet::default(), dictionary)
-}
-
fn lint_to_diagnostic(lint: Lint, source: &[char]) -> Diagnostic {
let range = span_to_range(source, lint.span);
diff --git a/harper-serve/src/main.rs b/harper-serve/src/main.rs
index fc00c37ad..dfb7e10e5 100644
--- a/harper-serve/src/main.rs
+++ b/harper-serve/src/main.rs
@@ -1,6 +1,6 @@
#![allow(dead_code)]
-use harper_core::{Dictionary, Document, FatToken, Lint, LintSet, Span, Suggestion};
+use harper_core::{Dictionary, Document, FatToken, Lint, LintSet, Linter, Span, Suggestion};
use std::net::SocketAddr;
use tokio::time::Instant;
use tracing::{info, Level};
@@ -90,9 +90,11 @@ struct ParseResponse {
async fn lint(Json(payload): Json<LintRequest>) -> (StatusCode, Json<LintResponse>) {
let text = payload.text;
- let dictionary = Dictionary::new();
let document = Document::new(&text, true);
- let lints = document.run_lint_set(&LintSet::default(), dictionary);
+
+ let dictionary = Dictionary::new();
+ let mut linter = LintSet::new().with_standard(dictionary);
+ let lints = linter.lint(&document);
(StatusCode::ACCEPTED, Json(LintResponse { lints }))
}
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index 6bdda3fe8..3631ed357 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -1,4 +1,4 @@
-use harper_core::{Dictionary, Document, LintSet};
+use harper_core::{Dictionary, Document, LintSet, Linter};
use serde::Serialize;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
@@ -22,7 +22,8 @@ pub fn lint(text: String) -> Vec<JsValue> {
let dictionary = Dictionary::new();
let document = Document::new(&text, true);
- let lints = document.run_lint_set(&LintSet::default(), dictionary);
+ let mut linter = LintSet::new().with_standard(dictionary);
+ let lints = linter.lint(&document);
lints
.into_iter()
diff --git a/web/src/lib/analysis.ts b/web/src/lib/analysis.ts
index d804dae1f..8d9ed8a1e 100644
--- a/web/src/lib/analysis.ts
+++ b/web/src/lib/analysis.ts
@@ -1,4 +1,4 @@
-const defaultUseWasm = false;
+const defaultUseWasm = true;
export interface ParseResponse {
tokens: Token[];