aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 0fe5c9320887f9168836b358368cff9ca262ea49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
mod highlights;
mod parsers;

use core::str;
use std::{
    cell::RefCell, collections::HashMap, env::{
        args,
        current_dir,
    }, fs::{
        create_dir,
        read,
    }, ops::Deref, process::Command
};

use dirs::cache_dir;
use highlights::HIGHLIGHTS;
use libloading::Library;
use parsers::{
    ALIASES,
    PARSERS,
    QUERIES,
};
use tree_sitter::Language;
use tree_sitter_highlight::{
    HighlightConfiguration,
    Highlighter,
    HtmlRenderer,
};
use url::Url;

fn get_config<'a>(
    lang: &'a str,
    configs: &'a RefCell<HashMap<&'a str, &'static HighlightConfiguration>>,
) -> Option<&'static HighlightConfiguration> {
    let lang = ALIASES.get(lang).unwrap_or(&lang);
    configs.borrow_mut().entry(lang).or_insert_with(|| {
        let install_info = PARSERS
            .get(lang)
            .expect("A valid language should have been passed in");
        let mut cache_dir = cache_dir().expect("Cache directory should be available");
        cache_dir.push("yah");

        let mut parsers_dir = current_dir().expect("Current directory should be available");
        parsers_dir.push(".parsers");
        if !parsers_dir.exists() {
            create_dir(&parsers_dir).expect("`parsers_dir` should be able to be created");
        }
        if !cache_dir.exists() {
            create_dir(&cache_dir).expect("`cache_dir` should be able to be created");
        }

        let parser_path = parsers_dir.join(format!("{lang}.so"));
        let repo_path = cache_dir.join(
            Url::parse(install_info.url)
                .unwrap()
                .path_segments()
                .expect("The `url` field should contain a valid URL")
                .last()
                .unwrap(),
        );

        if !parser_path.exists() {
            if !repo_path.exists() {
                Command::new("git")
                    .arg("clone")
                    .arg(install_info.url)
                    .arg("--depth")
                    .arg("1")
                    .current_dir(&cache_dir)
                    .spawn()
                    .expect("`git` should successfully cloned the treesitter repository")
                    .wait()
                    .expect("`git` should have started");
            }

            if install_info.requires_generate_from_grammar {
                if install_info.generate_requires_npm {
                    Command::new("npm")
                        .arg("install")
                        .current_dir(&repo_path)
                        .spawn()
                        .expect("`npm` should successfully installed dependencies")
                        .wait()
                        .expect("`npm` should have started");
                }

                Command::new("tree-sitter")
                    .arg("generate")
                    .arg("--no-bindings")
                    .current_dir(&repo_path)
                    .spawn()
                    .expect("`tree-sitter` should successfully generated the parser")
                    .wait()
                    .expect("`tree-sitter` should have started");
            }

            Command::new("tree-sitter")
                .arg("build")
                .arg("-o")
                .arg(&parser_path)
                .arg(
                    install_info
                        .location
                        .map_or(repo_path.clone(), |location| repo_path.join(location)),
                )
                .spawn()
                .expect("`tree-sitter` should successfully built the parser")
                .wait()
                .expect("`tree-sitter` should have started");
        }

        let library = unsafe {
            Library::new(parser_path)
                .expect("`parser_path` should contain a path to a valid C dylib")
        };
        let parser = unsafe {
            library
                .get::<unsafe extern "C" fn() -> Language>(format!("tree_sitter_{lang}").as_bytes())
                .expect("`parser_path` should contain a path to treesitter parser dylib ")(
            )
        };
        std::mem::forget(library); // this causes the dylib to not be unloaded with dlclose after this
        // scope is dropped, and thus extending its lifetime to static

        let mut config = HighlightConfiguration::new(
            parser,
            *lang,
            QUERIES
                .get(lang)
                .unwrap()
                .get("highlights")
                .map(Deref::deref)
                .unwrap_or(""),
            QUERIES
                .get(lang)
                .unwrap()
                .get("injections")
                .map(Deref::deref)
                .unwrap_or(""),
            QUERIES
                .get(lang)
                .unwrap()
                .get("locals")
                .map(Deref::deref)
                .unwrap_or(""),
        )
        .unwrap();
        config.configure(HIGHLIGHTS);
        Box::leak(Box::new(config))
    });
    configs.borrow_mut().get(lang).map(|v| *v)
}

fn main() {
    if let [_, lang, code_path] = args().collect::<Vec<String>>().as_slice() {
        let code = String::from_utf8(
            read(code_path).expect("`code_path` should contain a path to a file"),
        )
        .expect("`code_path` should contain a path to a valid UTF-8 file");
        // decode code as it may be html encoded
        let code = html_escape::decode_html_entities(&code);
        let mut highlighter = Highlighter::new();
        let configs = RefCell::new(HashMap::new());

        let config =
            get_config(lang, &configs).expect("A valid language should have been passed in");

        let events = highlighter
            .highlight(&config, code.as_bytes(), None, |v| {
                let lang = String::from(v).leak();
                get_config(lang, &configs)
            })
            .unwrap();

        let mut renderer = HtmlRenderer::new();
        renderer
            .render(events, code.as_bytes(), &|highlight, output| {
                output.extend(b"class=\"");
                let mut parts = HIGHLIGHTS[highlight.0].split('.').peekable();
                while let Some(part) = parts.next() {
                    output.extend(part.as_bytes());
                    if parts.peek().is_some() {
                        output.extend(b" ");
                    }
                }
                output.extend(b"\"");
            })
            .unwrap();
        print!(
            "{}",
            String::from_utf8(renderer.html).expect("`renderer.html` should contain valid UTF-8")
        )
    } else {
        panic!(
            "Need <lang> <code_path> as arguments, got {:?}",
            args().collect::<Vec<String>>()
        )
    }
}