~emersion/mrsh

a3e8e0570630cbafa59a9a6ae6ee64409c03b852 — Drew DeVault 3 years ago 0ffd30e
Implement eval builtin
4 files changed, 50 insertions(+), 0 deletions(-)

M builtin/builtin.c
A builtin/eval.c
M include/builtin.h
M meson.build
M builtin/builtin.c => builtin/builtin.c +1 -0
@@ 18,6 18,7 @@ static const struct builtin builtins[] = {
	{ ":", builtin_colon, true },
	{ "alias", builtin_alias, false },
	{ "cd", builtin_cd, true },
	{ "eval", builtin_eval, true },
	{ "exit", builtin_exit, true },
	{ "set", builtin_set, true },
	{ "times", builtin_times, true },

A builtin/eval.c => builtin/eval.c +47 -0
@@ 0,0 1,47 @@
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <errno.h>
#include <mrsh/builtin.h>
#include <mrsh/parser.h>
#include <mrsh/shell.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "buffer.h"
#include "builtin.h"

static const char eval_usage[] = "usage: eval [cmds...]\n";

int builtin_eval(struct mrsh_state *state, int argc, char *argv[]) {
	if (argc == 1) {
		fprintf(stderr, eval_usage);
		return EXIT_FAILURE;
	}

	struct buffer buf = {0};

	for (int i = 1; i < argc; ++i) {
		if (!buffer_reserve(&buf, strlen(argv[i]) + 1)) {
			fprintf(stderr, "Failed to expand parse buffer");
			return EXIT_FAILURE;
		}
		buffer_append(&buf, argv[i], strlen(argv[i]));
		if (i != argc - 1) {
			buffer_append_char(&buf, ' ');
		}
	}
	buffer_append_char(&buf, '\n');

	struct mrsh_parser *parser =
		mrsh_parser_create_from_buffer(buf.data, buf.len);
	struct mrsh_program *program = mrsh_parse_program(parser);
	buffer_finish(&buf);
	if (!program) {
		struct mrsh_position pos;
		fprintf(stderr, "%s %d:%d: %s\n",
				argv[1], pos.line, pos.column,
				mrsh_parser_error(parser, &pos));
		return EXIT_FAILURE;
	}
	return mrsh_run_program(state, program);
}

M include/builtin.h => include/builtin.h +1 -0
@@ 12,6 12,7 @@ int builtin_alias(struct mrsh_state *state, int argc, char *argv[]);
int builtin_cd(struct mrsh_state *state, int argc, char *argv[]);
int builtin_colon(struct mrsh_state *state, int argc, char *argv[]);
int builtin_exit(struct mrsh_state *state, int argc, char *argv[]);
int builtin_eval(struct mrsh_state *state, int argc, char *argv[]);
int builtin_source(struct mrsh_state *state, int argc, char *argv[]);
int builtin_times(struct mrsh_state *state, int argc, char *argv[]);


M meson.build => meson.build +1 -0
@@ 36,6 36,7 @@ lib_mrsh_static = static_library(
		'builtin/cd.c',
		'builtin/builtin.c',
		'builtin/colon.c',
		'builtin/eval.c',
		'builtin/exit.c',
		'builtin/set.c',
		'builtin/source.c',