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
pub use parity_wasm::elements::Module;

use std::{error, fmt};

pub mod imports;

#[cfg(feature = "binaryen")]
pub mod binaryenopt;
pub mod checkfloat;
pub mod checkstartfunc;
pub mod deployer;
pub mod dropsection;
pub mod remapimports;
pub mod remapstart;
pub mod repack;
pub mod snip;
pub mod trimexports;
pub mod trimstartfunc;
pub mod verifyexports;
pub mod verifyimports;

mod depgraph;

#[derive(Eq, PartialEq, Debug)]
pub enum ModuleKind {
    Creator,
    Translator,
    Validator,
}

#[derive(Eq, PartialEq, Debug, Clone)]
pub enum ModuleError {
    NotSupported,
    NotFound,
    Custom(String),
}

/// Utility interface for chisel modules.
pub trait ChiselModule<'a> {
    type ObjectReference: ?Sized;
    /// Returns the name of the chisel module.
    fn id(&'a self) -> String;

    fn kind(&'a self) -> ModuleKind;

    /// Borrows the instance as a trait object.
    fn as_abstract(&'a self) -> Self::ObjectReference;
}

pub trait ModuleCreator {
    /// Returns new module.
    fn create(&self) -> Result<Module, ModuleError>;
}

pub trait ModuleTranslator {
    /// Translates module. Returns new module or none if nothing was modified. Can fail with ModuleError::NotSupported.
    fn translate(&self, module: &Module) -> Result<Option<Module>, ModuleError>;

    /// Translates module in-place. Returns true if the module was modified. Can fail with ModuleError::NotSupported.
    fn translate_inplace(&self, module: &mut Module) -> Result<bool, ModuleError>;
}

pub trait ModuleValidator {
    /// Validates module. Returns true if it is valid or false if invalid.
    fn validate(&self, module: &Module) -> Result<bool, ModuleError>;
}

pub trait ModulePreset {
    fn with_preset(preset: &str) -> Result<Self, ModuleError>
    where
        Self: std::marker::Sized;
}

impl From<String> for ModuleError {
    fn from(error: String) -> Self {
        ModuleError::Custom(error)
    }
}

impl From<std::io::Error> for ModuleError {
    fn from(error: std::io::Error) -> Self {
        use std::error::Error;
        ModuleError::Custom(error.description().to_string())
    }
}

// Also aliased as parity_wasm::SerializationError
impl From<parity_wasm::elements::Error> for ModuleError {
    fn from(a: parity_wasm::elements::Error) -> Self {
        use std::error::Error;
        ModuleError::Custom(a.description().to_string())
    }
}

impl fmt::Display for ModuleError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                ModuleError::NotSupported => "Method unsupported",
                ModuleError::NotFound => "Not found",
                ModuleError::Custom(msg) => msg,
            }
        )
    }
}

impl error::Error for ModuleError {
    fn description(&self) -> &str {
        match self {
            ModuleError::NotSupported => "Method unsupported",
            ModuleError::NotFound => "Not found",
            ModuleError::Custom(msg) => msg,
        }
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        None
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use super::*;

    struct SampleModule {}

    impl ModuleCreator for SampleModule {
        fn create(&self) -> Result<Module, ModuleError> {
            Ok(Module::default())
        }
    }

    impl ModuleTranslator for SampleModule {
        fn translate(&self, _module: &Module) -> Result<Option<Module>, ModuleError> {
            Ok(Some(Module::default()))
        }
        fn translate_inplace(&self, _module: &mut Module) -> Result<bool, ModuleError> {
            Ok(true)
        }
    }

    impl ModuleValidator for SampleModule {
        fn validate(&self, _module: &Module) -> Result<bool, ModuleError> {
            Ok(true)
        }
    }

    impl<'a> ChiselModule<'a> for SampleModule {
        // Yes, it implements all the traits, but we will treat it as a validator when used as a
        // trait object for testing purposes.
        type ObjectReference = &'a dyn ModuleValidator;

        fn id(&'a self) -> String {
            "Sample".to_string()
        }

        fn kind(&'a self) -> ModuleKind {
            ModuleKind::Validator
        }

        fn as_abstract(&'a self) -> Self::ObjectReference {
            self as Self::ObjectReference
        }
    }

    #[test]
    fn creator_succeeds() {
        let creator = SampleModule {};
        let result = creator.create();
        assert!(result.is_ok());
    }

    #[test]
    fn translator_succeeds() {
        let translator = SampleModule {};
        let result = translator.translate(&Module::default());
        assert!(result.is_ok());
    }

    #[test]
    fn translator_inplace_succeeds() {
        let translator = SampleModule {};
        let result = translator.translate_inplace(&mut Module::default());
        assert!(result.is_ok());
    }

    #[test]
    fn validator_succeeds() {
        let validator = SampleModule {};
        let result = validator.validate(&Module::default());
        assert!(result.is_ok());
    }

    #[test]
    fn from_error() {
        let err: ModuleError = "custom message".to_string().into();
        assert_eq!(err, ModuleError::Custom("custom message".to_string()));
    }

    #[test]
    fn fmt_good() {
        // Add new tests for each enum variant here as they are implemented.
        let fmt_result_unsupported = format!("{}", ModuleError::NotSupported);
        assert_eq!("Method unsupported", fmt_result_unsupported);

        let fmt_result_custom = format!("{}", ModuleError::Custom("foo".to_string()));
        assert_eq!("foo", fmt_result_custom);
    }

    #[test]
    fn error_good() {
        // Add new tests for each enum variant here as they are implemented.
        let err_unsupported = ModuleError::NotSupported;
        let err_description_unsupported = err_unsupported.description();
        assert_eq!("Method unsupported", err_description_unsupported);

        let err_custom = ModuleError::Custom("bar".to_string());
        let err_description_custom = err_custom.description();
        assert_eq!("bar", err_description_custom);
    }

    #[test]
    fn opaque_module() {
        let validator = SampleModule {};
        assert_eq!(validator.id(), "Sample");

        let opaque: &dyn ChiselModule<ObjectReference = &dyn ModuleValidator> =
            &validator as &dyn ChiselModule<ObjectReference = &dyn ModuleValidator>;

        assert_eq!(opaque.kind(), ModuleKind::Validator);

        let as_trait: &dyn ModuleValidator = opaque.as_abstract();

        let result = as_trait.validate(&Module::default());
        assert!(result.is_ok());
    }
}