aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/vlib/builtin/js/builtin.v
blob: 86b60ad6e87007f4a47d152b71841fa3bcda9a60 (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
85
86
87
88
89
90
91
92
93
94
95
96
// 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 println(s any) {
	// Quickfix to properly print basic types
	// TODO: Add proper detection code for this
	JS.console.log(s.toString())
}

pub fn print(s any) {
	// TODO
	// $if js.node {
	JS.process.stdout.write(s.toString())
	// } $else {
	//	panic('Cannot `print` in a browser, use `println` instead')
	// }
}

pub fn eprintln(s any) {
	JS.console.error(s.toString())
}

pub fn eprint(s any) {
	// TODO
	// $if js.node {
	JS.process.stderr.write(s.toString())
	// } $else {
	//	panic('Cannot `eprint` in a browser, use `eprintln` instead')
	// }
}

// Exits the process in node, and halts execution in the browser
// because `process.exit` is undefined. Workaround for not having
// a 'real' way to exit in the browser.
pub fn exit(c int) {
	JS.process.exit(c)
	js_throw('exit($c)')
}

pub fn unwrap(opt any) any {
	o := &Option(opt)
	if o.state != 0 {
		js_throw(o.err)
	}
	return opt
}

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

struct Option {
	state byte
	err   Error
}

pub struct Error {
pub:
	msg  string
	code int
}

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" }'
}

pub fn error(s string) Option {
	return Option{
		state: 2
		err: Error{
			msg: s
		}
	}
}

pub fn error_with_code(s string, code int) Option {
	return Option{
		state: 2
		err: Error{
			msg: s
			code: code
		}
	}
}