Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: de095a637787bde12a3b25fe84d0786479e1939a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// xmlo object file reader
//
//  Copyright (C) 2014-2021 Ryan Specialty Group, LLC.
//
//  This file is part of TAME.
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! `xmlo` object file reader.
//!
//! This defines a lower-level event-based [`XmloReader`] similar to that of
//!   [`quick_xml`] (see [`XmloEvent`]),
//!     where the events are a slightly higher-level abstraction over the
//!     types of nodes present in the file.
//!
//! _Note that a "symbol" in the `xmlo` sense differs slightly from
//!   [`SymbolId`];_
//!     the former is more akin to an identifier.
//!
//! For more information on `xmlo` files,
//!   see the [parent crate][super].A
//!
//! This reader will be used by both the compiler and linker,
//!   and so its [`SymbolId`] type is generalized.
//!
//!
//! How To Use
//! ==========
//! The event-based API for [`XmloReader`] is similar to that of
//!   [`quick_xml`].
//! There is minor overhead incurred from parsing if the emitted events are
//!   not used,
//!     but it is quite minimal.
//!
//! The next [`XmloEvent`] is retrieved using [`XmloReader::read_event`].
//! _You should stop reading at [`XmloEvent::Eoh`];_
//!   reading the remainder of the object file has not yet been implemented.

use super::super::{SymAttrs, SymType};
use super::{XmloError, XmloEvent, XmloResult};
use crate::obj::xmlo::Dim;
use crate::span::UNKNOWN_SPAN;
use crate::sym::{GlobalSymbolInternUnchecked, GlobalSymbolResolve, SymbolId};
#[cfg(test)]
use crate::test::quick_xml::MockBytesStart as BytesStart;
#[cfg(test)]
use crate::test::quick_xml::MockXmlEvent as XmlEvent;
#[cfg(test)]
use crate::test::quick_xml::MockXmlReader as XmlReader;
#[cfg(not(test))]
use quick_xml::events::BytesStart;
#[cfg(not(test))]
use quick_xml::events::Event as XmlEvent;
#[cfg(not(test))]
use quick_xml::Reader as XmlReader;
use std::collections::VecDeque;
use std::convert::TryInto;
use std::io::BufRead;
use std::iter::Iterator;
use std::result::Result;

/// Wrapper around [`quick_xml::Reader`] for reading and parsing `xmlo`
///   object files.
///
/// This reader performs interning (see [crate::sym]) for data that is
///   expected to be duplicated or compared.
/// Other data are converted into more concise representations where
///   possible,
///     or are returned as owned [`String`] values otherwise,
///     with the understanding that values will be persisted within an IR
///     anyway.
/// This reader stores symbol attributes in the Legacy IR's [`SymAttrs`].
///
/// See [module-level documentation](self) for more information and
///   examples.
pub struct XmloReader<B>
where
    B: BufRead,
{
    /// Source `xmlo` reader.
    reader: XmlReader<B>,

    /// Internal buffer for [`XmlReader`].
    buffer: Vec<u8>,

    /// Another internal buffer for [`XmlReader`].
    ///
    /// This buffer exists to work around ownership rules.
    /// TODO: It this worth removing?  If not, remove this TODO.
    sub_buffer: Vec<u8>,

    /// Whether the root has been validated.
    ///
    /// This is used to ensure that we provide an error early on if we try
    ///   to process something that isn't a package.
    seen_root: bool,

    /// Name of the package currently being read.
    ///
    /// This is known after processing the root `package` element,
    ///   provided that it's a proper root node.
    pkg_name: Option<SymbolId>,

    /// Queue of events already processed,
    ///   to be returned on [`XmloReader::read_event`].
    ///
    /// This exists as an incremental transition toward producing a
    ///   streaming API and will eventually be eliminated.
    /// It does incur a small performance cost.
    event_queue: VecDeque<XmloEvent>,
}

impl<B> XmloReader<B>
where
    B: BufRead,
{
    /// Construct a new reader.
    pub fn new(reader: B) -> Self {
        let mut reader = XmlReader::from_reader(reader);

        // xmlo files are compiler output and should be trusted
        reader.check_end_names(false);

        Self {
            reader,
            // TODO: option to accept buffer
            buffer: Vec::new(),
            sub_buffer: Vec::new(),
            seen_root: false,
            pkg_name: None,
            event_queue: VecDeque::new(),
        }
    }

    /// Continue reading and produce the next event.
    ///
    /// An [`XmloEvent::Eoh`] event is emitted at the end of the header
    ///   (at the closing `preproc:fragment` node).
    ///
    /// Stack Warning
    /// =============
    /// The source file will be read until an event can be produced.
    /// This is recursive on the underlying [`XmlReader::read_event`],
    ///   and Rust dues not (at the time of writing) support tail call
    ///   optimization.
    /// This shouldn't be a concern for proper `xmlo` files as long as you
    ///   acknowledge [`XmloEvent::Eoh`] and do not continue reading
    ///   further.
    ///
    /// Errors
    /// ======
    /// - Any of [`XmloError`].
    ///   See private methods for more information.
    ///
    /// TODO: Augment failures with context
    pub fn read_event<'a>(&mut self) -> XmloResult<XmloEvent> {
        // Just to cut down on peak memory usage, cleaning up after a
        // previous run.  This does not affect behavior.
        self.buffer.clear();
        self.sub_buffer.clear();

        // Return queued events first before continuing processing.
        // This allows us to begin to transition to a streaming API without
        //   many structural changes,
        //     but will eventually go away.
        if let Some(event) = self.event_queue.pop_front() {
            return Ok(event);
        }

        let event = self.reader.read_event(&mut self.buffer)?;

        // Ensure that the first encountered node is something we expect
        if !self.seen_root {
            match &event {
                // We don't process namespaces, so we have to guess what
                // they may be (map xmlo files differ, for example)
                XmlEvent::Start(ele) => {
                    if !(ele.name() == b"package"
                        || ele.name() == b"lv:package")
                    {
                        return Err(XmloError::UnexpectedRoot);
                    }

                    self.seen_root = true;
                }
                _ => return self.read_event(),
            }
        }

        match event {
            XmlEvent::Empty(ele) if ele.name() == b"preproc:sym" => {
                Self::process_sym(&self.pkg_name, &ele)
            }

            XmlEvent::Start(ele) => match ele.name() {
                b"package" | b"lv:package" => Self::process_package(
                    &ele,
                    &mut self.pkg_name,
                    &mut self.event_queue,
                ),

                b"preproc:sym-dep" => Self::process_dep(
                    &ele,
                    &mut self.reader,
                    &mut self.sub_buffer,
                    &mut self.event_queue,
                ),

                b"preproc:fragment" => Self::process_fragment(
                    &ele,
                    &mut self.reader,
                    &mut self.sub_buffer,
                ),

                // `func` symbols include additional data for param
                // ordering, which we don't care about.  But `map` includes
                // source field information which we want to keep.  (We
                // don't care about `retmap` for our purposes.)
                b"preproc:sym" => {
                    let mut event = Self::process_sym(&self.pkg_name, &ele)?;

                    match &mut event {
                        XmloEvent::SymDecl(_, attrs, _)
                            if attrs.ty == Some(SymType::Map) =>
                        {
                            attrs.from = Self::process_map_from(
                                &mut self.reader,
                                &mut self.sub_buffer,
                            )?;

                            Ok(event)
                        }
                        _ => {
                            self.reader.read_to_end(
                                ele.name(),
                                &mut self.sub_buffer,
                            )?;

                            Ok(event)
                        }
                    }
                }

                // Just like the outer match, recurse
                _ => self.read_event(),
            },

            XmlEvent::End(ele) if ele.name() == b"preproc:fragments" => {
                Ok(XmloEvent::Eoh)
            }

            // Ignore and recurse, looking for something we can process
            _ => self.read_event(),
        }
    }

    /// Process `lv:package` element attributes.
    fn process_package<'a>(
        ele: &'a BytesStart<'a>,
        pkg_name: &mut Option<SymbolId>,
        event_queue: &mut VecDeque<XmloEvent>,
    ) -> XmloResult<XmloEvent> {
        let mut program = false;
        let mut elig = None;
        let mut name = None;
        let mut relroot = None;

        for attr in ele.attributes().with_checks(false).filter_map(Result::ok) {
            match attr.key {
                b"name" => {
                    name =
                        Some(unsafe { (&attr.value).intern_utf8_unchecked() });
                }

                b"__rootpath" => {
                    relroot =
                        Some(unsafe { (&attr.value).intern_utf8_unchecked() });
                }

                b"program" => {
                    program = &*attr.value == b"true";
                }

                b"preproc:elig-class-yields" => {
                    elig =
                        Some(unsafe { (&attr.value).intern_utf8_unchecked() });
                }

                _ => (),
            }
        }

        if let Some(given_name) = name {
            event_queue.push_back(XmloEvent::PkgName(given_name));
        }
        if let Some(given_relroot) = relroot {
            event_queue.push_back(XmloEvent::PkgRootPath(given_relroot));
        }
        if let Some(given_elig) = elig {
            event_queue.push_back(XmloEvent::PkgEligClassYields(given_elig));
        }
        if program {
            event_queue.push_back(XmloEvent::PkgProgramFlag);
        }

        *pkg_name = name;

        Ok(event_queue.pop_front().unwrap())
    }

    /// Process `preproc:sym` element attributes.
    ///
    /// The symbol name `preproc:sym/@name` is interned.
    /// All other known attributes are parsed
    ///   and unknown attributes are ignored.
    ///
    /// The result is a single [`XmloEvent::SymDecl`] with an interned
    ///   `preproc:sym/@name`.
    ///
    /// Errors
    /// ======
    /// - [`XmloError::UnassociatedSym`] if missing `preproc:sym/@name`.
    fn process_sym<'a>(
        pkg_name: &Option<SymbolId>,
        ele: &'a BytesStart<'a>,
    ) -> XmloResult<XmloEvent> {
        let mut name: Option<SymbolId> = None;
        let mut sym_attrs = SymAttrs::default();

        for attr in ele.attributes().with_checks(false).filter_map(Result::ok) {
            match attr.key {
                b"name" => {
                    name = Some(unsafe { attr.value.intern_utf8_unchecked() });
                }

                b"src" => {
                    sym_attrs.src =
                        Some(unsafe { attr.value.intern_utf8_unchecked() });
                }

                b"type" => {
                    sym_attrs.ty =
                        Some((*attr.value).try_into().map_err(|_| {
                            XmloError::InvalidType(unsafe {
                                String::from_utf8_unchecked(attr.value.to_vec())
                            })
                        })?);
                }

                b"dim" => {
                    sym_attrs.dim = Some(Self::char_to_dim(&attr.value)?);
                }

                b"dtype" => {
                    sym_attrs.dtype =
                        Some((*attr.value).try_into().map_err(|_| {
                            XmloError::InvalidDtype(unsafe {
                                String::from_utf8_unchecked(attr.value.to_vec())
                            })
                        })?);
                }

                b"extern" => {
                    sym_attrs.extern_ = &*attr.value == b"true";
                }

                b"preproc:generated" => {
                    sym_attrs.generated = &*attr.value == b"true";
                }

                b"parent" => {
                    sym_attrs.parent =
                        Some(unsafe { attr.value.intern_utf8_unchecked() });
                }

                b"yields" => {
                    sym_attrs.yields =
                        Some(unsafe { attr.value.intern_utf8_unchecked() });
                }

                b"desc" => {
                    sym_attrs.desc =
                        Some(unsafe { attr.value.intern_utf8_unchecked() });
                }

                b"virtual" => {
                    sym_attrs.virtual_ = &*attr.value == b"true";
                }

                b"isoverride" => {
                    sym_attrs.override_ = &*attr.value == b"true";
                }

                // As this reader evolves, we may wish to provide an error
                // for unknown attributes so that we can be sure that we've
                // handled them all.
                _ => (),
            }
        }

        sym_attrs.pkg_name = *pkg_name;

        name.map(|name_sym| {
            XmloEvent::SymDecl(name_sym, sym_attrs, UNKNOWN_SPAN)
        })
        .ok_or(XmloError::UnassociatedSym(UNKNOWN_SPAN))
    }

    /// Process `preproc:from` for `preproc:sym[@type="map"]` elements.
    ///
    /// Map symbols contain additional information describing source
    ///   inputs external to the system.
    ///
    /// Errors
    /// ======
    /// - [`XmloError::InvalidMapFrom`] if `@name` missing or if unexpected
    ///   data (e.g. elements) are encountered.
    /// - [`XmloError::XmlError`] on XML parsing failure.
    fn process_map_from<'a>(
        reader: &mut XmlReader<B>,
        buffer: &mut Vec<u8>,
    ) -> XmloResult<Option<SymbolId>> {
        let mut from = None;

        loop {
            match reader.read_event(buffer)? {
                XmlEvent::Empty(ele) if ele.name() == b"preproc:from" => {
                    if from.is_some() {
                        // This feature isn't actually utilized for the
                        //   input map.
                        return Err(XmloError::InvalidMapFrom(
                            "multiple preproc:from found for input map entry"
                                .into(),
                        ));
                    }

                    from.replace(
                        ele.attributes()
                            .with_checks(false)
                            .filter_map(Result::ok)
                            .find(|attr| attr.key == b"name")
                            .map_or(
                                Err(XmloError::InvalidMapFrom(
                                    "preproc:from/@name missing".into(),
                                )),
                                |attr| {
                                    Ok(unsafe {
                                        attr.value.intern_utf8_unchecked()
                                    })
                                },
                            )?,
                    );
                }

                XmlEvent::End(ele) if ele.name() == b"preproc:sym" => break,

                // Note that whitespace counts as text
                XmlEvent::Text(_) => (),

                _ => Err(XmloError::InvalidMapFrom("unexpected data".into()))?,
            };
        }

        Ok(from)
    }

    /// Process `preproc:sym-dep` element.
    ///
    /// This represents an adjacency list for a given identifier in the
    ///   dependency graph.
    /// The structure of this element is looks like this:
    ///
    /// ```xml
    /// <preproc:sym-dep name=":class:some-sym">
    ///   <preproc:sym-ref name="someOtherSym" />
    ///   <!-- ... -->
    /// </preproc:sym-dep>
    /// ```
    ///
    /// Errors
    /// ======
    ///  - [`XmloError::UnassociatedSymDep`] if missing `preproc:sym-dep/@name`.
    ///  - [`XmloError::MalformedSymRef`] if missing `preproc:sym-ref/@name`
    ///    or if any `preproc:sym-dep/node()` is not a `prepreoc:sym-ref`.
    ///  - [`XmloError::XmlError`] on XML parsing failure.
    fn process_dep<'a>(
        ele: &'a BytesStart<'a>,
        reader: &mut XmlReader<B>,
        buffer: &mut Vec<u8>,
        event_queue: &mut VecDeque<XmloEvent>,
    ) -> XmloResult<XmloEvent> {
        let name = ele
            .attributes()
            .with_checks(false)
            .filter_map(Result::ok)
            .find(|attr| attr.key == b"name")
            .map_or(Err(XmloError::UnassociatedSymDep), |attr| {
                Ok(unsafe { attr.value.intern_utf8_unchecked() })
            })?;

        event_queue.push_back(XmloEvent::SymDepStart(name));

        loop {
            match reader.read_event(buffer)? {
                XmlEvent::Empty(symref)
                    if symref.name() == b"preproc:sym-ref" =>
                {
                    event_queue.push_back(XmloEvent::Symbol(
                        symref
                            .attributes()
                            .with_checks(false)
                            .filter_map(Result::ok)
                            .find(|attr| attr.key == b"name")
                            .map_or(
                                Err(XmloError::MalformedSymRef(
                                    "preproc:sym-ref/@name missing".into(),
                                )),
                                |attr| {
                                    Ok(unsafe {
                                        attr.value.intern_utf8_unchecked()
                                    })
                                },
                            )?,
                    ));
                }

                // We assume that elements are properly nested, so this must
                // be the closing preproc:sym-dep tag.
                XmlEvent::End(_) => break,

                // Note that whitespace counts as text
                XmlEvent::Text(_) => (),

                _ => return Err(XmloError::MalformedSymRef(format!(
                    "preproc:sym-dep must contain only preproc:sym-ref children for `{}`",
                    name.lookup_str(),
                )))
            }
        }

        Ok(event_queue.pop_front().unwrap())
    }

    /// Process `preproc:fragment` element.
    ///
    /// This element represents the compiled code for the given symbol.
    /// The result is a single [`XmloEvent::Fragment`] with an interned
    ///   fragment and an interned `preproc:fragment/@id`.
    /// The fragment is _left escaped_,
    ///   since it is assumed that it will be written back out verbatim
    ///   without further modification;
    ///     this save us from having to spend time re-escaping on output
    ///     down the line.
    ///
    /// Errors
    /// ======
    /// - [`XmloError::UnassociatedFragment`] if missing `preproc:fragment/@id`.
    /// - [`XmloError::MissingFragmentText`] if missing
    ///   `preproc:fragment/text()`.
    /// - [`XmloError::XmlError`] for XML parsing errors.
    fn process_fragment<'a>(
        ele: &'a BytesStart<'a>,
        reader: &mut XmlReader<B>,
        buffer: &mut Vec<u8>,
    ) -> XmloResult<XmloEvent> {
        let mut src_attrs = ele.attributes();
        let mut filtered = src_attrs.with_checks(false).filter_map(Result::ok);

        let id = filtered
            .find(|attr| attr.key == b"id")
            .filter(|attr| &*attr.value != b"")
            .map_or(Err(XmloError::UnassociatedFragment), |attr| {
                Ok(unsafe { attr.value.intern_utf8_unchecked() })
            })?;

        let text = match reader.read_event(buffer)? {
            XmlEvent::Text(ev) => {
                // It is wasteful to unescape only to have to re-escape
                // again on write, so keep the text raw (escaped), and also
                // trust that it's valid UTF-8, having come from the
                // compiler.
                Ok(unsafe { ev.escaped().clone_uninterned_utf8_unchecked() })
            }
            _ => Err(XmloError::MissingFragmentText(id)),
        }?;

        Ok(XmloEvent::Fragment(id, text))
    }

    /// Convert single-character `@dim` to a [`Dim`].
    fn char_to_dim(value: &[u8]) -> XmloResult<Dim> {
        match value {
            [b'0'] => Ok(Dim::Scalar),
            [b'1'] => Ok(Dim::Vector),
            [b'2'] => Ok(Dim::Matrix),
            _ => Err(XmloError::InvalidDim(
                unsafe { value.intern_utf8_unchecked() },
                UNKNOWN_SPAN,
            )),
        }
    }
}

impl<B> Iterator for XmloReader<B>
where
    B: BufRead,
{
    type Item = XmloResult<XmloEvent>;

    /// Invoke [`XmloReader::read_event`] and yield the result via an
    ///   [`Iterator`] API.
    ///
    /// *Warning*: This will always return [`Some`] for now.
    /// Future changes may alter this behavior.
    /// To terminate the iterator,
    ///   it's recommended that you use [`Iterator::take_while`] to filter
    ///   on the desired predicate,
    ///     such as [`XmloEvent::Eoh`].
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.read_event())
    }
}

impl<B> From<B> for XmloReader<B>
where
    B: BufRead,
{
    fn from(buf: B) -> Self {
        Self::new(buf)
    }
}

#[cfg(test)]
mod test;