sphinx_inv 0.4.0

A rust library to parse Sphinx `objects.inv` files
Documentation
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use crate::{
    error::SphinxParseError,
    priority::SphinxPriority,
    roles::{SphinxType, role_domain},
};
use winnow::{
    ModalResult, Parser,
    ascii::till_line_ending,
    combinator::{alt, opt, preceded, repeat_till, trace},
    stream::AsChar,
    token::take_while,
};

// basically just a wrapper so the type system can keep track of whether it's minified or not for us
#[derive(Debug, PartialEq, Clone)]
enum ReferenceString {
    Minified(String),
    Expanded(String),
}

/// A reference to something (can be either internal or external)
/// has all the info to be serialized or deserialised from a sphinx
/// inventory file.
#[derive(Debug, Clone)]
pub struct SphinxReference {
    /// The public name of the object that user will need to use to
    /// refer to it.
    pub name: String,

    /// the type of the object consisting of a domain and a role.
    /// see [`SphinxType`] for more info
    pub sphinx_type: SphinxType,

    /// The priority of the object during search. Not used
    /// in this project but required by sphinx.
    pub priority: SphinxPriority,

    location: ReferenceString,
    display_name: ReferenceString,
}

impl PartialEq for SphinxReference {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.sphinx_type == other.sphinx_type
            && self.priority == other.priority
            && self.expanded_location() == other.expanded_location()
            && self.expanded_display_name() == other.expanded_display_name()
    }
}

impl SphinxReference {
    /// Create a new reference object
    pub fn new(
        name: &str,
        sphinx_type: SphinxType,
        priority: SphinxPriority,
        location: &str,
        display_name: &str,
    ) -> Self {
        let loc = if location.ends_with("#$") {
            ReferenceString::Minified(location.to_string())
        } else {
            ReferenceString::Expanded(location.to_string())
        };

        let disp_name = if display_name == "-" {
            ReferenceString::Minified(display_name.to_string())
        } else {
            ReferenceString::Expanded(display_name.to_string())
        };
        Self {
            name: name.to_string(),
            sphinx_type,
            priority,
            location: loc,
            display_name: disp_name,
        }
    }

    /// Get the expanded location. where `$` is replaced with the full name
    pub fn expanded_location(&self) -> String {
        match &self.location {
            ReferenceString::Expanded(s) => s.clone(),
            ReferenceString::Minified(s) => s.replace('$', &self.name),
        }
    }

    /// Get the expanded display name, where `-` is a shortcut that gets
    /// expanded to the full `name` field.
    pub fn expanded_display_name(&self) -> String {
        match &self.display_name {
            ReferenceString::Expanded(s) => s.clone(),
            ReferenceString::Minified(_) => self.name.clone(),
        }
    }

    /// A minified version of the location where the fragment of the
    /// url is truncated if it is equal to the `name field`
    pub fn minified_location(&self) -> String {
        match &self.location {
            ReferenceString::Minified(s) => s.clone(),
            ReferenceString::Expanded(s) => match s.split_once('#') {
                Some((prefix, _suffix)) => format!("{prefix}#$"),
                None => s.clone(),
            },
        }
    }

    /// A minified version of the location where the fragment of the
    /// display name is replaced by `-` if it is equal to the `name field`
    pub fn minified_display_name(&self) -> String {
        match &self.display_name {
            ReferenceString::Minified(s) => s.clone(),
            ReferenceString::Expanded(_s) => "-".to_string(),
        }
    }

    /// Get a formatted sphinx reference with all shortcuts in
    /// location and displayname fully expanded
    pub fn fmt_expanded(&self) -> String {
        format!(
            "{} {} {} {} {}",
            self.name,
            self.sphinx_type,
            self.priority,
            self.expanded_location(),
            self.expanded_display_name()
        )
    }

    /// Get a formatted sphinx reference with
    /// location and displayname fully minified
    /// see [`minified_display_name`] and [`minified_location`]
    /// for more info
    pub fn fmt_minified(&self) -> String {
        format!(
            "{} {} {} {} {}",
            self.name,
            self.sphinx_type,
            self.priority,
            self.minified_location(),
            self.minified_display_name()
        )
    }
}

pub(crate) fn word<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
    take_while(1.., |c| {
        (AsChar::is_alphanum(c) || c == '_') && !AsChar::is_newline(c)
    })
    .parse_next(input)
}

fn non_space<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
    take_while(1.., |c| !AsChar::is_space(c) && !AsChar::is_newline(c)).parse_next(input)
}

fn non_word<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
    take_while(1.., |c| {
        !(AsChar::is_alphanum(c) || c == '_' || AsChar::is_newline(c))
    })
    .parse_next(input)
}

fn priority(input: &mut &str) -> ModalResult<SphinxPriority> {
    preceded(" ", alt(("-1", "1", "0", "2")))
        .parse_to()
        .parse_next(input)
}

fn uri<'s>(input: &mut &'s str) -> ModalResult<Option<&'s str>> {
    trace("uri", preceded(" ", opt(non_space))).parse_next(input)
}

fn display_name<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
    trace("display_name", preceded(" ", till_line_ending)).parse_next(input)
}

fn name_domain_role(input: &mut &str) -> ModalResult<(String, SphinxType)> {
    // this is a bit nasty, but it's necessary to make sure we parse at least one word
    // the first word is not allowed to be the role and there are some cases where this one
    // contains a : which trips up the parser, so we take the first word a bit more liberally
    let (first_word, (mut prefix_vec, role)): (&str, (String, SphinxType)) = trace(
        "name_domain_role",
        (
            non_space,
            repeat_till(0.., alt((word, non_word)), role_domain),
        ),
    )
    .parse_next(input)?;
    // the last space was separating the title and the domain, so we pop that off
    let _ = prefix_vec.pop();
    Ok((format!("{first_word}{prefix_vec}"), role))
}

/// Parse a line consisting of a sphinx reference.
/// see [`SphinxReference`] for more info.
pub fn parse_reference(line: &str, line_num: usize) -> Result<SphinxReference, SphinxParseError> {
    let ((name, sphinx_type), prio, loc, dispname) =
        (name_domain_role, priority, uri, display_name)
            .parse(line)
            .map_err(|error| SphinxParseError::from_str_parse(&error, line_num))?;

    Ok(SphinxReference::new(
        &name,
        sphinx_type,
        prio,
        loc.unwrap_or_default(),
        dispname,
    ))
}

#[cfg(test)]
mod test {

    use crate::{
        CRole,
        error::SphinxParseError,
        roles::{PyRole, RstRole, StdRole},
    };

    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn test_hard_dummy_record() -> Result<(), SphinxParseError> {
        // TODO:
        // for the error reporting I had to disallow strings that conform to `(\w+):` but I'm
        // undecided on whether I want to keep this behaviour. Revisit this once I'm done adding
        // domains. it might also be useful to see some other nasty stuff from cmake or whatever
        let input = "asdfasdf :foo std ::endl :: _bar_baz : something- : hello std:label 1 library/stdtypes.html asdf";

        let sphinx_ref = parse_reference(input, 0)?;

        assert_eq!(
            sphinx_ref.name,
            "asdfasdf :foo std ::endl :: _bar_baz : something- : hello".to_string()
        );
        assert_eq!(sphinx_ref.sphinx_type, SphinxType::Std(StdRole::Label));
        assert_eq!(sphinx_ref.priority, SphinxPriority::Standard);
        assert_eq!(
            sphinx_ref.location,
            ReferenceString::Expanded("library/stdtypes.html".to_string())
        );
        assert_eq!(
            sphinx_ref.display_name,
            ReferenceString::Expanded("asdf".to_string())
        );

        Ok(())
    }

    #[test]
    fn test_index_line() -> Result<(), SphinxParseError> {
        let input = "index std:doc -1  Furo".to_string();

        let sphinx_ref = parse_reference(&input, 0)?;
        assert_eq!(sphinx_ref.name, "index".to_string());
        assert_eq!(sphinx_ref.sphinx_type, SphinxType::Std(StdRole::Doc));
        assert_eq!(sphinx_ref.priority, SphinxPriority::Omit);
        assert_eq!(
            sphinx_ref.location,
            ReferenceString::Expanded(String::new())
        );
        assert_eq!(
            sphinx_ref.display_name,
            ReferenceString::Expanded("Furo".to_string())
        );

        Ok(())
    }
    #[test]
    fn test_parse_example_record_with_rst_directive() -> Result<(), SphinxParseError> {
        let input = "str.join rst:directive:option 1 library/stdtypes.html#$ -".to_string();

        let sphinx_ref = parse_reference(&input, 0)?;
        assert_eq!(sphinx_ref.name, "str.join".to_string());
        assert_eq!(
            sphinx_ref.sphinx_type,
            SphinxType::ReStructuredText(RstRole::Option)
        );
        assert_eq!(sphinx_ref.priority, SphinxPriority::Standard);
        assert_eq!(
            sphinx_ref.location,
            ReferenceString::Minified("library/stdtypes.html#$".to_string())
        );
        assert_eq!(
            sphinx_ref.display_name,
            ReferenceString::Minified("-".to_string())
        );

        Ok(())
    }

    #[test]
    fn type_parse_unknown_domain_err() {
        let header = "str.join asdf:method 1 library/stdtypes.html#$ -".to_string();
        let result = parse_reference(&header, 0);
        assert_eq!(
            result,
            Err(SphinxParseError::from_str(
                "str.join asdf:method 1 library/stdtypes.html#$ -",
                "invalid missing domain:role\nexpected `std`, `py`, `c`, `rst`, `cpp`, `js`, `math`",
                48,
                0
            ))
        );
    }
    #[test]

    fn type_parse_py_role_err() {
        let header = "str.join py:asdf 1 library/stdtypes.html#$ -".to_string();
        let result = parse_reference(&header, 0);
        assert_eq!(
            result,
            Err(SphinxParseError::from_str(
                "str.join py:asdf 1 library/stdtypes.html#$ -",
                "invalid python role\nexpected `attribute`, `data`, `exception`, `function`, `method`, `module`, `property`, `class`",
                12,
                0
            ))
        );
    }

    #[test]
    fn test_parse_example_record_with_newline() {
        let input = "str.join\n py:method 1 library/stdtypes.html#$ -";

        let result = parse_reference(input, 0);
        assert!(result.is_err());
    }
    #[test]
    fn test_parse_example_record() -> Result<(), SphinxParseError> {
        let input = "str.join py:method 1 library/stdtypes.html#$ -".to_string();

        let sphinx_ref = parse_reference(&input, 0)?;
        assert_eq!(sphinx_ref.name, "str.join".to_string());
        assert_eq!(sphinx_ref.sphinx_type, SphinxType::Python(PyRole::Method));
        assert_eq!(sphinx_ref.priority, SphinxPriority::Standard);
        assert_eq!(
            sphinx_ref.location,
            ReferenceString::Minified("library/stdtypes.html#$".to_string())
        );
        assert_eq!(
            sphinx_ref.display_name,
            ReferenceString::Minified("-".to_string())
        );

        Ok(())
    }

    #[test]
    fn test_lkd_hard_line_with_rst_directive() -> Result<(), SphinxParseError> {
        let input = "accel/qaic/aic080:qualcomm cloud ai 80 (aic080) rst:directive:option -1 accel/qaic/aic080.html#qualcomm-cloud-ai-80-aic080 Qualcomm Cloud AI 80 (AIC080)".to_string();

        let sphinx_ref = parse_reference(&input, 0)?;
        assert_eq!(
            sphinx_ref.sphinx_type,
            SphinxType::ReStructuredText(RstRole::Option)
        );
        assert_eq!(sphinx_ref.priority, SphinxPriority::Omit);
        assert_eq!(
            sphinx_ref.location,
            ReferenceString::Expanded(
                "accel/qaic/aic080.html#qualcomm-cloud-ai-80-aic080".to_string()
            )
        );
        assert_eq!(
            sphinx_ref.display_name,
            ReferenceString::Expanded("Qualcomm Cloud AI 80 (AIC080)".to_string())
        );

        Ok(())
    }

    #[test]
    fn test_lkd_hard_line() -> Result<(), SphinxParseError> {
        let input = "accel/qaic/aic080:qualcomm cloud ai 80 (aic080) std:label -1 accel/qaic/aic080.html#qualcomm-cloud-ai-80-aic080 Qualcomm Cloud AI 80 (AIC080)".to_string();

        let sphinx_ref = parse_reference(&input, 0)?;
        assert_eq!(
            sphinx_ref.name,
            "accel/qaic/aic080:qualcomm cloud ai 80 (aic080)".to_string()
        );
        assert_eq!(sphinx_ref.sphinx_type, SphinxType::Std(StdRole::Label));
        assert_eq!(sphinx_ref.priority, SphinxPriority::Omit);
        assert_eq!(
            sphinx_ref.location,
            ReferenceString::Expanded(
                "accel/qaic/aic080.html#qualcomm-cloud-ai-80-aic080".to_string()
            )
        );
        assert_eq!(
            sphinx_ref.display_name,
            ReferenceString::Expanded("Qualcomm Cloud AI 80 (AIC080)".to_string())
        );

        Ok(())
    }

    #[test]
    fn new_reference() {
        assert_eq!(
            SphinxReference {
                name: "foo".to_string(),
                sphinx_type: SphinxType::C(CRole::Macro),
                priority: SphinxPriority::Standard,
                location: ReferenceString::Expanded("foo/bar".to_string()),
                display_name: ReferenceString::Minified("-".to_string())
            },
            SphinxReference::new(
                "foo",
                SphinxType::C(CRole::Macro),
                SphinxPriority::Standard,
                "foo/bar",
                "-"
            )
        );
    }
}