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
//! JSON generation

use {items, utils};
use serde_json;

use std::{io};
use std;

/// The result type for JSON errors.
pub type JsonResult<T> = std::result::Result<T, JsonError>;

/// Errors that may occur during JSON operations.
#[derive(Debug)]
pub enum JsonError {
	FailedToCreateDirectory(io::Error),
	FailedToCreateJsonFile(io::Error),
	FailedToWriteJsonAbiFile(serde_json::Error),
}

impl JsonError {
	/// Returns a JSON error indicating that the creation of the
	/// directory that will contain the JSON file failed.
	pub fn failed_to_create_dir(err: io::Error) -> Self {
		JsonError::FailedToCreateDirectory(err)
	}

	/// Returns a JSON error indicating that the creation of the JSON
	/// abi file failed.
	pub fn failed_to_create_json_file(err: io::Error) -> Self {
		JsonError::FailedToCreateJsonFile(err)
	}

	/// Returns a JSON error indicating that the writing of the JSON
	/// abi file failed.
	pub fn failed_to_write_json_abi_file(err: serde_json::Error) -> Self {
		JsonError::FailedToWriteJsonAbiFile(err)
	}
}

impl std::fmt::Display for JsonError {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
		match self {
			JsonError::FailedToCreateDirectory(err) => {
				write!(f, "failed to create directory for JSON abi file: {:?}", err)
			}
			JsonError::FailedToCreateJsonFile(err) => {
				write!(f, "failed to create JSON abi file: {:?}", err)
			}
			JsonError::FailedToWriteJsonAbiFile(err) => {
				write!(f, "failed to write JSON abi file: {:?}", err)
			}
		}
	}
}

impl std::error::Error for JsonError {
	fn description(&self) -> &str {
		match self {
			JsonError::FailedToCreateDirectory(_) => {
				"failed to create directory for the JSON abi file"
			}
			JsonError::FailedToCreateJsonFile(_) => "failed to create JSON abi file",
			JsonError::FailedToWriteJsonAbiFile(_) => "failed to write JSON abi file",
		}
	}

	fn cause(&self) -> Option<&std::error::Error> {
		match self {
			JsonError::FailedToCreateDirectory(err) => Some(err),
			JsonError::FailedToCreateJsonFile(err) => Some(err),
			JsonError::FailedToWriteJsonAbiFile(err) => Some(err),
		}
	}
}

/// Writes generated abi JSON file to destination in default target directory.
///
/// # Note
///
/// The generated JSON information may be used by offline tools around WebJS for example.
pub fn write_json_abi(intf: &items::Interface) -> JsonResult<()> {
	use std::{env, fs, path};

	let target = {
		let mut target =
			path::PathBuf::from(env::var("CARGO_TARGET_DIR").unwrap_or(".".to_owned()));
		target.push("target");
		target.push("json");
		fs::create_dir_all(&target).map_err(|err| JsonError::failed_to_create_dir(err))?;
		target.push(&format!("{}.json", intf.name()));
		target
	};

	let mut f =
		fs::File::create(target).map_err(|err| JsonError::failed_to_create_json_file(err))?;

	let abi: Abi = intf.into();

	serde_json::to_writer_pretty(&mut f, &abi)
		.map_err(|err| JsonError::failed_to_write_json_abi_file(err))?;

	Ok(())
}

#[derive(Serialize, Debug)]
pub struct FunctionEntry {
    pub name: String,
    #[serde(rename = "inputs")]
    pub arguments: Vec<Argument>,
    pub outputs: Vec<Argument>,
    pub constant: bool,
}

#[derive(Serialize, Debug)]
pub struct Argument {
    pub name: String,
    #[serde(rename = "type")]
    pub type_: String,
}

#[derive(Serialize, Debug)]
pub struct ConstructorEntry {
    #[serde(rename = "inputs")]
    pub arguments: Vec<Argument>,
}

#[derive(Serialize, Debug)]
#[serde(tag = "type")]
pub enum AbiEntry {
    #[serde(rename = "event")]
    Event(EventEntry),
    #[serde(rename = "function")]
    Function(FunctionEntry),
    #[serde(rename = "constructor")]
    Constructor(ConstructorEntry),
}

#[derive(Serialize, Debug)]
pub struct EventInput {
    pub name: String,
    #[serde(rename = "type")]
    pub type_: String,
    pub indexed: bool,
}

#[derive(Serialize, Debug)]
pub struct EventEntry {
    pub name: String,
    pub inputs: Vec<EventInput>,
}

#[derive(Serialize, Debug)]
pub struct Abi(pub Vec<AbiEntry>);

impl<'a> From<&'a items::Interface> for Abi {
    fn from(intf: &items::Interface) -> Self {
        let mut result = Vec::new();
        for item in intf.items() {
            match *item {
                items::Item::Event(ref event) => result.push(AbiEntry::Event(event.into())),
                items::Item::Signature(ref signature) => result.push(AbiEntry::Function(signature.into())),
                _ => {}
            }
        }

        if let Some(constructor) = intf.constructor() {
            result.push(AbiEntry::Constructor(FunctionEntry::from(constructor).into()));
        }

        Abi(result)
    }
}

impl<'a> From<&'a items::Event> for EventEntry {
    fn from(item: &items::Event) -> Self {
        EventEntry {
            name: item.name.to_string(),
            inputs: item.indexed
                .iter()
                .map(|&(ref pat, ref ty)|
                    EventInput {
                        name: quote! { #pat }.to_string(),
                        type_: utils::canonicalize_type(ty),
                        indexed: true,
                    }
                )
                .chain(
                    item.data
                        .iter()
                        .map(|&(ref pat, ref ty)|
                            EventInput {
                                name: quote! { #pat }.to_string(),
                                type_: utils::canonicalize_type(ty),
                                indexed: false,
                            }
                        )
                    )
                .collect(),
        }
    }
}

impl<'a> From<&'a items::Signature> for FunctionEntry {
    fn from(item: &items::Signature) -> Self {
        FunctionEntry {
            name: item.name.to_string(),
            arguments: item.arguments
                .iter()
                .map(|&(ref pat, ref ty)|
                    Argument {
                        name: quote! { #pat }.to_string(),
                        type_: utils::canonicalize_type(ty),
                    }
                )
                .collect(),
            outputs: item.return_types
                .iter()
                .enumerate()
                .map(|(idx, ty)| Argument { name: format!("returnValue{}", idx), type_: utils::canonicalize_type(ty) })
                .collect(),
            constant: item.is_constant,
        }
    }
}

impl From<FunctionEntry> for ConstructorEntry {
    fn from(func: FunctionEntry) -> Self {
        ConstructorEntry { arguments: func.arguments }
    }
}