aboutsummaryrefslogtreecommitdiffstats
path: root/apsh.c
blob: 4e7183b8ba4f1df5f62191ca1fb833e7a1e039b6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* See LICENSE file for copyright and license details. */
#include "common.h"

USAGE("");


void
initialise_parser_context(struct parser_context *ctx)
{
	memset(ctx, 0, sizeof(*ctx));
	ctx->preparser_line_number = 1;
	ctx->tokeniser_line_number = 1;
	ctx->mode_stack = ecalloc(1, sizeof(*ctx->mode_stack));
	ctx->mode_stack->mode = NORMAL_MODE;
	ctx->mode_stack->she_is_comment = 1;
	ctx->parser_state = ecalloc(1, sizeof(*ctx->parser_state));
	ctx->here_documents_next = &ctx->here_documents_first;
}

int
main(int argc, char *argv[])
{
	struct parser_context ctx;
	char *buffer = NULL;
	size_t buffer_size = 0;
	size_t buffer_head = 0;
	size_t buffer_tail = 0;
	ssize_t r;
	size_t n, nremoved;

	ARGBEGIN {
	default:
		usage();
	} ARGEND;

	if (argc)
		usage();

	initialise_parser_context(&ctx);
	ctx.tty_input = isatty(STDIN_FILENO);
	if (ctx.tty_input)
		weprintf("apsh is currently not implemented to be interactive\n");

	for (;;) {
		if (buffer_size - buffer_head < PARSE_RINGBUFFER_MIN_AVAILABLE) {
			if (buffer_tail && buffer_head - buffer_tail <= buffer_tail) {
				memcpy(&buffer[0], &buffer[buffer_tail], buffer_head - buffer_tail);
				buffer_head -= buffer_tail;
				buffer_tail = 0;
			}
			if (buffer_size - buffer_head < PARSE_RINGBUFFER_MIN_AVAILABLE)
				buffer = erealloc(buffer, buffer_size += PARSE_RINGBUFFER_INCREASE_SIZE);
		}

		r = read(STDIN_FILENO, &buffer[buffer_head], buffer_size - buffer_head);
		if (r <= 0) {
			if (!r)
				break;
			eprintf("read <stdin>:");
		}
		n = (size_t)r;

		buffer_head += n;
		buffer_tail += n = parse(&ctx, &buffer[buffer_tail], buffer_head - buffer_tail, &nremoved);
		buffer_head -= nremoved;
	}

	ctx.end_of_file_reached = 1;
	buffer_tail += parse(&ctx, &buffer[buffer_tail], buffer_head - buffer_tail, &nremoved);
	buffer_head -= nremoved;
	if (buffer_tail != buffer_head || ctx.premature_end_of_file)
		eprintf("premature end of file reached\n");

	free(buffer);
	return 0;
}