Skip to main content

strop_syntax/
lib.rs

1//! strop-syntax: tree-sitter highlighting. Parsers statically linked
2//! (0002 §2.2 — never dlopen'd grammars); queries are data (0001 §5.11),
3//! embedded defaults now, runtime overrides when config lands (0005).
4
5use std::collections::HashMap;
6
7use streaming_iterator::StreamingIterator;
8pub mod languages;
9
10use tree_sitter::{Parser, Query, QueryCursor};
11
12/// Semantic classes the renderer maps to palette colors. Kept small and
13/// stable; the query capture names map onto these.
14#[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/// A colored span, in byte offsets.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct Span {
51    pub start: usize,
52    pub end: usize,
53    pub class: Class,
54}
55
56/// One language's parser + highlight query. Reparses on demand; the
57/// incremental edit-diff feed (0001 pillar 4) lands when the core reports
58/// edits — prototype correctness first, per-frame cost is invisible at
59/// demo file sizes.
60pub struct Highlighter {
61    parser: Parser,
62    query: Query,
63    /// Capture index → class, resolved once at construction.
64    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            // basename/extension both missed: one bounded read of the
73            // first line, and the shebang decides (languages::detect)
74            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, // never a real revision
94            spans: Vec::new(),
95        })
96    }
97
98    /// Highlight spans intersecting `[first_byte, last_byte)` of the rope.
99    /// Reparses only when the text changed. `revision` is the document's
100    /// edit counter (0020 §5: the len+first+last key under-invalidated
101    /// same-length middle edits deterministically).
102    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(); // prototype: whole-buffer; chunk callback when hot
112            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                    // most specific wins: smallest containing span
123                    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        // return only visible spans; spans are sorted, binary search the window
140        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
146/// First line of a file, capped at 256 bytes so a minified no-newline
147/// blob can't turn a probe into a full read. `None` on any IO/decoding
148/// hiccup — shebang detection is a best-effort fallback, never an error.
149fn 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        // the 0002 §5 gate: C++ grammar's scanner is C++ — a broken
182        // static-libstdc++ link fails here, per-PR, not at a user's file.
183        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:?}"); // auto → @type.builtin
186    }
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        // for_path compiles each vendored Helix query against its
200        // grammar — node drift upstream surfaces here as a None.
201        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        // extensionless file on disk: for_path must read its first
209        // line once and hand it to the shebang fallback
210        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}