~torresjrjr/dc

ref: 8ceb910df45458ad9590c403d85cbcbd9312f664 dc/dc.ha -rw-r--r-- 5.8 KiB
8ceb910dByron Torres handle io::close errors 3 months ago
                                                                                
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
use ascii;
use bufio;
use encoding::utf8;
use fmt;
use fs;
use getopt;
use io;
use math;
use os;
use os::exec;
use strconv;
use strings;

let S: []f64 = [];

export fn main() void = {
	const help: [_]getopt::help = [
		"desk calculator",
		"[file ...]",
	];
	const cmd = getopt::parse(os::args, help...);
	defer getopt::finish(&cmd);

	static const buf: [1]u8 = [0...];

	for (let i = 0z; i < len(cmd.args); i += 1) {
		const filename = switch (cmd.args[i]) {
		case "-" =>
			fmt::fatal("dc: invalid filename '-'");
		case "" =>
			fmt::fatal("dc: invalid filename ''");
		case =>
			yield cmd.args[i];
		};

		const file = match (os::open(filename)) {
		case let f: io::file =>
			yield f;
		case let err: fs::error =>
			fmt::fatal("dc: {} '{}'", fs::strerror(err), filename);
		};
		defer io::close(file)!;

		const in = bufio::buffered(file, buf, []);
		match (dc(&in)) {
		case void =>
			void;
		case io::error =>
			fmt::fatal("dc: IO error");
		};
	};

	const in = bufio::buffered(os::stdin, buf, []);
	match (dc(&in)) {
	case void =>
		void;
	case io::error =>
		fmt::fatal("dc: IO error");
	};
};

fn dc(in: *bufio::bufstream) (void | io::error) = {
	for (true) {
		const r = match (bufio::scanrune(&in.stream)) {
		case utf8::invalid =>
			fmt::fatal("dc: invalid utf8 input");
		case io::error =>
			fmt::fatal("dc: IO error");
		case io::EOF =>
			break;
		case let r: rune =>
			yield r;
		};

		if (!ascii::isgraph(r)) {
			continue;
		};

		if (ascii::isdigit(r)) {
			bufio::unreadrune(in, r);
			push(scan_number(in));
			continue;
		};

		if (r == '_') {
			push(-scan_number(in));
			continue;
		};

		switch (r) {
		// misc
		case 'q' =>
			os::exit(0);
		case '!' =>
			const cmdline = match (bufio::scanline(&in.stream)) {
			case io::error =>
				fmt::fatal("dc: IO error");
			case io::EOF =>
				fmt::errorln("dc: no shell command given")?;
				continue;
			case let input: []u8 =>
				yield match (strings::try_fromutf8(input)) {
				case utf8::invalid =>
					fmt::errorln("dc: invalid shell command input")?;
					continue;
				case let c: str =>
					yield c;
				};
			};
			const argv = strings::split(cmdline, " ");
			if (len(argv) == 0) {
				continue;
			};
			const cmd = os::exec::cmd(argv[0], argv[1..]...)!; //TODO

			const pipe = os::exec::pipe();
			os::exec::addfile(&cmd, pipe.1, os::stdout_file);

			const proc = os::exec::start(&cmd)!; //TODO
			io::close(pipe.1)!;

			let data = io::drain(pipe.0);
			io::close(pipe.0)!;

			const status = os::exec::wait(&proc);
		// printing
		case 'p' =>
			if (len(S) == 0) {
				fmt::errorln("dc: stack empty")?;
				continue;
			};
			fmt::println(peek())?;
		case 'n' =>
			if (len(S) == 0) {
				fmt::errorln("dc: stack empty")?;
				continue;
			};
			fmt::println(pop())?;
		case 'f' =>
			for (let i = len(S) - 1; i < len(S); i -= 1) {
				fmt::println(S[i])?;
			};
		// stack control
		case 'c' =>
			clear();
		case 'd' =>
			if (len(S) == 0) {
				fmt::errorln("dc: stack empty")?;
				continue;
			};
			push(peek());
		case 'r' =>
			if (len(S) < 2) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const b = pop();
			const a = pop();
			push(b);
			push(a);
		case 'R' =>
			let n = pop(): int;
			if (n > 1) {
				const l = len(S): int;
				const n = if (n < l) n else l;
				const i = l - n;
				const a = S[i];
				delete(S[i]);
				append(S, a);
			} else if (n < -1) {
				const l = len(S): int;
				const n = if (-n < l) -n else l;
				const i = l - n;
				const a = pop();
				insert(S[i], a);
			};
		// arithmetic
		case '+' =>
			if (len(S) < 2) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const b = pop();
			const a = pop();
			push(a + b);
		case '-' =>
			if (len(S) < 2) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const b = pop();
			const a = pop();
			push(a - b);
		case '*' =>
			if (len(S) < 2) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const b = pop();
			const a = pop();
			push(a * b);
		case '/' =>
			if (len(S) < 2) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const b = pop();
			const a = pop();
			push(a / b);
		case '%' =>
			if (len(S) < 2) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const b = pop();
			const a = pop();
			push(math::modf64(a, b));
		case '^' =>
			if (len(S) < 2) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const b = pop();
			const a = pop();
			push(math::powf64(a, b));
		case 'v' =>
			if (len(S) < 1) {
				fmt::errorln("dc: stack has too few elements")?;
				continue;
			};
			const a = pop();
			push(math::sqrtf64(a));
		case =>
			fmt::errorfln("dc: unimplemented '{}'", r)?;
		};
	};
};

@noreturn fn usage_exit(help: []getopt::help) void = {
	getopt::printusage(os::stderr, os::args[0], help);
	os::exit(1);
};

fn scan_number(in: *bufio::bufstream) f64 = {
	let num: []u8 = [];
	defer free(num);
	let seen_decimal = false;
	for (true) {
		const r = match (bufio::scanrune(in)) {
		case utf8::invalid =>
			fmt::fatal("dc: invalid utf8 input");
		case io::error =>
			fmt::fatal("dc: IO error");
		case io::EOF =>
			yield ' ';
		case let r: rune =>
			yield r;
		};
		if (ascii::isdigit(r) || (!seen_decimal && r == '.')) {
			append(num, r: u32: u8);
			if (r == '.') {
				seen_decimal = true;
			};
		} else {
			bufio::unreadrune(in, r);
			match (strconv::stof64(strings::fromutf8(num))) {
			case (strconv::invalid | strconv::overflow) =>
				abort("dc: invalid numerical input");
			case let n: f64 =>
				return n;
			};
		};
	};
	abort("Unreachable");
};

fn pop() f64 = {
	const a = S[len(S) - 1];
	delete(S[len(S) - 1]);
	return a;
};

fn push(el: f64) void = {
	append(S, el);
};

fn peek() f64 = {
	return S[len(S) - 1];
};

fn clear() void = {
	for (len(S) != 0) {
		delete(S[len(S) - 1]);
	};
};