comparison keiko/lib.c @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:bfdcc3820b32
1 /* lib.c */
2 /* Copyright (c) 2017 J. M. Spivey */
3
4 #include "primtab.h"
5
6 int lib_argc(void) {
7 return saved_argc;
8 }
9
10 void lib_argv(int n, char *s) {
11 /* Buffer overflow waiting to happen */
12 strcpy(s, saved_argv[n]);
13 }
14
15 void lib_print_num(int n) {
16 printf("%d", n);
17 }
18
19 void lib_print_string(char *s) {
20 fputs(s, stdout);
21 }
22
23 void lib_print_char(char c) {
24 putchar(c);
25 }
26
27 static FILE *infile = NULL;
28
29 int lib_open_in(char *name) {
30 FILE *f = fopen(name, "r");
31 if (f == NULL) return 0;
32 if (infile != NULL) fclose(infile);
33 infile = f;
34 return 1;
35 }
36
37 void lib_close_in(void) {
38 if (infile == NULL) return;
39 fclose(infile);
40 infile = NULL;
41 }
42
43 void lib_read_char(char *p) {
44 FILE *f = (infile == NULL ? stdin : infile);
45 int ch = fgetc(f);
46 *p = (ch == EOF ? 127 : ch);
47 }
48
49 #define PRIMS(direct, indirect, wrapper) \
50 wrapper(scratch_alloc, P, I) \
51 wrapper(lib_argc, I) \
52 wrapper(lib_argv, V, I, P) \
53 wrapper(lib_print_num, V, I) \
54 wrapper(lib_print_string, V, P) \
55 wrapper(lib_print_char, V, C) \
56 wrapper(lib_open_in, I, P) \
57 wrapper(lib_close_in, V) \
58 wrapper(lib_read_char, V, P) \
59 wrapper(exit, V, I)
60
61 /* Using PPRIMTAB adds an offset to compensate for static links */
62 PPRIMTAB(PRIMS)