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
// Copyright (c) 2017-2021 Fabian Schuiki

//! Representation of the input and output arguments of functions, processes,
//! and entitites.

use crate::{
    ir::{Arg, Unit},
    table::PrimaryTable,
    ty::Type,
};

/// A description of the input and output arguments of a unit.
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct Signature {
    args: PrimaryTable<Arg, ArgData>,
    inp: Vec<Arg>,
    oup: Vec<Arg>,
    retty: Option<Type>,
}

/// Argument direction.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
enum ArgDir {
    Input,
    Output,
}

/// A single argument of a `Function`, `Process`, or `Entity`.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
struct ArgData {
    ty: Type,
    dir: ArgDir,
    num: u16,
}

impl Signature {
    /// Create a new signature.
    pub fn new() -> Self {
        Default::default()
    }

    /// Add an input argument.
    pub fn add_input(&mut self, ty: Type) -> Arg {
        let arg = self.args.add(ArgData {
            ty,
            dir: ArgDir::Input,
            num: self.inp.len() as u16,
        });
        self.inp.push(arg);
        arg
    }

    /// Add an output argument.
    pub fn add_output(&mut self, ty: Type) -> Arg {
        let arg = self.args.add(ArgData {
            ty,
            dir: ArgDir::Output,
            num: self.oup.len() as u16,
        });
        self.oup.push(arg);
        arg
    }

    /// Set the return type of the signature.
    pub fn set_return_type(&mut self, ty: Type) {
        self.retty = Some(ty);
    }

    /// Get the return type of the signature.
    pub fn return_type(&self) -> Type {
        self.retty.clone().unwrap()
    }

    /// Check whether the signature has any inputs.
    pub fn has_inputs(&self) -> bool {
        !self.inp.is_empty()
    }

    /// Check whether the signature has any outputs.
    pub fn has_outputs(&self) -> bool {
        !self.oup.is_empty()
    }

    /// Check whether the signature has a return type.
    pub fn has_return_type(&self) -> bool {
        self.retty.is_some()
    }

    /// Return an iterator over the inputs of the signature.
    pub fn inputs<'a>(&'a self) -> impl Iterator<Item = Arg> + 'a {
        self.inp.iter().cloned()
    }

    /// Return an iterator over the outputs of the signature.
    pub fn outputs<'a>(&'a self) -> impl Iterator<Item = Arg> + 'a {
        self.oup.iter().cloned()
    }

    /// Return an iterator over the arguments of the signature.
    ///
    /// Inputs come first, then outputs.
    pub fn args<'a>(&'a self) -> impl Iterator<Item = Arg> + 'a {
        self.inputs().chain(self.outputs())
    }

    /// Return the type of argument `arg`.
    pub fn arg_type(&self, arg: Arg) -> Type {
        self.args[arg].ty.clone()
    }

    /// Check whether `arg` is an input.
    pub fn is_input(&self, arg: Arg) -> bool {
        self.args[arg].dir == ArgDir::Input
    }

    /// Check whether `arg` is an output.
    pub fn is_output(&self, arg: Arg) -> bool {
        self.args[arg].dir == ArgDir::Output
    }

    /// Dump the signature in human-readable form.
    pub fn dump<'a>(&'a self, unit: &Unit<'a>) -> SignatureDumper<'a> {
        SignatureDumper(self, *unit)
    }
}

impl Eq for Signature {}

impl PartialEq for Signature {
    fn eq(&self, other: &Self) -> bool {
        self.args().count() == other.args().count()
            && self
                .args()
                .zip(other.args())
                .all(|(a, b)| self.args[a] == other.args[b])
    }
}

impl std::fmt::Display for Signature {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use std::iter::{once, repeat};
        write!(f, "(")?;
        for (arg, sep) in self.inputs().zip(once("").chain(repeat(", "))) {
            write!(f, "{}{}", sep, self.arg_type(arg))?;
        }
        if self.has_outputs() {
            write!(f, ") -> (")?;
            for (arg, sep) in self.outputs().zip(once("").chain(repeat(", "))) {
                write!(f, "{}{}", sep, self.arg_type(arg))?;
            }
        }
        write!(f, ")")?;
        if let Some(ref retty) = self.retty {
            write!(f, " {}", retty)?;
        }
        Ok(())
    }
}

impl std::fmt::Debug for Signature {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

/// Temporary object to dump a `Signature` in human-readable form for debugging.
pub struct SignatureDumper<'a>(&'a Signature, Unit<'a>);

impl std::fmt::Display for SignatureDumper<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use std::iter::{once, repeat};
        write!(f, "(")?;
        for (arg, sep) in self.0.inputs().zip(once("").chain(repeat(", "))) {
            let value = self.1.arg_value(arg);
            write!(
                f,
                "{}{} {}",
                sep,
                self.1.value_type(value),
                value.dump(&self.1)
            )?;
        }
        write!(f, ")")?;
        if self.0.has_outputs() {
            write!(f, " -> (")?;
            for (arg, sep) in self.0.outputs().zip(once("").chain(repeat(", "))) {
                let value = self.1.arg_value(arg);
                write!(
                    f,
                    "{}{} {}",
                    sep,
                    self.1.value_type(value),
                    value.dump(&self.1)
                )?;
            }
            write!(f, ")")?;
        }
        if self.0.has_return_type() {
            write!(f, " {}", self.0.return_type())?;
        }
        Ok(())
    }
}