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: u64::MAX, spans: Vec::new(),
95 })
96 }
97
98 pub fn highlight(
103 &mut self,
104 rope: &ropey::Rope,
105 revision: u64,
106 first_byte: usize,
107 last_byte: usize,
108 ) -> Vec<Span> {
109 let hash = revision;
110 if hash != self.source_hash {
111 let text = rope.to_string(); let Some(tree) = self.parser.parse(&text, None) else {
113 return Vec::new();
114 };
115 let mut cursor = QueryCursor::new();
116 let mut by_byte: HashMap<usize, (usize, Class)> = HashMap::new();
117 let mut matches = cursor.matches(&self.query, tree.root_node(), text.as_bytes());
118 while let Some(m) = { StreamingIterator::next(&mut matches) } {
119 for cap in m.captures {
120 let node = cap.node;
121 let class = self.classes[cap.index as usize];
122 let entry = by_byte
124 .entry(node.start_byte())
125 .or_insert((node.end_byte(), class));
126 if node.end_byte() - node.start_byte() <= entry.0 - node.start_byte() {
127 *entry = (node.end_byte(), class);
128 }
129 }
130 }
131 let mut spans: Vec<Span> = by_byte
132 .into_iter()
133 .map(|(start, (end, class))| Span { start, end, class })
134 .collect();
135 spans.sort_by_key(|s| (s.start, s.end));
136 self.spans = spans;
137 self.source_hash = hash;
138 }
139 let lo = self.spans.partition_point(|s| s.end <= first_byte);
141 let hi = self.spans.partition_point(|s| s.start < last_byte);
142 self.spans[lo..hi.max(lo)].to_vec()
143 }
144}
145
146fn first_line(path: &str) -> Option<String> {
150 use std::io::{BufRead, BufReader, Read};
151 let mut line = String::new();
152 BufReader::new(std::fs::File::open(path).ok()?)
153 .take(256)
154 .read_line(&mut line)
155 .ok()?;
156 Some(line)
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 fn classes_for(path: &str, src: &str) -> Vec<Class> {
164 let mut hl = Highlighter::for_path(path).expect("language");
165 let rope = ropey::Rope::from_str(src);
166 hl.highlight(&rope, 0, 0, src.len())
167 .iter()
168 .map(|s| s.class)
169 .collect()
170 }
171
172 #[test]
173 fn rust_keywords_and_strings() {
174 let classes = classes_for("x.rs", "fn main() { let s = \"hi\"; }\n");
175 assert!(classes.contains(&Class::Keyword), "{classes:?}");
176 assert!(classes.contains(&Class::String), "{classes:?}");
177 }
178
179 #[test]
180 fn cpp_highlights_with_cxx_scanner() {
181 let classes = classes_for("x.cpp", "auto edge = hone(blade);\n");
184 assert!(!classes.is_empty(), "cpp grammar produced no spans");
185 assert!(classes.contains(&Class::Type), "{classes:?}"); }
187
188 #[test]
189 fn python_and_go_and_ts() {
190 assert!(classes_for("x.py", "def f(x):\n return x\n").contains(&Class::Keyword));
191 assert!(classes_for("x.go", "package main\nfunc main() {}\n").contains(&Class::Keyword));
192 assert!(!classes_for("x.ts", "const x: number = 1;\n").is_empty());
193 assert!(!classes_for("x.json", "{\"a\": 1}\n").is_empty());
194 assert!(!classes_for("x.sh", "#!/bin/sh\necho hi\n").is_empty());
195 }
196
197 #[test]
198 fn fish_lua_and_sql() {
199 assert!(!classes_for("x.fish", "set -l name rust\n").is_empty());
202 assert!(classes_for("x.lua", "local x = 1\n").contains(&Class::Keyword));
203 assert!(classes_for("x.sql", "SELECT * FROM users;\n").contains(&Class::Keyword));
204 }
205
206 #[test]
207 fn shebang_script_file_resolves() {
208 let path =
211 std::env::temp_dir().join(format!("strop-syntax-shebang-{}", std::process::id()));
212 std::fs::write(&path, "#!/usr/bin/env bash\necho hi\n").unwrap();
213 let resolved = Highlighter::for_path(path.to_str().unwrap());
214 std::fs::remove_file(&path).ok();
215 let mut hl = resolved.expect("bash via shebang");
216 let rope = ropey::Rope::from_str("#!/usr/bin/env bash\necho hi\n");
217 assert!(!hl.highlight(&rope, 0, 0, rope.len_bytes()).is_empty());
218 }
219}