diff options
Diffstat (limited to 'sys/cmd/rc')
-rw-r--r-- | sys/cmd/rc/code.c | 164 | ||||
-rw-r--r-- | sys/cmd/rc/exec.c | 576 | ||||
-rw-r--r-- | sys/cmd/rc/exec.h | 33 | ||||
-rw-r--r-- | sys/cmd/rc/input.c | 1045 | ||||
-rw-r--r-- | sys/cmd/rc/io.c | 359 | ||||
-rw-r--r-- | sys/cmd/rc/lex.c | 207 | ||||
-rw-r--r-- | sys/cmd/rc/main.c | 47 | ||||
-rw-r--r-- | sys/cmd/rc/parse.c | 1418 | ||||
-rw-r--r-- | sys/cmd/rc/parse.h | 107 | ||||
-rw-r--r-- | sys/cmd/rc/prompt.c | 17 | ||||
-rw-r--r-- | sys/cmd/rc/rc.h | 196 | ||||
-rw-r--r-- | sys/cmd/rc/rules.mk | 29 | ||||
-rw-r--r-- | sys/cmd/rc/syntax.y | 104 | ||||
-rw-r--r-- | sys/cmd/rc/sys.c | 139 | ||||
-rw-r--r-- | sys/cmd/rc/tree.c | 79 | ||||
-rw-r--r-- | sys/cmd/rc/util.c | 65 | ||||
-rw-r--r-- | sys/cmd/rc/var.c | 271 | ||||
-rw-r--r-- | sys/cmd/rc/wait.c | 3 |
18 files changed, 4859 insertions, 0 deletions
diff --git a/sys/cmd/rc/code.c b/sys/cmd/rc/code.c new file mode 100644 index 0000000..6deed89 --- /dev/null +++ b/sys/cmd/rc/code.c @@ -0,0 +1,164 @@ +#include "rc.h" +#include "parse.h" +#include "exec.h" + +// ----------------------------------------------------------------------- +// types + +struct Interpreter +{ + int i, cap; + Code *code; +}; + +Code *compiled = nil; +static struct Interpreter interpreter; +#define emiti(x) ((void)(interpreter.i != interpreter.cap || grow()), interpreter.code[interpreter.i].i = (x), interpreter.i++) +#define emitf(x) ((void)(interpreter.i != interpreter.cap || grow()), interpreter.code[interpreter.i].f = (x), interpreter.i++) +#define emits(x) ((void)(interpreter.i != interpreter.cap || grow()), interpreter.code[interpreter.i].s = (x), interpreter.i++) + +static +int +grow(void) +{ + interpreter.cap += 100; + interpreter.code = erealloc(interpreter.code, sizeof(*interpreter.code)*interpreter.cap); + memset(interpreter.code+interpreter.cap-100, 0, 100*sizeof(*interpreter.code)); + + return 0; +} + +static +void +stashaddr(int a) +{ + if(interpreter.i <= a || a < 0) + fatal("bad address %d in interpreter", a); + + interpreter.code[a].i = interpreter.i; +} + +static +void +walk(Tree *node) +{ + int p; + Tree *n; + + if(!node) + return; + + switch(node->type){ + default: + print(errio, "bad type %d in interpreter walk\n", node->type); + break; + + case '$': + emitf(Xmark); + walk(node->child[0]); + emitf(Xdollar); + break; + + case '&': + emitf(Xasync); + p = emiti(0); + emitf(Xexit); + stashaddr(p); + break; + + case ';': + walk(node->child[0]); + walk(node->child[1]); + break; + + case '^': + emitf(Xmark); + walk(node->child[1]); + emitf(Xmark); + walk(node->child[0]); + emitf(Xconcatenate); + break; + + case Targs: + walk(node->child[1]); + walk(node->child[0]); + break; + + case Tparen: case Tblock: + walk(node->child[0]); + break; + + case Tbasic: + emitf(Xmark); + walk(node->child[0]); + emitf(Xbasic); + break; + + case Tword: + emitf(Xword); + emits(strdup(node->str)); + break; + + case '=': + for(n=node; node && node->type == '='; node = node->child[2]) + ; + if(node){ + for(node=n; node->type=='='; node = node->child[2]){ + emitf(Xmark); + walk(node->child[1]); + emitf(Xmark); + walk(node->child[0]); + emitf(Xlocal); + } + walk(node); + for(node=n; node->type=='='; node = node->child[2]) + emitf(Xunlocal); + }else{ + for(node=n; node; node=node->child[2]){ + emitf(Xmark); + walk(node->child[1]); + emitf(Xmark); + walk(node->child[0]); + emitf(Xassign); + } + } + node = n; + break; + } +} + +// ----------------------------------------------------------------------- +// main exports + +void +freecode(Code *c) +{ + if(--c[0].i!=0) + return; + efree(c); +} + +Code * +copycode(Code *c) +{ + c[0].i++; + return c; +} + +int +compile(Tree *node) +{ + flush(errio); + print(errio, "%t\n", node); + + interpreter.i = 0; + emiti(1); // reference count + + walk(node); + + emitf(Xreturn); + emitf(nil); + + compiled = interpreter.code; + return 0; +} diff --git a/sys/cmd/rc/exec.c b/sys/cmd/rc/exec.c new file mode 100644 index 0000000..868b1dc --- /dev/null +++ b/sys/cmd/rc/exec.c @@ -0,0 +1,576 @@ +#include "rc.h" +#include "exec.h" + +#include <sys/wait.h> + +int yyparse(void); + +struct Builtin{ + char *name; + void (*func)(void); +}; + +// ----------------------------------------------------------------------- +// globals + +static Word nullpath = { .str="", .link=nil }; + +struct Builtin builtin[]={ + {".", xdot}, + 0, +}; + +/* stub out until we need */ +void Xasync(void){} +void Xconcatenate(void){} +void Xexit(void){} +void Xfunc(void){} +void Xfor(void){} +void Xglob(void){} +void Xjump(void){} +void Xmatch(void){} +void Xpipe(void){} +void Xread(void){} +// ----------------------------------------------------------------------- +// internal + +/* words and lists */ + +static +void +pushword(char *str) +{ + if(!shell->args) + fatal("attempt to push on empty argument stack"); + + shell->args->word = makeword(str, shell->args->word); +} + +static +void +popword(void) +{ + Word *w; + if(!shell->args) + fatal("tried to pop word on empty argument stack"); + + w = shell->args->word; + if(!w) + fatal("tried to pop word but nothing there"); + + shell->args->word = w->link; + efree(w->str); + efree(w); +} + +static +Word* +copywords(Word *a, Word *tail) +{ + Word *v = nil, **end; + + for(end=&v; a; a = a->link,end=&(*end)->link) + *end = makeword(a->str, nil); + *end = tail; + + return v; +} + +static +void +freewords(Word *w) +{ + Word *n; + while(w){ + efree(w->str); + n = w->link; + efree(w); + w = n; + } +} + +static +void +freelist(Word *w) +{ + Word *n; + while(w){ + n = w->link; + efree(w->str); + efree(w); + w = n; + } + +} + +static +void +pushlist(void) +{ + List *stack = emalloc(sizeof(*stack)); + + stack->word = nil; + stack->link = shell->args; + + shell->args = stack; +} + +static +void +poplist(void) +{ + List *stack = shell->args; + if(!stack) + fatal("attempted to pop an empty argument stack"); + + freelist(stack->word); + shell->args = stack->link; + efree(stack); +} + +/* system interop */ +static +Word* +path(char *w) +{ + Word *path; + + if(strncmp(w, "/", 1)==0 + || strncmp(w, "./", 2)==0 + || strncmp(w, "../", 3)==0 + || (path = var("path")->val)==0) + path=&nullpath; + + return path; +} + +static +void +xx(void) +{ + popword(); // "exec" + if(!shell->args->word){ + Xerror("empty argument list"); + return; + } + + execute(shell->args->word, path(shell->args->word->str)); + poplist(); +} + +static +int +xforkx(void) +{ + int n, pid; + char buf[ERRMAX]; + + switch(pid=fork()){ + case -1: + return -1; + case 0: // child + clearwait(); + pushword("exec"); + xx(); + exit(1); + /*unreachable*/ + default: + addwait(pid); + return pid; + } +} + +/* redirections */ +void +pushredir(int type, int from, int to) +{ + Redir *r = emalloc(sizeof(*r)); + + r->type = type; + r->from = from; + r->to = to; + r->link = shell->redir; + + shell->redir = r; +} + +/* byte code */ +static +void +run(Code *c, int pc, Var *local) +{ + Thread *new = emalloc(sizeof(*new)); + + new->code.i = pc; + new->code.exe = copycode(c); + new->args = nil; + new->local = local; + new->cmd.path = nil; + new->cmd.io = nil; + new->flag.eof = 0; + new->line = 1; + new->link = shell; + + shell = new; +} + +// ----------------------------------------------------------------------- +// exported builtins + +// XXX: find a better place for these +Word* +makeword(char *str, Word *link) +{ + Word *w = emalloc(sizeof(*w)); + + w->str = strdup(str); + w->link = link; + + return w; +} + +void +freeword(Word *word) +{ + Word *n; + + while(word){ + efree(word->str); + n = word->link; + efree(word); + word = n; + } +} + +int +count(Word *w) +{ + int n; + for(n = 0; w; n++) + w = w->link; + return n; +} + +// ----------------------------------------------------------------------- +// builtins + +static Code dotcmd[14] = +{ + [0] = {.i = 1}, + [1] = {.f = Xmark}, + [2] = {.f = Xword}, + [3] = {.s = "0"}, + [4] = {.f = Xlocal}, + [5] = {.f = Xmark}, + [6] = {.f = Xword}, + [7] = {.s = "*"}, + [8] = {.f = Xlocal}, + [9] = {.f = Xreadcmd}, + [10] = {.f = Xunlocal}, + [11] = {.f = Xunlocal}, + [12] = {.f = Xreturn}, +}; + +void +xdot(void) +{ + Word *p; + List *argv; + char *base; + int fd, iflag = 0; + Thread *old; + char file[512]; + + old = shell; + popword(); +#if 0 + if(old->args->word && strcmp(old->args->word->str, "-i")==0){ + iflag = 1; + popword(); + } +#endif + /* get input file */ + if(!old->args->word){ + Xerror("usage: . [-i] file [arg ...]\n"); + return; + } + + base = strdup(old->args->word->str); + popword(); + for(fd=-1, p=path(base); p ; p = p->link){ + strcpy(file, p->str); + + if(file[0]) + strcat(file, "/"); + strcat(file, base); + + if((fd = open(file, 0))>=0) + break; + } + + if(fd<0){ + print(errio, "%s: ", base); + //setstatus("can't open"); + Xerror(".: can't open\n"); + return; + } + /* set up for a new command loop */ + run(dotcmd, 1, nil); + pushredir(Rclose, fd, 0); + + shell->cmd.path = base; + shell->cmd.io = openfd(fd); + + /* push $* value */ + pushlist(); + shell->args->word = old->args->word; + + /* free caller's copy of $* */ + argv = old->args; + old->args = argv->link; + efree(argv); + + /* push $0 value */ + pushlist(); + pushword(base); + //ndot++; +} + +void +xboot(int argc, char *argv[]) +{ + int i; + Code bootstrap[32]; + char num[12]; + + i = 0; + bootstrap[i++].i = 1; + bootstrap[i++].f = Xmark; + bootstrap[i++].f = Xword; + bootstrap[i++].s="*"; + bootstrap[i++].f = Xassign; + bootstrap[i++].f = Xmark; + bootstrap[i++].f = Xmark; + bootstrap[i++].f = Xword; + bootstrap[i++].s="*"; + bootstrap[i++].f = Xdollar; + bootstrap[i++].f = Xword; + bootstrap[i++].s = "/dev/stdin"; + bootstrap[i++].f = Xword; + bootstrap[i++].s="."; + bootstrap[i++].f = Xbasic; + bootstrap[i++].f = Xexit; + bootstrap[i].i = 0; + + run(bootstrap, 1, nil); + pushlist(); // prime bootstrap argv + + argv0 = strdup(argv[0]); + for(i = argc-1; i > 0; --i) + pushword(argv[i]); + + /* interpreter loop */ + for(;;){ + shell->code.i++; + (*shell->code.exe[shell->code.i-1].f)(); + } +} + +// ----------------------------------------------------------------------- +// exported interpreter bytecode + +void +Xmark(void) +{ + pushlist(); +} + +void +Xerror(char *msg) +{ + print(errio, "rc: %s", msg); + flush(errio); + while(!shell->flag.i) + Xreturn(); +} + +void +Xreturn(void) +{ + Thread *run = shell; + + printf("returning\n"); + + while(run->args) + poplist(); + freecode(run->code.exe); + + shell = run->link; + efree(run); + if(!shell) + exit(0); +} + +void +Xword(void) +{ + pushword(shell->code.exe[shell->code.i++].s); +} + +void +Xdollar(void) +{ + int n; + char *s, *t; + Word *a, *star; + + if(count(shell->args->word)!=1){ + Xerror("variable name not singleton!\n"); + return; + } + s = shell->args->word->str; + // deglob(s); + n = 0; + + for(t = s;'0'<=*t && *t<='9';t++) + n = n*10+*t-'0'; + + a = shell->args->link->word; + + if(n==0 || *t) + a = copywords(var(s)->val, a); + else{ + star = var("*")->val; + if(star && 1<=n && n<=count(star)){ + while(--n) + star = star->link; + + a = makeword(star->str, a); + } + } + + poplist(); + shell->args->word = a; +} + +void +Xassign(void) +{ + Var *v; + + if(count(shell->args->word)!=1){ + Xerror("variable name not singleton!\n"); + return; + } + //deglob(runq->argv->words->word); + v = var(shell->args->word->str); + poplist(); + + //globlist(); + freewords(v->val); + v->val = shell->args->word; + v->new = 1; + if(v->update) + v->update(v); + + shell->args->word = nil; + poplist(); +} + + +void +Xreadcmd(void) +{ + Thread *root; + Word *prompt; + + flush(errio); + root = shell; + + if(yyparse()){ + exit(1); + }else{ + --root->code.i; /* re-execute Xreadcmd after codebuf runs */ + run(compiled, 1, root->local); + } + + freeparsetree(); +} + +void +Xlocal(void) +{ + if(count(shell->args->word)!=1){ + Xerror("variable name must be singleton\n"); + return; + } + //deglob(shell->args->word->str); + + shell->local = makevar(strdup(shell->args->word->str), shell->local); + shell->local->val = copywords(shell->args->link->word, nil); + shell->local->new = 1; + + poplist(); + poplist(); +} + +void +Xunlocal(void) +{ + Var *v = shell->local, *hide; + if(!v) + fatal("Xunlocal: no locals!", 0); + + printf("unlocal\n"); + + shell->local = v->link; + hide = var(v->name); + hide->new = 1; + + efree(v->name); + freewords(v->val); + efree(v); +} + +void +Xbasic(void) +{ + Var *v; + Word *arg; + int pid, status; + struct Builtin *b; + + arg = shell->args->word; + if(!arg){ + Xerror("empty argument list\n"); + return; + } + print(errio, "recieved arg: %v\n", arg); // for debugging + flush(errio); + + v = var(arg->str); + if(v->func){ + // xfunc(v); + return; + } + // see if it matches a builtin + for(b = builtin; b->name; b++){ + if(strcmp(b->name, arg->str)==0){ + b->func(); + return; + } + } + + // run the external command + if((pid = xforkx()) < 0) { + Xerror("try again"); + return; + } + + poplist(); + do{ + waitpid(pid, &status, 0); + } while(!WIFEXITED(status) && !WIFSIGNALED(status)); + + printf("done waiting\n"); +} diff --git a/sys/cmd/rc/exec.h b/sys/cmd/rc/exec.h new file mode 100644 index 0000000..ef826fb --- /dev/null +++ b/sys/cmd/rc/exec.h @@ -0,0 +1,33 @@ +#pragma once + +/* + * opcode routines + * Arguments on stack (...) + * Arguments in line [...] + * Code in line with jump around {...} + */ + +void Xasync(void); +void Xconcatenate(void); +void Xdollar(void); +void Xexit(void); +void Xfunc(void); +void Xfor(void); +void Xglob(void); +void Xjump(void); +void Xmark(void); +void Xmatch(void); +void Xpipe(void); +void Xread(void); +void Xreturn(void); +void Xlocal(void); +void Xreadcmd(void); +void Xunlocal(void); +void Xassign(void); +void Xbasic(void); // Xbasic(args) run command and wait for result +void Xerror(char*); +void Xword(void); + +/* builtin commands */ +void xdot(void); +void xboot(int argc, char *argv[]); diff --git a/sys/cmd/rc/input.c b/sys/cmd/rc/input.c new file mode 100644 index 0000000..cf05382 --- /dev/null +++ b/sys/cmd/rc/input.c @@ -0,0 +1,1045 @@ +#include "rc.h"
+#include <termios.h>
+#include <sys/ioctl.h>
+
+struct Mode {
+ ushort raw : 1;
+ ushort multiline : 1;
+ ushort mask : 1;
+ ushort defer : 1;
+ struct {
+ ushort on : 1;
+ ushort insert : 1;
+ } vi ;
+};
+
+static struct Mode mode;
+static struct termios originalterm;
+
+/*
+ * The structure represents the state during line editing.
+ * We pass this state to functions implementing specific editing
+ * functionalities
+ */
+struct TerminalState
+{
+ int ifd; /* Terminal stdin file descriptor. */
+ int ofd; /* Terminal stdout file descriptor. */
+ char *buf; /* Edited line buffer. */
+ uintptr buflen; /* Edited line buffer size. */
+ char *prompt; /* Prompt to display. */
+ uintptr plen; /* Prompt length. */
+ uintptr pos; /* Current cursor position. */
+ uintptr oldpos; /* Previous refresh cursor position. */
+ uintptr len; /* Current edited line length. */
+ uintptr cols; /* Number of columns in terminal. */
+ uintptr maxrows; /* Maximum num of rows used so far (multiline mode) */
+ int history_index; /* The history index we are currently editing. */
+};
+
+enum
+{
+ KeyNil = 0, /* nil */
+ KeyCtrlA = 1, /* Ctrl+a */
+ KeyCtrlB = 2, /* Ctrl-b */
+ KeyCtrlC = 3, /* Ctrl-c */
+ KeyCtrlD = 4, /* Ctrl-d */
+ KeyCtrlE = 5, /* Ctrl-e */
+ KeyCtrlF = 6, /* Ctrl-f */
+ KeyCtrlH = 8, /* Ctrl-h */
+ KeyTab = 9, /* Tab */
+ KeyCtrlK = 11, /* Ctrl+k */
+ KeyCtrlL = 12, /* Ctrl+l */
+ KeyEnter = 13, /* Enter */
+ KeyCtrlN = 14, /* Ctrl-n */
+ KeyCtrlP = 16, /* Ctrl-p */
+ KeyCtrlT = 20, /* Ctrl-t */
+ KeyCtrlU = 21, /* Ctrl+u */
+ KeyCtrlW = 23, /* Ctrl+w */
+ KeyEsc = 27, /* Escape */
+ KeyBackspace = 127 /* Backspace */
+};
+
+
+
+static void doatexit(void);
+
+static
+void
+normalcursor(int fd)
+{
+ write(fd,"\e[2 q",5);
+}
+
+static
+void
+insertcursor(int fd)
+{
+ write(fd,"\e[6 q",5);
+}
+
+/* Raw mode: 1960 magic shit. */
+static
+int
+enterraw(int fd)
+{
+ struct termios raw;
+
+ if(!isatty(0))
+ goto fatal;
+
+ if(!mode.defer) {
+ atexit(doatexit);
+ mode.defer = 1;
+ }
+ if(tcgetattr(fd,&originalterm) == -1)
+ goto fatal;
+
+ raw = originalterm; /* modify the original mode */
+ /* input modes: no break, no CR to NL, no parity check, no strip char,
+ * no start/stop output control. */
+ raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
+ /* output modes - disable post processing */
+ raw.c_oflag &= ~(OPOST);
+ /* control modes - set 8 bit chars */
+ raw.c_cflag |= (CS8);
+ /* local modes - choing off, canonical off, no extended functions,
+ * no signal chars (^Z,^C) */
+ raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
+ /* control chars - set return condition: min number of bytes and timer.
+ * We want read to return every single byte, without timeout. */
+ raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
+
+ /* put terminal in raw mode after flushing */
+ if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
+ mode.raw = 1;
+ return 1;
+
+fatal:
+ errno = ENOTTY;
+ return 0;
+}
+
+static
+void
+exitraw(int fd)
+{
+ /* Don't even check the return value as it's too late. */
+ if(mode.raw && tcsetattr(fd,TCSAFLUSH,&originalterm) != -1)
+ mode.raw = 0;
+}
+
+/* Use the ESC [6n escape sequence to query the horizontal cursor position
+ * and return it. On error -1 is returned, on success the position of the
+ * cursor. */
+static
+int
+cursorposition(int ifd, int ofd)
+{
+ char buf[32];
+ int cols, rows;
+ unsigned int i = 0;
+
+ /* Report cursor location */
+ if(write(ofd, "\x1b[6n", 4) != 4)
+ return -1;
+
+ /* Read the response: ESC [ rows ; cols R */
+ while(i < sizeof(buf)-1) {
+ if(read(ifd,buf+i,1) != 1)
+ break;
+ if(buf[i] == 'R')
+ break;
+ i++;
+ }
+ buf[i] = '\0';
+
+ /* Parse it. */
+ if(buf[0] != KeyEsc || buf[1] != '[')
+ return -1;
+ if(sscanf(buf+2,"%d;%d",&rows,&cols) != 2)
+ return -1;
+
+ return cols;
+}
+
+/* Try to get the number of columns in the current terminal, or assume 80
+ * if it fails. */
+static
+int
+columns(int ifd, int ofd)
+{
+ struct winsize ws;
+
+ if(ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0){
+ /* ioctl() failed. Try to query the terminal itself. */
+ int start, cols;
+
+ /* Get the initial position so we can restore it later. */
+ start = cursorposition(ifd,ofd);
+ if(start == -1)
+ goto failed;
+
+ /* Go to right margin and get position. */
+ if(write(ofd,"\x1b[999C",6) != 6)
+ goto failed;
+ cols = cursorposition(ifd,ofd);
+ if(cols == -1)
+ goto failed;
+
+ /* Restore position. */
+ if(cols > start){
+ char esc[32];
+ snprintf(esc,32,"\x1b[%dD",cols-start);
+ if(write(ofd,esc,strlen(esc)) == -1)
+ ;
+ }
+ return cols;
+ }else
+ return ws.ws_col;
+
+failed:
+ return 80;
+}
+
+static
+void
+clear(void)
+{
+ if(write(1,"\x1b[H\x1b[2J",7) <= 0)
+ ;
+}
+
+/* Beep, used for completion when there is nothing to complete or when all
+ * the choices were already shown. */
+static
+void
+beep(void)
+{
+ fprintf(stderr, "\x7");
+ fflush(stderr);
+}
+
+/* =========================== Line editing ================================= */
+
+/* We define a very simple "append buffer" structure, that is an heap
+ * allocated string where we can append to. This is useful in order to
+ * write all the escape sequences in a buffer and flush them to the standard
+ * output in a single call, to avoid flickering effects. */
+struct Buffer {
+ int len;
+ char *b;
+};
+
+static
+void
+initbuffer(struct Buffer *ab)
+{
+ ab->b = nil;
+ ab->len = 0;
+}
+
+static
+void
+append(struct Buffer *ab, const char *s, int len)
+{
+ char *new = realloc(ab->b,ab->len+len);
+
+ if (new == nil) return;
+ memcpy(new+ab->len,s,len);
+ ab->b = new;
+ ab->len += len;
+}
+
+static
+void
+freebuffer(struct Buffer *ab)
+{
+ free(ab->b);
+}
+
+/* Single line low level line refresh.
+ *
+ * Rewrite the currently edited line accordingly to the buffer content,
+ * cursor position, and number of columns of the terminal. */
+static
+void
+refreshsingleline(struct TerminalState *term)
+{
+ char esc[64];
+ struct Buffer ab;
+
+ uintptr plen = term->plen;
+ int fd = term->ofd;
+ char *buf = term->buf;
+ uintptr len = term->len;
+ uintptr pos = term->pos;
+
+ while((plen+pos) >= term->cols) {
+ buf++;
+ len--;
+ pos--;
+ }
+ while(plen+len > term->cols)
+ len--;
+
+ // TODO: do we need so much malloc pressure?
+ initbuffer(&ab);
+
+ /* move cursor to left edge */
+ snprintf(esc,64,"\r");
+ append(&ab,"\r",1);
+
+ /* write the prompt and the current buffer content */
+ append(&ab,term->prompt,strlen(term->prompt));
+#if 0
+ if(mode.vi.on){
+ if(mode.vi.insert)
+ append(&ab,"[I]",3);
+ else
+ append(&ab,"[N]",3);
+ }
+ append(&ab,">",1);
+#endif
+ if(mode.mask == 1)
+ while(len--)
+ append(&ab,"*",1);
+ else
+ append(&ab,buf,len);
+
+
+ snprintf(esc,64,"\x1b[0K"); // erase to right
+ append(&ab,esc,strlen(esc));
+
+ snprintf(esc,64,"\r\x1b[%dC", (int)(pos+plen)); // move cursor to original position
+ append(&ab,esc,strlen(esc));
+
+ if(write(fd,ab.b,ab.len) == -1) /* Can't recover from write error. */
+ ;
+
+ freebuffer(&ab);
+}
+
+/* Multi line low level line refresh.
+ *
+ * Rewrite the currently edited line accordingly to the buffer content,
+ * cursor position, and number of columns of the terminal. */
+static
+void
+refreshmultilines(struct TerminalState *term)
+{
+ char esc[64];
+ int plen = term->plen;
+ int rows = (plen+term->len+term->cols-1)/term->cols; /* rows used by current buf. */
+ int rpos = (plen+term->oldpos+term->cols)/term->cols; /* cursor relative row. */
+ int rpos2; /* rpos after refresh. */
+ int col; /* colum position, zero-based. */
+ int i;
+ int old_rows = term->maxrows;
+ int fd = term->ofd, j;
+ struct Buffer ab;
+
+ /* Update maxrows if needed. */
+ if(rows > (int)term->maxrows)
+ term->maxrows = rows;
+
+ /* First step: clear all the lines used before. To do so start by
+ * going to the last row. */
+ initbuffer(&ab);
+ if(old_rows-rpos > 0){
+ snprintf(esc,64,"\x1b[%dB", old_rows-rpos);
+ append(&ab,esc,strlen(esc));
+ }
+
+ /* Now for every row clear it, go up. */
+ for(j = 0; j < old_rows-1; j++){
+ snprintf(esc,64,"\r\x1b[0K\x1b[1A");
+ append(&ab,esc,strlen(esc));
+ }
+
+ /* clean the top line. */
+ snprintf(esc,64,"\r\x1b[0K");
+ append(&ab,esc,strlen(esc));
+
+ /* Write the prompt and the current buffer content */
+ append(&ab,term->prompt,strlen(term->prompt));
+ if(mode.mask == 1){
+ for(i = 0; i < term->len; i++) append(&ab,"*",1);
+ }else
+ append(&ab,term->buf,term->len);
+
+ /* If we are at the very end of the screen with our prompt, we need to
+ * emit a newline and move the prompt to the first column. */
+ if(term->pos && term->pos == term->len && (term->pos+plen) % term->cols == 0) {
+ append(&ab,"\n",1);
+ snprintf(esc,64,"\r");
+ append(&ab,esc,strlen(esc));
+ rows++;
+ if(rows > (int)term->maxrows)
+ term->maxrows = rows;
+ }
+
+ /* Move cursor to right position. */
+ rpos2 = (plen+term->pos+term->cols)/term->cols; /* current cursor relative row. */
+
+ /* Go up till we reach the expected positon. */
+ if(rows-rpos2 > 0){
+ snprintf(esc,64,"\x1b[%dA", rows-rpos2);
+ append(&ab,esc,strlen(esc));
+ }
+
+ /* Set column. */
+ col = (plen+(int)term->pos) % (int)term->cols;
+ if(col)
+ snprintf(esc,64,"\r\x1b[%dC", col);
+ else
+ snprintf(esc,64,"\r");
+ append(&ab,esc,strlen(esc));
+
+ term->oldpos = term->pos;
+
+ if(write(fd,ab.b,ab.len) == -1) /* Can't recover from write error. */
+ ;
+
+ freebuffer(&ab);
+}
+
+/* Calls the two low level functions refreshSingleLine() or
+ * refreshMultiLine() according to the selected mode. */
+static
+void
+refreshline(struct TerminalState *term)
+{
+ if(mode.multiline)
+ refreshmultilines(term);
+ else
+ refreshsingleline(term);
+}
+
+/* insert the character 'c' at cursor current position.
+ * on error writing to the terminal -1 is returned, otherwise 0. */
+int
+insert(struct TerminalState *term, char c)
+{
+ char d;
+ if(term->len < term->buflen){
+ if(term->len == term->pos){
+ term->buf[term->pos] = c;
+ term->pos++;
+ term->len++;
+ term->buf[term->len] = '\0';
+ if((!mode.multiline && term->plen+term->len < term->cols)){
+ d = (mode.mask==1) ? '*' : c;
+ if(write(term->ofd,&d,1) == -1)
+ return 0;
+ } else
+ refreshline(term);
+ }else{
+ memmove(term->buf+term->pos+1,term->buf+term->pos,term->len-term->pos);
+ term->buf[term->pos] = c;
+ term->len++;
+ term->pos++;
+ term->buf[term->len] = '\0';
+ refreshline(term);
+ }
+ }
+ return 1;
+}
+
+/* move cursor to the left n boxes */
+static
+void
+moveleft(struct TerminalState *term, int n)
+{
+ if(term->pos > n){
+ term->pos -= n;
+ refreshline(term);
+ }else if(term->pos){
+ term->pos = 0;
+ refreshline(term);
+ }
+}
+
+/* move cursor to the right n boxes */
+static
+void
+moveright(struct TerminalState *term, int n)
+{
+ if(term->pos < term->len-n){
+ term->pos += n;
+ refreshline(term);
+ }else if(term->pos != term->len){
+ term->pos = term->len;
+ refreshline(term);
+ }
+}
+
+/* Move cursor to the start of the line. */
+static
+void
+movehome(struct TerminalState *term) {
+ if(term->pos != 0){
+ term->pos = 0;
+ refreshline(term);
+ }
+}
+
+/* move cursor to the end of the line. */
+static
+void
+moveend(struct TerminalState *term)
+{
+ if(term->pos != term->len){
+ term->pos = term->len;
+ refreshline(term);
+ }
+}
+
+/* Substitute the currently edited line with the next or previous history
+ * entry as specified by 'dir'. */
+void
+movehistory(struct TerminalState *term, int dir)
+{
+}
+
+/* delete the character at the right of the cursor without altering the cursor
+ * position. basically this is what happens with the "Delete" keyboard key. */
+void
+delete(struct TerminalState *term)
+{
+ if(term->len > 0 && term->pos < term->len){
+ memmove(term->buf+term->pos,term->buf+term->pos+1,term->len-term->pos-1);
+ term->len--;
+ term->buf[term->len] = '\0';
+ refreshline(term);
+ }
+}
+
+/* backspace implementation. */
+static
+void
+backspace(struct TerminalState *term)
+{
+ if(term->pos > 0 && term->len > 0){
+ memmove(term->buf+term->pos-1,term->buf+term->pos,term->len-term->pos);
+ term->pos--;
+ term->len--;
+ term->buf[term->len] = '\0';
+ refreshline(term);
+ }
+}
+
+#define ITERATE_BACK_UNTIL(CONDITION) \
+ uintptr d, x = term->pos; \
+ char *it = term->buf + x; \
+ \
+ while(n-- > 0 && it > term->buf){ \
+ while(it > term->buf && CONDITION(it[-1])) \
+ --it; \
+ } \
+ \
+ return it; \
+
+static
+int
+prevword(struct TerminalState *term, int n)
+{
+ char *it = term->buf + term->pos;
+
+ while(n-- > 0 && it > term->buf){
+ /* consume any leading space chars */
+ while(isspace(it[-1]) && --it >= term->buf)
+ ;
+
+ /* consume word chars */
+ while(it > term->buf && (isalnum(it[-1]) || it[-1] == '_'))
+ --it;
+ }
+
+ return it-term->buf;
+}
+
+static
+int
+nextword(struct TerminalState *term, int n)
+{
+ char *it = term->buf + term->pos;
+ char *end = term->buf + term->len;
+
+ while(n-- > 0 && it < end){
+ /* consume any leading word chars */
+ while(it < end && (isalnum(*it) || *it == '_'))
+ ++it;
+ /* consume any space chars */
+ while(isspace(*it) && it < end)
+ ++it;
+ }
+
+ return it-term->buf;
+}
+
+static
+void
+deleteprevword(struct TerminalState *term)
+{
+ uintptr old_pos = term->pos;
+ uintptr diff;
+
+ while(term->pos > 0 && term->buf[term->pos-1] == ' ')
+ term->pos--;
+ while(term->pos > 0 && term->buf[term->pos-1] != ' ')
+ term->pos--;
+
+ diff = old_pos - term->pos;
+ memmove(term->buf+term->pos,term->buf+old_pos,term->len-old_pos+1);
+
+ term->len -= diff;
+
+ refreshline(term);
+}
+
+static
+void
+normalmode(int fd)
+{
+ mode.vi.insert = 0;
+ normalcursor(fd);
+}
+
+static
+void
+insertmode(int fd)
+{
+ mode.vi.insert = 1;
+ insertcursor(fd);
+}
+
+static
+int
+vi(struct TerminalState *term, char c)
+{
+ int n = 1;
+
+action:
+ switch(c){
+ /* # of repeats */
+ case '1': case '2': case '3':
+ case '4': case '5': case '6':
+ case '7': case '8': case '9':
+ n = 0;
+ while('0' <= c && c <= '9'){
+ n = 10*n + (c-'0');
+ if(read(term->ifd, &c, 1)<1)
+ return -1;
+ }
+ goto action;
+
+ /* movements */
+ case 'l':
+ moveright(term, n);
+ break;
+
+ case 'h':
+ moveleft(term, n);
+ break;
+
+ case '0':
+ movehome(term);
+ break;
+
+ case '$':
+ moveend(term);
+ break;
+
+ case 'b':
+ term->pos = prevword(term,n);
+ refreshline(term);
+ break;
+
+ case 'w':
+ term->pos = nextword(term,n);
+ refreshline(term);
+ break;
+
+ case 'a':
+ if(term->pos < term->len){
+ term->pos++;
+ refreshline(term);
+ }
+ goto insertmode;
+
+ case 'A':
+ moveend(term);
+ goto insertmode;
+
+ case 'I':
+ movehome(term);
+ goto insertmode;
+
+ case 'i': insertmode:
+ insertmode(term->ofd);
+ break;
+
+ case 'C':
+ insertmode(term->ofd);
+ /* fallthough */
+ case 'D':
+ term->len = term->pos;
+ term->buf[term->pos] = 0;
+ refreshline(term);
+ break;
+
+ case 'd':
+ if(read(term->ifd,&c,1))
+ break;
+ switch(c){
+ default:
+ beep();
+ normalmode(term->ofd);
+ break;
+ }
+
+ default:
+ beep();
+ break;
+ }
+
+ return 0;
+}
+
+
+/* This function is the core of the line editing capability of linenoise.
+ * It expects 'fd' to be already in "raw mode" so that every key pressed
+ * will be returned ASAP to read().
+ *
+ * The resulting string is put into 'buf' when the user type enter, or
+ * when ctrl+d is typed.
+ *
+ * The function returns the length of the current buffer. */
+static
+int
+interact(int ifd, int ofd, char *buf, uintptr len, char *prompt)
+{
+ char c;
+ int n;
+ char esc[3];
+
+ struct TerminalState term;
+ /*
+ * populate the state that we pass to functions implementing
+ * specific editing functionalities
+ */
+ term.ifd = ifd;
+ term.ofd = ofd;
+ term.buf = buf;
+ term.buflen = len;
+ term.prompt = prompt;
+ term.plen = strlen(prompt);
+ term.oldpos = term.pos = 0;
+ term.len = 0;
+ term.cols = columns(ifd, ofd);
+ term.maxrows = 0;
+ term.history_index = 0;
+
+ /* Buffer starts empty. */
+ term.buf[0] = '\0';
+ term.buflen--; /* Make sure there is always space for the nulterm */
+
+ if(write(term.ofd,prompt,term.plen) == -1)
+ return -1;
+
+ for(;;){
+ n = read(term.ifd,&c,1);
+ if(n <= 0)
+ return term.len;
+
+ switch(c){
+ case KeyEnter:
+ if(mode.multiline)
+ moveend(&term);
+ return (int)term.len;
+
+ case KeyCtrlC:
+ errno = EAGAIN;
+ return -1;
+
+ case KeyBackspace:
+ case KeyCtrlH:
+ backspace(&term);
+ break;
+
+ case KeyCtrlD:
+ if(term.len > 0)
+ delete(&term);
+ break;
+
+ case KeyCtrlT:
+ if(term.pos > 0 && term.pos < term.len){
+ int aux = buf[term.pos-1];
+ buf[term.pos-1] = buf[term.pos];
+ buf[term.pos] = aux;
+ if (term.pos != term.len-1) term.pos++;
+ refreshline(&term);
+ }
+ break;
+
+ case KeyCtrlB:
+ moveleft(&term, 1);
+ break;
+
+ case KeyCtrlF: /* ctrl-f */
+ moveright(&term, 1);
+ break;
+
+ case KeyCtrlP: /* ctrl-p */
+ /* TODO next history */
+ break;
+
+ case KeyCtrlN: /* ctrl-n */
+ /* TODO prev history */
+ break;
+
+ case KeyEsc: /* escape sequence */
+ /*
+ * try to read two bytes representing the escape sequence.
+ * if we read less than 2 and we are in vi mode, interpret as command
+ * NOTE: we could do a timed read here
+ */
+ switch(read(term.ifd,esc,2)){
+ case 0:
+ if(mode.vi.on){
+ if(mode.vi.insert){
+ normalmode(term.ofd);
+ if(term.pos > 0){
+ --term.pos;
+ refreshline(&term);
+ }
+ continue;
+ }
+ }
+ case 1:
+ if(mode.vi.on){
+ if(mode.vi.insert){
+ normalmode(term.ofd);
+ if(vi(&term,esc[0]) < 0)
+ return -1;
+ continue;
+ }
+ }
+ default: // 2
+ ;
+ }
+
+ /* ESC [ sequences. */
+ if(esc[0] == '['){
+ if(0 <= esc[1] && esc[1] <= '9'){
+ /* extended escape, read additional byte. */
+ if(read(term.ifd,esc+2,1) == -1)
+ break;
+
+ if(esc[2] == '~'){
+ switch(esc[1]){
+ case '3': /* delete key. */
+ delete(&term);
+ break;
+ }
+ }
+ }else{
+ switch(esc[1]) {
+ case 'A': /* up */
+ movehistory(&term, 1);
+ break;
+ case 'B': /* down */
+ movehistory(&term, 0);
+ break;
+ case 'C': /* right */
+ moveright(&term, 1);
+ break;
+ case 'D': /* left */
+ moveleft(&term, 1);
+ break;
+ case 'H': /* home */
+ movehome(&term);
+ break;
+ case 'F': /* end*/
+ moveend(&term);
+ break;
+ }
+ }
+ }
+ /* ESC O sequences. */
+ else if(esc[0] == 'O'){
+ switch(esc[1]) {
+ case 'H': /* home */
+ movehome(&term);
+ break;
+ case 'F': /* end*/
+ moveend(&term);
+ break;
+ }
+ }
+
+ break;
+
+ default:
+ if(mode.vi.on && !mode.vi.insert){
+ if(vi(&term,c) < 0)
+ return -1;
+ }else if(!insert(&term,c))
+ return -1;
+ break;
+
+ case KeyCtrlU: /* Ctrl+u, delete the whole line. */
+ buf[0] = '\0';
+ term.pos = term.len = 0;
+ refreshline(&term);
+ break;
+
+ case KeyCtrlK: /* Ctrl+k, delete from current to end of line. */
+ buf[term.pos] = '\0';
+ term.len = term.pos;
+ refreshline(&term);
+ break;
+
+ case KeyCtrlA: /* Ctrl+a, go to the start of the line */
+ movehome(&term);
+ break;
+
+ case KeyCtrlE: /* ctrl+e, go to the end of the line */
+ moveend(&term);
+ break;
+
+ case KeyCtrlL: /* ctrl+term, clear screen */
+ clear();
+ refreshline(&term);
+ break;
+
+ case KeyCtrlW: /* ctrl+w, delete previous word */
+ deleteprevword(&term);
+ break;
+ }
+ }
+ return term.len;
+}
+
+/*
+ * this special mode is used by linenoise in order to print scan codes
+ * on screen for debugging / development purposes. It is implemented
+ * by the linenoise_example program using the --keycodes option.
+ */
+void
+printkeycode(void)
+{
+ int n;
+ char c, quit[4];
+
+ printf("entering debugging mode. printing key codes.\n"
+ "press keys to see scan codes. type 'quit' at any time to exit.\n");
+
+ if(!enterraw(0))
+ return;
+
+ memset(quit,' ',4);
+
+ for(;;){
+ n = read(0,&c,1);
+ if(n <= 0)
+ continue;
+ memmove(quit,quit+1,sizeof(quit)-1); // shift string to left
+ quit[arrlen(quit)-1] = c; /* Insert current char on the right. */
+
+ if(memcmp(quit,"quit",sizeof(quit)) == 0)
+ break;
+
+ printf("'%c' %02x (%d) (type quit to exit)\n", isprint(c) ? c : '?', (int)c, (int)c);
+ printf("\r"); /* go to left edge manually, we are in raw mode. */
+ fflush(stdout);
+ }
+ exitraw(0);
+}
+
+/*
+ * This function calls the line editing function edit() using
+ * the stdin set in raw mode
+ */
+static
+int
+raw(char *buf, uintptr len, char *prompt)
+{
+ int n;
+
+ if(!len){
+ errno = EINVAL;
+ return -1;
+ }
+
+ // XXX: should we not hardcode stdin and stdout fd?
+ if(!enterraw(0)) return -1;
+ n = interact(0, 1, buf, len, prompt);
+ exitraw(0);
+
+ return n;
+}
+
+/*
+ * called when readline() is called with the standard
+ * input file descriptor not attached to a TTY. For example when the
+ * program is called in pipe or with a file redirected to its standard input
+ * in this case, we want to be able to return the line regardless of its length
+ */
+static
+int
+notty(void)
+{
+ int c;
+
+ for(;;){
+ c = fgetc(stdin);
+ put(&shell->cmd.io, c);
+ }
+}
+
+void
+enablevi(void)
+{
+ mode.vi.on = 1;
+ insertmode(1);
+}
+
+/*
+ * The high level function that is the main API.
+ * This function checks if the terminal has basic capabilities and later
+ * either calls the line editing function or uses dummy fgets() so that
+ * you will be able to type something even in the most desperate of the
+ * conditions.
+ */
+int
+readline(char *prompt)
+{
+ int n;
+
+ // reset the command buffer
+ shell->cmd.io->e = shell->cmd.io->b = shell->cmd.io->buf;
+
+ if(!isatty(0))
+ return notty();
+
+ if((n = raw(shell->cmd.io->e, shell->cmd.io->cap-1, prompt)) == -1)
+ return 0;
+ shell->cmd.io->e += n;
+
+ /* insert a newline character at the end */
+ put(&shell->cmd.io, '\n');
+ printf("\n");
+
+ return 1;
+}
+
+/* At exit we'll try to fix the terminal to the initial conditions. */
+static
+void
+doatexit(void)
+{
+ exitraw(0);
+ normalcursor(1);
+}
diff --git a/sys/cmd/rc/io.c b/sys/cmd/rc/io.c new file mode 100644 index 0000000..7f2d869 --- /dev/null +++ b/sys/cmd/rc/io.c @@ -0,0 +1,359 @@ +#include "rc.h" +#include "parse.h" + +#define CAP0 512 + +Io* +openfd(int fd) +{ + Io *io = emalloc(sizeof(*io) + CAP0); + + io->fd = fd; + io->cap = CAP0; + io->b = io->e = io->buf; + io->s = nil; + + return io; +} + +Io* +openstr(void) +{ + char *s; + Io *io = emalloc(sizeof(*io) + CAP0); + + io->fd = -1; + io->cap = CAP0; + io->b = io->s = emalloc(101); + io->e = io->b+100; + + for(s = io->b; s<=io->e; s++) + *s=0; + + return io; +} + +#if 0 +/* + * open a corebuffer to read. EOF occurs after reading len characters from buf + */ + +Io* +opencore(char *s, int len) +{ + Io *io = emalloc(sizeof(*io)); + char *buf = emalloc(len); + io->fd = -1 /*open("/dev/null", 0)*/; + io->b = io->s = buf; + io->e = buf+len; + memcpy(buf, s, len); + + return io; +} +#endif + +void +iorewind(Io *io) +{ + if(io->fd==-1) + io->b = io->s; + else{ + io->b = io->e = io->buf; + lseek(io->fd, 0L, 0); + } +} + +void +terminate(Io *io) +{ + if(io->fd>=0) + close(io->fd); + if(io->s) + efree(io->s); + + efree((char *)io); +} + +static +int +refill(Io *io) +{ + int n; + + if(io->fd==-1 || (n = read(io->fd, io->buf, io->cap))<=0) + return EOF; + + io->b = io->buf; + io->e = io->buf+n; + + return *io->b++&0xff; +} + + +void +flush(Io *io) +{ + int n; + char *s; + + if(io->s){ + n = io->e-io->s; + io->s = realloc(io->s, n+101); + if(io->s==0) + panicf("Can't realloc %d bytes in flush!", n+101); + io->b = io->s+n; + io->e = io->b+100; + for(s = io->b;s<=io->e;s++) *s='\0'; + }else{ + n = io->b-io->buf; + if(n && write(io->fd, io->buf, n) < 0) + write(3, "write error\n", 12); + io->b = io->buf; + io->e = io->buf + io->cap; + } +} + + +static +void +printchar(Io *io, int c) +{ + if(io->b==io->e) + flush(io); + + *io->b++=c; +} + +void +printquote(Io *io, char *s) +{ + printchar(io, '\''); + for(;*s;s++) + if(*s=='\'') + print(io, "''"); + else printchar(io, *s); + printchar(io, '\''); +} + +void +printstr(Io *io, char *s) +{ + if(s==0) + s="(null)"; + while(*s) printchar(io, *s++); +} + +void +printword(Io *io, char *s) +{ + char *t; + + for(t = s;*t;t++) + if(!iswordchar(*t)) + break; + + if(t==s || *t) + printquote(io, s); + else + printstr(io, s); +} + +void +printptr(Io *io, void *v) +{ + int n; + uintptr p; + + p = (uintptr)v; + if(sizeof(uintptr) == sizeof(uvlong) && p>>32) + for(n = 60;n>=32;n-=4) printchar(io, "0123456789ABCDEF"[(p>>n)&0xF]); + + for(n = 28;n>=0;n-=4) printchar(io, "0123456789ABCDEF"[(p>>n)&0xF]); +} + +static +void +printint(Io *io, int n) +{ + if(n<0){ + if(n!=INT_MIN){ + printchar(io, '-'); + printint(io, -n); + return; + } + /* n is two's complement minimum integer */ + n = -(INT_MIN+1); + printchar(io, '-'); + printint(io, n/10); + printchar(io, n%10+'1'); + return; + } + if(n>9) + printint(io, n/10); + printchar(io, n%10+'0'); +} + +static +void +printoct(Io *io, unsigned n) +{ + if(n>7) + printoct(io, n>>3); + printchar(io, (n&7)+'0'); +} + +static +void +printval(Io *io, Word *a) +{ + if(a){ + while(a->link && a->link->str){ + printword(io, a->str); + printchar(io, ' '); + a = a->link; + } + printword(io, a->str); + } +} + +static +void +printtree(Io *io, Tree *t) +{ + if(!t) + return; + + switch(t->type){ + case Tword: + print(io,"{%s}",t->str); + break; + + case Tbasic: + print(io, ">%t", t->child[0]); + break; + + case Targs: + if(!t->child[0]) + print(io, "%t", t->child[1]); + else if(!t->child[1]) + print(io, "%t", t->child[0]); + else + print(io, "[%t %t]", t->child[0], t->child[1]); + break; + + case ';': + if(t->child[0]){ + if(t->child[1]) + print(io, ";[%t %t]", t->child[0], t->child[1]); + else + print(io, "%t", t->child[0]); + }else + print(io, "%t", t->child[1]); + break; + + case '&': + print(io, "&(%t)", t->child[0]); + break; + + default: + print(io, "bad(%d)[%p %p %p]", t->type, t->child[0], t->child[1], t->child[2]); + } +} + +// ----------------------------------------------------------------------- +// exports + +/* readers */ +int +get(Io *io) +{ + if(io->b==io->e) + return refill(io); + + return *io->b++ & 0xFF; +} + +/* writers */ +int +put(Io **iop, char c) +{ + int nb, ne, nc; + Io *io = *iop; + char *e = io->b + io->cap; + + if(io->e == e){ + nb = io->b - io->buf; + ne = io->e - io->buf; + nc = 2*io->cap; + + if(!(io = erealloc(io, sizeof(*io)+nc))) + return 0; + + io->b = io->buf + nb; + io->e = io->buf + ne; + io->cap = nc; + + *iop = io; + } + + *io->e++ = c; + return 1; +} + +/* printers */ +static int pfmtnest; + +void +print(Io *io, char *fmt, ...) +{ + va_list args; + char err[ERRMAX]; + + va_start(args, fmt); + pfmtnest++; + + for(;*fmt;fmt++) + if(*fmt!='%') + printchar(io, *fmt); + else + switch(*++fmt){ + case '\0': + va_end(args); + return; + case 'c': + printchar(io, va_arg(args, int)); + break; + case 'd': + printint(io, va_arg(args, int)); + break; + case 'o': + printoct(io, va_arg(args, unsigned)); + break; + case 'p': + printptr(io, va_arg(args, void*)); + break; + case 'Q': + printquote(io, va_arg(args, char *)); + break; + case 'q': + printword(io, va_arg(args, char *)); + break; + case 's': + printstr(io, va_arg(args, char *)); + break; + case 't': + printtree(io, va_arg(args, struct Tree *)); + break; + case 'v': + printval(io, va_arg(args, struct Word *)); + break; + default: + printchar(io, *fmt); + break; + } + + va_end(args); + + if(--pfmtnest==0) + flush(io); +} diff --git a/sys/cmd/rc/lex.c b/sys/cmd/rc/lex.c new file mode 100644 index 0000000..ec9e94d --- /dev/null +++ b/sys/cmd/rc/lex.c @@ -0,0 +1,207 @@ +#include "rc.h" +#include "parse.h" + +static int advance(void); +// ----------------------------------------------------------------------- +// lexer + +struct Lexer +{ + int c[2]; + ushort doprompt; + char buf[BUFSIZ]; +}; + +static struct Lexer lexer = { .c={0, EOF}, .doprompt=1 }; + +void +yyerror(char *msg) +{ + print(errio, "\nrc: "); + + if(lexer.buf[0] && lexer.buf[0]!='\n') + print(errio, "@ %q: ", lexer.buf); + + print(errio, "%s\n", msg); + flush(errio); + + while(lexer.c[0] !='\n' && lexer.c[0] != EOF) + advance(); +} + +int +readc(void) +{ + int c; + static int peek = EOF; + + if(peek!=EOF){ + c = peek; + peek = EOF; + return c; + } + if(shell->flag.eof) + return EOF; + + if(!prompt(&lexer.doprompt)) + exit(1); // XXX: hack for signal handling right now... + + c = get(shell->cmd.io); + + lexer.doprompt = lexer.doprompt || c=='\n' || c==EOF; + + if(c==EOF) + shell->flag.eof = 1; + + return c; +} + +static +int +peekc(void) +{ + if(lexer.c[1] == EOF) + lexer.c[1] = readc(); + + return lexer.c[1]; +} + +static +int +advance(void) +{ + int c = peekc(); + lexer.c[0] = lexer.c[1], lexer.c[1] = EOF; + + return c; +} + +static +void +skipws(void) +{ + int c; + for(;;){ + c = peekc(); + if(c== ' ' || c == '\t') + advance(); + else + return; + } +} + +static +void +skipnl(void) +{ + int c; + for(;;){ + c = peekc(); + if(c== ' ' || c == '\t' || c == '\n') + advance(); + else + return; + } +} + +static +int +nextis(int c) +{ + if(peekc()==c){ + advance(); + return 1; + } + return 0; +} + +static +char * +putbyte(char *buf, int c) +{ + if(!buf) + return buf; + + if(buf == arrend(lexer.buf)){ + fatal("lexer: out of buffer space"); + return nil; + } + *buf++ = c; + return buf; +} + +#define onebyte(c) ((c&0x80)==0x00) +#define twobyte(c) ((c&0xe0)==0xc0) +#define threebyte(c) ((c&0xf0)==0xe0) +#define fourbyte(c) ((c&0xf8)==0xf0) + +static +char * +putrune(char *buf, int c) +{ + buf = putbyte(buf, c); + if(onebyte(c)) + return buf; + if(twobyte(c)) + return putbyte(buf,c); + if(threebyte(c)){ + buf = putbyte(buf,c); + return putbyte(buf,c); + } + if(fourbyte(c)){ + buf = putbyte(buf,c); + buf = putbyte(buf,c); + return putbyte(buf,c); + } + fatal("malformed utf8 stream"); + + return nil; +} + +// ----------------------------------------------------------------------- +// exported functions + +int +iswordchar(int c) +{ + return !strchr("\n \t#;&|^$=`'{}()<>", c) && c!=EOF; +} + +int +yylex(void) +{ + int c; + Tree *node; + char *w = lexer.buf; + + yylval.tree = nil; + + skipws(); + switch(c=advance()){ + case EOF: + return EOF; + case '&': + lexer.buf[0] = '&'; + lexer.buf[1] = 0; + return '&'; + + default: + ; + } + if(!iswordchar(c)) + return c; + + for(;;){ + w = putrune(w, c); + c = peekc(); + if(!iswordchar(c)) + break; + advance(); + } + w[0] = 0; + + node = token(Tword, lexer.buf); + + yylval.tree = node; + return node->type; +} diff --git a/sys/cmd/rc/main.c b/sys/cmd/rc/main.c new file mode 100644 index 0000000..46a4e0f --- /dev/null +++ b/sys/cmd/rc/main.c @@ -0,0 +1,47 @@ +#include "rc.h" +#include "parse.h" +#include "exec.h" + +int rcpid; +Io *errio = nil; +Thread *shell = nil; + +int +main(int argc, char *argv[]) +{ + int i; + Code bootstrap[32]; + char num[12]; + + errio = openfd(2); + + initenv(); + initpath(); + + itoa(num, rcpid = getpid()); + setvar("pid", makeword(num, nil)); + + xboot(argc, argv); +#if 0 + Thread root = { + .cmd = { + .path = "<nil>", + .io = openfd(0), + }, + .line = 0, + .flag = { + .i = 1, + .eof = 0, + }, + }; + + shell = &root; + errio = openfd(2); +#if 1 + while(!yyparse()) + ; +#else + printkeycode() +#endif +#endif +} diff --git a/sys/cmd/rc/parse.c b/sys/cmd/rc/parse.c new file mode 100644 index 0000000..e2e4afa --- /dev/null +++ b/sys/cmd/rc/parse.c @@ -0,0 +1,1418 @@ +/* A Bison parser, made by GNU Bison 3.8.2. */ + +/* Bison implementation for Yacc-like parsers in C + + Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2021 Free Software Foundation, + Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + +/* C LALR(1) parser skeleton written by Richard Stallman, by + simplifying the original so-called "semantic" parser. */ + +/* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, + especially those whose name start with YY_ or yy_. They are + private implementation details that can be changed or removed. */ + +/* All symbols defined below should begin with yy or YY, to avoid + infringing on user name space. This should be done even for local + variables, as they might otherwise be expanded by user macros. + There are some unavoidable exceptions within include files to + define necessary library symbols; they are noted "INFRINGES ON + USER NAME SPACE" below. */ + +/* Identify Bison output, and Bison version. */ +#define YYBISON 30802 + +/* Bison version string. */ +#define YYBISON_VERSION "3.8.2" + +/* Skeleton name. */ +#define YYSKELETON_NAME "yacc.c" + +/* Pure parsers. */ +#define YYPURE 0 + +/* Push parsers. */ +#define YYPUSH 0 + +/* Pull parsers. */ +#define YYPULL 1 + + + + +/* First part of user prologue. */ +#line 5 "sys/cmd/rc/syntax.y" + + #include "rc.h" + + int yylex(void); + void yyerror(char *); + +#line 78 "sys/cmd/rc/parse.c" + +# ifndef YY_CAST +# ifdef __cplusplus +# define YY_CAST(Type, Val) static_cast<Type> (Val) +# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val) +# else +# define YY_CAST(Type, Val) ((Type) (Val)) +# define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) +# endif +# endif +# ifndef YY_NULLPTR +# if defined __cplusplus +# if 201103L <= __cplusplus +# define YY_NULLPTR nullptr +# else +# define YY_NULLPTR 0 +# endif +# else +# define YY_NULLPTR ((void*)0) +# endif +# endif + +#include "parse.h" +/* Symbol kind. */ +enum yysymbol_kind_t +{ + YYSYMBOL_YYEMPTY = -2, + YYSYMBOL_YYEOF = 0, /* "end of file" */ + YYSYMBOL_YYerror = 1, /* error */ + YYSYMBOL_YYUNDEF = 2, /* "invalid token" */ + YYSYMBOL_Tword = 3, /* Tword */ + YYSYMBOL_Tif = 4, /* Tif */ + YYSYMBOL_Telse = 5, /* Telse */ + YYSYMBOL_Tbang = 6, /* Tbang */ + YYSYMBOL_Targs = 7, /* Targs */ + YYSYMBOL_Tbasic = 8, /* Tbasic */ + YYSYMBOL_Tparen = 9, /* Tparen */ + YYSYMBOL_Tblock = 10, /* Tblock */ + YYSYMBOL_Twhile = 11, /* Twhile */ + YYSYMBOL_12_n_ = 12, /* '\n' */ + YYSYMBOL_13_ = 13, /* '$' */ + YYSYMBOL_14_ = 14, /* '(' */ + YYSYMBOL_15_ = 15, /* ')' */ + YYSYMBOL_16_ = 16, /* '{' */ + YYSYMBOL_17_ = 17, /* '}' */ + YYSYMBOL_18_ = 18, /* ';' */ + YYSYMBOL_19_ = 19, /* '&' */ + YYSYMBOL_20_ = 20, /* '=' */ + YYSYMBOL_21_ = 21, /* '^' */ + YYSYMBOL_YYACCEPT = 22, /* $accept */ + YYSYMBOL_rc = 23, /* rc */ + YYSYMBOL_line = 24, /* line */ + YYSYMBOL_body = 25, /* body */ + YYSYMBOL_paren = 26, /* paren */ + YYSYMBOL_block = 27, /* block */ + YYSYMBOL_cmds = 28, /* cmds */ + YYSYMBOL_cmdsln = 29, /* cmdsln */ + YYSYMBOL_ifbody = 30, /* ifbody */ + YYSYMBOL_cmd = 31, /* cmd */ + YYSYMBOL_basic = 32, /* basic */ + YYSYMBOL_atom = 33, /* atom */ + YYSYMBOL_word = 34, /* word */ + YYSYMBOL_executable = 35, /* executable */ + YYSYMBOL_nonkeyword = 36, /* nonkeyword */ + YYSYMBOL_keyword = 37, /* keyword */ + YYSYMBOL_nl = 38 /* nl */ +}; +typedef enum yysymbol_kind_t yysymbol_kind_t; + + + + +#ifdef short +# undef short +#endif + +/* On compilers that do not define __PTRDIFF_MAX__ etc., make sure + <limits.h> and (if available) <stdint.h> are included + so that the code can choose integer types of a good width. */ + +#ifndef __PTRDIFF_MAX__ +# include <limits.h> /* INFRINGES ON USER NAME SPACE */ +# if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ +# include <stdint.h> /* INFRINGES ON USER NAME SPACE */ +# define YY_STDINT_H +# endif +#endif + +/* Narrow types that promote to a signed type and that can represent a + signed or unsigned integer of at least N bits. In tables they can + save space and decrease cache pressure. Promoting to a signed type + helps avoid bugs in integer arithmetic. */ + +#ifdef __INT_LEAST8_MAX__ +typedef __INT_LEAST8_TYPE__ yytype_int8; +#elif defined YY_STDINT_H +typedef int_least8_t yytype_int8; +#else +typedef signed char yytype_int8; +#endif + +#ifdef __INT_LEAST16_MAX__ +typedef __INT_LEAST16_TYPE__ yytype_int16; +#elif defined YY_STDINT_H +typedef int_least16_t yytype_int16; +#else +typedef short yytype_int16; +#endif + +/* Work around bug in HP-UX 11.23, which defines these macros + incorrectly for preprocessor constants. This workaround can likely + be removed in 2023, as HPE has promised support for HP-UX 11.23 + (aka HP-UX 11i v2) only through the end of 2022; see Table 2 of + <https://h20195.www2.hpe.com/V2/getpdf.aspx/4AA4-7673ENW.pdf>. */ +#ifdef __hpux +# undef UINT_LEAST8_MAX +# undef UINT_LEAST16_MAX +# define UINT_LEAST8_MAX 255 +# define UINT_LEAST16_MAX 65535 +#endif + +#if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ +typedef __UINT_LEAST8_TYPE__ yytype_uint8; +#elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \ + && UINT_LEAST8_MAX <= INT_MAX) +typedef uint_least8_t yytype_uint8; +#elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX +typedef unsigned char yytype_uint8; +#else +typedef short yytype_uint8; +#endif + +#if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ +typedef __UINT_LEAST16_TYPE__ yytype_uint16; +#elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \ + && UINT_LEAST16_MAX <= INT_MAX) +typedef uint_least16_t yytype_uint16; +#elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX +typedef unsigned short yytype_uint16; +#else +typedef int yytype_uint16; +#endif + +#ifndef YYPTRDIFF_T +# if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__ +# define YYPTRDIFF_T __PTRDIFF_TYPE__ +# define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__ +# elif defined PTRDIFF_MAX +# ifndef ptrdiff_t +# include <stddef.h> /* INFRINGES ON USER NAME SPACE */ +# endif +# define YYPTRDIFF_T ptrdiff_t +# define YYPTRDIFF_MAXIMUM PTRDIFF_MAX +# else +# define YYPTRDIFF_T long +# define YYPTRDIFF_MAXIMUM LONG_MAX +# endif +#endif + +#ifndef YYSIZE_T +# ifdef __SIZE_TYPE__ +# define YYSIZE_T __SIZE_TYPE__ +# elif defined size_t +# define YYSIZE_T size_t +# elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ +# include <stddef.h> /* INFRINGES ON USER NAME SPACE */ +# define YYSIZE_T size_t +# else +# define YYSIZE_T unsigned +# endif +#endif + +#define YYSIZE_MAXIMUM \ + YY_CAST (YYPTRDIFF_T, \ + (YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \ + ? YYPTRDIFF_MAXIMUM \ + : YY_CAST (YYSIZE_T, -1))) + +#define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X)) + + +/* Stored state numbers (used for stacks). */ +typedef yytype_int8 yy_state_t; + +/* State numbers in computations. */ +typedef int yy_state_fast_t; + +#ifndef YY_ +# if defined YYENABLE_NLS && YYENABLE_NLS +# if ENABLE_NLS +# include <libintl.h> /* INFRINGES ON USER NAME SPACE */ +# define YY_(Msgid) dgettext ("bison-runtime", Msgid) +# endif +# endif +# ifndef YY_ +# define YY_(Msgid) Msgid +# endif +#endif + + +#ifndef YY_ATTRIBUTE_PURE +# if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) +# define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) +# else +# define YY_ATTRIBUTE_PURE +# endif +#endif + +#ifndef YY_ATTRIBUTE_UNUSED +# if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) +# define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) +# else +# define YY_ATTRIBUTE_UNUSED +# endif +#endif + +/* Suppress unused-variable warnings by "using" E. */ +#if ! defined lint || defined __GNUC__ +# define YY_USE(E) ((void) (E)) +#else +# define YY_USE(E) /* empty */ +#endif + +/* Suppress an incorrect diagnostic about yylval being uninitialized. */ +#if defined __GNUC__ && ! defined __ICC && 406 <= __GNUC__ * 100 + __GNUC_MINOR__ +# if __GNUC__ * 100 + __GNUC_MINOR__ < 407 +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") +# else +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ + _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") +# endif +# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ + _Pragma ("GCC diagnostic pop") +#else +# define YY_INITIAL_VALUE(Value) Value +#endif +#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_END +#endif +#ifndef YY_INITIAL_VALUE +# define YY_INITIAL_VALUE(Value) /* Nothing. */ +#endif + +#if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ +# define YY_IGNORE_USELESS_CAST_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") +# define YY_IGNORE_USELESS_CAST_END \ + _Pragma ("GCC diagnostic pop") +#endif +#ifndef YY_IGNORE_USELESS_CAST_BEGIN +# define YY_IGNORE_USELESS_CAST_BEGIN +# define YY_IGNORE_USELESS_CAST_END +#endif + + +#define YY_ASSERT(E) ((void) (0 && (E))) + +#if !defined yyoverflow + +/* The parser invokes alloca or malloc; define the necessary symbols. */ + +# ifdef YYSTACK_USE_ALLOCA +# if YYSTACK_USE_ALLOCA +# ifdef __GNUC__ +# define YYSTACK_ALLOC __builtin_alloca +# elif defined __BUILTIN_VA_ARG_INCR +# include <alloca.h> /* INFRINGES ON USER NAME SPACE */ +# elif defined _AIX +# define YYSTACK_ALLOC __alloca +# elif defined _MSC_VER +# include <malloc.h> /* INFRINGES ON USER NAME SPACE */ +# define alloca _alloca +# else +# define YYSTACK_ALLOC alloca +# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS +# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ + /* Use EXIT_SUCCESS as a witness for stdlib.h. */ +# ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +# endif +# endif +# endif +# endif +# endif + +# ifdef YYSTACK_ALLOC + /* Pacify GCC's 'empty if-body' warning. */ +# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) +# ifndef YYSTACK_ALLOC_MAXIMUM + /* The OS might guarantee only one guard page at the bottom of the stack, + and a page size can be as small as 4096 bytes. So we cannot safely + invoke alloca (N) if N exceeds 4096. Use a slightly smaller number + to allow for a few compiler-allocated temporary stack slots. */ +# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ +# endif +# else +# define YYSTACK_ALLOC YYMALLOC +# define YYSTACK_FREE YYFREE +# ifndef YYSTACK_ALLOC_MAXIMUM +# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM +# endif +# if (defined __cplusplus && ! defined EXIT_SUCCESS \ + && ! ((defined YYMALLOC || defined malloc) \ + && (defined YYFREE || defined free))) +# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ +# ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +# endif +# endif +# ifndef YYMALLOC +# define YYMALLOC malloc +# if ! defined malloc && ! defined EXIT_SUCCESS +void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# ifndef YYFREE +# define YYFREE free +# if ! defined free && ! defined EXIT_SUCCESS +void free (void *); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# endif +#endif /* !defined yyoverflow */ + +#if (! defined yyoverflow \ + && (! defined __cplusplus \ + || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) + +/* A type that is properly aligned for any stack member. */ +union yyalloc +{ + yy_state_t yyss_alloc; + YYSTYPE yyvs_alloc; +}; + +/* The size of the maximum gap between one aligned stack and the next. */ +# define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1) + +/* The size of an array large to enough to hold all stacks, each with + N elements. */ +# define YYSTACK_BYTES(N) \ + ((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \ + + YYSTACK_GAP_MAXIMUM) + +# define YYCOPY_NEEDED 1 + +/* Relocate STACK from its old location to the new one. The + local variables YYSIZE and YYSTACKSIZE give the old and new number of + elements in the stack, and YYPTR gives the new location of the + stack. Advance YYPTR to a properly aligned location for the next + stack. */ +# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ + do \ + { \ + YYPTRDIFF_T yynewbytes; \ + YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ + Stack = &yyptr->Stack_alloc; \ + yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \ + yyptr += yynewbytes / YYSIZEOF (*yyptr); \ + } \ + while (0) + +#endif + +#if defined YYCOPY_NEEDED && YYCOPY_NEEDED +/* Copy COUNT objects from SRC to DST. The source and destination do + not overlap. */ +# ifndef YYCOPY +# if defined __GNUC__ && 1 < __GNUC__ +# define YYCOPY(Dst, Src, Count) \ + __builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src))) +# else +# define YYCOPY(Dst, Src, Count) \ + do \ + { \ + YYPTRDIFF_T yyi; \ + for (yyi = 0; yyi < (Count); yyi++) \ + (Dst)[yyi] = (Src)[yyi]; \ + } \ + while (0) +# endif +# endif +#endif /* !YYCOPY_NEEDED */ + +/* YYFINAL -- State number of the termination state. */ +#define YYFINAL 24 +/* YYLAST -- Last index in YYTABLE. */ +#define YYLAST 49 + +/* YYNTOKENS -- Number of terminals. */ +#define YYNTOKENS 22 +/* YYNNTS -- Number of nonterminals. */ +#define YYNNTS 17 +/* YYNRULES -- Number of rules. */ +#define YYNRULES 33 +/* YYNSTATES -- Number of states. */ +#define YYNSTATES 48 + +/* YYMAXUTOK -- Last valid token kind. */ +#define YYMAXUTOK 266 + + +/* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM + as returned by yylex, with out-of-bounds checking. */ +#define YYTRANSLATE(YYX) \ + (0 <= (YYX) && (YYX) <= YYMAXUTOK \ + ? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \ + : YYSYMBOL_YYUNDEF) + +/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM + as returned by yylex. */ +static const yytype_int8 yytranslate[] = +{ + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 12, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 13, 2, 19, 2, + 14, 15, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, + 2, 20, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 21, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 16, 2, 17, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11 +}; + +#if YYDEBUG +/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ +static const yytype_int8 yyrline[] = +{ + 0, 34, 34, 35, 38, 39, 42, 43, 46, 49, + 52, 53, 56, 57, 60, 61, 67, 68, 69, 70, + 73, 74, 83, 84, 87, 88, 91, 92, 95, 96, + 99, 99, 101, 103 +}; +#endif + +/** Accessing symbol of state STATE. */ +#define YY_ACCESSING_SYMBOL(State) YY_CAST (yysymbol_kind_t, yystos[State]) + +#if YYDEBUG || 0 +/* The user-facing name of the symbol whose (internal) number is + YYSYMBOL. No bounds checking. */ +static const char *yysymbol_name (yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED; + +/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. + First, the terminals, then, starting at YYNTOKENS, nonterminals. */ +static const char *const yytname[] = +{ + "\"end of file\"", "error", "\"invalid token\"", "Tword", "Tif", + "Telse", "Tbang", "Targs", "Tbasic", "Tparen", "Tblock", "Twhile", + "'\\n'", "'$'", "'('", "')'", "'{'", "'}'", "';'", "'&'", "'='", "'^'", + "$accept", "rc", "line", "body", "paren", "block", "cmds", "cmdsln", + "ifbody", "cmd", "basic", "atom", "word", "executable", "nonkeyword", + "keyword", "nl", YY_NULLPTR +}; + +static const char * +yysymbol_name (yysymbol_kind_t yysymbol) +{ + return yytname[yysymbol]; +} +#endif + +#define YYPACT_NINF (-10) + +#define yypact_value_is_default(Yyn) \ + ((Yyn) == YYPACT_NINF) + +#define YYTABLE_NINF (-3) + +#define yytable_value_is_error(Yyn) \ + 0 + +/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing + STATE-NUM. */ +static const yytype_int8 yypact[] = +{ + 3, -10, -2, 21, 7, 15, 9, -10, 7, 22, + 21, 10, -10, 7, -10, -10, -10, -10, -10, -10, + 18, -10, 7, 20, -10, -10, -10, -10, -10, -10, + 23, 21, 27, 1, -10, -10, -10, 21, -10, -10, + -10, 38, -10, -10, -10, -10, 1, -10 +}; + +/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. + Performed when YYTABLE does not specify something else to do. Zero + means the default is an error. */ +static const yytype_int8 yydefact[] = +{ + 16, 28, 0, 0, 16, 0, 0, 18, 16, 4, + 17, 20, 26, 16, 32, 30, 31, 29, 22, 23, + 0, 12, 16, 6, 1, 3, 5, 10, 11, 24, + 21, 0, 0, 16, 9, 7, 13, 0, 27, 8, + 33, 18, 19, 14, 25, 32, 16, 15 +}; + +/* YYPGOTO[NTERM-NUM]. */ +static const yytype_int8 yypgoto[] = +{ + -10, -10, 37, 5, -10, 14, 29, -10, -10, 0, + -10, -9, -10, -10, -1, -10, 4 +}; + +/* YYDEFGOTO[NTERM-NUM]. */ +static const yytype_int8 yydefgoto[] = +{ + 0, 5, 6, 20, 14, 7, 21, 22, 42, 23, + 10, 17, 30, 11, 12, 19, 33 +}; + +/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If + positive, shift that token. If negative, reduce the rule whose + number is the opposite. If YYTABLE_NINF, syntax error. */ +static const yytype_int8 yytable[] = +{ + 9, 29, 18, -2, 1, 2, 1, 2, 9, 18, + 1, 2, 13, 40, 3, 24, 3, 4, 32, 4, + 3, 25, 38, 4, 1, 15, 16, 35, 44, 8, + 18, 31, 36, 43, 3, 34, 18, 8, 27, 28, + 27, 28, 39, 45, 37, 26, 47, 41, 0, 46 +}; + +static const yytype_int8 yycheck[] = +{ + 0, 10, 3, 0, 3, 4, 3, 4, 8, 10, + 3, 4, 14, 12, 13, 0, 13, 16, 13, 16, + 13, 12, 31, 16, 3, 4, 5, 22, 37, 0, + 31, 21, 12, 33, 13, 17, 37, 8, 18, 19, + 18, 19, 15, 5, 21, 8, 46, 33, -1, 45 +}; + +/* YYSTOS[STATE-NUM] -- The symbol kind of the accessing symbol of + state STATE-NUM. */ +static const yytype_int8 yystos[] = +{ + 0, 3, 4, 13, 16, 23, 24, 27, 28, 31, + 32, 35, 36, 14, 26, 4, 5, 33, 36, 37, + 25, 28, 29, 31, 0, 12, 24, 18, 19, 33, + 34, 21, 25, 38, 17, 25, 12, 21, 33, 15, + 12, 27, 30, 31, 33, 5, 38, 31 +}; + +/* YYR1[RULE-NUM] -- Symbol kind of the left-hand side of rule RULE-NUM. */ +static const yytype_int8 yyr1[] = +{ + 0, 22, 23, 23, 24, 24, 25, 25, 26, 27, + 28, 28, 29, 29, 30, 30, 31, 31, 31, 31, + 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, + 37, 37, 38, 38 +}; + +/* YYR2[RULE-NUM] -- Number of symbols on the right-hand side of rule RULE-NUM. */ +static const yytype_int8 yyr2[] = +{ + 0, 2, 0, 2, 1, 2, 1, 2, 3, 3, + 2, 2, 1, 2, 1, 4, 0, 1, 1, 4, + 1, 2, 1, 1, 1, 3, 1, 3, 1, 2, + 1, 1, 0, 2 +}; + + +enum { YYENOMEM = -2 }; + +#define yyerrok (yyerrstatus = 0) +#define yyclearin (yychar = YYEMPTY) + +#define YYACCEPT goto yyacceptlab +#define YYABORT goto yyabortlab +#define YYERROR goto yyerrorlab +#define YYNOMEM goto yyexhaustedlab + + +#define YYRECOVERING() (!!yyerrstatus) + +#define YYBACKUP(Token, Value) \ + do \ + if (yychar == YYEMPTY) \ + { \ + yychar = (Token); \ + yylval = (Value); \ + YYPOPSTACK (yylen); \ + yystate = *yyssp; \ + goto yybackup; \ + } \ + else \ + { \ + yyerror (YY_("syntax error: cannot back up")); \ + YYERROR; \ + } \ + while (0) + +/* Backward compatibility with an undocumented macro. + Use YYerror or YYUNDEF. */ +#define YYERRCODE YYUNDEF + + +/* Enable debugging if requested. */ +#if YYDEBUG + +# ifndef YYFPRINTF +# include <stdio.h> /* INFRINGES ON USER NAME SPACE */ +# define YYFPRINTF fprintf +# endif + +# define YYDPRINTF(Args) \ +do { \ + if (yydebug) \ + YYFPRINTF Args; \ +} while (0) + + + + +# define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \ +do { \ + if (yydebug) \ + { \ + YYFPRINTF (stderr, "%s ", Title); \ + yy_symbol_print (stderr, \ + Kind, Value); \ + YYFPRINTF (stderr, "\n"); \ + } \ +} while (0) + + +/*-----------------------------------. +| Print this symbol's value on YYO. | +`-----------------------------------*/ + +static void +yy_symbol_value_print (FILE *yyo, + yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) +{ + FILE *yyoutput = yyo; + YY_USE (yyoutput); + if (!yyvaluep) + return; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + YY_USE (yykind); + YY_IGNORE_MAYBE_UNINITIALIZED_END +} + + +/*---------------------------. +| Print this symbol on YYO. | +`---------------------------*/ + +static void +yy_symbol_print (FILE *yyo, + yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) +{ + YYFPRINTF (yyo, "%s %s (", + yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name (yykind)); + + yy_symbol_value_print (yyo, yykind, yyvaluep); + YYFPRINTF (yyo, ")"); +} + +/*------------------------------------------------------------------. +| yy_stack_print -- Print the state stack from its BOTTOM up to its | +| TOP (included). | +`------------------------------------------------------------------*/ + +static void +yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop) +{ + YYFPRINTF (stderr, "Stack now"); + for (; yybottom <= yytop; yybottom++) + { + int yybot = *yybottom; + YYFPRINTF (stderr, " %d", yybot); + } + YYFPRINTF (stderr, "\n"); +} + +# define YY_STACK_PRINT(Bottom, Top) \ +do { \ + if (yydebug) \ + yy_stack_print ((Bottom), (Top)); \ +} while (0) + + +/*------------------------------------------------. +| Report that the YYRULE is going to be reduced. | +`------------------------------------------------*/ + +static void +yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp, + int yyrule) +{ + int yylno = yyrline[yyrule]; + int yynrhs = yyr2[yyrule]; + int yyi; + YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n", + yyrule - 1, yylno); + /* The symbols being reduced. */ + for (yyi = 0; yyi < yynrhs; yyi++) + { + YYFPRINTF (stderr, " $%d = ", yyi + 1); + yy_symbol_print (stderr, + YY_ACCESSING_SYMBOL (+yyssp[yyi + 1 - yynrhs]), + &yyvsp[(yyi + 1) - (yynrhs)]); + YYFPRINTF (stderr, "\n"); + } +} + +# define YY_REDUCE_PRINT(Rule) \ +do { \ + if (yydebug) \ + yy_reduce_print (yyssp, yyvsp, Rule); \ +} while (0) + +/* Nonzero means print parse trace. It is left uninitialized so that + multiple parsers can coexist. */ +int yydebug; +#else /* !YYDEBUG */ +# define YYDPRINTF(Args) ((void) 0) +# define YY_SYMBOL_PRINT(Title, Kind, Value, Location) +# define YY_STACK_PRINT(Bottom, Top) +# define YY_REDUCE_PRINT(Rule) +#endif /* !YYDEBUG */ + + +/* YYINITDEPTH -- initial size of the parser's stacks. */ +#ifndef YYINITDEPTH +# define YYINITDEPTH 200 +#endif + +/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only + if the built-in stack extension method is used). + + Do not make this value too large; the results are undefined if + YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) + evaluated with infinite-precision integer arithmetic. */ + +#ifndef YYMAXDEPTH +# define YYMAXDEPTH 10000 +#endif + + + + + + +/*-----------------------------------------------. +| Release the memory associated to this symbol. | +`-----------------------------------------------*/ + +static void +yydestruct (const char *yymsg, + yysymbol_kind_t yykind, YYSTYPE *yyvaluep) +{ + YY_USE (yyvaluep); + if (!yymsg) + yymsg = "Deleting"; + YY_SYMBOL_PRINT (yymsg, yykind, yyvaluep, yylocationp); + + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + YY_USE (yykind); + YY_IGNORE_MAYBE_UNINITIALIZED_END +} + + +/* Lookahead token kind. */ +int yychar; + +/* The semantic value of the lookahead symbol. */ +YYSTYPE yylval; +/* Number of syntax errors so far. */ +int yynerrs; + + + + +/*----------. +| yyparse. | +`----------*/ + +int +yyparse (void) +{ + yy_state_fast_t yystate = 0; + /* Number of tokens to shift before error messages enabled. */ + int yyerrstatus = 0; + + /* Refer to the stacks through separate pointers, to allow yyoverflow + to reallocate them elsewhere. */ + + /* Their size. */ + YYPTRDIFF_T yystacksize = YYINITDEPTH; + + /* The state stack: array, bottom, top. */ + yy_state_t yyssa[YYINITDEPTH]; + yy_state_t *yyss = yyssa; + yy_state_t *yyssp = yyss; + + /* The semantic value stack: array, bottom, top. */ + YYSTYPE yyvsa[YYINITDEPTH]; + YYSTYPE *yyvs = yyvsa; + YYSTYPE *yyvsp = yyvs; + + int yyn; + /* The return value of yyparse. */ + int yyresult; + /* Lookahead symbol kind. */ + yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY; + /* The variables used to return semantic value and location from the + action routines. */ + YYSTYPE yyval; + + + +#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) + + /* The number of symbols on the RHS of the reduced rule. + Keep to zero when no symbol should be popped. */ + int yylen = 0; + + YYDPRINTF ((stderr, "Starting parse\n")); + + yychar = YYEMPTY; /* Cause a token to be read. */ + + goto yysetstate; + + +/*------------------------------------------------------------. +| yynewstate -- push a new state, which is found in yystate. | +`------------------------------------------------------------*/ +yynewstate: + /* In all cases, when you get here, the value and location stacks + have just been pushed. So pushing a state here evens the stacks. */ + yyssp++; + + +/*--------------------------------------------------------------------. +| yysetstate -- set current state (the top of the stack) to yystate. | +`--------------------------------------------------------------------*/ +yysetstate: + YYDPRINTF ((stderr, "Entering state %d\n", yystate)); + YY_ASSERT (0 <= yystate && yystate < YYNSTATES); + YY_IGNORE_USELESS_CAST_BEGIN + *yyssp = YY_CAST (yy_state_t, yystate); + YY_IGNORE_USELESS_CAST_END + YY_STACK_PRINT (yyss, yyssp); + + if (yyss + yystacksize - 1 <= yyssp) +#if !defined yyoverflow && !defined YYSTACK_RELOCATE + YYNOMEM; +#else + { + /* Get the current used size of the three stacks, in elements. */ + YYPTRDIFF_T yysize = yyssp - yyss + 1; + +# if defined yyoverflow + { + /* Give user a chance to reallocate the stack. Use copies of + these so that the &'s don't force the real ones into + memory. */ + yy_state_t *yyss1 = yyss; + YYSTYPE *yyvs1 = yyvs; + + /* Each stack pointer address is followed by the size of the + data in use in that stack, in bytes. This used to be a + conditional around just the two extra args, but that might + be undefined if yyoverflow is a macro. */ + yyoverflow (YY_("memory exhausted"), + &yyss1, yysize * YYSIZEOF (*yyssp), + &yyvs1, yysize * YYSIZEOF (*yyvsp), + &yystacksize); + yyss = yyss1; + yyvs = yyvs1; + } +# else /* defined YYSTACK_RELOCATE */ + /* Extend the stack our own way. */ + if (YYMAXDEPTH <= yystacksize) + YYNOMEM; + yystacksize *= 2; + if (YYMAXDEPTH < yystacksize) + yystacksize = YYMAXDEPTH; + + { + yy_state_t *yyss1 = yyss; + union yyalloc *yyptr = + YY_CAST (union yyalloc *, + YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize)))); + if (! yyptr) + YYNOMEM; + YYSTACK_RELOCATE (yyss_alloc, yyss); + YYSTACK_RELOCATE (yyvs_alloc, yyvs); +# undef YYSTACK_RELOCATE + if (yyss1 != yyssa) + YYSTACK_FREE (yyss1); + } +# endif + + yyssp = yyss + yysize - 1; + yyvsp = yyvs + yysize - 1; + + YY_IGNORE_USELESS_CAST_BEGIN + YYDPRINTF ((stderr, "Stack size increased to %ld\n", + YY_CAST (long, yystacksize))); + YY_IGNORE_USELESS_CAST_END + + if (yyss + yystacksize - 1 <= yyssp) + YYABORT; + } +#endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ + + + if (yystate == YYFINAL) + YYACCEPT; + + goto yybackup; + + +/*-----------. +| yybackup. | +`-----------*/ +yybackup: + /* Do appropriate processing given the current state. Read a + lookahead token if we need one and don't already have one. */ + + /* First try to decide what to do without reference to lookahead token. */ + yyn = yypact[yystate]; + if (yypact_value_is_default (yyn)) + goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* YYCHAR is either empty, or end-of-input, or a valid lookahead. */ + if (yychar == YYEMPTY) + { + YYDPRINTF ((stderr, "Reading a token\n")); + yychar = yylex (); + } + + if (yychar <= YYEOF) + { + yychar = YYEOF; + yytoken = YYSYMBOL_YYEOF; + YYDPRINTF ((stderr, "Now at end of input.\n")); + } + else if (yychar == YYerror) + { + /* The scanner already issued an error message, process directly + to error recovery. But do not keep the error token as + lookahead, it is too special and may lead us to an endless + loop in error recovery. */ + yychar = YYUNDEF; + yytoken = YYSYMBOL_YYerror; + goto yyerrlab1; + } + else + { + yytoken = YYTRANSLATE (yychar); + YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); + } + + /* If the proper action on seeing token YYTOKEN is to reduce or to + detect an error, take that action. */ + yyn += yytoken; + if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) + goto yydefault; + yyn = yytable[yyn]; + if (yyn <= 0) + { + if (yytable_value_is_error (yyn)) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + /* Count tokens shifted since error; after three, turn off error + status. */ + if (yyerrstatus) + yyerrstatus--; + + /* Shift the lookahead token. */ + YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); + yystate = yyn; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + + /* Discard the shifted token. */ + yychar = YYEMPTY; + goto yynewstate; + + +/*-----------------------------------------------------------. +| yydefault -- do the default action for the current state. | +`-----------------------------------------------------------*/ +yydefault: + yyn = yydefact[yystate]; + if (yyn == 0) + goto yyerrlab; + goto yyreduce; + + +/*-----------------------------. +| yyreduce -- do a reduction. | +`-----------------------------*/ +yyreduce: + /* yyn is the number of a rule to reduce with. */ + yylen = yyr2[yyn]; + + /* If YYLEN is nonzero, implement the default value of the action: + '$$ = $1'. + + Otherwise, the following line sets YYVAL to garbage. + This behavior is undocumented and Bison + users should not rely upon it. Assigning to YYVAL + unconditionally makes the parser a bit smaller, and it avoids a + GCC warning that YYVAL may be used uninitialized. */ + yyval = yyvsp[1-yylen]; + + + YY_REDUCE_PRINT (yyn); + switch (yyn) + { + case 2: /* rc: %empty */ +#line 34 "sys/cmd/rc/syntax.y" + { return 0; } +#line 1125 "sys/cmd/rc/parse.c" + break; + + case 3: /* rc: line '\n' */ +#line 35 "sys/cmd/rc/syntax.y" + { return compile((yyvsp[-1].tree)); } +#line 1131 "sys/cmd/rc/parse.c" + break; + + case 5: /* line: cmds line */ +#line 39 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree2(';', (yyvsp[-1].tree), (yyvsp[0].tree)); } +#line 1137 "sys/cmd/rc/parse.c" + break; + + case 7: /* body: cmdsln body */ +#line 43 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree2(';', (yyvsp[-1].tree), (yyvsp[0].tree)); } +#line 1143 "sys/cmd/rc/parse.c" + break; + + case 8: /* paren: '(' body ')' */ +#line 46 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree1(Tparen, (yyvsp[-1].tree)); } +#line 1149 "sys/cmd/rc/parse.c" + break; + + case 9: /* block: '{' body '}' */ +#line 49 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree1(Tblock, (yyvsp[-1].tree)); } +#line 1155 "sys/cmd/rc/parse.c" + break; + + case 11: /* cmds: cmd '&' */ +#line 53 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree1('&', (yyvsp[-1].tree)); } +#line 1161 "sys/cmd/rc/parse.c" + break; + + case 14: /* ifbody: cmd */ +#line 60 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree2(Tif, nil, (yyvsp[0].tree)); } +#line 1167 "sys/cmd/rc/parse.c" + break; + + case 15: /* ifbody: block Telse nl cmd */ +#line 61 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree3(Tif, nil, (yyvsp[-3].tree), (yyvsp[-2].tree)); } +#line 1173 "sys/cmd/rc/parse.c" + break; + + case 16: /* cmd: %empty */ +#line 67 "sys/cmd/rc/syntax.y" + { (yyval.tree) = nil; } +#line 1179 "sys/cmd/rc/parse.c" + break; + + case 17: /* cmd: basic */ +#line 68 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree1(Tbasic, (yyvsp[0].tree)); } +#line 1185 "sys/cmd/rc/parse.c" + break; + + case 19: /* cmd: Tif paren nl ifbody */ +#line 70 "sys/cmd/rc/syntax.y" + { (yyval.tree) = hangchild1((yyvsp[-2].tree), (yyvsp[-3].tree), 0); } +#line 1191 "sys/cmd/rc/parse.c" + break; + + case 21: /* basic: basic word */ +#line 74 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree2(Targs, (yyvsp[-1].tree), (yyvsp[0].tree)); } +#line 1197 "sys/cmd/rc/parse.c" + break; + + case 23: /* atom: keyword */ +#line 84 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree1(Tword, (yyvsp[0].tree)); } +#line 1203 "sys/cmd/rc/parse.c" + break; + + case 25: /* word: word '^' atom */ +#line 88 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree2('^', (yyvsp[-2].tree), (yyvsp[0].tree)); } +#line 1209 "sys/cmd/rc/parse.c" + break; + + case 27: /* executable: executable '^' atom */ +#line 92 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree2('^', (yyvsp[-2].tree), (yyvsp[0].tree)); } +#line 1215 "sys/cmd/rc/parse.c" + break; + + case 29: /* nonkeyword: '$' atom */ +#line 96 "sys/cmd/rc/syntax.y" + { (yyval.tree) = maketree1('$', (yyvsp[0].tree)); } +#line 1221 "sys/cmd/rc/parse.c" + break; + + +#line 1225 "sys/cmd/rc/parse.c" + + default: break; + } + /* User semantic actions sometimes alter yychar, and that requires + that yytoken be updated with the new translation. We take the + approach of translating immediately before every use of yytoken. + One alternative is translating here after every semantic action, + but that translation would be missed if the semantic action invokes + YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or + if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an + incorrect destructor might then be invoked immediately. In the + case of YYERROR or YYBACKUP, subsequent parser actions might lead + to an incorrect destructor call or verbose syntax error message + before the lookahead is translated. */ + YY_SYMBOL_PRINT ("-> $$ =", YY_CAST (yysymbol_kind_t, yyr1[yyn]), &yyval, &yyloc); + + YYPOPSTACK (yylen); + yylen = 0; + + *++yyvsp = yyval; + + /* Now 'shift' the result of the reduction. Determine what state + that goes to, based on the state we popped back to and the rule + number reduced by. */ + { + const int yylhs = yyr1[yyn] - YYNTOKENS; + const int yyi = yypgoto[yylhs] + *yyssp; + yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp + ? yytable[yyi] + : yydefgoto[yylhs]); + } + + goto yynewstate; + + +/*--------------------------------------. +| yyerrlab -- here on detecting error. | +`--------------------------------------*/ +yyerrlab: + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE (yychar); + /* If not already recovering from an error, report this error. */ + if (!yyerrstatus) + { + ++yynerrs; + yyerror (YY_("syntax error")); + } + + if (yyerrstatus == 3) + { + /* If just tried and failed to reuse lookahead token after an + error, discard it. */ + + if (yychar <= YYEOF) + { + /* Return failure if at end of input. */ + if (yychar == YYEOF) + YYABORT; + } + else + { + yydestruct ("Error: discarding", + yytoken, &yylval); + yychar = YYEMPTY; + } + } + + /* Else will try to reuse lookahead token after shifting the error + token. */ + goto yyerrlab1; + + +/*---------------------------------------------------. +| yyerrorlab -- error raised explicitly by YYERROR. | +`---------------------------------------------------*/ +yyerrorlab: + /* Pacify compilers when the user code never invokes YYERROR and the + label yyerrorlab therefore never appears in user code. */ + if (0) + YYERROR; + ++yynerrs; + + /* Do not reclaim the symbols of the rule whose action triggered + this YYERROR. */ + YYPOPSTACK (yylen); + yylen = 0; + YY_STACK_PRINT (yyss, yyssp); + yystate = *yyssp; + goto yyerrlab1; + + +/*-------------------------------------------------------------. +| yyerrlab1 -- common code for both syntax error and YYERROR. | +`-------------------------------------------------------------*/ +yyerrlab1: + yyerrstatus = 3; /* Each real token shifted decrements this. */ + + /* Pop stack until we find a state that shifts the error token. */ + for (;;) + { + yyn = yypact[yystate]; + if (!yypact_value_is_default (yyn)) + { + yyn += YYSYMBOL_YYerror; + if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror) + { + yyn = yytable[yyn]; + if (0 < yyn) + break; + } + } + + /* Pop the current state because it cannot handle the error token. */ + if (yyssp == yyss) + YYABORT; + + + yydestruct ("Error: popping", + YY_ACCESSING_SYMBOL (yystate), yyvsp); + YYPOPSTACK (1); + yystate = *yyssp; + YY_STACK_PRINT (yyss, yyssp); + } + + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + + + /* Shift the error token. */ + YY_SYMBOL_PRINT ("Shifting", YY_ACCESSING_SYMBOL (yyn), yyvsp, yylsp); + + yystate = yyn; + goto yynewstate; + + +/*-------------------------------------. +| yyacceptlab -- YYACCEPT comes here. | +`-------------------------------------*/ +yyacceptlab: + yyresult = 0; + goto yyreturnlab; + + +/*-----------------------------------. +| yyabortlab -- YYABORT comes here. | +`-----------------------------------*/ +yyabortlab: + yyresult = 1; + goto yyreturnlab; + + +/*-----------------------------------------------------------. +| yyexhaustedlab -- YYNOMEM (memory exhaustion) comes here. | +`-----------------------------------------------------------*/ +yyexhaustedlab: + yyerror (YY_("memory exhausted")); + yyresult = 2; + goto yyreturnlab; + + +/*----------------------------------------------------------. +| yyreturnlab -- parsing is finished, clean up and return. | +`----------------------------------------------------------*/ +yyreturnlab: + if (yychar != YYEMPTY) + { + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = YYTRANSLATE (yychar); + yydestruct ("Cleanup: discarding lookahead", + yytoken, &yylval); + } + /* Do not reclaim the symbols of the rule whose action triggered + this YYABORT or YYACCEPT. */ + YYPOPSTACK (yylen); + YY_STACK_PRINT (yyss, yyssp); + while (yyssp != yyss) + { + yydestruct ("Cleanup: popping", + YY_ACCESSING_SYMBOL (+*yyssp), yyvsp); + YYPOPSTACK (1); + } +#ifndef yyoverflow + if (yyss != yyssa) + YYSTACK_FREE (yyss); +#endif + + return yyresult; +} + +#line 104 "sys/cmd/rc/syntax.y" + diff --git a/sys/cmd/rc/parse.h b/sys/cmd/rc/parse.h new file mode 100644 index 0000000..5328340 --- /dev/null +++ b/sys/cmd/rc/parse.h @@ -0,0 +1,107 @@ +/* A Bison parser, made by GNU Bison 3.8.2. */ + +/* Bison interface for Yacc-like parsers in C + + Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2021 Free Software Foundation, + Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + +/* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, + especially those whose name start with YY_ or yy_. They are + private implementation details that can be changed or removed. */ + +#ifndef YY_YY_SYS_CMD_RC_PARSE_H_INCLUDED +# define YY_YY_SYS_CMD_RC_PARSE_H_INCLUDED +/* Debug traces. */ +#ifndef YYDEBUG +# define YYDEBUG 0 +#endif +#if YYDEBUG +extern int yydebug; +#endif + +/* Token kinds. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + enum yytokentype + { + YYEMPTY = -2, + YYEOF = 0, /* "end of file" */ + YYerror = 256, /* error */ + YYUNDEF = 257, /* "invalid token" */ + Tword = 258, /* Tword */ + Tif = 259, /* Tif */ + Telse = 260, /* Telse */ + Tbang = 261, /* Tbang */ + Targs = 262, /* Targs */ + Tbasic = 263, /* Tbasic */ + Tparen = 264, /* Tparen */ + Tblock = 265, /* Tblock */ + Twhile = 266 /* Twhile */ + }; + typedef enum yytokentype yytoken_kind_t; +#endif +/* Token kinds. */ +#define YYEMPTY -2 +#define YYEOF 0 +#define YYerror 256 +#define YYUNDEF 257 +#define Tword 258 +#define Tif 259 +#define Telse 260 +#define Tbang 261 +#define Targs 262 +#define Tbasic 263 +#define Tparen 264 +#define Tblock 265 +#define Twhile 266 + +/* Value type. */ +#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED +union YYSTYPE +{ +#line 20 "sys/cmd/rc/syntax.y" + + struct Tree *tree; + +#line 93 "sys/cmd/rc/parse.h" + +}; +typedef union YYSTYPE YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 +# define YYSTYPE_IS_DECLARED 1 +#endif + + +extern YYSTYPE yylval; + + +int yyparse (void); + + +#endif /* !YY_YY_SYS_CMD_RC_PARSE_H_INCLUDED */ diff --git a/sys/cmd/rc/prompt.c b/sys/cmd/rc/prompt.c new file mode 100644 index 0000000..b4b1d96 --- /dev/null +++ b/sys/cmd/rc/prompt.c @@ -0,0 +1,17 @@ +#include "rc.h" + +int +prompt(ushort *flag) +{ + int f = *flag; + if(f){ + if(!readline("> ")){ + shell->flag.eof = 1; + return 0; + } + + shell->line++; + *flag = 0; + } + return 1; +} diff --git a/sys/cmd/rc/rc.h b/sys/cmd/rc/rc.h new file mode 100644 index 0000000..1c2aa6b --- /dev/null +++ b/sys/cmd/rc/rc.h @@ -0,0 +1,196 @@ +#pragma once + +#include <u.h> +#include <libn.h> + +// ----------------------------------------------------------------------- +// types + +typedef struct Io Io; +typedef struct Var Var; +typedef struct Word Word; +typedef struct List List; +typedef struct Tree Tree; +typedef struct Redir Redir; +typedef union Code Code; +typedef struct Thread Thread; + +typedef struct WaitMsg WaitMsg; + +struct Io +{ + int fd, cap; + char *s; + char *b, *e, buf[]; +}; + +struct Tree +{ + int type; + char *str; + Tree *child[3]; + Tree *link; +}; + +struct Word +{ + char *str; + Word *link; +}; + +struct List +{ + Word *word; + List *link; +}; + +/* + * the first word of any code vector is a reference count + * always create a new reference to a code vector by calling copycode() + * always call freecode() when deleting a reference + */ +union Code +{ + int i; + void (*f)(void); + char *s; +}; + +struct Var +{ + char *name; + Word *val; + short new : 1; + short newfunc : 1; + Code *func; + void (*update)(Var *); + Var *link; +}; + +enum +{ + Rclose, + Rdup, + Ropen, +}; + +struct Redir +{ + char type; /* what to do */ + short from, to; /* what to do it to */ + struct Redir *link; /* what else to do (reverse order) */ +}; + +struct Thread +{ + struct { + int i; + Code *exe; + } code; // execution stack + struct { + Io *io; + char *path; + } cmd; // command input + + List *args; // argument stack + Var *local; // local variables + Redir *redir; // list of redirections + + struct { + ushort i : 1; + ushort eof : 1; + } flag; // flags for process + + int pid; + long line; + + Tree *nodes; // memory allocation + Thread *link; // process we return to +}; + +struct WaitMsg +{ + int pid; // of loved one + ulong time[3]; // of loved one & descendants + char *msg; +}; + +// ----------------------------------------------------------------------- +// globals + +extern int rcpid; +extern Thread *shell; +extern Io *errio; +extern Code *compiled; + +// ----------------------------------------------------------------------- +// functions + +/* util.c */ +void itoa(char*, long i); +void fatal(char *, ...); +void *emalloc(uintptr); +void *erealloc(void*, uintptr); +void efree(void*); + +/* read.c */ +int readline(char *); +void enablevi(void); + +/* prompt.c */ +int prompt(ushort *); + +/* io.c */ +Io *openfd(int fd); +Io *openstr(void); +void terminate(Io *io); + +int get(Io *); +int put(Io **, char); + +void flush(Io *io); +void print(Io *, char *, ...); + +/* lex.c */ +int iswordchar(int c); +int yylex(void); + +/* tree.c */ +Tree *maketree(void); +Tree *maketree1(int, Tree*); +Tree *maketree2(int, Tree*, Tree*); +Tree *maketree3(int, Tree*, Tree*, Tree*); + +Tree *token(int, char *); +Tree *hangchild1(Tree *, Tree *, int at); + +void freeparsetree(void); + +/* sys.c */ +void initenv(void); + +void addwait(int); +void clearwait(void); +int waitfor(int); + +void execute(Word *, Word*); + +/* exec.c */ +// XXX: odd place for this +int count(Word *); +Word *makeword(char *str, Word *link); +void freeword(Word *w); +void initpath(void); + +/* var.c */ +Var *var(char*); +Var *definevar(char*, Var *); +Var *globalvar(char*); +Var *makevar(char *name, Var *link); +void setvar(char *, Word *); +char **mkenv(void); + +/* code.c */ +int compile(Tree *); +Code *copycode(Code *c); +void freecode(Code *c); diff --git a/sys/cmd/rc/rules.mk b/sys/cmd/rc/rules.mk new file mode 100644 index 0000000..44c9b7a --- /dev/null +++ b/sys/cmd/rc/rules.mk @@ -0,0 +1,29 @@ +include share/push.mk +# Iterate through subdirectory tree + +# Local sources +SRCS_$(d) :=\ + $(d)/util.c\ + $(d)/input.c\ + $(d)/prompt.c\ + $(d)/io.c\ + $(d)/lex.c\ + $(d)/parse.c\ + $(d)/tree.c\ + $(d)/code.c\ + $(d)/var.c\ + $(d)/sys.c\ + $(d)/exec.c\ + $(d)/main.c + +BINS_$(d) := $(d)/rc + +include share/paths.mk +$(d)/parse.h $(d)/parse.c: $(d)/syntax.y + yacc --header=$(<D)/parse.h --output=$(<D)/parse.c $(<) + +# Local rules +$(BINS_$(d)): $(OBJS_$(d)) $(OBJ_DIR)/sys/libn/libn.a $(d)/parse.h + $(COMPLINK) + +include share/pop.mk diff --git a/sys/cmd/rc/syntax.y b/sys/cmd/rc/syntax.y new file mode 100644 index 0000000..247cc8a --- /dev/null +++ b/sys/cmd/rc/syntax.y @@ -0,0 +1,104 @@ +%token Tword Tif Telse Tbang +%token Targs +%token Tbasic Tparen Tblock + +%{ + #include "rc.h" + + int yylex(void); + void yyerror(char *); +%} + +/* operator precendence: lowest first */ +%right Telse +%left Twhile +%left '\n' +%left Tbang +%right '$' + +/* semantic types */ +%union{ + struct Tree *tree; +} +%type<tree> line cmds cmdsln body paren block ifbody assign; +%type<tree> cmd basic executable nonkeyword keyword word atom arg args; +%type<tree> Tbang; +%type<tree> Tword Tif Telse; + +/* grammar */ + +%start rc + +%% +rc: +/*empty*/ { return 0; } +| line '\n' { return compile($1); } + +line: + cmd +| cmds line { $$ = maketree2(';', $1, $2); } + +body: + cmd +| cmdsln body { $$ = maketree2(';', $1, $2); } + +paren: + '(' body ')' { $$ = maketree1(Tparen, $2); } + +block: + '{' body '}' { $$ = maketree1(Tblock, $2); } + +cmds: + cmd ';' +| cmd '&' { $$ = maketree1('&', $1); } + +cmdsln: + cmds +| cmd '\n' + +ifbody: + cmd %prec Telse { $$ = maketree2(Tif, nil, $1); } +| block Telse nl cmd { $$ = maketree3(Tif, nil, $1, $2); } + +assign: + executable '=' word { $$ = maketree2('=', $1, $3); } + +cmd: +/* empty */ %prec Twhile { $$ = nil; } +| basic { $$ = maketree1(Tbasic, $1); } +| block +| Tif paren nl ifbody { $$ = hangchild1($2, $1, 0); } + +basic: + executable +| basic word { $$ = maketree2(Targs, $1, $2); } + +arg: word + +args: + arg +| args arg { $$ = maketree2(Targs, $1, $2); } + +atom: + nonkeyword +| keyword { $$ = maketree1(Tword, $1); } + +word: + atom +| word '^' atom { $$ = maketree2('^', $1, $3); } + +executable: + nonkeyword +| executable '^' atom { $$ = maketree2('^', $1, $3); } + +nonkeyword: + Tword +| '$' atom { $$ = maketree1('$', $2); } + +keyword: + Tif|Telse + +nl: +/*empty*/ +| nl '\n' +%% diff --git a/sys/cmd/rc/sys.c b/sys/cmd/rc/sys.c new file mode 100644 index 0000000..2c6a19d --- /dev/null +++ b/sys/cmd/rc/sys.c @@ -0,0 +1,139 @@ +#include "rc.h" + +struct Wait +{ + int len, cap, *pid; +}; + +static struct Wait wait; + +// ----------------------------------------------------------------------- +// internal + +static +char** +mkargv(Word *args) +{ + char **argv=emalloc((count(args)+2)*sizeof(char *)); + char **argp=argv+1; /* leave one at front for runcoms */ + + for(;args;args=args->link) + *argp++=args->str; + *argp=nil; + + return argv; +} + +static +Word* +envval(char *s) +{ + Word *v; + char *t, c; + + for(t=s; *t && *t!='\1'; t++) + ; + + c = *t; + *t = '\0'; + + v = makeword(s, (c=='\0') ? nil : envval(t+1)); + *t=c; + + return v; +} + +// ----------------------------------------------------------------------- +// exported + +void +initenv(void) +{ + extern char **environ; + + char *s; + char **env; + + for(env=environ; *env; env++) { + for(s=*env; *s && *s != '(' && *s != '='; s++) + ; + switch(*s){ + case '\0': + break; + case '(': /* ignore functions */ + break; + case '=': + *s = '\0'; + setvar(*env, envval(s+1)); + *s = '='; + break; + } + } +} + +void +clearwait(void) +{ + wait.len = 0; +} + +int +havewait(int pid) +{ + int i; + + for(i=0; i<wait.len; i++) + if(wait.pid[i] == pid) + return 1; + return 0; +} + +void +addwait(int pid) +{ + if(wait.len == wait.cap){ + wait.cap = wait.cap + 2; + wait.pid = erealloc(wait.pid, wait.cap*sizeof(*wait.pid)); + } + wait.pid[wait.len++] = pid; +} + +/* +int +waitfor(int pid) +{ + Thread *p; + struct WaitMsg *w; + char errbuf[ERRMAX]; + + if(pid >= 0 && !havewait(pid)) + return 0; +} +*/ + +void +execute(Word *cmd, Word *path) +{ + int nc; + char **argv = mkargv(cmd); + char **env = mkenv(); + char file[1024]; + + for(; path; path=path->link){ + nc = strlen(path->str); + if(nc < arrlen(file)){ + strcpy(file, path->str); + if(*file){ + strcat(file, "/"); + nc++; + } + if(nc+strlen(argv[1]) < 1024){ + strcat(file, argv[1]); + execve(file, argv+1, env); + }else + fatal("command name too long"); + } + } + efree(argv); + fatal("failed to exec\n"); +} diff --git a/sys/cmd/rc/tree.c b/sys/cmd/rc/tree.c new file mode 100644 index 0000000..0e2146f --- /dev/null +++ b/sys/cmd/rc/tree.c @@ -0,0 +1,79 @@ +#include "rc.h" +#include "parse.h" + +static Tree *nodes; + +Tree* +maketree(void) +{ + Tree *node = emalloc(sizeof(*node)); + + node->link = nodes; + nodes = node; + return node; +} + +void +freeparsetree(void) +{ + Tree *t, *nt; + for(t = nodes; t; t = nt) { + nt = t->link; + if(t->str) + efree(t->str); + efree(t); + } + nodes = nil; +} + +Tree* +maketree1(int type, Tree *c0) +{ + return maketree2(type, c0, nil); +} + +Tree* +maketree2(int type, Tree *c0, Tree *c1) +{ + return maketree3(type, c0, c1, nil); +} + +Tree* +maketree3(int type, Tree *c0, Tree *c1, Tree *c2) +{ + Tree *node = maketree(); + + node->type = type; + node->child[0] = c0; + node->child[1] = c1; + node->child[2] = c2; + + return node; +} + +Tree* +hangchild1(Tree *node, Tree *c, int i) +{ + node->child[i] = c; + + return node; +} + +Tree* +token(int type, char *s) +{ + Tree *node = maketree(); + + node->type = type; + node->str = strdup(s); + + return node; +} + +/* +Tree* +basic(Tree *node) +{ + return maketree1(Tbasic, node); +} +*/ diff --git a/sys/cmd/rc/util.c b/sys/cmd/rc/util.c new file mode 100644 index 0000000..b0be788 --- /dev/null +++ b/sys/cmd/rc/util.c @@ -0,0 +1,65 @@ +#include "rc.h" + +void +fatal(char *msg, ...) +{ + va_list args; + vfprintf(stderr, msg, args); + va_end(args); + + abort(); +} + +void* +emalloc(uintptr n) +{ + void *p; + if(!(p = malloc(n))) + fatal("out of memory: can't allocate %d bytes", n); + + memset(p, 0, n); + return p; +} + +void* +erealloc(void *p, uintptr n) +{ + void *r; + if(!(r = realloc(p,n))) + fatal("out of memory: can't reallocate %d bytes", n); + + return r; +} + +void +efree(void *p) +{ + if(p) + free(p); + // TODO: log the double free +} + + +char *bp; + +static +void +iacvt(int n) +{ + if(n<0){ + *bp++='-'; + n=-n; /* doesn't work for n==-inf */ + } + if(n/10) + iacvt(n/10); + + *bp++=n%10+'0'; +} + +void +itoa(char *s, long n) +{ + bp = s; + iacvt(n); + *bp='\0'; +} diff --git a/sys/cmd/rc/var.c b/sys/cmd/rc/var.c new file mode 100644 index 0000000..f0e5f5b --- /dev/null +++ b/sys/cmd/rc/var.c @@ -0,0 +1,271 @@ +#include "rc.h" + +static Var *globals[512]; + +// ----------------------------------------------------------------------- +// internals + +static +int +hash(char *s, int len) +{ + int h =0, i = 1; + while(*s) + h += *s++*i++; + + h %= len; + return h < 0 ? h+len : h; +} + +static +void +·setvar(char *name, Word *val, int call) +{ + Var *v = var(name); + freeword(v->val); + + v->val = val; + v->new = 1; // this never turns off? + + if(call && v->update) + v->update(v); +} + +static +char* +list2strcolon(Word *words) +{ + char *value, *s, *t; + int len = 0; + Word *ap; + for(ap = words;ap;ap = ap->link) + len+=1+strlen(ap->str); + + value = emalloc(len+1); + + s = value; + for(ap = words; ap; ap = ap->link){ + for(t = ap->str;*t;) *s++=*t++; + *s++=':'; + } + + if(s==value) + *s='\0'; + else + s[-1]='\0'; + + return value; +} + +static +void +littlepath(Var *v) +{ + /* convert $path to $PATH */ + char *p; + Word *w; + + p = list2strcolon(v->val); + w = emalloc(sizeof(*w)); + w->str = p; + w->link = nil; + + ·setvar("PATH", w, 1); +} + +static +void +bigpath(Var *v) +{ + /* convert $PATH to $path */ + char *p, *q; + Word **l, *w; + + if(v->val == nil){ + ·setvar("path", nil, 0); + return; + } + + p = v->val->str; + w = nil; + l = &w; + + /* Doesn't handle escaped colon nonsense. */ + if(p[0] == 0) + p = nil; + + while(p){ + q = strchr(p, ':'); + if(q) + *q = 0; + + *l = makeword(p[0] ? p : ".", nil); + l = &(*l)->link; + + if(q){ + *q = ':'; + p = q+1; + }else + p = nil; + } + ·setvar("path", w, 0); +} + + + +// ----------------------------------------------------------------------- +// exports + +Var* +makevar(char *name, Var *link) +{ + Var *v = emalloc(sizeof(*v)); + + v->name = name; + v->val = 0; + v->new = 0; + v->newfunc = 0; + v->link = link; + v->func = nil; + v->update = nil; + + return v; +} + +void +setvar(char *name, Word *val) +{ + ·setvar(name, val, 1); +} + +Var* +definevar(char *name, Var *link) +{ + Var *v = emalloc(sizeof(*v)); + + v->name = name; + v->val = 0; + v->link = link; + + return v; +} + +Var* +globalvar(char *name) +{ + int h; + Var *v; + + h = hash(name, arrlen(globals)); + + if(strcmp(name,"PATH")==0){ + flush(errio); + } + + for(v = globals[h]; v; v = v->link){ + if(strcmp(v->name, name) == 0){ + return v; + } + } + + return globals[h] = definevar(strdup(name), globals[h]); +} + +Var* +var(char *name) +{ + Var *v; + if(shell){ + for(v = shell->local; v; v=v->link) + if(strcmp(v->name, name) == 0) + return v; + } + return globalvar(name); +} + +static +int +cmpenv(const void *a, const void *b) +{ + return strcmp(*(char**)a, *(char**)b); +} + +char** +mkenv(void) +{ + char **env, **ep, *p, *q; + Var **h, *v; + Word *a; + int nvar=0, nchr=0, sep; + +#define BODY \ + if((v==var(v->name)) && v->val){ \ + nvar++; \ + nchr+=strlen(v->name)+1; \ + for(a=v->val;a;a=a->link) \ + nchr+=strlen(a->str)+1; \ + } + + for(v= shell->local; v; v=v->link){ + BODY + } + for(h=globals; h!=arrend(globals); h++){ + for(v = *h; v; v=v->link){ + BODY + } + } + +#undef BODY + + env=emalloc((nvar+1)*sizeof(*env)+nchr); + ep=env; + p=(char *)&env[nvar+1]; + +#define BODY \ + if((v==var(v->name)) && v->val){ \ + *ep++=p; \ + q=v->name; \ + while(*q) \ + *p++=*q++; \ + sep='='; \ + for(a=v->val;a;a=a->link){ \ + *p++=sep; \ + sep='\1'; \ + q=a->str; \ + while(*q) \ + *p++=*q++; \ + } \ + *p++='\0'; \ + } + + for(v=shell->local; v; v=v->link){ + BODY + } + for(h=globals; h!=arrend(globals); h++){ + for(v = *h; v; v=v->link){ + BODY + } + } +#undef BODY + + *ep=0; + + qsort((char *)env, nvar, sizeof ep[0], cmpenv); + return env; +} + +void +initpath(void) +{ + Var *v; + + v = globalvar("path"); + v->update = littlepath; + + v = globalvar("PATH"); + v->update = bigpath; + + flush(errio); + bigpath(v); +} + diff --git a/sys/cmd/rc/wait.c b/sys/cmd/rc/wait.c new file mode 100644 index 0000000..06f9614 --- /dev/null +++ b/sys/cmd/rc/wait.c @@ -0,0 +1,3 @@ +#include "rc.h" +#include <sys/wait.h> + |