harper_comments/
comment_parser.rs

1use std::path::Path;
2
3use crate::comment_parsers;
4use comment_parsers::{Go, JavaDoc, JsDoc, Lua, Solidity, Unit};
5use harper_core::Token;
6use harper_core::parsers::{self, MarkdownOptions, Parser};
7use harper_core::spell::MutableDictionary;
8use tree_sitter::Node;
9
10use crate::masker::CommentMasker;
11
12pub struct CommentParser {
13    inner: parsers::Mask<CommentMasker, Box<dyn Parser>>,
14}
15
16impl CommentParser {
17    pub fn create_ident_dict(&self, source: &[char]) -> Option<MutableDictionary> {
18        self.inner.masker.create_ident_dict(source)
19    }
20
21    pub fn new_from_language_id(
22        language_id: &str,
23        markdown_options: MarkdownOptions,
24    ) -> Option<Self> {
25        let language = match language_id {
26            "c" => tree_sitter_c::LANGUAGE,
27            "clojure" => tree_sitter_clojure::LANGUAGE,
28            "cmake" => tree_sitter_cmake::LANGUAGE,
29            "cpp" => tree_sitter_cpp::LANGUAGE,
30            "csharp" => tree_sitter_c_sharp::LANGUAGE,
31            "dart" => harper_tree_sitter_dart::LANGUAGE,
32            "go" => tree_sitter_go::LANGUAGE,
33            "haskell" => tree_sitter_haskell::LANGUAGE,
34            "java" => tree_sitter_java::LANGUAGE,
35            "javascript" => tree_sitter_javascript::LANGUAGE,
36            "javascriptreact" => tree_sitter_typescript::LANGUAGE_TSX,
37            "kotlin" => tree_sitter_kotlin_ng::LANGUAGE,
38            "lua" => tree_sitter_lua::LANGUAGE,
39            "nix" => tree_sitter_nix::LANGUAGE,
40            "php" => tree_sitter_php::LANGUAGE_PHP,
41            "ruby" => tree_sitter_ruby::LANGUAGE,
42            "rust" => tree_sitter_rust::LANGUAGE,
43            "scala" => tree_sitter_scala::LANGUAGE,
44            "shellscript" => tree_sitter_bash::LANGUAGE,
45            "solidity" => tree_sitter_solidity::LANGUAGE,
46            "swift" => tree_sitter_swift::LANGUAGE,
47            "toml" => tree_sitter_toml_ng::LANGUAGE,
48            "typescript" => tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
49            "typescriptreact" => tree_sitter_typescript::LANGUAGE_TSX,
50            _ => return None,
51        };
52
53        let comment_parser: Box<dyn Parser> = match language_id {
54            "go" => Box::new(Go::new_markdown(markdown_options)),
55            "java" => Box::new(JavaDoc::default()),
56            "javascript" | "javascriptreact" | "typescript" | "typescriptreact" => {
57                Box::new(JsDoc::new_markdown(markdown_options))
58            }
59            "lua" => Box::new(Lua::new_markdown(markdown_options)),
60            "solidity" => Box::new(Solidity::new_markdown(markdown_options)),
61            _ => Box::new(Unit::new_markdown(markdown_options)),
62        };
63
64        Some(Self {
65            inner: parsers::Mask::new(
66                CommentMasker::new(language.into(), Self::node_condition),
67                comment_parser,
68            ),
69        })
70    }
71
72    /// Infer the programming language from a provided filename.
73    pub fn new_from_filename(filename: &Path, markdown_options: MarkdownOptions) -> Option<Self> {
74        Self::new_from_language_id(Self::filename_to_filetype(filename)?, markdown_options)
75    }
76
77    /// Convert a provided path to a corresponding Language Server Protocol file
78    /// type.
79    ///
80    /// Note to contributors: try to keep this in sync with
81    /// [`Self::new_from_language_id`]
82    fn filename_to_filetype(path: &Path) -> Option<&'static str> {
83        Some(match path.extension()?.to_str()? {
84            "c" => "c",
85            "bb" | "cljc" | "cljd" | "clj" | "cljs" => "clojure",
86            "cmake" => "cmake",
87            "cpp" | "h" => "cpp",
88            "cs" => "csharp",
89            "dart" => "dart",
90            "go" => "go",
91            "hs" => "haskell",
92            "java" => "java",
93            "js" => "javascript",
94            "jsx" => "javascriptreact",
95            "kt" | "kts" => "kotlin",
96            "lua" => "lua",
97            "nix" => "nix",
98            "php" => "php",
99            "rb" => "ruby",
100            "rs" => "rust",
101            "sbt" | "sc" | "scala" | "mill" => "scala",
102            "bash" | "sh" => "shellscript",
103            "sol" => "solidity",
104            "swift" => "swift",
105            "toml" => "toml",
106            "ts" => "typescript",
107            "tsx" => "typescriptreact",
108            _ => return None,
109        })
110    }
111
112    fn node_condition(n: &Node) -> bool {
113        n.kind().contains("comment")
114    }
115}
116
117impl Parser for CommentParser {
118    fn parse(&self, source: &[char]) -> Vec<Token> {
119        self.inner.parse(source)
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::CommentParser;
126    use harper_core::parsers::{MarkdownOptions, StrParser};
127
128    #[test]
129    fn hang() {
130        use std::sync::mpsc::channel;
131        use std::thread;
132        use std::time::Duration;
133
134        let (tx, rx) = channel::<()>();
135
136        let handle = thread::spawn(move || {
137            let opts = MarkdownOptions::default();
138            let parser = CommentParser::new_from_language_id("java", opts).unwrap();
139            let _res = parser.parse_str("//{@j");
140            tx.send(()).expect("send failed");
141        });
142
143        rx.recv_timeout(Duration::from_secs(10)).expect("timed out");
144        handle.join().expect("failed to join");
145    }
146}