Skip to main content

tree_sitter_loader/
loader.rs

1#![cfg_attr(not(any(test, doctest)), doc = include_str!("../README.md"))]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4#[cfg(unix)]
5use std::fmt::Write as _;
6#[cfg(any(feature = "tree-sitter-highlight", feature = "tree-sitter-tags"))]
7use std::ops::Range;
8#[cfg(feature = "tree-sitter-highlight")]
9use std::sync::Mutex;
10use std::{
11    collections::HashMap,
12    env, fs,
13    hash::{Hash as _, Hasher as _},
14    io::{BufRead, BufReader},
15    marker::PhantomData,
16    mem,
17    path::{Path, PathBuf},
18    process::Command,
19    sync::LazyLock,
20    time::{SystemTime, SystemTimeError},
21};
22
23use etcetera::BaseStrategy as _;
24use fs4::fs_std::FileExt;
25use libloading::{Library, Symbol};
26use log::{error, info, warn};
27use once_cell::sync::OnceCell;
28use regex::{Regex, RegexBuilder};
29use semver::Version;
30use serde::{Deserialize, Deserializer, Serialize};
31use thiserror::Error;
32use tree_sitter::Language;
33#[cfg(any(feature = "tree-sitter-highlight", feature = "tree-sitter-tags"))]
34use tree_sitter::QueryError;
35#[cfg(feature = "tree-sitter-highlight")]
36use tree_sitter::QueryErrorKind;
37#[cfg(feature = "wasm")]
38use tree_sitter::WasmError;
39#[cfg(feature = "tree-sitter-highlight")]
40use tree_sitter_highlight::HighlightConfiguration;
41#[cfg(feature = "tree-sitter-tags")]
42use tree_sitter_tags::{Error as TagsError, TagsConfiguration};
43
44static GRAMMAR_NAME_REGEX: LazyLock<Regex> =
45    LazyLock::new(|| Regex::new(r#""name":\s*"(.*?)""#).unwrap());
46
47const WASI_SDK_VERSION: &str = include_str!("../wasi-sdk-version").trim_ascii();
48
49pub type LoaderResult<T> = Result<T, LoaderError>;
50
51#[derive(Debug, Error)]
52pub enum LoaderError {
53    #[error(transparent)]
54    Compiler(CompilerError),
55    #[error("Parser compilation failed.\nStdout: {0}\nStderr: {1}")]
56    Compilation(String, String),
57    #[error("Failed to execute curl for {0} -- {1}")]
58    Curl(String, std::io::Error),
59    #[error("Failed to load language in current directory:\n{0}")]
60    CurrentDirectoryLoad(Box<Self>),
61    #[error("External file path {0} is outside of parser directory {1}")]
62    ExternalFile(String, String),
63    #[error("Failed to extract archive {0} to {1}")]
64    Extraction(String, String),
65    #[error("Failed to load language for file name {0}:\n{1}")]
66    FileNameLoad(String, Box<Self>),
67    #[error("Failed to parse the language name from grammar.json at {0}")]
68    GrammarJSON(String),
69    #[error(transparent)]
70    HomeDir(#[from] etcetera::HomeDirError),
71    #[error(transparent)]
72    IO(IoError),
73    #[error(transparent)]
74    Library(LibraryError),
75    #[error("Failed to compare binary and source timestamps:\n{0}")]
76    ModifiedTime(Box<Self>),
77    #[error("No language found")]
78    NoLanguage,
79    #[error(transparent)]
80    Query(LoaderQueryError),
81    #[error("Failed to load language for scope '{0}':\n{1}")]
82    ScopeLoad(String, Box<Self>),
83    #[error(transparent)]
84    Serialization(#[from] serde_json::Error),
85    #[error(transparent)]
86    Symbol(SymbolError),
87    #[error(transparent)]
88    Tags(#[from] TagsError),
89    #[error("Failed to execute tar for {0} -- {1}")]
90    Tar(String, std::io::Error),
91    #[error(transparent)]
92    Time(#[from] SystemTimeError),
93    #[error("Unknown scope '{0}'")]
94    UnknownScope(String),
95    #[error("Failed to download wasi-sdk from {0}")]
96    WasiSDKDownload(String),
97    #[error(transparent)]
98    WasiSDKClang(#[from] WasiSDKClangError),
99    #[error("Unsupported platform for wasi-sdk")]
100    WasiSDKPlatform,
101    #[cfg(feature = "wasm")]
102    #[error(transparent)]
103    Wasm(#[from] WasmError),
104    #[error("Failed to run wasi-sdk clang -- {0}")]
105    WasmCompiler(std::io::Error),
106    #[error("wasi-sdk clang command failed: {0}")]
107    WasmCompilation(String),
108}
109
110#[derive(Debug, Error)]
111pub struct CompilerError {
112    pub error: std::io::Error,
113    pub command: Box<Command>,
114}
115
116impl std::fmt::Display for CompilerError {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        write!(
119            f,
120            "Failed to execute the C compiler with the following command:\n{:?}\nError: {}",
121            *self.command, self.error
122        )?;
123        Ok(())
124    }
125}
126
127#[derive(Debug, Error)]
128pub struct IoError {
129    pub error: std::io::Error,
130    pub path: Option<String>,
131}
132
133impl IoError {
134    fn new(error: std::io::Error, path: Option<&Path>) -> Self {
135        Self {
136            error,
137            path: path.map(|p| p.to_string_lossy().to_string()),
138        }
139    }
140}
141
142impl std::fmt::Display for IoError {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        write!(f, "{}", self.error)?;
145        if let Some(ref path) = self.path {
146            write!(f, " ({path})")?;
147        }
148        Ok(())
149    }
150}
151
152#[derive(Debug, Error)]
153pub struct LibraryError {
154    pub error: libloading::Error,
155    pub path: String,
156}
157
158impl std::fmt::Display for LibraryError {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        write!(
161            f,
162            "Error opening dynamic library {} -- {}",
163            self.path, self.error
164        )?;
165        Ok(())
166    }
167}
168
169#[derive(Debug, Error)]
170pub struct LoaderQueryError {
171    pub error: QueryError,
172    pub file: Option<String>,
173}
174
175impl std::fmt::Display for LoaderQueryError {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        if let Some(ref path) = self.file {
178            writeln!(f, "Error in query file {path}:")?;
179        }
180        write!(f, "{}", self.error)?;
181        Ok(())
182    }
183}
184
185#[derive(Debug, Error)]
186pub struct SymbolError {
187    pub error: libloading::Error,
188    pub symbol_name: String,
189    pub path: String,
190}
191
192impl std::fmt::Display for SymbolError {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        write!(
195            f,
196            "Failed to load symbol {} from {} -- {}",
197            self.symbol_name, self.path, self.error
198        )?;
199        Ok(())
200    }
201}
202
203#[derive(Debug, Error)]
204pub struct WasiSDKClangError {
205    pub wasi_sdk_dir: String,
206    pub possible_executables: Vec<&'static str>,
207    pub download: bool,
208}
209
210impl std::fmt::Display for WasiSDKClangError {
211    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        if self.download {
213            write!(
214                f,
215                "Failed to find clang executable in downloaded wasi-sdk at '{}'.",
216                self.wasi_sdk_dir
217            )?;
218        } else {
219            write!(f, "TREE_SITTER_WASI_SDK_PATH is set to '{}', but no clang executable found in 'bin/' directory.", self.wasi_sdk_dir)?;
220        }
221
222        let possible_exes = self.possible_executables.join(", ");
223        write!(f, " Looked for: {possible_exes}.")?;
224
225        Ok(())
226    }
227}
228
229pub const DEFAULT_HIGHLIGHTS_QUERY_FILE_NAME: &str = "highlights.scm";
230
231pub const DEFAULT_INJECTIONS_QUERY_FILE_NAME: &str = "injections.scm";
232
233pub const DEFAULT_LOCALS_QUERY_FILE_NAME: &str = "locals.scm";
234
235pub const DEFAULT_TAGS_QUERY_FILE_NAME: &str = "tags.scm";
236
237#[derive(Default, Deserialize, Serialize)]
238pub struct Config {
239    #[serde(default)]
240    #[serde(
241        rename = "parser-directories",
242        deserialize_with = "deserialize_parser_directories"
243    )]
244    pub parser_directories: Vec<PathBuf>,
245}
246
247#[derive(Serialize, Deserialize, Clone, Default)]
248#[serde(untagged)]
249pub enum PathsJSON {
250    #[default]
251    Empty,
252    Single(PathBuf),
253    Multiple(Vec<PathBuf>),
254}
255
256impl PathsJSON {
257    fn into_vec(self) -> Option<Vec<PathBuf>> {
258        match self {
259            Self::Empty => None,
260            Self::Single(s) => Some(vec![s]),
261            Self::Multiple(s) => Some(s),
262        }
263    }
264
265    const fn is_empty(&self) -> bool {
266        matches!(self, Self::Empty)
267    }
268
269    /// Represent this set of paths as a string that can be included in templates
270    #[must_use]
271    pub fn to_variable_value<'a>(&'a self, default: &'a PathBuf) -> &'a str {
272        match self {
273            Self::Empty => Some(default),
274            Self::Single(path_buf) => Some(path_buf),
275            Self::Multiple(paths) => paths.first(),
276        }
277        .map_or("", |path| path.as_os_str().to_str().unwrap_or(""))
278    }
279}
280
281#[derive(Serialize, Deserialize, Clone)]
282#[serde(untagged)]
283pub enum PackageJSONAuthor {
284    String(String),
285    Object {
286        name: String,
287        email: Option<String>,
288        url: Option<String>,
289    },
290}
291
292#[derive(Serialize, Deserialize, Clone)]
293#[serde(untagged)]
294pub enum PackageJSONRepository {
295    String(String),
296    Object { url: String },
297}
298
299#[derive(Serialize, Deserialize)]
300pub struct PackageJSON {
301    pub name: String,
302    pub version: Version,
303    pub description: Option<String>,
304    pub author: Option<PackageJSONAuthor>,
305    pub maintainers: Option<Vec<PackageJSONAuthor>>,
306    pub license: Option<String>,
307    pub repository: Option<PackageJSONRepository>,
308    #[serde(default)]
309    #[serde(rename = "tree-sitter", skip_serializing_if = "Option::is_none")]
310    pub tree_sitter: Option<Vec<LanguageConfigurationJSON>>,
311}
312
313fn default_path() -> PathBuf {
314    PathBuf::from(".")
315}
316
317#[derive(Serialize, Deserialize, Clone)]
318#[serde(rename_all = "kebab-case")]
319pub struct LanguageConfigurationJSON {
320    #[serde(default = "default_path")]
321    pub path: PathBuf,
322    pub scope: Option<String>,
323    pub file_types: Option<Vec<String>>,
324    pub content_regex: Option<String>,
325    pub first_line_regex: Option<String>,
326    pub injection_regex: Option<String>,
327    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
328    pub highlights: PathsJSON,
329    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
330    pub injections: PathsJSON,
331    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
332    pub locals: PathsJSON,
333    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
334    pub tags: PathsJSON,
335    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
336    pub external_files: PathsJSON,
337}
338
339#[derive(Serialize, Deserialize)]
340#[serde(rename_all = "kebab-case")]
341pub struct TreeSitterJSON {
342    #[serde(rename = "$schema")]
343    pub schema: Option<String>,
344    pub grammars: Vec<Grammar>,
345    pub metadata: Metadata,
346    #[serde(default)]
347    pub bindings: Bindings,
348}
349
350impl TreeSitterJSON {
351    pub fn from_file(path: &Path) -> LoaderResult<Self> {
352        let path = path.join("tree-sitter.json");
353        Ok(serde_json::from_str(&fs::read_to_string(&path).map_err(
354            |e| LoaderError::IO(IoError::new(e, Some(path.as_path()))),
355        )?)?)
356    }
357
358    #[must_use]
359    pub fn has_multiple_language_configs(&self) -> bool {
360        self.grammars.len() > 1
361    }
362}
363
364#[derive(Serialize, Deserialize)]
365#[serde(rename_all = "kebab-case")]
366pub struct Grammar {
367    pub name: String,
368    #[serde(skip_serializing_if = "Option::is_none")]
369    pub camelcase: Option<String>,
370    #[serde(skip_serializing_if = "Option::is_none")]
371    pub title: Option<String>,
372    pub scope: String,
373    #[serde(skip_serializing_if = "Option::is_none")]
374    pub path: Option<PathBuf>,
375    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
376    pub external_files: PathsJSON,
377    pub file_types: Option<Vec<String>>,
378    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
379    pub highlights: PathsJSON,
380    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
381    pub injections: PathsJSON,
382    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
383    pub locals: PathsJSON,
384    #[serde(default, skip_serializing_if = "PathsJSON::is_empty")]
385    pub tags: PathsJSON,
386    #[serde(skip_serializing_if = "Option::is_none")]
387    pub injection_regex: Option<String>,
388    #[serde(skip_serializing_if = "Option::is_none")]
389    pub first_line_regex: Option<String>,
390    #[serde(skip_serializing_if = "Option::is_none")]
391    pub content_regex: Option<String>,
392    #[serde(skip_serializing_if = "Option::is_none")]
393    pub class_name: Option<String>,
394}
395
396#[derive(Serialize, Deserialize)]
397pub struct Metadata {
398    pub version: Version,
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub license: Option<String>,
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub description: Option<String>,
403    #[serde(skip_serializing_if = "Option::is_none")]
404    pub authors: Option<Vec<Author>>,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub links: Option<Links>,
407    #[serde(skip)]
408    pub namespace: Option<String>,
409}
410
411#[derive(Serialize, Deserialize)]
412pub struct Author {
413    pub name: String,
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub email: Option<String>,
416    #[serde(skip_serializing_if = "Option::is_none")]
417    pub url: Option<String>,
418}
419
420#[derive(Serialize, Deserialize)]
421pub struct Links {
422    pub repository: String,
423    #[serde(skip_serializing_if = "Option::is_none")]
424    pub funding: Option<String>,
425}
426
427#[derive(Serialize, Deserialize, Clone)]
428#[serde(default)]
429pub struct Bindings {
430    pub c: bool,
431    pub go: bool,
432    pub java: bool,
433    #[serde(skip)]
434    pub kotlin: bool,
435    pub node: bool,
436    pub python: bool,
437    pub rust: bool,
438    pub swift: bool,
439    pub zig: bool,
440}
441
442impl Bindings {
443    /// return available languages and its default enabled state.
444    #[must_use]
445    pub const fn languages(&self) -> [(&'static str, bool); 8] {
446        [
447            ("c", true),
448            ("go", true),
449            ("java", false),
450            // Comment out Kotlin until the bindings are actually available.
451            // ("kotlin", false),
452            ("node", true),
453            ("python", true),
454            ("rust", true),
455            ("swift", true),
456            ("zig", false),
457        ]
458    }
459
460    /// construct Bindings from a language list. If a language isn't supported, its name will be put on the error part.
461    pub fn with_enabled_languages<'a, I>(languages: I) -> Result<Self, &'a str>
462    where
463        I: Iterator<Item = &'a str>,
464    {
465        let mut out = Self {
466            c: false,
467            go: false,
468            java: false,
469            kotlin: false,
470            node: false,
471            python: false,
472            rust: false,
473            swift: false,
474            zig: false,
475        };
476
477        for v in languages {
478            match v {
479                "c" => out.c = true,
480                "go" => out.go = true,
481                "java" => out.java = true,
482                // Comment out Kotlin until the bindings are actually available.
483                // "kotlin" => out.kotlin = true,
484                "node" => out.node = true,
485                "python" => out.python = true,
486                "rust" => out.rust = true,
487                "swift" => out.swift = true,
488                "zig" => out.zig = true,
489                unsupported => return Err(unsupported),
490            }
491        }
492
493        Ok(out)
494    }
495}
496
497impl Default for Bindings {
498    fn default() -> Self {
499        Self {
500            c: true,
501            go: true,
502            java: false,
503            kotlin: false,
504            node: true,
505            python: true,
506            rust: true,
507            swift: true,
508            zig: false,
509        }
510    }
511}
512
513// Replace `~` or `$HOME` with home path string.
514// (While paths like "~/.tree-sitter/config.json" can be deserialized,
515// they're not valid path for I/O modules.)
516fn deserialize_parser_directories<'de, D>(deserializer: D) -> Result<Vec<PathBuf>, D::Error>
517where
518    D: Deserializer<'de>,
519{
520    let paths = Vec::<PathBuf>::deserialize(deserializer)?;
521    let Ok(home) = etcetera::home_dir() else {
522        return Ok(paths);
523    };
524    let standardized = paths
525        .into_iter()
526        .map(|path| standardize_path(path, &home))
527        .collect();
528    Ok(standardized)
529}
530
531fn standardize_path(path: PathBuf, home: &Path) -> PathBuf {
532    if let Ok(p) = path.strip_prefix("~") {
533        return home.join(p);
534    }
535    if let Ok(p) = path.strip_prefix("$HOME") {
536        return home.join(p);
537    }
538    path
539}
540
541impl Config {
542    #[must_use]
543    pub fn initial() -> Self {
544        let home_dir = etcetera::home_dir().expect("Cannot determine home directory");
545        Self {
546            parser_directories: vec![
547                home_dir.join("github"),
548                home_dir.join("src"),
549                home_dir.join("source"),
550                home_dir.join("projects"),
551                home_dir.join("dev"),
552                home_dir.join("git"),
553            ],
554        }
555    }
556}
557
558const BUILD_TARGET: &str = env!("BUILD_TARGET");
559
560pub struct LanguageConfiguration<'a> {
561    pub scope: Option<String>,
562    pub content_regex: Option<Regex>,
563    pub first_line_regex: Option<Regex>,
564    pub injection_regex: Option<Regex>,
565    pub file_types: Vec<String>,
566    pub root_path: PathBuf,
567    pub highlights_filenames: Option<Vec<PathBuf>>,
568    pub injections_filenames: Option<Vec<PathBuf>>,
569    pub locals_filenames: Option<Vec<PathBuf>>,
570    pub tags_filenames: Option<Vec<PathBuf>>,
571    pub language_name: String,
572    language_id: usize,
573    #[cfg(feature = "tree-sitter-highlight")]
574    highlight_config: OnceCell<Option<HighlightConfiguration>>,
575    #[cfg(feature = "tree-sitter-tags")]
576    tags_config: OnceCell<Option<TagsConfiguration>>,
577    #[cfg(feature = "tree-sitter-highlight")]
578    highlight_names: &'a Mutex<Vec<String>>,
579    #[cfg(feature = "tree-sitter-highlight")]
580    use_all_highlight_names: bool,
581    _phantom: PhantomData<&'a ()>,
582}
583
584pub struct Loader {
585    pub parser_lib_path: PathBuf,
586    languages_by_id: Vec<(PathBuf, OnceCell<Language>, Option<Vec<PathBuf>>)>,
587    language_configurations: Vec<LanguageConfiguration<'static>>,
588    language_configuration_ids_by_file_type: HashMap<String, Vec<usize>>,
589    language_configuration_in_current_path: Option<usize>,
590    language_configuration_ids_by_first_line_regex: HashMap<String, Vec<usize>>,
591    #[cfg(feature = "tree-sitter-highlight")]
592    highlight_names: Box<Mutex<Vec<String>>>,
593    #[cfg(feature = "tree-sitter-highlight")]
594    use_all_highlight_names: bool,
595    debug_build: bool,
596    sanitize_build: bool,
597    force_rebuild: bool,
598
599    #[cfg(feature = "wasm")]
600    wasm_store: Mutex<Option<tree_sitter::WasmStore>>,
601}
602
603pub struct CompileConfig<'a> {
604    pub src_path: &'a Path,
605    pub header_paths: Vec<&'a Path>,
606    pub parser_path: PathBuf,
607    pub scanner_path: Option<PathBuf>,
608    pub external_files: Option<&'a [PathBuf]>,
609    pub output_path: Option<PathBuf>,
610    pub flags: &'a [&'a str],
611    pub sanitize: bool,
612    pub name: String,
613}
614
615impl<'a> CompileConfig<'a> {
616    #[must_use]
617    pub fn new(
618        src_path: &'a Path,
619        externals: Option<&'a [PathBuf]>,
620        output_path: Option<PathBuf>,
621    ) -> Self {
622        Self {
623            src_path,
624            header_paths: vec![src_path],
625            parser_path: src_path.join("parser.c"),
626            scanner_path: None,
627            external_files: externals,
628            output_path,
629            flags: &[],
630            sanitize: false,
631            name: String::new(),
632        }
633    }
634}
635
636impl Loader {
637    pub fn new() -> LoaderResult<Self> {
638        let parser_lib_path = if let Ok(path) = env::var("TREE_SITTER_LIBDIR") {
639            PathBuf::from(path)
640        } else {
641            if cfg!(target_os = "macos") {
642                let legacy_apple_path = etcetera::base_strategy::Apple::new()?
643                    .cache_dir() // `$HOME/Library/Caches/`
644                    .join("tree-sitter");
645                if legacy_apple_path.exists() && legacy_apple_path.is_dir() {
646                    std::fs::remove_dir_all(&legacy_apple_path).map_err(|e| {
647                        LoaderError::IO(IoError::new(e, Some(legacy_apple_path.as_path())))
648                    })?;
649                }
650            }
651
652            etcetera::choose_base_strategy()?
653                .cache_dir()
654                .join("tree-sitter")
655                .join("lib")
656        };
657        Ok(Self::with_parser_lib_path(parser_lib_path))
658    }
659
660    #[must_use]
661    pub fn with_parser_lib_path(parser_lib_path: PathBuf) -> Self {
662        Self {
663            parser_lib_path,
664            languages_by_id: Vec::new(),
665            language_configurations: Vec::new(),
666            language_configuration_ids_by_file_type: HashMap::new(),
667            language_configuration_in_current_path: None,
668            language_configuration_ids_by_first_line_regex: HashMap::new(),
669            #[cfg(feature = "tree-sitter-highlight")]
670            highlight_names: Box::new(Mutex::new(Vec::new())),
671            #[cfg(feature = "tree-sitter-highlight")]
672            use_all_highlight_names: true,
673            debug_build: false,
674            sanitize_build: false,
675            force_rebuild: false,
676
677            #[cfg(feature = "wasm")]
678            wasm_store: Mutex::default(),
679        }
680    }
681
682    #[cfg(feature = "tree-sitter-highlight")]
683    #[cfg_attr(docsrs, doc(cfg(feature = "tree-sitter-highlight")))]
684    pub fn configure_highlights(&mut self, names: &[String]) {
685        self.use_all_highlight_names = false;
686        let mut highlights = self.highlight_names.lock().unwrap();
687        highlights.clear();
688        highlights.extend(names.iter().cloned());
689    }
690
691    #[must_use]
692    #[cfg(feature = "tree-sitter-highlight")]
693    #[cfg_attr(docsrs, doc(cfg(feature = "tree-sitter-highlight")))]
694    pub fn highlight_names(&self) -> Vec<String> {
695        self.highlight_names.lock().unwrap().clone()
696    }
697
698    pub fn find_all_languages(&mut self, config: &Config) -> LoaderResult<()> {
699        if config.parser_directories.is_empty() {
700            warn!(concat!(
701                "You have not configured any parser directories!\n",
702                "Please run `tree-sitter init-config` and edit the resulting\n",
703                "configuration file to indicate where we should look for\n",
704                "language grammars.\n"
705            ));
706        }
707        for parser_container_dir in &config.parser_directories {
708            if let Ok(entries) = fs::read_dir(parser_container_dir) {
709                for entry in entries {
710                    let entry = entry.map_err(|e| LoaderError::IO(IoError::new(e, None)))?;
711                    if let Some(parser_dir_name) = entry.file_name().to_str() {
712                        if parser_dir_name.starts_with("tree-sitter-") {
713                            self.find_language_configurations_at_path(
714                                &parser_container_dir.join(parser_dir_name),
715                                false,
716                            )
717                            .ok();
718                        }
719                    }
720                }
721            }
722        }
723        Ok(())
724    }
725
726    pub fn languages_at_path(&mut self, path: &Path) -> LoaderResult<Vec<(Language, String)>> {
727        if let Ok(configurations) = self.find_language_configurations_at_path(path, true) {
728            let mut language_ids = configurations
729                .iter()
730                .map(|c| (c.language_id, c.language_name.clone()))
731                .collect::<Vec<_>>();
732            language_ids.sort_unstable();
733            language_ids.dedup();
734            language_ids
735                .into_iter()
736                .map(|(id, name)| Ok((self.language_for_id(id)?, name)))
737                .collect::<LoaderResult<Vec<_>>>()
738        } else {
739            Ok(Vec::new())
740        }
741    }
742
743    #[must_use]
744    pub fn get_all_language_configurations(&self) -> Vec<(&LanguageConfiguration, &Path)> {
745        self.language_configurations
746            .iter()
747            .map(|c| (c, self.languages_by_id[c.language_id].0.as_ref()))
748            .collect()
749    }
750
751    pub fn language_configuration_for_scope(
752        &self,
753        scope: &str,
754    ) -> LoaderResult<Option<(Language, &LanguageConfiguration)>> {
755        for configuration in &self.language_configurations {
756            if configuration.scope.as_ref().is_some_and(|s| s == scope) {
757                let language = self.language_for_id(configuration.language_id)?;
758                return Ok(Some((language, configuration)));
759            }
760        }
761        Ok(None)
762    }
763
764    pub fn language_configuration_for_first_line_regex(
765        &self,
766        path: &Path,
767    ) -> LoaderResult<Option<(Language, &LanguageConfiguration)>> {
768        self.language_configuration_ids_by_first_line_regex
769            .iter()
770            .try_fold(None, |_, (regex, ids)| {
771                if let Some(regex) = Self::regex(Some(regex)) {
772                    let file = fs::File::open(path)
773                        .map_err(|e| LoaderError::IO(IoError::new(e, Some(path))))?;
774                    let reader = BufReader::new(file);
775                    let first_line = reader
776                        .lines()
777                        .next()
778                        .transpose()
779                        .map_err(|e| LoaderError::IO(IoError::new(e, Some(path))))?;
780                    if let Some(first_line) = first_line {
781                        if regex.is_match(&first_line) && !ids.is_empty() {
782                            let configuration = &self.language_configurations[ids[0]];
783                            let language = self.language_for_id(configuration.language_id)?;
784                            return Ok(Some((language, configuration)));
785                        }
786                    }
787                }
788
789                Ok(None)
790            })
791    }
792
793    pub fn language_configuration_for_file_name(
794        &self,
795        path: &Path,
796    ) -> LoaderResult<Option<(Language, &LanguageConfiguration)>> {
797        // Find all the language configurations that match this file name
798        // or a suffix of the file name.
799        let configuration_ids = path
800            .file_name()
801            .and_then(|n| n.to_str())
802            .and_then(|file_name| self.language_configuration_ids_by_file_type.get(file_name))
803            .or_else(|| {
804                let mut path = path.to_owned();
805                let mut extensions = Vec::with_capacity(2);
806                while let Some(extension) = path.extension() {
807                    extensions.push(extension.to_str()?.to_string());
808                    path = PathBuf::from(path.file_stem()?.to_os_string());
809                }
810                extensions.reverse();
811                // Try longest extension suffixs first (e.g. "foo.bar.baz"->"bar.baz"->"baz"),
812                // stopping at the first match.
813                (0..extensions.len())
814                    .map(|i| extensions[i..].join("."))
815                    .find_map(|key| self.language_configuration_ids_by_file_type.get(&key))
816            });
817
818        if let Some(configuration_ids) = configuration_ids {
819            if !configuration_ids.is_empty() {
820                let configuration = if configuration_ids.len() == 1 {
821                    &self.language_configurations[configuration_ids[0]]
822                }
823                // If multiple language configurations match, then determine which
824                // one to use by applying the configurations' content regexes.
825                else {
826                    let file_contents =
827                        fs::read(path).map_err(|e| LoaderError::IO(IoError::new(e, Some(path))))?;
828                    let file_contents = String::from_utf8_lossy(&file_contents);
829                    let mut best_score = -2isize;
830                    let mut best_configuration_id = None;
831                    for configuration_id in configuration_ids {
832                        let config = &self.language_configurations[*configuration_id];
833
834                        // If the language configuration has a content regex, assign
835                        // a score based on the length of the first match.
836                        let score;
837                        if let Some(content_regex) = &config.content_regex {
838                            if let Some(mat) = content_regex.find(&file_contents) {
839                                score = (mat.end() - mat.start()) as isize;
840                            }
841                            // If the content regex does not match, then *penalize* this
842                            // language configuration, so that language configurations
843                            // without content regexes are preferred over those with
844                            // non-matching content regexes.
845                            else {
846                                score = -1;
847                            }
848                        } else {
849                            score = 0;
850                        }
851                        if score > best_score {
852                            best_configuration_id = Some(*configuration_id);
853                            best_score = score;
854                        }
855                    }
856
857                    &self.language_configurations[best_configuration_id.unwrap()]
858                };
859
860                let language = self.language_for_id(configuration.language_id)?;
861                return Ok(Some((language, configuration)));
862            }
863        }
864
865        Ok(None)
866    }
867
868    pub fn language_configuration_for_injection_string(
869        &self,
870        string: &str,
871    ) -> LoaderResult<Option<(Language, &LanguageConfiguration)>> {
872        let mut best_match_length = 0;
873        let mut best_match_position = None;
874        for (i, configuration) in self.language_configurations.iter().enumerate() {
875            if let Some(injection_regex) = &configuration.injection_regex {
876                if let Some(mat) = injection_regex.find(string) {
877                    let length = mat.end() - mat.start();
878                    if length > best_match_length {
879                        best_match_position = Some(i);
880                        best_match_length = length;
881                    }
882                }
883            }
884        }
885
886        if let Some(i) = best_match_position {
887            let configuration = &self.language_configurations[i];
888            let language = self.language_for_id(configuration.language_id)?;
889            Ok(Some((language, configuration)))
890        } else {
891            Ok(None)
892        }
893    }
894
895    pub fn language_for_configuration(
896        &self,
897        configuration: &LanguageConfiguration,
898    ) -> LoaderResult<Language> {
899        self.language_for_id(configuration.language_id)
900    }
901
902    fn language_for_id(&self, id: usize) -> LoaderResult<Language> {
903        let (path, language, externals) = &self.languages_by_id[id];
904        language
905            .get_or_try_init(|| {
906                let src_path = path.join("src");
907                self.load_language_at_path(CompileConfig::new(
908                    &src_path,
909                    externals.as_deref(),
910                    None,
911                ))
912            })
913            .cloned()
914    }
915
916    pub fn compile_parser_at_path(
917        &self,
918        grammar_path: &Path,
919        output_path: PathBuf,
920        flags: &[&str],
921    ) -> LoaderResult<()> {
922        let src_path = grammar_path.join("src");
923        let mut config = CompileConfig::new(&src_path, None, Some(output_path));
924        config.flags = flags;
925        self.load_language_at_path(config).map(|_| ())
926    }
927
928    pub fn load_language_at_path(&self, mut config: CompileConfig) -> LoaderResult<Language> {
929        let grammar_path = config.src_path.join("grammar.json");
930        config.name = Self::grammar_json_name(&grammar_path)?;
931        self.load_language_at_path_with_name(config)
932    }
933
934    pub fn load_language_at_path_with_name(
935        &self,
936        mut config: CompileConfig,
937    ) -> LoaderResult<Language> {
938        let mut lib_name = config.name.clone();
939        let language_fn_name = format!("tree_sitter_{}", config.name.replace('-', "_"));
940        if self.debug_build {
941            lib_name.push_str(".debug._");
942        }
943
944        if self.sanitize_build {
945            lib_name.push_str(".sanitize._");
946            config.sanitize = true;
947        }
948
949        if config.output_path.is_none() {
950            fs::create_dir_all(&self.parser_lib_path).map_err(|e| {
951                LoaderError::IO(IoError::new(e, Some(self.parser_lib_path.as_path())))
952            })?;
953        }
954
955        let mut recompile = self.force_rebuild || config.output_path.is_some(); // if specified, always recompile
956
957        let output_path = config.output_path.unwrap_or_else(|| {
958            let mut path = self.parser_lib_path.join(lib_name);
959            path.set_extension(env::consts::DLL_EXTENSION);
960            #[cfg(feature = "wasm")]
961            if self.wasm_store.lock().unwrap().is_some() {
962                path.set_extension("wasm");
963            }
964            path
965        });
966        config.output_path = Some(output_path.clone());
967
968        let parser_path = config.src_path.join("parser.c");
969        config.scanner_path = self.get_scanner_path(config.src_path);
970
971        let mut paths_to_check = vec![parser_path];
972
973        if let Some(scanner_path) = config.scanner_path.as_ref() {
974            paths_to_check.push(scanner_path.clone());
975        }
976
977        paths_to_check.extend(
978            config
979                .external_files
980                .unwrap_or_default()
981                .iter()
982                .map(|p| config.src_path.join(p)),
983        );
984
985        if !recompile {
986            recompile = needs_recompile(&output_path, &paths_to_check)?;
987        }
988
989        #[cfg(feature = "wasm")]
990        if let Some(wasm_store) = self.wasm_store.lock().unwrap().as_mut() {
991            if recompile {
992                self.compile_parser_to_wasm(
993                    &config.name,
994                    config.src_path,
995                    config
996                        .scanner_path
997                        .as_ref()
998                        .and_then(|p| p.strip_prefix(config.src_path).ok()),
999                    &output_path,
1000                )?;
1001            }
1002
1003            let wasm_bytes = fs::read(&output_path)
1004                .map_err(|e| LoaderError::IO(IoError::new(e, Some(output_path.as_path()))))?;
1005            return Ok(wasm_store.load_language(&config.name, &wasm_bytes)?);
1006        }
1007
1008        // Create a unique lock path based on the output path hash to prevent
1009        // interference when multiple processes build the same grammar (by name)
1010        // to different output locations
1011        let lock_hash = {
1012            let mut hasher = std::hash::DefaultHasher::new();
1013            output_path.hash(&mut hasher);
1014            format!("{:x}", hasher.finish())
1015        };
1016
1017        let lock_path = if env::var("CROSS_RUNNER").is_ok() {
1018            tempfile::tempdir()
1019                .expect("create a temp dir")
1020                .path()
1021                .to_path_buf()
1022        } else {
1023            etcetera::choose_base_strategy()?.cache_dir()
1024        }
1025        .join("tree-sitter")
1026        .join("lock")
1027        .join(format!("{}-{lock_hash}.lock", config.name));
1028
1029        if let Ok(lock_file) = fs::OpenOptions::new().write(true).open(&lock_path) {
1030            recompile = false;
1031            if lock_file.try_lock_exclusive().is_err() {
1032                // if we can't acquire the lock, another process is compiling the parser, wait for
1033                // it and don't recompile
1034                lock_file
1035                    .lock_exclusive()
1036                    .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path.as_path()))))?;
1037                recompile = false;
1038            } else {
1039                // if we can acquire the lock, check if the lock file is older than 30 seconds, a
1040                // run that was interrupted and left the lock file behind should not block
1041                // subsequent runs
1042                let time = lock_file
1043                    .metadata()
1044                    .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path.as_path()))))?
1045                    .modified()
1046                    .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path.as_path()))))?
1047                    .elapsed()?
1048                    .as_secs();
1049                if time > 30 {
1050                    fs::remove_file(&lock_path)
1051                        .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path.as_path()))))?;
1052                    recompile = true;
1053                }
1054            }
1055        }
1056
1057        if recompile {
1058            let parent_path = lock_path.parent().unwrap();
1059            fs::create_dir_all(parent_path)
1060                .map_err(|e| LoaderError::IO(IoError::new(e, Some(parent_path))))?;
1061            let lock_file = fs::OpenOptions::new()
1062                .create(true)
1063                .truncate(true)
1064                .write(true)
1065                .open(&lock_path)
1066                .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path.as_path()))))?;
1067            lock_file
1068                .lock_exclusive()
1069                .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path.as_path()))))?;
1070
1071            self.compile_parser_to_dylib(&config, &lock_file, &lock_path)?;
1072
1073            if config.scanner_path.is_some() {
1074                self.check_external_scanner(&output_path)?;
1075            }
1076        }
1077
1078        // Ensure the dynamic library exists before trying to load it. This can
1079        // happen in race conditions where we couldn't acquire the lock because
1080        // another process was compiling but it still hasn't finished by the
1081        // time we reach this point, so the output file still doesn't exist.
1082        //
1083        // Instead of allowing the `load_language` call below to fail, return a
1084        // clearer error to the user here.
1085        if !output_path.exists() {
1086            let msg = format!(
1087                "Dynamic library `{}` not found after build attempt. \
1088                Are you running multiple processes building to the same output location?",
1089                output_path.display()
1090            );
1091
1092            Err(LoaderError::IO(IoError::new(
1093                std::io::Error::new(std::io::ErrorKind::NotFound, msg),
1094                Some(output_path.as_path()),
1095            )))?;
1096        }
1097
1098        Self::load_language(&output_path, &language_fn_name)
1099    }
1100
1101    pub fn load_language(path: &Path, function_name: &str) -> LoaderResult<Language> {
1102        let library = unsafe { Library::new(path) }.map_err(|e| {
1103            LoaderError::Library(LibraryError {
1104                error: e,
1105                path: path.to_string_lossy().to_string(),
1106            })
1107        })?;
1108        let language = unsafe {
1109            let language_fn = library
1110                .get::<Symbol<unsafe extern "C" fn() -> Language>>(function_name.as_bytes())
1111                .map_err(|e| {
1112                    LoaderError::Symbol(SymbolError {
1113                        error: e,
1114                        symbol_name: function_name.to_string(),
1115                        path: path.to_string_lossy().to_string(),
1116                    })
1117                })?;
1118            language_fn()
1119        };
1120        mem::forget(library);
1121        Ok(language)
1122    }
1123
1124    fn compile_parser_to_dylib(
1125        &self,
1126        config: &CompileConfig,
1127        lock_file: &fs::File,
1128        lock_path: &Path,
1129    ) -> LoaderResult<()> {
1130        let mut cc_config = cc::Build::new();
1131        cc_config
1132            .cargo_metadata(false)
1133            .cargo_warnings(false)
1134            .target(BUILD_TARGET)
1135            // BUILD_TARGET from the build environment becomes a runtime host for cc.
1136            // Otherwise, when cross compiled, cc will keep looking for a cross-compiler
1137            // on the target system instead of the native compiler.
1138            .host(BUILD_TARGET)
1139            .debug(self.debug_build)
1140            .file(&config.parser_path)
1141            .includes(&config.header_paths)
1142            .std("c11");
1143
1144        if let Some(scanner_path) = config.scanner_path.as_ref() {
1145            cc_config.file(scanner_path);
1146        }
1147
1148        if self.debug_build {
1149            cc_config.opt_level(0).extra_warnings(true);
1150        } else {
1151            cc_config.opt_level(2).extra_warnings(false);
1152        }
1153
1154        for flag in config.flags {
1155            cc_config.define(flag, None);
1156        }
1157
1158        let compiler = cc_config.get_compiler();
1159        let mut command = Command::new(compiler.path());
1160        command.args(compiler.args());
1161        for (key, value) in compiler.env() {
1162            command.env(key, value);
1163        }
1164
1165        let output_path = config.output_path.as_ref().unwrap();
1166
1167        let temp_dir = if compiler.is_like_msvc() {
1168            let out = format!("-out:{}", output_path.to_str().unwrap());
1169            command.arg(if self.debug_build { "-LDd" } else { "-LD" });
1170            command.arg("-utf-8");
1171
1172            // Windows creates intermediate files when compiling (.exp, .lib, .obj), which causes
1173            // issues when multiple processes are compiling in the same directory. This creates a
1174            // temporary directory for those files to go into, which is deleted after compilation.
1175            let temp_dir = output_path.parent().unwrap().join(format!(
1176                "tmp_{}_{:?}",
1177                std::process::id(),
1178                std::thread::current().id()
1179            ));
1180            std::fs::create_dir_all(&temp_dir).unwrap();
1181
1182            command.arg(format!("/Fo{}\\", temp_dir.display()));
1183            command.args(cc_config.get_files());
1184            command.arg("-link").arg(out);
1185            command.arg(format!("/IMPLIB:{}.lib", temp_dir.join("temp").display()));
1186
1187            Some(temp_dir)
1188        } else {
1189            command.arg("-Werror=implicit-function-declaration");
1190            if cfg!(any(target_os = "macos", target_os = "ios")) {
1191                command.arg("-dynamiclib");
1192                // TODO: remove when supported
1193                command.arg("-UTREE_SITTER_REUSE_ALLOCATOR");
1194            } else {
1195                command.arg("-shared");
1196                command.arg("-Wl,--no-undefined");
1197                #[cfg(target_os = "openbsd")]
1198                command.arg("-lc");
1199            }
1200            command.args(cc_config.get_files());
1201            command.arg("-o").arg(output_path);
1202
1203            None
1204        };
1205
1206        let output = command.output().map_err(|e| {
1207            LoaderError::Compiler(CompilerError {
1208                error: e,
1209                command: Box::new(command),
1210            })
1211        })?;
1212
1213        if let Some(temp_dir) = temp_dir {
1214            let _ = fs::remove_dir_all(temp_dir);
1215        }
1216
1217        FileExt::unlock(lock_file)
1218            .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path))))?;
1219        fs::remove_file(lock_path)
1220            .map_err(|e| LoaderError::IO(IoError::new(e, Some(lock_path))))?;
1221
1222        if output.status.success() {
1223            Ok(())
1224        } else {
1225            Err(LoaderError::Compilation(
1226                String::from_utf8_lossy(&output.stdout).to_string(),
1227                String::from_utf8_lossy(&output.stderr).to_string(),
1228            ))
1229        }
1230    }
1231
1232    #[cfg(unix)]
1233    fn check_external_scanner(&self, library_path: &Path) -> LoaderResult<()> {
1234        let section = " T ";
1235        // Older ppc toolchains incorrectly report functions in the Data section. This bug has been
1236        // fixed, but we still need to account for older systems.
1237        let old_ppc_section = if cfg!(all(target_arch = "powerpc64", target_os = "linux")) {
1238            Some(" D ")
1239        } else {
1240            None
1241        };
1242        let nm_cmd = env::var("NM").unwrap_or_else(|_| "nm".to_owned());
1243        let command = Command::new(nm_cmd)
1244            .arg("--defined-only")
1245            .arg(library_path)
1246            .output();
1247        if let Ok(output) = command {
1248            if output.status.success() {
1249                let mut non_static_symbols = String::new();
1250                for line in String::from_utf8_lossy(&output.stdout).lines() {
1251                    if line.contains(section) || old_ppc_section.is_some_and(|s| line.contains(s)) {
1252                        if let Some(function_name) =
1253                            line.split_whitespace().collect::<Vec<_>>().get(2)
1254                        {
1255                            if !line.contains("tree_sitter_") {
1256                                writeln!(&mut non_static_symbols, "  `{function_name}`").unwrap();
1257                            }
1258                        }
1259                    }
1260                }
1261                if !non_static_symbols.is_empty() {
1262                    warn!(
1263                        "Found non-static non-tree-sitter functions in the external scanner\n{non_static_symbols}\n{}",
1264                        concat!(
1265                            "Consider making these functions static, they can cause conflicts ",
1266                            "when another tree-sitter project uses the same function name."
1267                        )
1268                    );
1269                }
1270            }
1271        } else {
1272            warn!(
1273                "Failed to run `nm` to verify symbols in {}",
1274                library_path.display()
1275            );
1276        }
1277
1278        Ok(())
1279    }
1280
1281    #[cfg(windows)]
1282    fn check_external_scanner(&self, _library_path: &Path) -> LoaderResult<()> {
1283        // TODO: there's no nm command on windows, whoever wants to implement this can and should :)
1284        Ok(())
1285    }
1286
1287    pub fn compile_parser_to_wasm(
1288        &self,
1289        language_name: &str,
1290        src_path: &Path,
1291        scanner_filename: Option<&Path>,
1292        output_path: &Path,
1293    ) -> LoaderResult<()> {
1294        let clang_executable = self.ensure_wasi_sdk_exists()?;
1295
1296        let mut command = Command::new(&clang_executable);
1297        command.current_dir(src_path).args([
1298            "--target=wasm32-unknown-wasi",
1299            "-o",
1300            output_path.to_str().unwrap(),
1301            "-fPIC",
1302            "-shared",
1303            if self.debug_build { "-g" } else { "-Os" },
1304            format!("-Wl,--export=tree_sitter_{language_name}").as_str(),
1305            "-Wl,--allow-undefined",
1306            "-Wl,--no-entry",
1307            "-nostdlib",
1308            "-fno-exceptions",
1309            "-fvisibility=hidden",
1310            "-I",
1311            ".",
1312            "parser.c",
1313        ]);
1314
1315        if let Some(scanner_filename) = scanner_filename {
1316            command.arg(scanner_filename);
1317        }
1318
1319        let output = command.output().map_err(LoaderError::WasmCompiler)?;
1320
1321        if !output.status.success() {
1322            return Err(LoaderError::WasmCompilation(
1323                String::from_utf8_lossy(&output.stderr).to_string(),
1324            ));
1325        }
1326
1327        Ok(())
1328    }
1329
1330    /// Extracts a tar.gz archive with `tar`, stripping the first path component.
1331    fn extract_tar_gz_with_strip(
1332        &self,
1333        archive_path: &Path,
1334        destination: &Path,
1335    ) -> LoaderResult<()> {
1336        let status = Command::new("tar")
1337            .arg("-xzf")
1338            .arg(archive_path)
1339            .arg("--strip-components=1")
1340            .arg("-C")
1341            .arg(destination)
1342            .status()
1343            .map_err(|e| LoaderError::Tar(archive_path.to_string_lossy().to_string(), e))?;
1344
1345        if !status.success() {
1346            return Err(LoaderError::Extraction(
1347                archive_path.to_string_lossy().to_string(),
1348                destination.to_string_lossy().to_string(),
1349            ));
1350        }
1351
1352        Ok(())
1353    }
1354
1355    /// This ensures that the wasi-sdk is available, downloading and extracting it if necessary,
1356    /// and returns the path to the `clang` executable.
1357    ///
1358    /// If `TREE_SITTER_WASI_SDK_PATH` is set, it will use that path to look for the clang executable.
1359    fn ensure_wasi_sdk_exists(&self) -> LoaderResult<PathBuf> {
1360        let possible_executables = if cfg!(windows) {
1361            vec![
1362                "clang.exe",
1363                "wasm32-unknown-wasi-clang.exe",
1364                "wasm32-wasi-clang.exe",
1365            ]
1366        } else {
1367            vec!["clang", "wasm32-unknown-wasi-clang", "wasm32-wasi-clang"]
1368        };
1369
1370        if let Ok(wasi_sdk_path) = std::env::var("TREE_SITTER_WASI_SDK_PATH") {
1371            let wasi_sdk_dir = PathBuf::from(wasi_sdk_path);
1372
1373            for exe in &possible_executables {
1374                let clang_exe = wasi_sdk_dir.join("bin").join(exe);
1375                if clang_exe.exists() {
1376                    return Ok(clang_exe);
1377                }
1378            }
1379
1380            return Err(LoaderError::WasiSDKClang(WasiSDKClangError {
1381                wasi_sdk_dir: wasi_sdk_dir.to_string_lossy().to_string(),
1382                possible_executables,
1383                download: false,
1384            }));
1385        }
1386
1387        let cache_dir = etcetera::choose_base_strategy()?
1388            .cache_dir()
1389            .join("tree-sitter");
1390        fs::create_dir_all(&cache_dir)
1391            .map_err(|e| LoaderError::IO(IoError::new(e, Some(cache_dir.as_path()))))?;
1392
1393        let wasi_sdk_dir = cache_dir.join("wasi-sdk");
1394
1395        for exe in &possible_executables {
1396            let clang_exe = wasi_sdk_dir.join("bin").join(exe);
1397            if clang_exe.exists() {
1398                return Ok(clang_exe);
1399            }
1400        }
1401
1402        fs::create_dir_all(&wasi_sdk_dir)
1403            .map_err(|e| LoaderError::IO(IoError::new(e, Some(wasi_sdk_dir.as_path()))))?;
1404
1405        let arch_os = if cfg!(target_os = "macos") {
1406            if cfg!(target_arch = "aarch64") {
1407                "arm64-macos"
1408            } else {
1409                "x86_64-macos"
1410            }
1411        } else if cfg!(target_os = "windows") {
1412            if cfg!(target_arch = "aarch64") {
1413                "arm64-windows"
1414            } else {
1415                "x86_64-windows"
1416            }
1417        } else if cfg!(target_os = "linux") {
1418            if cfg!(target_arch = "aarch64") {
1419                "arm64-linux"
1420            } else {
1421                "x86_64-linux"
1422            }
1423        } else {
1424            return Err(LoaderError::WasiSDKPlatform);
1425        };
1426
1427        let sdk_filename = format!("wasi-sdk-{WASI_SDK_VERSION}-{arch_os}.tar.gz");
1428        let wasi_sdk_major_version = WASI_SDK_VERSION
1429            .trim_end_matches(char::is_numeric) // trim minor version...
1430            .trim_end_matches('.'); // ...and '.' separator
1431        let sdk_url = format!(
1432            "https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-{wasi_sdk_major_version}/{sdk_filename}",
1433        );
1434
1435        info!("Downloading wasi-sdk from {sdk_url}...");
1436        let temp_tar_path = cache_dir.join(sdk_filename);
1437
1438        let status = Command::new("curl")
1439            .arg("-f")
1440            .arg("-L")
1441            .arg("-o")
1442            .arg(&temp_tar_path)
1443            .arg(&sdk_url)
1444            .status()
1445            .map_err(|e| LoaderError::Curl(sdk_url.clone(), e))?;
1446
1447        if !status.success() {
1448            return Err(LoaderError::WasiSDKDownload(sdk_url));
1449        }
1450
1451        info!("Extracting wasi-sdk to {}...", wasi_sdk_dir.display());
1452        self.extract_tar_gz_with_strip(&temp_tar_path, &wasi_sdk_dir)?;
1453
1454        fs::remove_file(temp_tar_path).ok();
1455        for exe in &possible_executables {
1456            let clang_exe = wasi_sdk_dir.join("bin").join(exe);
1457            if clang_exe.exists() {
1458                return Ok(clang_exe);
1459            }
1460        }
1461
1462        Err(LoaderError::WasiSDKClang(WasiSDKClangError {
1463            wasi_sdk_dir: wasi_sdk_dir.to_string_lossy().to_string(),
1464            possible_executables,
1465            download: true,
1466        }))
1467    }
1468
1469    #[must_use]
1470    #[cfg(feature = "tree-sitter-highlight")]
1471    pub fn highlight_config_for_injection_string<'a>(
1472        &'a self,
1473        string: &str,
1474    ) -> Option<&'a HighlightConfiguration> {
1475        match self.language_configuration_for_injection_string(string) {
1476            Err(e) => {
1477                error!("Failed to load language for injection string '{string}': {e}");
1478                None
1479            }
1480            Ok(None) => None,
1481            Ok(Some((language, configuration))) => {
1482                match configuration.highlight_config(language, None) {
1483                    Err(e) => {
1484                        error!(
1485                            "Failed to load higlight config for injection string '{string}': {e}"
1486                        );
1487                        None
1488                    }
1489                    Ok(None) => None,
1490                    Ok(Some(config)) => Some(config),
1491                }
1492            }
1493        }
1494    }
1495
1496    #[must_use]
1497    pub fn get_language_configuration_in_current_path(&self) -> Option<&LanguageConfiguration> {
1498        self.language_configuration_in_current_path
1499            .map(|i| &self.language_configurations[i])
1500    }
1501
1502    pub fn find_language_configurations_at_path(
1503        &mut self,
1504        parser_path: &Path,
1505        set_current_path_config: bool,
1506    ) -> LoaderResult<&[LanguageConfiguration]> {
1507        let initial_language_configuration_count = self.language_configurations.len();
1508
1509        match TreeSitterJSON::from_file(parser_path) {
1510            Ok(config) => {
1511                let language_count = self.languages_by_id.len();
1512                for grammar in config.grammars {
1513                    // Determine the path to the parser directory. This can be specified in
1514                    // the tree-sitter.json, but defaults to the directory containing the
1515                    // tree-sitter.json.
1516                    let language_path =
1517                        parser_path.join(grammar.path.unwrap_or(PathBuf::from(".")));
1518
1519                    // Determine if a previous language configuration in this package.json file
1520                    // already uses the same language.
1521                    let mut language_id = None;
1522                    for (id, (path, _, _)) in
1523                        self.languages_by_id.iter().enumerate().skip(language_count)
1524                    {
1525                        if language_path == *path {
1526                            language_id = Some(id);
1527                        }
1528                    }
1529
1530                    // If not, add a new language path to the list.
1531                    let language_id = if let Some(language_id) = language_id {
1532                        language_id
1533                    } else {
1534                        self.languages_by_id.push((
1535                            language_path,
1536                            OnceCell::new(),
1537                            grammar
1538                                .external_files
1539                                .clone()
1540                                .into_vec()
1541                                .map(|files| {
1542                                    files
1543                                        .into_iter()
1544                                        .map(|path| {
1545                                            let path = parser_path.join(path);
1546                                            // prevent p being above/outside of parser_path
1547                                            if path.starts_with(parser_path) {
1548                                                Ok(path)
1549                                            } else {
1550                                                Err(LoaderError::ExternalFile(
1551                                                    path.to_string_lossy().to_string(),
1552                                                    parser_path.to_string_lossy().to_string(),
1553                                                ))
1554                                            }
1555                                        })
1556                                        .collect::<LoaderResult<Vec<_>>>()
1557                                })
1558                                .transpose()?,
1559                        ));
1560                        self.languages_by_id.len() - 1
1561                    };
1562
1563                    let configuration = LanguageConfiguration {
1564                        root_path: parser_path.to_path_buf(),
1565                        language_name: grammar.name,
1566                        scope: Some(grammar.scope),
1567                        language_id,
1568                        file_types: grammar.file_types.unwrap_or_default(),
1569                        content_regex: Self::regex(grammar.content_regex.as_deref()),
1570                        first_line_regex: Self::regex(grammar.first_line_regex.as_deref()),
1571                        injection_regex: Self::regex(grammar.injection_regex.as_deref()),
1572                        injections_filenames: grammar.injections.into_vec(),
1573                        locals_filenames: grammar.locals.into_vec(),
1574                        tags_filenames: grammar.tags.into_vec(),
1575                        highlights_filenames: grammar.highlights.into_vec(),
1576                        #[cfg(feature = "tree-sitter-highlight")]
1577                        highlight_config: OnceCell::new(),
1578                        #[cfg(feature = "tree-sitter-tags")]
1579                        tags_config: OnceCell::new(),
1580                        #[cfg(feature = "tree-sitter-highlight")]
1581                        highlight_names: &self.highlight_names,
1582                        #[cfg(feature = "tree-sitter-highlight")]
1583                        use_all_highlight_names: self.use_all_highlight_names,
1584                        _phantom: PhantomData,
1585                    };
1586
1587                    for file_type in &configuration.file_types {
1588                        self.language_configuration_ids_by_file_type
1589                            .entry(file_type.clone())
1590                            .or_default()
1591                            .push(self.language_configurations.len());
1592                    }
1593                    if let Some(first_line_regex) = &configuration.first_line_regex {
1594                        self.language_configuration_ids_by_first_line_regex
1595                            .entry(first_line_regex.to_string())
1596                            .or_default()
1597                            .push(self.language_configurations.len());
1598                    }
1599
1600                    self.language_configurations.push(unsafe {
1601                        mem::transmute::<LanguageConfiguration<'_>, LanguageConfiguration<'static>>(
1602                            configuration,
1603                        )
1604                    });
1605
1606                    if set_current_path_config
1607                        && self.language_configuration_in_current_path.is_none()
1608                    {
1609                        self.language_configuration_in_current_path =
1610                            Some(self.language_configurations.len() - 1);
1611                    }
1612                }
1613            }
1614            Err(LoaderError::Serialization(e)) => {
1615                warn!(
1616                    "Failed to parse {} -- {e}",
1617                    parser_path.join("tree-sitter.json").display()
1618                );
1619            }
1620            _ => {}
1621        }
1622
1623        // If we didn't find any language configurations in the tree-sitter.json file,
1624        // but there is a grammar.json file, then use the grammar file to form a simple
1625        // language configuration.
1626        if self.language_configurations.len() == initial_language_configuration_count
1627            && parser_path.join("src").join("grammar.json").exists()
1628        {
1629            let grammar_path = parser_path.join("src").join("grammar.json");
1630            let language_name = Self::grammar_json_name(&grammar_path)?;
1631            let configuration = LanguageConfiguration {
1632                root_path: parser_path.to_owned(),
1633                language_name,
1634                language_id: self.languages_by_id.len(),
1635                file_types: Vec::new(),
1636                scope: None,
1637                content_regex: None,
1638                first_line_regex: None,
1639                injection_regex: None,
1640                injections_filenames: None,
1641                locals_filenames: None,
1642                highlights_filenames: None,
1643                tags_filenames: None,
1644                #[cfg(feature = "tree-sitter-highlight")]
1645                highlight_config: OnceCell::new(),
1646                #[cfg(feature = "tree-sitter-tags")]
1647                tags_config: OnceCell::new(),
1648                #[cfg(feature = "tree-sitter-highlight")]
1649                highlight_names: &self.highlight_names,
1650                #[cfg(feature = "tree-sitter-highlight")]
1651                use_all_highlight_names: self.use_all_highlight_names,
1652                _phantom: PhantomData,
1653            };
1654            self.language_configurations.push(unsafe {
1655                mem::transmute::<LanguageConfiguration<'_>, LanguageConfiguration<'static>>(
1656                    configuration,
1657                )
1658            });
1659            self.languages_by_id
1660                .push((parser_path.to_owned(), OnceCell::new(), None));
1661        }
1662
1663        Ok(&self.language_configurations[initial_language_configuration_count..])
1664    }
1665
1666    fn regex(pattern: Option<&str>) -> Option<Regex> {
1667        pattern.and_then(|r| RegexBuilder::new(r).multi_line(true).build().ok())
1668    }
1669
1670    fn grammar_json_name(grammar_path: &Path) -> LoaderResult<String> {
1671        let file = fs::File::open(grammar_path)
1672            .map_err(|e| LoaderError::IO(IoError::new(e, Some(grammar_path))))?;
1673
1674        let first_three_lines = BufReader::new(file)
1675            .lines()
1676            .take(3)
1677            .collect::<Result<Vec<_>, std::io::Error>>()
1678            .map_err(|_| LoaderError::GrammarJSON(grammar_path.to_string_lossy().to_string()))?
1679            .join("\n");
1680
1681        let name = GRAMMAR_NAME_REGEX
1682            .captures(&first_three_lines)
1683            .and_then(|c| c.get(1))
1684            .ok_or_else(|| LoaderError::GrammarJSON(grammar_path.to_string_lossy().to_string()))?;
1685
1686        Ok(name.as_str().to_string())
1687    }
1688
1689    pub fn select_language(
1690        &mut self,
1691        path: Option<&Path>,
1692        current_dir: &Path,
1693        scope: Option<&str>,
1694        // path to dynamic library, name of language
1695        lib_info: Option<&(PathBuf, &str)>,
1696    ) -> LoaderResult<Language> {
1697        if let Some((ref lib_path, language_name)) = lib_info {
1698            let language_fn_name = format!("tree_sitter_{}", language_name.replace('-', "_"));
1699            Self::load_language(lib_path, &language_fn_name)
1700        } else if let Some(scope) = scope {
1701            if let Some(config) = self
1702                .language_configuration_for_scope(scope)
1703                .map_err(|e| LoaderError::ScopeLoad(scope.to_string(), Box::new(e)))?
1704            {
1705                Ok(config.0)
1706            } else {
1707                Err(LoaderError::UnknownScope(scope.to_string()))
1708            }
1709        } else if let Some((lang, _)) = if let Some(path) = path {
1710            self.language_configuration_for_file_name(path)
1711                .map_err(|e| {
1712                    LoaderError::FileNameLoad(
1713                        path.file_name().unwrap().to_string_lossy().to_string(),
1714                        Box::new(e),
1715                    )
1716                })?
1717        } else {
1718            None
1719        } {
1720            Ok(lang)
1721        } else if let Some(id) = self.language_configuration_in_current_path {
1722            Ok(self.language_for_id(self.language_configurations[id].language_id)?)
1723        } else if let Some(lang) = self
1724            .languages_at_path(current_dir)
1725            .map_err(|e| LoaderError::CurrentDirectoryLoad(Box::new(e)))?
1726            .first()
1727            .cloned()
1728        {
1729            Ok(lang.0)
1730        } else if let Some(lang) = if let Some(path) = path {
1731            self.language_configuration_for_first_line_regex(path)?
1732        } else {
1733            None
1734        } {
1735            Ok(lang.0)
1736        } else {
1737            Err(LoaderError::NoLanguage)
1738        }
1739    }
1740
1741    pub const fn debug_build(&mut self, flag: bool) {
1742        self.debug_build = flag;
1743    }
1744
1745    pub const fn sanitize_build(&mut self, flag: bool) {
1746        self.sanitize_build = flag;
1747    }
1748
1749    pub const fn force_rebuild(&mut self, rebuild: bool) {
1750        self.force_rebuild = rebuild;
1751    }
1752
1753    #[cfg(feature = "wasm")]
1754    #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))]
1755    pub fn use_wasm(&mut self, engine: &tree_sitter::wasmtime::Engine) {
1756        *self.wasm_store.lock().unwrap() = Some(tree_sitter::WasmStore::new(engine).unwrap());
1757    }
1758
1759    #[must_use]
1760    pub fn get_scanner_path(&self, src_path: &Path) -> Option<PathBuf> {
1761        let path = src_path.join("scanner.c");
1762        path.exists().then_some(path)
1763    }
1764}
1765
1766impl LanguageConfiguration<'_> {
1767    #[cfg(feature = "tree-sitter-highlight")]
1768    pub fn highlight_config(
1769        &self,
1770        language: Language,
1771        paths: Option<&[PathBuf]>,
1772    ) -> LoaderResult<Option<&HighlightConfiguration>> {
1773        let (highlights_filenames, injections_filenames, locals_filenames) = match paths {
1774            Some(paths) => (
1775                Some(
1776                    paths
1777                        .iter()
1778                        .filter(|p| p.ends_with(DEFAULT_HIGHLIGHTS_QUERY_FILE_NAME))
1779                        .cloned()
1780                        .collect::<Vec<_>>(),
1781                ),
1782                Some(
1783                    paths
1784                        .iter()
1785                        .filter(|p| p.ends_with(DEFAULT_TAGS_QUERY_FILE_NAME))
1786                        .cloned()
1787                        .collect::<Vec<_>>(),
1788                ),
1789                Some(
1790                    paths
1791                        .iter()
1792                        .filter(|p| p.ends_with(DEFAULT_LOCALS_QUERY_FILE_NAME))
1793                        .cloned()
1794                        .collect::<Vec<_>>(),
1795                ),
1796            ),
1797            None => (None, None, None),
1798        };
1799        self.highlight_config
1800            .get_or_try_init(|| {
1801                let (highlights_query, highlight_ranges) = self.read_queries(
1802                    if highlights_filenames.is_some() {
1803                        highlights_filenames.as_deref()
1804                    } else {
1805                        self.highlights_filenames.as_deref()
1806                    },
1807                    DEFAULT_HIGHLIGHTS_QUERY_FILE_NAME,
1808                )?;
1809                let (injections_query, injection_ranges) = self.read_queries(
1810                    if injections_filenames.is_some() {
1811                        injections_filenames.as_deref()
1812                    } else {
1813                        self.injections_filenames.as_deref()
1814                    },
1815                    DEFAULT_INJECTIONS_QUERY_FILE_NAME,
1816                )?;
1817                let (locals_query, locals_ranges) = self.read_queries(
1818                    if locals_filenames.is_some() {
1819                        locals_filenames.as_deref()
1820                    } else {
1821                        self.locals_filenames.as_deref()
1822                    },
1823                    DEFAULT_LOCALS_QUERY_FILE_NAME,
1824                )?;
1825
1826                if highlights_query.is_empty() {
1827                    Ok(None)
1828                } else {
1829                    let mut result = HighlightConfiguration::new(
1830                        language,
1831                        &self.language_name,
1832                        &highlights_query,
1833                        &injections_query,
1834                        &locals_query,
1835                    )
1836                    .map_err(|error| match error.kind {
1837                        QueryErrorKind::Language => {
1838                            LoaderError::Query(LoaderQueryError { error, file: None })
1839                        }
1840                        _ => {
1841                            if error.offset < injections_query.len() {
1842                                Self::include_path_in_query_error(
1843                                    error,
1844                                    &injection_ranges,
1845                                    &injections_query,
1846                                    0,
1847                                )
1848                            } else if error.offset < injections_query.len() + locals_query.len() {
1849                                Self::include_path_in_query_error(
1850                                    error,
1851                                    &locals_ranges,
1852                                    &locals_query,
1853                                    injections_query.len(),
1854                                )
1855                            } else {
1856                                Self::include_path_in_query_error(
1857                                    error,
1858                                    &highlight_ranges,
1859                                    &highlights_query,
1860                                    injections_query.len() + locals_query.len(),
1861                                )
1862                            }
1863                        }
1864                    })?;
1865                    let mut all_highlight_names = self.highlight_names.lock().unwrap();
1866                    if self.use_all_highlight_names {
1867                        for capture_name in result.query.capture_names() {
1868                            if !all_highlight_names.iter().any(|x| x == capture_name) {
1869                                all_highlight_names.push((*capture_name).to_string());
1870                            }
1871                        }
1872                    }
1873                    result.configure(all_highlight_names.as_slice());
1874                    drop(all_highlight_names);
1875                    Ok(Some(result))
1876                }
1877            })
1878            .map(Option::as_ref)
1879    }
1880
1881    #[cfg(feature = "tree-sitter-tags")]
1882    pub fn tags_config(&self, language: Language) -> LoaderResult<Option<&TagsConfiguration>> {
1883        self.tags_config
1884            .get_or_try_init(|| {
1885                let (tags_query, tags_ranges) = self
1886                    .read_queries(self.tags_filenames.as_deref(), DEFAULT_TAGS_QUERY_FILE_NAME)?;
1887                let (locals_query, locals_ranges) = self.read_queries(
1888                    self.locals_filenames.as_deref(),
1889                    DEFAULT_LOCALS_QUERY_FILE_NAME,
1890                )?;
1891                if tags_query.is_empty() {
1892                    Ok(None)
1893                } else {
1894                    TagsConfiguration::new(language, &tags_query, &locals_query)
1895                        .map(Some)
1896                        .map_err(|error| {
1897                            if let TagsError::Query(error) = error {
1898                                if error.offset < locals_query.len() {
1899                                    Self::include_path_in_query_error(
1900                                        error,
1901                                        &locals_ranges,
1902                                        &locals_query,
1903                                        0,
1904                                    )
1905                                } else {
1906                                    Self::include_path_in_query_error(
1907                                        error,
1908                                        &tags_ranges,
1909                                        &tags_query,
1910                                        locals_query.len(),
1911                                    )
1912                                }
1913                            } else {
1914                                error.into()
1915                            }
1916                        })
1917                }
1918            })
1919            .map(Option::as_ref)
1920    }
1921
1922    #[cfg(any(feature = "tree-sitter-highlight", feature = "tree-sitter-tags"))]
1923    fn include_path_in_query_error(
1924        mut error: QueryError,
1925        ranges: &[(PathBuf, Range<usize>)],
1926        source: &str,
1927        start_offset: usize,
1928    ) -> LoaderError {
1929        let offset_within_section = error.offset - start_offset;
1930        let (path, range) = ranges
1931            .iter()
1932            .find(|(_, range)| range.contains(&offset_within_section))
1933            .unwrap_or_else(|| ranges.last().unwrap());
1934        error.offset = offset_within_section - range.start;
1935        error.row = source[range.start..offset_within_section]
1936            .matches('\n')
1937            .count();
1938        LoaderError::Query(LoaderQueryError {
1939            error,
1940            file: Some(path.to_string_lossy().to_string()),
1941        })
1942    }
1943
1944    #[allow(clippy::type_complexity)]
1945    #[cfg(any(feature = "tree-sitter-highlight", feature = "tree-sitter-tags"))]
1946    fn read_queries(
1947        &self,
1948        paths: Option<&[PathBuf]>,
1949        default_path: &str,
1950    ) -> LoaderResult<(String, Vec<(PathBuf, Range<usize>)>)> {
1951        let mut query = String::new();
1952        let mut path_ranges = Vec::new();
1953        if let Some(paths) = paths {
1954            for path in paths {
1955                let abs_path = self.root_path.join(path);
1956                let prev_query_len = query.len();
1957                query += &fs::read_to_string(&abs_path)
1958                    .map_err(|e| LoaderError::IO(IoError::new(e, Some(abs_path.as_path()))))?;
1959                path_ranges.push((path.clone(), prev_query_len..query.len()));
1960            }
1961        } else {
1962            // highlights.scm is needed to test highlights, and tags.scm to test tags
1963            if default_path == DEFAULT_HIGHLIGHTS_QUERY_FILE_NAME
1964                || default_path == DEFAULT_TAGS_QUERY_FILE_NAME
1965            {
1966                warn!(
1967                    concat!(
1968                        "You should add a `{}` entry pointing to the {} path in the `tree-sitter` ",
1969                        "object in the grammar's tree-sitter.json file. See more here: ",
1970                        "https://tree-sitter.github.io/tree-sitter/3-syntax-highlighting#query-paths"
1971                    ),
1972                    default_path.replace(".scm", ""),
1973                    default_path
1974                );
1975            }
1976            let queries_path = self.root_path.join("queries");
1977            let path = queries_path.join(default_path);
1978            if path.exists() {
1979                query = fs::read_to_string(&path)
1980                    .map_err(|e| LoaderError::IO(IoError::new(e, Some(path.as_path()))))?;
1981                path_ranges.push((PathBuf::from(default_path), 0..query.len()));
1982            }
1983        }
1984
1985        Ok((query, path_ranges))
1986    }
1987}
1988
1989fn needs_recompile(lib_path: &Path, paths_to_check: &[PathBuf]) -> LoaderResult<bool> {
1990    if !lib_path.exists() {
1991        return Ok(true);
1992    }
1993    let lib_mtime = mtime(lib_path).map_err(|e| LoaderError::ModifiedTime(Box::new(e)))?;
1994    for path in paths_to_check {
1995        if mtime(path).map_err(|e| LoaderError::ModifiedTime(Box::new(e)))? > lib_mtime {
1996            return Ok(true);
1997        }
1998    }
1999    Ok(false)
2000}
2001
2002fn mtime(path: &Path) -> LoaderResult<SystemTime> {
2003    fs::metadata(path)
2004        .map_err(|e| LoaderError::IO(IoError::new(e, Some(path))))?
2005        .modified()
2006        .map_err(|e| LoaderError::IO(IoError::new(e, Some(path))))
2007}