Skip to main content

badness_parser/semantic/
completion.rs

1//! Static word lists and metadata used only by completion and hover.
2
3use std::collections::HashMap;
4use std::sync::LazyLock;
5
6use serde::Deserialize;
7
8include!(concat!(env!("OUT_DIR"), "/expl3_names.rs"));
9
10/// Public expl3 names from the pinned CWL catalog, without argument signatures.
11pub fn expl3_names() -> &'static [&'static str] {
12    EXPL3_NAMES
13}
14
15/// Whether a built-in command spells a known symbol without consuming arguments.
16/// Callers must let document definitions and declarations override this fact.
17pub fn is_symbol_command(name: &str) -> bool {
18    super::signature::command_completion_kind(name)
19        == Some(super::signature::CommandCompletionKind::Symbol)
20}
21
22// The baked `.sty`/`.cls` name lists are generated from TeX Live's tlpdb. File
23// order is completion rank; comments and the primary/secondary separator are not
24// candidates.
25const PACKAGE_NAMES_TXT: &str = include_str!("../../data/package_names.txt");
26const CLASS_NAMES_TXT: &str = include_str!("../../data/class_names.txt");
27
28static PACKAGE_NAMES: LazyLock<Vec<&'static str>> =
29    LazyLock::new(|| parse_name_list(PACKAGE_NAMES_TXT));
30static CLASS_NAMES: LazyLock<Vec<&'static str>> =
31    LazyLock::new(|| parse_name_list(CLASS_NAMES_TXT));
32
33fn parse_name_list(text: &'static str) -> Vec<&'static str> {
34    text.lines()
35        .filter(|line| !line.is_empty() && !line.starts_with('#') && *line != "---")
36        .collect()
37}
38
39/// All known `.sty` package name stems, in completion-rank order.
40pub fn package_names() -> &'static [&'static str] {
41    &PACKAGE_NAMES
42}
43
44/// All known `.cls` class name stems, in completion-rank order.
45pub fn class_names() -> &'static [&'static str] {
46    &CLASS_NAMES
47}
48
49const COLORS_JSON: &str = include_str!("../../data/colors.json");
50const TIKZ_LIBRARIES_JSON: &str = include_str!("../../data/tikz_libraries.json");
51const ARG_ENUMS_JSON: &str = include_str!("../../data/arg_enums.json");
52
53#[derive(Deserialize)]
54struct ColorsData {
55    names: Vec<String>,
56    models: Vec<String>,
57}
58
59#[derive(Deserialize)]
60struct TikzLibrariesData {
61    tikz: Vec<String>,
62    pgf: Vec<String>,
63}
64
65static COLORS: LazyLock<ColorsData> = LazyLock::new(|| {
66    serde_json::from_str(COLORS_JSON).expect("bundled data/colors.json must be valid")
67});
68static TIKZ_LIBRARIES: LazyLock<TikzLibrariesData> = LazyLock::new(|| {
69    serde_json::from_str(TIKZ_LIBRARIES_JSON)
70        .expect("bundled data/tikz_libraries.json must be valid")
71});
72static ARG_ENUMS: LazyLock<HashMap<String, HashMap<usize, Vec<String>>>> = LazyLock::new(|| {
73    serde_json::from_str(ARG_ENUMS_JSON).expect("bundled data/arg_enums.json must be valid")
74});
75
76fn as_static_slice(names: &'static [String]) -> Vec<&'static str> {
77    names.iter().map(String::as_str).collect()
78}
79
80/// Built-in color names for color-argument completion.
81pub fn color_names() -> &'static [&'static str] {
82    static NAMES: LazyLock<Vec<&'static str>> = LazyLock::new(|| as_static_slice(&COLORS.names));
83    &NAMES
84}
85
86/// Built-in color models for `\definecolor` model completion.
87pub fn color_models() -> &'static [&'static str] {
88    static MODELS: LazyLock<Vec<&'static str>> = LazyLock::new(|| as_static_slice(&COLORS.models));
89    &MODELS
90}
91
92/// Built-in TikZ library names.
93pub fn tikz_libraries() -> &'static [&'static str] {
94    static LIBS: LazyLock<Vec<&'static str>> =
95        LazyLock::new(|| as_static_slice(&TIKZ_LIBRARIES.tikz));
96    &LIBS
97}
98
99/// Built-in PGF library names.
100pub fn pgf_libraries() -> &'static [&'static str] {
101    static LIBS: LazyLock<Vec<&'static str>> =
102        LazyLock::new(|| as_static_slice(&TIKZ_LIBRARIES.pgf));
103    &LIBS
104}
105
106/// Suggested values for a command's brace-group argument.
107pub fn arg_enum_values(name: &str, index: usize) -> Option<&'static [String]> {
108    ARG_ENUMS.get(name)?.get(&index).map(Vec::as_slice)
109}
110
111type PackageMetaMap = phf::Map<&'static str, PackageMeta>;
112
113/// Shipped CTAN metadata for one package or class stem.
114#[derive(Debug, Clone, Copy)]
115pub struct PackageMeta {
116    pub desc: Option<&'static str>,
117    pub ctan: Option<&'static str>,
118}
119
120impl PackageMeta {
121    /// The canonical CTAN package page, when a catalogue id is known.
122    pub fn ctan_url(&self) -> Option<String> {
123        self.ctan.map(|id| format!("https://ctan.org/pkg/{id}"))
124    }
125}
126
127const fn meta(desc: Option<&'static str>, ctan: Option<&'static str>) -> PackageMeta {
128    PackageMeta { desc, ctan }
129}
130
131include!(concat!(env!("OUT_DIR"), "/package_metadata.rs"));
132
133/// The shipped CTAN metadata for a package or class stem.
134pub fn package_metadata(name: &str) -> Option<&'static PackageMeta> {
135    PACKAGE_METADATA.get(name)
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn expl3_catalog_is_sorted_and_separate_from_signatures() {
144        let names = expl3_names();
145        assert_eq!(names.len(), 4708);
146        assert!(names.windows(2).all(|pair| pair[0] < pair[1]));
147        for name in ["tl_set:Nn", "seq_map_inline:Nn", "cs_new:Npn", "l_tmpa_tl"] {
148            assert!(names.binary_search(&name).is_ok());
149            assert!(crate::semantic::signature::cwl().command(name).is_none());
150            assert!(
151                crate::semantic::signature::builtin()
152                    .command(name)
153                    .is_none()
154            );
155        }
156        assert!(names.iter().all(|name| !name.contains("__")));
157    }
158
159    #[test]
160    fn arg_enums_load_and_resolve() {
161        assert_eq!(
162            arg_enum_values("pagenumbering", 0),
163            Some(
164                ["arabic", "roman", "Roman", "alph", "Alph"]
165                    .map(String::from)
166                    .as_slice()
167            )
168        );
169        assert!(arg_enum_values("pagestyle", 0).is_some());
170        assert!(arg_enum_values("pagestyle", 1).is_none());
171        assert!(arg_enum_values("definitelynotacommand", 0).is_none());
172    }
173
174    #[test]
175    fn package_metadata_resolves_stem_to_ctan_facts() {
176        let meta = package_metadata("amsmath").expect("amsmath in metadata DB");
177        assert_eq!(meta.desc, Some("AMS mathematical facilities for LaTeX"));
178        assert_eq!(
179            meta.ctan_url().as_deref(),
180            Some("https://ctan.org/pkg/latex-amsmath")
181        );
182        assert!(package_metadata("definitely-not-a-real-package").is_none());
183    }
184}