Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: 52078edca4cd40870a88866652f2d463a5c00911 (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
// Graph abstraction
//
//  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/>.

//! Abstract graph as the basis for concrete ASGs.

use super::ident::IdentKind;
use super::object::{
    FragmentText, IdentObjectData, IdentObjectState, Source, TransitionError,
};
use super::Sections;
use crate::sym::Symbol;
use petgraph::graph::{IndexType, NodeIndex};
use std::fmt::Debug;
use std::result::Result;

/// An abstract semantic graph of [objects][super::object].
///
/// This IR focuses on the definition and manipulation of objects and their
///   dependencies.
/// See [`IdentObject`](super::object::IdentObject) for a summary of valid
///   identifier object state transitions.
///
/// Objects are never deleted from the graph,
///   so [`ObjectRef`]s will remain valid for the lifetime of the ASG.
///
/// For more information,
///   see the [module-level documentation][self].
pub trait Asg<'i, O, Ix>
where
    Ix: IndexType,
    O: IdentObjectState<'i, O>,
{
    /// Declare a concrete identifier.
    ///
    /// An identifier declaration is similar to a declaration in a header
    ///   file in a language like C,
    ///     describing the structure of the identifier.
    /// Once declared,
    ///   this information cannot be changed.
    ///
    /// Identifiers are uniquely identified by a [`Symbol`] `name`.
    /// If an identifier of the same `name` already exists,
    ///   then the provided declaration is compared against the existing
    ///   declaration---should
    ///     they be incompatible,
    ///       then the operation will fail;
    ///     otherwise,
    ///       the existing identifier will be returned.
    ///
    /// If a concrete identifier has already been declared (see
    ///   [`Asg::declare`]),
    ///     then extern declarations will be compared and,
    ///       if compatible,
    ///       the identifier will be immediately _resolved_ and the object
    ///         on the graph will not be altered.
    /// Resolution will otherwise fail in error.
    ///
    /// For more information on state transitions that can occur when
    ///   redeclaring an identifier that already exists,
    ///     see [`IdentObjectState::resolve`].
    ///
    /// A successful declaration will add an identifier to the graph
    ///   and return an [`ObjectRef`] reference.
    fn declare(
        &mut self,
        name: &'i Symbol<'i>,
        kind: IdentKind,
        src: Source<'i>,
    ) -> AsgResult<ObjectRef<Ix>, Ix>;

    /// Declare an abstract identifier.
    ///
    /// An _extern_ declaration declares an identifier the same as
    ///   [`Asg::declare`],
    ///     but omits source information.
    /// Externs are identifiers that are expected to be defined somewhere
    ///   else ("externally"),
    ///     and are resolved at [link-time][crate::ld].
    ///
    /// If a concrete identifier has already been declared (see
    ///   [`Asg::declare`]),
    ///     then the declarations will be compared and,
    ///       if compatible,
    ///       the identifier will be immediately _resolved_ and the object
    ///         on the graph will not be altered.
    /// Resolution will otherwise fail in error.
    ///
    /// See [`IdentObjectState::extern_`] and
    ///   [`IdentObjectState::resolve`] for more information on
    ///   compatibility related to extern resolution.
    fn declare_extern(
        &mut self,
        name: &'i Symbol<'i>,
        kind: IdentKind,
        src: Source<'i>,
    ) -> AsgResult<ObjectRef<Ix>, Ix>;

    /// Set the fragment associated with a concrete identifier.
    ///
    /// Fragments are intended for use by the [linker][crate::ld].
    /// For more information,
    ///   see [`IdentObjectState::set_fragment`].
    fn set_fragment(
        &mut self,
        identi: ObjectRef<Ix>,
        text: FragmentText,
    ) -> AsgResult<ObjectRef<Ix>, Ix>;

    /// Retrieve an object from the graph by [`ObjectRef`].
    ///
    /// Since an [`ObjectRef`] should only be produced by an [`Asg`],
    ///   and since objects are never deleted from the graph,
    ///   this should never fail so long as references are not shared
    ///   between multiple graphs.
    /// It is nevertheless wrapped in an [`Option`] just in case.
    fn get<I: Into<ObjectRef<Ix>>>(&self, index: I) -> Option<&O>;

    /// Attempt to retrieve an identifier from the graph by name.
    ///
    /// Since only identifiers carry a name,
    ///   this method cannot be used to retrieve all possible objects on the
    ///   graph---for
    ///     that, see [`Asg::get`].
    fn lookup(&self, name: &'i Symbol<'i>) -> Option<ObjectRef<Ix>>;

    /// Declare that `dep` is a dependency of `ident`.
    ///
    /// An object must be declared as a dependency if its value must be
    ///   computed before computing the value of `ident`.
    /// The [linker][crate::ld] will ensure this ordering.
    ///
    /// See [`add_dep_lookup`][Asg::add_dep_lookup] if identifiers have to
    ///   be looked up by [`Symbol`] or if they may not yet have been
    ///   declared.
    fn add_dep(&mut self, ident: ObjectRef<Ix>, dep: ObjectRef<Ix>);

    /// Check whether `dep` is a dependency of `ident`.
    fn has_dep(&self, ident: ObjectRef<Ix>, dep: ObjectRef<Ix>) -> bool;

    /// Declare that `dep` is a dependency of `ident`,
    ///   regardless of whether they are known.
    ///
    /// In contrast to [`add_dep`][Asg::add_dep],
    ///   this method will add the dependency even if one or both of `ident`
    ///   or `dep` have not yet been declared.
    /// In such a case,
    ///   a missing identifier will be added as a placeholder,
    ///     allowing the ASG to be built with partial information as
    ///     identifiers continue to be discovered.
    /// See [`IdentObjectState::declare`] for more information.
    ///
    /// References to both identifiers are returned in argument order.
    fn add_dep_lookup(
        &mut self,
        ident: &'i Symbol<'i>,
        dep: &'i Symbol<'i>,
    ) -> (ObjectRef<Ix>, ObjectRef<Ix>);
}

/// Sort a graph into different [`Sections`]
///
/// Allow a graph to be partitioned into different [`Sections`] that can be
///   used as an `Intermediate Representation`.
pub trait SortableAsg<'i, O, Ix>
where
    O: IdentObjectData<'i>,
    Ix: IndexType,
{
    fn sort(
        &'i self,
        roots: &[ObjectRef<Ix>],
    ) -> AsgResult<Sections<'i, O>, Ix>;
}

/// A [`Result`] with a hard-coded [`AsgError`] error type.
///
/// This is the result of every [`Asg`] operation that could potentially
///   fail in error.
pub type AsgResult<T, Ix> = Result<T, AsgError<Ix>>;

/// Reference to an [object][super::object] stored within the [`Asg`].
///
/// IdentObject references are integer offsets,
///   not pointers.
/// See the [module-level documentation][self] for more information.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
pub struct ObjectRef<Ix>(pub NodeIndex<Ix>);

impl<Ix> From<NodeIndex<Ix>> for ObjectRef<Ix>
where
    Ix: IndexType,
{
    fn from(index: NodeIndex<Ix>) -> Self {
        Self(index)
    }
}

impl<Ix> From<ObjectRef<Ix>> for NodeIndex<Ix>
where
    Ix: IndexType,
{
    fn from(objref: ObjectRef<Ix>) -> Self {
        objref.0
    }
}

/// There are currently no data stored on edges ("edge weights").
pub type AsgEdge = ();

/// Each node of the graph represents an object.
///
/// Enclosed in an [`Option`] to permit moving owned values out of the
///   graph.
pub type Node<O> = Option<O>;

/// An error from an ASG operation.
///
/// Storing [`Symbol`] would require that this have a lifetime,
///   which is very inconvenient when chaining [`Result`],
///   so this stores only owned values.
/// The caller will know the problem values.
#[derive(Debug, PartialEq)]
pub enum AsgError<Ix: Debug> {
    /// An object could not change state in the manner requested.
    ///
    /// See [`Asg::declare`] and [`Asg::set_fragment`] for more
    ///   information.
    /// See also [`TransitionError`].
    ObjectTransition(TransitionError),

    /// The node was not expected in the current context
    UnexpectedNode(String),

    /// The graph has a cyclic dependency
    Cycles(Vec<Vec<ObjectRef<Ix>>>),
}

impl<Ix: Debug> std::fmt::Display for AsgError<Ix> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::ObjectTransition(err) => std::fmt::Display::fmt(&err, fmt),
            Self::UnexpectedNode(msg) => {
                write!(fmt, "unexpected node: {}", msg)
            }
            Self::Cycles(cycles) => {
                write!(fmt, "Cyclic dependencies detected: {:?}", cycles)
            }
        }
    }
}

impl<Ix: Debug> std::error::Error for AsgError<Ix> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::ObjectTransition(err) => err.source(),
            _ => None,
        }
    }
}

impl<Ix: Debug> From<TransitionError> for AsgError<Ix> {
    fn from(err: TransitionError) -> Self {
        Self::ObjectTransition(err)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    mod objref {
        use super::*;

        #[test]
        fn to_from_nodeindex() {
            let index = NodeIndex::<u32>::new(5);
            let objref: ObjectRef<u32> = ObjectRef::from(index);

            assert_eq!(index, objref.0);
            assert_eq!(index, objref.into());
        }
    }
}