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