1use std::collections::HashMap;
6
7use streaming_iterator::StreamingIterator;
8pub mod languages;
9
10use tree_sitter::{Parser, Query, QueryCursor};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Class {
16 Keyword,
17 Function,
18 Type,
19 String,
20 Comment,
21 Number,
22 Operator,
23 Punctuation,
24 Constant,
25 Variable,
26 Attribute,
27}
28
29impl Class {
30 fn from_capture(name: &str) -> Self {
31 let head = name.split('.').next().unwrap_or(name);
32 match head {
33 "keyword" => Class::Keyword,
34 "function" | "constructor" => Class::Function,
35 "type" => Class::Type,
36 "string" | "character" => Class::String,
37 "comment" => Class::Comment,
38 "number" | "float" => Class::Number,
39 "operator" => Class::Operator,
40 "punctuation" => Class::Punctuation,
41 "constant" | "boolean" => Class::Constant,
42 "attribute" | "property" => Class::Attribute,
43 _ => Class::Variable,
44 }
45 }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct Span {
51 pub start: usize,
52 pub end: usize,
53 pub class: Class,
54}
55
56pub struct Highlighter {
61 parser: Parser,
62 query: Query,
63 classes: Vec<Class>,
65 source_hash: u64,
66 spans: Vec<Span>,
67}
68
69impl Highlighter {
70 pub fn for_path(path: &str) -> Option<Self> {
71 let spec = languages::detect(path, None).or_else(|| {
72 let line = first_line(path)?;
75 languages::detect(path, Some(&line))
76 })?;
77 Self::from_spec(spec)
78 }
79
80 fn from_spec(spec: languages::LanguageSpec) -> Option<Self> {
81 let mut parser = Parser::new();
82 parser.set_language(&spec.language).ok()?;
83 let query = Query::new(&spec.language, spec.highlights).ok()?;
84 let classes = query
85 .capture_names()
86 .iter()
87 .map(|n| Class::from_capture(n))
88 .collect();
89 Some(Self {
90 parser,
91 query,
92 classes,
93 source_hash: 0,
94 spans: Vec::new(),
95 })
96 }
97
98 pub fn highlight(
102 &mut self,
103 rope: &ropey::Rope,
104 first_byte: usize,
105 last_byte: usize,
106 ) -> Vec<Span> {
107 let mut hasher = std::hash::DefaultHasher::new();
108 std::hash::Hash::hash(&rope.len_bytes(), &mut hasher);
109 if let (Some(first), Some(last)) = (
112 rope.get_byte(0),
113 rope.len_bytes()
114 .checked_sub(1)
115 .and_then(|i| rope.get_byte(i)),
116 ) {
117 std::hash::Hash::hash(&(first, last), &mut hasher);
118 }
119 let hash = std::hash::Hasher::finish(&hasher);
120 if hash != self.source_hash {
121 let text = rope.to_string(); let Some(tree) = self.parser.parse(&text, None) else {
123 return Vec::new();
124 };
125 let mut cursor = QueryCursor::new();
126 let mut by_byte: HashMap<usize, (usize, Class)> = HashMap::new();
127 let mut matches = cursor.matches(&self.query, tree.root_node(), text.as_bytes());
128 while let Some(m) = { StreamingIterator::next(&mut matches) } {
129 for cap in m.captures {
130 let node = cap.node;
131 let class = self.classes[cap.index as usize];
132 let entry = by_byte
134 .entry(node.start_byte())
135 .or_insert((node.end_byte(), class));
136 if node.end_byte() - node.start_byte() <= entry.0 - node.start_byte() {
137 *entry = (node.end_byte(), class);
138 }
139 }
140 }
141 let mut spans: Vec<Span> = by_byte
142 .into_iter()
143 .map(|(start, (end, class))| Span { start, end, class })
144 .collect();
145 spans.sort_by_key(|s| (s.start, s.end));
146 self.spans = spans;
147 self.source_hash = hash;
148 }
149 let lo = self.spans.partition_point(|s| s.end <= first_byte);
151 let hi = self.spans.partition_point(|s| s.start < last_byte);
152 self.spans[lo..hi.max(lo)].to_vec()
153 }
154}
155
156fn first_line(path: &str) -> Option<String> {
160 use std::io::{BufRead, BufReader, Read};
161 let mut line = String::new();
162 BufReader::new(std::fs::File::open(path).ok()?)
163 .take(256)
164 .read_line(&mut line)
165 .ok()?;
166 Some(line)
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn classes_for(path: &str, src: &str) -> Vec<Class> {
174 let mut hl = Highlighter::for_path(path).expect("language");
175 let rope = ropey::Rope::from_str(src);
176 hl.highlight(&rope, 0, src.len())
177 .iter()
178 .map(|s| s.class)
179 .collect()
180 }
181
182 #[test]
183 fn rust_keywords_and_strings() {
184 let classes = classes_for("x.rs", "fn main() { let s = \"hi\"; }\n");
185 assert!(classes.contains(&Class::Keyword), "{classes:?}");
186 assert!(classes.contains(&Class::String), "{classes:?}");
187 }
188
189 #[test]
190 fn cpp_highlights_with_cxx_scanner() {
191 let classes = classes_for("x.cpp", "auto edge = hone(blade);\n");
194 assert!(!classes.is_empty(), "cpp grammar produced no spans");
195 assert!(classes.contains(&Class::Type), "{classes:?}"); }
197
198 #[test]
199 fn python_and_go_and_ts() {
200 assert!(classes_for("x.py", "def f(x):\n return x\n").contains(&Class::Keyword));
201 assert!(classes_for("x.go", "package main\nfunc main() {}\n").contains(&Class::Keyword));
202 assert!(!classes_for("x.ts", "const x: number = 1;\n").is_empty());
203 assert!(!classes_for("x.json", "{\"a\": 1}\n").is_empty());
204 assert!(!classes_for("x.sh", "#!/bin/sh\necho hi\n").is_empty());
205 }
206
207 #[test]
208 fn fish_lua_and_sql() {
209 assert!(!classes_for("x.fish", "set -l name rust\n").is_empty());
212 assert!(classes_for("x.lua", "local x = 1\n").contains(&Class::Keyword));
213 assert!(classes_for("x.sql", "SELECT * FROM users;\n").contains(&Class::Keyword));
214 }
215
216 #[test]
217 fn shebang_script_file_resolves() {
218 let path =
221 std::env::temp_dir().join(format!("strop-syntax-shebang-{}", std::process::id()));
222 std::fs::write(&path, "#!/usr/bin/env bash\necho hi\n").unwrap();
223 let resolved = Highlighter::for_path(path.to_str().unwrap());
224 std::fs::remove_file(&path).ok();
225 let mut hl = resolved.expect("bash via shebang");
226 let rope = ropey::Rope::from_str("#!/usr/bin/env bash\necho hi\n");
227 assert!(!hl.highlight(&rope, 0, rope.len_bytes()).is_empty());
228 }
229}