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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
use std::error::{Error};
use std::fmt::{self, Debug, Display, Formatter};
use super::engine::{glsp, Guard, Span, with_vm};
use super::val::{Val};
use super::vm::{Frame};
use super::wrap::{ToVal};

pub type GResult<T> = Result<T, GError>;

/**
The error type generated by GameLisp code.

[`GResult<T>`](type.GResult.html) is an alias for `Result<T, GError>`.

The easiest way to generate an error yourself is by using one of the macros 
[`bail!`](macro.bail.html), [`ensure!`](macro.ensure.html) or [`error!`](macro.error.html).

The [`macro-no-op`](https://gamelisp.rs/std/macro-no-op) signal is represented by a special kind 
of `GError` which is not caught by [`try`](https://gamelisp.rs/std/try) or 
[`try-verbose`](https://gamelisp.rs/std/try-verbose). This means that in order to trigger a 
[`macro_no_op!`](macro.macro_no_op.html), the enclosing function must return `GResult<T>`.

The [`with_source` method](#method.with_source) can be used to chain together two `GErrors`, 
or to chain an arbitrary [`Error`](https://doc.rust-lang.org/std/error/trait.Error.html) type
onto a `GError`.
*/

pub struct GError {
	pub(crate) payload: Box<Payload>
}

//we separate the GError from its Payload to make GResult several words smaller. the
//only trade-off is one extra allocation when an error does occur.
pub(crate) enum Payload {
	Error {
		val: Val,
		file_location: Option<String>,
		stack_trace: Option<String>,

		defer_chain: Option<GError>,
		source: Option<Box<dyn Error + 'static>>
	},
	MacroNoOp
}

impl GError {
	pub fn new() -> GError {
		GError::from_str("explicit call to bail!, error!, or GError::new")
	}

	pub fn from_str(st: &str) -> GError {
		GError::from_val(st)
	}

	pub fn from_val<T: ToVal>(t: T) -> GError {
		let val = t.to_val().unwrap_or(Val::Nil);
		let file_location = glsp::file_location();
		let stack_trace = if glsp::errors_verbose() {
			Some(glsp::stack_trace())
		} else {
			None
		};

		GError {
			payload: Box::new(Payload::Error {
				val,
				file_location,
				stack_trace,
				defer_chain: None,
				source: None
			})
		}
	}

	pub fn macro_no_op() -> GError {
		with_vm(|vm| {
			if vm.in_expander() {
				GError {
					payload: Box::new(Payload::MacroNoOp)
				}
			} else {
				GError::from_str("(macro-no-op) called outside of any macro expander")
			}
		})
	}

	/**
	Returns `true` if this error was generated using [`macro_no_op!`](macro.macro_no_op.html) or 
	[`GError::macro_no_op`](#method.macro_no_op).
	*/
	pub fn is_macro_no_op(&self) -> bool {
		match &*self.payload {
			Payload::MacroNoOp => true,
			Payload::Error { .. } => false
		}
	}

	/**
	Returns the error's payload. Panics if this error is a macro-no-op.
	*/
	pub fn val(&self) -> Val {
		match &*self.payload {
			Payload::MacroNoOp => panic!(),
			Payload::Error { val, .. } => val.clone()
		}
	}

	/**
	Returns the error's saved stack trace.

	Errors invoked in a dynamic context where verbose errors are disabled (for example,
	the dynamic scope of a [`try` form](https://gamelisp.rs/std/try)) will not have a
	stack trace.
	*/
	pub fn stack_trace(&self) -> Option<&str> {
		match &*self.payload {
			Payload::MacroNoOp => panic!(),
			Payload::Error { stack_trace, .. } => stack_trace.as_ref().map(|s| &**s)
		}
	}

	#[allow(dead_code)]
	pub(crate) fn defer_chain(&self) -> Option<&GError> {
		match &*self.payload {
			Payload::MacroNoOp => panic!(),
			Payload::Error { defer_chain, .. } => defer_chain.as_ref()
		}
	}

	pub(crate) fn chain_defer_error(&mut self, defer_error: GError) {
		if self.is_macro_no_op() {
			*self = defer_error;
		} else {
			match &mut *self.payload {
				Payload::Error { ref mut defer_chain, .. } => {
					if let Some(ref mut defer_chain) = defer_chain {
						defer_chain.chain_defer_error(defer_error);
					} else {
						*defer_chain = Some(defer_error);
					}
				}
				Payload::MacroNoOp => unreachable!()
			}
		}
	}

	/**
	Chains another error onto this `GError`.

	This can be used to wrap arbitrary [`Error` types][0] in a `GError`.

	[0]: https://doc.rust-lang.org/std/error/trait.Error.html

		let words = match fs::read_to_string("words.txt") {
			Ok(words) => words,
			Err(fs_err) => {
				return Err(error!("failed to open words.txt").with_source(fs_err))
			}
		};
	*/
	pub fn with_source(mut self, source_to_add: impl Error + 'static) -> GError {
		match &mut *self.payload {
			Payload::MacroNoOp => panic!(),
			Payload::Error { source, .. } => *source = Some(Box::new(source_to_add))
		}

		self
	}

	#[doc(hidden)]
	pub fn new_at(span: Span) -> GError {
		glsp::push_frame(Frame::ErrorAt(span));
		let _guard = Guard::new(|| glsp::pop_frame());

		GError::new()
	}

	#[doc(hidden)]
	pub fn from_str_at(span: Span, st: &str) -> GError {
		glsp::push_frame(Frame::ErrorAt(span));
		let _guard = Guard::new(|| glsp::pop_frame());

		GError::from_str(st)
	}

	#[doc(hidden)]
	pub fn from_val_at<T: ToVal>(span: Span, t: T) -> GError {
		glsp::push_frame(Frame::ErrorAt(span));
		let _guard = Guard::new(|| glsp::pop_frame());

		GError::from_val(t)
	}
}

impl Error for GError {
	fn source(&self) -> Option<&(dyn Error + 'static)> {
		if let Payload::Error { source: Some(ref source), .. } = *self.payload {
			Some(source.as_ref())
		} else {
			None
		}
	}
}

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

impl Display for GError {
	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
		match &*self.payload {
			Payload::MacroNoOp => panic!(),
			Payload::Error { val, file_location, stack_trace, source, defer_chain } => {
				match (file_location, stack_trace) {
					(&None, &None) => {
						write!(f, "{:?}", val)
					}
					(&Some(ref file_location), &None) => {
						write!(f, "{}: {:?}", file_location, val)
					}
					(_, &Some(ref stack_trace)) => {
						write!(f, "stack trace:\n")?;
						for line in stack_trace.lines() {
							write!(f, "    {}\n", line)?;
						}

						//we print error values using {} rather than {:?}. this is because most
						//error messages are strings, and escaping curly braces can be confusing.
						//"clause must end with }" becomes "clause must end with }}".
						if let Some(ref source) = *source {
							write!(f, "\nerrors:")?;

							fn write_source(
								f: &mut Formatter, 
								source: &(dyn Error + 'static)
							) -> fmt::Result {
								//if the source is a GError, we can't stringify it using {},
								//because that would print its full stack trace again
								match source.downcast_ref::<GError>() {
									Some(error) => write!(f, "\n    {}", error.val())?,
									None => write!(f, "\n    {}", source)?
								}

								if let Some(source2) = source.source() {
									write_source(f, source2)
								} else {
									Ok(())
								}
							}

							write!(f, "\n    {}", &val)?;
							write_source(f, source.as_ref())?;
						} else {
							write!(f, "\nerror: {}", &val)?;
						}

						if let Some(ref defer_chain) = defer_chain {
							write!(f, "\n\nwhile this error was unwinding, \
							         a (defer) form also failed:\n")?;
							write!(f, "\n{}", defer_chain)?;
						}

						Ok(())
					}
				}
			}
		}
	}
}

/**
Constructs a [`GError`](struct.GError.html) by formatting a string.

This is usually more convenient than calling `GError`'s constructors directly.

`error!()` is equivalent to [`GError::new()`][0].

[0]: struct.GError.html#method.new

`error!(x)` is equivalent to [`GError::from_val(x)`][1].

[1]: struct.GError.html#method.from_val

`error!("{}", a)` is equivalent to [`GError::from_str(&format!("{}", a))`][2].

[2]: struct.GError.html#method.from_str
*/

#[macro_export]
macro_rules! error {
	() => ($crate::GError::new());
	($val:expr) => ($crate::GError::from_val($val));
	($fmt:literal, $($arg:tt)+) => ($crate::GError::from_str(&format!($fmt, $($arg)+)));
}

#[doc(hidden)]
#[macro_export]
macro_rules! error_at {
	($span:expr) => ($crate::GError::new_at($span));
	($span:expr, $val:expr) => ($crate::GError::from_val_at($span, $val));
	($span:expr, $fmt:literal, $($arg:tt)+) => (
		$crate::GError::from_str_at($span, &format!($fmt, $($arg)+))
	);
}

/**
Constructs a [`GError`](struct.GError.html) and returns it.

The arguments to `bail!` are the same as the arguments to [`error!`](macro.error.html).
For example, `bail!(x)` is equivalent to:
	
	return Err(GError::from_val(x))
*/

#[macro_export]
macro_rules! bail {
	($($arg:tt)*) => (return Err($crate::error!($($arg)*)));
}

#[doc(hidden)]
#[macro_export]
macro_rules! bail_at {
	($span:expr) => (return Err($crate::error_at!($span)));
	($span:expr, $($arg:tt)+) => (return Err($crate::error_at!($span, $($arg)*)));
}

/**
Tests a condition, returning an error if the result is `false`.

The first argument must be an expression of type `bool`. If it evaluates to `false`, 
the remaining arguments are all passed to [`bail!`](macro.bail.html). If it evaluates to `true`,
those arguments aren't evaluated at all.
*/

#[macro_export]
macro_rules! ensure {
	($condition:expr) => (
		if !($condition) {
			bail!("ensure!({}) failed", stringify!($condition))
		}
	);
	($condition:expr, $($arg:tt)*) => (
		if !($condition) {
			bail!($($arg)*)
		}
	);
}

#[doc(hidden)]
#[macro_export]
macro_rules! ensure_at {
	($span:expr, $condition:expr) => (
		if !($condition) {
			bail_at!($span, "ensure!({}) failed", stringify!($condition))
		}
	);
	($span:expr, $condition:expr, $($arg:tt)*) => (
		if !($condition) {
			bail_at!($span, $($arg)*)
		}
	);
}

/**
Constructs a [`GError`](struct.GError.html) which represents a macro-no-op, and returns it.

`macro_no_op!()` is equivalent to: 
	
	return Err(GError::macro_no_op())
*/

#[macro_export]
macro_rules! macro_no_op {
	() => (return Err($crate::GError::macro_no_op()));
}