Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: af37b58872d6d86e3200198f4579319d5c2c8ba3 (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
// Read from xmlo and immediately lower to ASG IR
//
//  Copyright (C) 2014-2020 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/>.

use super::reader::{XmloError, XmloEvent, XmloReader};
use crate::ir::asg::{Asg, IdentKind, IdentObjectState, ObjectRef, Source};
use crate::sym::{Interner, Symbol};
use petgraph::graph::IndexType;
use std::convert::TryInto;
use std::error::Error;
use std::hash::BuildHasher;
use std::collections::HashSet;
use std::io::BufRead;

// TODO error type
pub type Result<'i, S, Ix> =
    std::result::Result<AsgBuilderResult<'i, S, Ix>, Box<dyn Error>>;

pub struct AsgBuilderResult<'i, S, Ix>
where
    S: BuildHasher + Default,
    Ix: IndexType,
{
    pub roots: Vec<ObjectRef<Ix>>,
    pub found: HashSet<&'i str, S>,
    pub name: Option<&'i Symbol<'i>>,
    pub relroot: Option<String>,
}

pub trait AsgBuilder<'i, O, S, Ix>
where
    O: IdentObjectState<'i, O>,
    S: BuildHasher + Default,
    Ix: IndexType,
{
    fn build<G: Asg<'i, O, Ix>>(
        self,
        graph: &mut G,
        first: bool,
    ) -> Result<'i, S, Ix>;
}

impl<'i, B, I, O, S, Ix> AsgBuilder<'i, O, S, Ix> for XmloReader<'i, B, I>
where
    B: BufRead,
    I: Interner<'i>,
    O: IdentObjectState<'i, O>,
    S: BuildHasher + Default,
    Ix: IndexType,
{
    // TOOD: remove first
    fn build<G: Asg<'i, O, Ix>>(
        mut self,
        graph: &mut G,
        first: bool,
    ) -> Result<'i, S, Ix> {
        // TODO
        let mut found: HashSet<&'i str, S> = Default::default();

        let mut roots = Vec::new();
        let mut elig = None;

        let mut name: Option<&'i Symbol<'i>> = None;
        let mut relroot: Option<String> = None;

        loop {
            match self.read_event() {
                Ok(XmloEvent::Package(attrs)) => {
                    if first {
                        name = attrs.name;
                        relroot = attrs.relroot;
                    }
                    elig = attrs.elig;
                }

                Ok(XmloEvent::SymDeps(sym, deps)) => {
                    // TODO: API needs to expose whether a symbol is already
                    // known so that we can warn on them

                    // Maps should not pull in symbols since we may end up
                    // mapping to params that are never actually used
                    if !sym.starts_with(":map:") {
                        for dep_sym in deps {
                            graph.add_dep_lookup(sym, dep_sym);
                        }
                    }
                }

                Ok(XmloEvent::SymDecl(sym, attrs)) => {
                    if let Some(sym_src) = attrs.src {
                        found.insert(sym_src);
                    } else {
                        let owned = attrs.src.is_none();
                        let extern_ = attrs.extern_;

                        let kind = (&attrs).try_into().map_err(|err| {
                            format!("sym `{}` attrs error: {}", sym, err)
                        });

                        let mut src: Source = attrs.into();

                        // Existing convention is to omit @src of local package
                        // (in this case, the program being linked)
                        if first {
                            src.pkg_name = None;
                        }

                        match kind {
                            Ok(kindval) => {
                                // TODO: inefficient
                                let link_root = owned
                                    && (kindval == IdentKind::Meta
                                        || kindval == IdentKind::Map
                                        || kindval == IdentKind::RetMap);

                                if extern_ {
                                    graph.declare_extern(sym, kindval, src)?;
                                } else {
                                    let node =
                                        graph.declare(sym, kindval, src)?;

                                    if link_root {
                                        roots.push(node);
                                    }
                                }
                            }
                            Err(e) => return Err(e.into()),
                        };
                    }
                }

                Ok(XmloEvent::Fragment(sym, text)) => {
                    match graph.lookup(sym) {
                        Some(frag) => match graph.set_fragment(frag, text) {
                            Ok(_) => (),
                            Err(e) => return Err(e.into()),
                        },
                        None => {
                            return Err(XmloError::MissingFragment(
                                String::from("missing fragment"),
                            )
                            .into());
                        }
                    };
                }

                // We don't need to read any further than the end of the
                // header (symtable, sym-deps, fragments)
                Ok(XmloEvent::Eoh) => break,

                Err(e) => return Err(e.into()),
            }
        }

        if let Some(elig_sym) = elig {
            roots.push(graph.lookup(elig_sym).expect(
                "internal error: package elig references nonexistant symbol",
            ));
        }

        Ok(AsgBuilderResult {
            roots,
            found,
            name,
            relroot,
        })
    }
}