| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- /* m2compiler-V3 runtime shim (C).
- *
- * Bridges Modula-2 external procedures to the host. Memory layout
- * matches the compiler's: a STRING (ARRAY OF CHAR) value is a
- * descriptor [0] = LONGCARD element count, then the bytes; the
- * compiler passes the descriptor's address as an `l`.
- *
- * Linked with every V3 program image.
- */
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- /* Write the contents of a string descriptor to fd 1. Returns the
- number of bytes written. */
- long m2write(long *desc)
- {
- long n = desc[0];
- if (n > 0)
- write(1, (char *)(desc + 1), (size_t)n);
- return n;
- }
- /* Write a newline to fd 1. */
- long m2writeln(void)
- {
- write(1, "\n", 1);
- return 0;
- }
- /* Read one character from stdin (0 at EOF). */
- long m2readchar(void)
- {
- int c = getchar();
- return (c == EOF) ? 0 : c;
- }
- /* Read a signed decimal integer from stdin, skipping leading
- whitespace. The first non-digit after the number is consumed. */
- long m2readint(void)
- {
- long v = 0;
- int c;
- int neg = 0;
- do { c = getchar(); } while (c == ' ' || c == '\t' ||
- c == '\n' || c == '\r');
- if (c == '-') { neg = 1; c = getchar(); }
- while (c >= '0' && c <= '9') {
- v = v * 10 + (c - '0');
- c = getchar();
- }
- return neg ? -v : v;
- }
- /* Set a string descriptor's logical length (header). */
- long m2setlen(long *desc, long n)
- {
- desc[0] = n;
- return n;
- }
- /* Write a single character (byte) to fd 1. */
- long m2writechar(long c)
- {
- char ch = (char)c;
- write(1, &ch, 1);
- return 0;
- }
- /* Write a signed decimal integer to fd 1. */
- long m2writeint(long v)
- {
- char buf[32];
- int i = 0;
- int neg = 0;
- unsigned long u;
- if (v < 0) { neg = 1; u = (unsigned long)(-v); }
- else u = (unsigned long)v;
- do { buf[i++] = (char)('0' + (u % 10)); u /= 10; } while (u != 0);
- if (neg) buf[i++] = '-';
- while (i > 0)
- write(1, &buf[--i], 1);
- return 0;
- }
- /* Terminate the process. */
- long m2exit(long code)
- {
- exit((int)code);
- return 0;
- }
|