maya-mel 0.1.2

Single-entry Autodesk Maya MEL parsing and analysis library.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#![forbid(unsafe_code)]
//! Shared spans, tokens, and source mapping primitives.
//!
//! These types are useful when consuming diagnostics or mapping byte ranges
//! back to display text.

use std::ops::Range;
use std::sync::Arc;

pub use text_size::{TextRange, TextSize};

#[must_use]
pub const fn text_size(value: u32) -> TextSize {
    TextSize::new(value)
}

#[must_use]
pub const fn text_range(start: u32, end: u32) -> TextRange {
    TextRange::new(text_size(start), text_size(end))
}

#[must_use]
pub fn range_start(range: TextRange) -> u32 {
    range.start().into()
}

#[must_use]
pub fn range_end(range: TextRange) -> u32 {
    range.end().into()
}

#[must_use]
pub fn range_len(range: TextRange) -> u32 {
    range.len().into()
}

#[must_use]
pub fn text_slice(text: &str, range: TextRange) -> &str {
    &text[range_start(range) as usize..range_end(range) as usize]
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceMapEdit {
    source_start: u32,
    source_end: u32,
    display_start: u32,
    display_end: u32,
}

impl SourceMapEdit {
    #[must_use]
    pub const fn new(
        source_start: u32,
        source_end: u32,
        display_start: u32,
        display_end: u32,
    ) -> Self {
        Self {
            source_start,
            source_end,
            display_start,
            display_end,
        }
    }

    #[must_use]
    pub const fn source_start(self) -> u32 {
        self.source_start
    }

    #[must_use]
    pub const fn source_end(self) -> u32 {
        self.source_end
    }

    #[must_use]
    pub const fn display_start(self) -> u32 {
        self.display_start
    }

    #[must_use]
    pub const fn display_end(self) -> u32 {
        self.display_end
    }

    #[must_use]
    pub const fn delta_after(self) -> i64 {
        self.display_end as i64 - self.source_end as i64
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum SourceMapKind {
    Identity {
        len: usize,
    },
    Indexed {
        source_to_display: Arc<[u32]>,
    },
    Sparse {
        source_len: usize,
        display_len: usize,
        edits: Arc<[SourceMapEdit]>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceMap {
    kind: SourceMapKind,
}

impl SourceMap {
    #[must_use]
    pub fn identity(len: usize) -> Self {
        Self {
            kind: SourceMapKind::Identity { len },
        }
    }

    #[must_use]
    pub fn from_source_to_display(source_to_display: Vec<u32>) -> Self {
        Self::from_shared_source_to_display(source_to_display.into())
    }

    #[must_use]
    pub fn from_shared_source_to_display(source_to_display: Arc<[u32]>) -> Self {
        if source_to_display
            .iter()
            .enumerate()
            .all(|(offset, mapped)| *mapped == u32::try_from(offset).unwrap_or(u32::MAX))
        {
            return Self::identity(source_to_display.len().saturating_sub(1));
        }
        Self {
            kind: SourceMapKind::Indexed { source_to_display },
        }
    }

    #[must_use]
    pub fn from_sparse_edits(
        source_len: usize,
        display_len: usize,
        edits: Arc<[SourceMapEdit]>,
    ) -> Self {
        if source_len == display_len && edits.is_empty() {
            return Self::identity(source_len);
        }
        Self {
            kind: SourceMapKind::Sparse {
                source_len,
                display_len,
                edits,
            },
        }
    }

    #[must_use]
    pub fn display_offset(&self, offset: u32) -> usize {
        match &self.kind {
            SourceMapKind::Identity { len } => usize::try_from(offset).unwrap_or(*len).min(*len),
            SourceMapKind::Indexed { source_to_display } => source_to_display
                .get(offset as usize)
                .copied()
                .or_else(|| source_to_display.last().copied())
                .unwrap_or(offset)
                as usize,
            SourceMapKind::Sparse {
                source_len,
                display_len,
                edits,
            } => sparse_source_to_display(*source_len, *display_len, edits, offset),
        }
    }

    #[must_use]
    pub fn display_range(&self, range: TextRange) -> Range<usize> {
        self.display_offset(range_start(range))..self.display_offset(range_end(range))
    }

    #[must_use]
    pub fn source_offset_for_display(&self, display_offset: usize) -> u32 {
        match &self.kind {
            SourceMapKind::Identity { len } => {
                u32::try_from(display_offset.min(*len)).unwrap_or(u32::MAX)
            }
            SourceMapKind::Indexed { source_to_display } => {
                match source_to_display
                    .binary_search_by(|mapped| mapped.cmp(&(display_offset as u32)))
                {
                    Ok(mut index) => {
                        while index + 1 < source_to_display.len()
                            && source_to_display[index + 1] <= display_offset as u32
                        {
                            index += 1;
                        }
                        u32::try_from(index).unwrap_or(u32::MAX)
                    }
                    Err(0) => 0,
                    Err(index) => u32::try_from(index - 1).unwrap_or(u32::MAX),
                }
            }
            SourceMapKind::Sparse {
                source_len,
                display_len,
                edits,
            } => sparse_display_to_source(*source_len, *display_len, edits, display_offset),
        }
    }

    #[must_use]
    pub fn source_range_from_display_range(&self, range: Range<usize>) -> TextRange {
        text_range(
            self.source_offset_for_display(range.start),
            self.source_offset_for_display(range.end),
        )
    }
}

fn sparse_source_to_display(
    source_len: usize,
    display_len: usize,
    edits: &[SourceMapEdit],
    offset: u32,
) -> usize {
    let clamped = usize::try_from(offset)
        .unwrap_or(source_len)
        .min(source_len) as u32;
    let Some(index) = edits
        .partition_point(|edit| edit.source_start() <= clamped)
        .checked_sub(1)
    else {
        return clamped as usize;
    };
    let edit = edits[index];
    if clamped == edit.source_start() {
        return edit.display_start() as usize;
    }
    if clamped <= edit.source_end() {
        return edit.display_end() as usize;
    }
    let mapped = (clamped as i64 + edit.delta_after()).clamp(0, display_len as i64);
    mapped as usize
}

fn sparse_display_to_source(
    source_len: usize,
    display_len: usize,
    edits: &[SourceMapEdit],
    offset: usize,
) -> u32 {
    let clamped = offset.min(display_len) as u32;
    let Some(index) = edits
        .partition_point(|edit| edit.display_start() <= clamped)
        .checked_sub(1)
    else {
        return clamped;
    };
    let edit = edits[index];
    if clamped == edit.display_start() {
        return edit.source_start();
    }
    if clamped <= edit.display_end() {
        return edit.source_end();
    }
    let mapped = (clamped as i64 - edit.delta_after()).clamp(0, source_len as i64);
    mapped as u32
}

#[derive(Debug, Clone, Copy)]
pub struct SourceView<'a> {
    text: &'a str,
    source_map: &'a SourceMap,
}

impl<'a> SourceView<'a> {
    #[must_use]
    pub fn new(text: &'a str, source_map: &'a SourceMap) -> Self {
        Self { text, source_map }
    }

    #[must_use]
    pub fn text(self) -> &'a str {
        self.text
    }

    #[must_use]
    pub fn source_map(self) -> &'a SourceMap {
        self.source_map
    }

    #[must_use]
    pub fn display_range(self, range: TextRange) -> Range<usize> {
        self.source_map.display_range(range)
    }

    #[must_use]
    pub fn display_slice(self, range: TextRange) -> &'a str {
        &self.text[self.display_range(range)]
    }

    #[must_use]
    pub fn slice(self, range: TextRange) -> &'a str {
        self.display_slice(range)
    }

    #[must_use]
    pub fn source_range_from_display_range(self, range: Range<usize>) -> TextRange {
        self.source_map.source_range_from_display_range(range)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TokenKind {
    Whitespace,
    LineComment,
    BlockComment,
    Ident,
    IntLiteral,
    FloatLiteral,
    StringLiteral,
    Flag,
    Dollar,
    Backquote,
    LParen,
    RParen,
    LBracket,
    RBracket,
    LBrace,
    RBrace,
    Dot,
    Pipe,
    Comma,
    Semi,
    Assign,
    PlusEq,
    MinusEq,
    StarEq,
    SlashEq,
    Plus,
    PlusPlus,
    Minus,
    MinusMinus,
    Star,
    Slash,
    Percent,
    Caret,
    Question,
    Colon,
    EqEq,
    NotEq,
    LtLt,
    Lt,
    Le,
    GtGt,
    Gt,
    Ge,
    AndAnd,
    OrOr,
    Bang,
    Unknown,
    Eof,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Token {
    pub kind: TokenKind,
    pub range: TextRange,
}

impl Token {
    #[must_use]
    pub const fn new(kind: TokenKind, range: TextRange) -> Self {
        Self { kind, range }
    }
}

impl TokenKind {
    #[must_use]
    pub const fn is_trivia(self) -> bool {
        matches!(
            self,
            Self::Whitespace | Self::LineComment | Self::BlockComment
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LexDiagnostic {
    pub message: &'static str,
    pub range: TextRange,
}

impl LexDiagnostic {
    #[must_use]
    pub const fn new(message: &'static str, range: TextRange) -> Self {
        Self { message, range }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Lexed {
    pub tokens: Vec<Token>,
    pub diagnostics: Vec<LexDiagnostic>,
}

#[cfg(test)]
mod tests {
    use super::{LexDiagnostic, SourceMap, SourceMapEdit, Token, TokenKind, range_len, text_range};

    #[test]
    fn text_range_helpers_keep_offsets() {
        let range = text_range(10, 15);
        assert_eq!(range_len(range), 5);
        assert!(!range.is_empty());
    }

    #[test]
    fn token_constructor_keeps_fields() {
        let token = Token::new(TokenKind::Semi, text_range(1, 2));
        assert_eq!(token.kind, TokenKind::Semi);
        assert_eq!(token.range, text_range(1, 2));
    }

    #[test]
    fn lex_diagnostic_constructor_keeps_fields() {
        let diagnostic = LexDiagnostic::new("bad token", text_range(2, 4));
        assert_eq!(diagnostic.message, "bad token");
        assert_eq!(diagnostic.range, text_range(2, 4));
    }

    #[test]
    fn trivia_kinds_are_marked_as_trivia() {
        assert!(TokenKind::Whitespace.is_trivia());
        assert!(TokenKind::LineComment.is_trivia());
        assert!(TokenKind::BlockComment.is_trivia());
        assert!(!TokenKind::Ident.is_trivia());
    }

    #[test]
    fn source_map_can_map_display_offsets_back_to_source_offsets() {
        let map = SourceMap::from_source_to_display(vec![0, 3, 3, 4]);
        assert_eq!(map.source_offset_for_display(0), 0);
        assert_eq!(map.source_offset_for_display(3), 2);
        assert_eq!(map.source_offset_for_display(4), 3);
        assert_eq!(map.source_range_from_display_range(0..3), text_range(0, 2));
    }

    #[test]
    fn identity_source_map_avoids_index_materialization() {
        let map = SourceMap::identity(8);
        assert_eq!(map.display_offset(3), 3);
        assert_eq!(map.display_offset(99), 8);
        assert_eq!(map.source_offset_for_display(5), 5);
        assert_eq!(map.source_offset_for_display(99), 8);
        assert_eq!(map.source_range_from_display_range(2..6), text_range(2, 6));
    }

    #[test]
    fn sparse_source_map_handles_positive_delta() {
        let map = SourceMap::from_sparse_edits(4, 5, vec![SourceMapEdit::new(1, 2, 1, 3)].into());
        assert_eq!(map.display_offset(0), 0);
        assert_eq!(map.display_offset(1), 1);
        assert_eq!(map.display_offset(2), 3);
        assert_eq!(map.display_offset(4), 5);
        assert_eq!(map.source_offset_for_display(0), 0);
        assert_eq!(map.source_offset_for_display(1), 1);
        assert_eq!(map.source_offset_for_display(2), 2);
        assert_eq!(map.source_offset_for_display(3), 2);
        assert_eq!(map.source_offset_for_display(5), 4);
    }

    #[test]
    fn sparse_source_map_handles_negative_delta() {
        let map = SourceMap::from_sparse_edits(6, 4, vec![SourceMapEdit::new(1, 5, 1, 3)].into());
        assert_eq!(map.display_offset(0), 0);
        assert_eq!(map.display_offset(1), 1);
        assert_eq!(map.display_offset(2), 3);
        assert_eq!(map.display_offset(5), 3);
        assert_eq!(map.display_offset(6), 4);
        assert_eq!(map.source_offset_for_display(0), 0);
        assert_eq!(map.source_offset_for_display(1), 1);
        assert_eq!(map.source_offset_for_display(2), 5);
        assert_eq!(map.source_offset_for_display(3), 5);
        assert_eq!(map.source_offset_for_display(4), 6);
    }
}