2021-01-18 13:20:06 +01:00
|
|
|
// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
|
2019-09-14 22:48:30 +02:00
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
module builtin
|
|
|
|
|
2020-12-08 17:49:20 +01:00
|
|
|
fn (a any) toString()
|
|
|
|
|
2021-10-20 15:02:21 +02:00
|
|
|
[noreturn]
|
2020-06-20 13:22:49 +02:00
|
|
|
pub fn panic(s string) {
|
2021-09-11 13:24:47 +02:00
|
|
|
eprintln('V panic: $s\n$js_stacktrace()')
|
2020-06-20 13:22:49 +02:00
|
|
|
exit(1)
|
2020-06-04 20:26:18 +02:00
|
|
|
}
|
2020-11-24 12:54:26 +01:00
|
|
|
|
2021-08-25 13:40:53 +02:00
|
|
|
// IError holds information about an error instance
|
|
|
|
pub interface IError {
|
|
|
|
msg string
|
|
|
|
code int
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error is the default implementation of IError, that is returned by e.g. `error()`
|
2021-02-28 21:20:21 +01:00
|
|
|
pub struct Error {
|
|
|
|
pub:
|
|
|
|
msg string
|
|
|
|
code int
|
2020-11-24 12:54:26 +01:00
|
|
|
}
|
|
|
|
|
2021-08-25 13:40:53 +02:00
|
|
|
struct None__ {
|
|
|
|
msg string
|
|
|
|
code int
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (_ None__) str() string {
|
|
|
|
return 'none'
|
|
|
|
}
|
|
|
|
|
2021-08-30 19:47:18 +02:00
|
|
|
pub const none__ = IError(None__{'', 0})
|
|
|
|
|
|
|
|
pub struct Option {
|
|
|
|
state byte
|
|
|
|
err IError = none__
|
|
|
|
}
|
|
|
|
|
2021-08-25 13:40:53 +02:00
|
|
|
pub fn (err IError) str() string {
|
|
|
|
return match err {
|
|
|
|
None__ { 'none' }
|
|
|
|
Error { err.msg }
|
2021-09-16 06:07:48 +02:00
|
|
|
else { 'Error: $err.msg' }
|
2021-08-25 13:40:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-24 12:54:26 +01:00
|
|
|
pub fn (o Option) str() string {
|
2021-03-24 19:39:59 +01:00
|
|
|
if o.state == 0 {
|
|
|
|
return 'Option{ ok }'
|
|
|
|
}
|
|
|
|
if o.state == 1 {
|
|
|
|
return 'Option{ none }'
|
|
|
|
}
|
|
|
|
return 'Option{ error: "$o.err" }'
|
2020-11-24 12:54:26 +01:00
|
|
|
}
|
|
|
|
|
2021-08-25 13:40:53 +02:00
|
|
|
fn trace_error(x string) {
|
|
|
|
eprintln('> ${@FN} | $x')
|
|
|
|
}
|
|
|
|
|
|
|
|
// error returns a default error instance containing the error given in `message`.
|
|
|
|
// Example: `if ouch { return error('an error occurred') }`
|
|
|
|
[inline]
|
|
|
|
pub fn error(message string) IError {
|
2021-08-29 13:27:17 +02:00
|
|
|
// trace_error(message)
|
2021-08-25 13:40:53 +02:00
|
|
|
return &Error{
|
|
|
|
msg: message
|
2020-11-24 12:54:26 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-25 13:40:53 +02:00
|
|
|
// error_with_code returns a default error instance containing the given `message` and error `code`.
|
|
|
|
// `if ouch { return error_with_code('an error occurred', 1) }`
|
|
|
|
[inline]
|
|
|
|
pub fn error_with_code(message string, code int) IError {
|
|
|
|
// trace_error('$message | code: $code')
|
|
|
|
return &Error{
|
|
|
|
msg: message
|
|
|
|
code: code
|
2020-11-24 12:54:26 +01:00
|
|
|
}
|
|
|
|
}
|