aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/vlib/builtin/js/builtin.v
blob: 7c82d1ad98b324e3dae21f28f6ca88ebe34081d9 (plain)
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
// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

module builtin

fn (a any) toString()

pub fn panic(s string) {
	eprintln('V panic: $s')
	exit(1)
}

// 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()`
pub struct Error {
pub:
	msg  string
	code int
}

struct None__ {
	msg  string
	code int
}

fn (_ None__) str() string {
	return 'none'
}

pub const none__ = IError(None__{'', 0})

pub struct Option {
	state byte
	err   IError = none__
}

pub fn (err IError) str() string {
	return match err {
		None__ { 'none' }
		Error { err.msg }
		else { '$err.type_name(): $err.msg' }
	}
}

pub fn (o Option) str() string {
	if o.state == 0 {
		return 'Option{ ok }'
	}
	if o.state == 1 {
		return 'Option{ none }'
	}
	return 'Option{ error: "$o.err" }'
}

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 {
	// trace_error(message)
	return &Error{
		msg: message
	}
}

// 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
	}
}