mrsh/parser/program.c -rw-r--r-- 27.8 KiB View raw
                                                                                
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <ctype.h>
#include <mrsh/buffer.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ast.h"
#include "parser.h"

static const char *operator_str(enum symbol_name sym) {
	for (size_t i = 0; i < operators_len; ++i) {
		if (operators[i].name == sym) {
			return operators[i].str;
		}
	}
	return NULL;
}

static bool operator(struct mrsh_parser *state, enum symbol_name sym,
		struct mrsh_range *range) {
	if (!symbol(state, sym)) {
		return false;
	}

	struct mrsh_position begin = state->pos;

	const char *str = operator_str(sym);
	assert(str != NULL);

	char buf[operators_max_str_len];
	parser_read(state, buf, strlen(str));
	assert(strncmp(str, buf, strlen(str)) == 0);

	if (range != NULL) {
		range->begin = begin;
		range->end = state->pos;
	}

	consume_symbol(state);
	return true;
}

static int separator_op(struct mrsh_parser *state) {
	if (token(state, "&", NULL)) {
		return '&';
	}
	if (token(state, ";", NULL)) {
		return ';';
	}
	return -1;
}

static size_t peek_alias(struct mrsh_parser *state) {
	size_t n = peek_word(state, 0);

	for (size_t i = 0; i < n; ++i) {
		char c = state->buf.data[i];
		switch (c) {
		case '_':
		case '!':
		case '%':
		case ',':
		case '@':
			break;
		default:
			if (!isalnum(c)) {
				return 0;
			}
		}
	}

	return n;
}

static void apply_aliases(struct mrsh_parser *state) {
	if (state->alias == NULL) {
		return;
	}

	const char *last_repl = NULL;
	while (true) {
		if (!symbol(state, TOKEN)) {
			return;
		}

		size_t alias_len = peek_alias(state);
		if (alias_len == 0) {
			return;
		}

		char *name = strndup(state->buf.data, alias_len);
		const char *repl = state->alias(name, state->alias_user_data);
		free(name);
		if (repl == NULL || last_repl == repl) {
			break;
		}

		size_t trailing_len = state->buf.len - alias_len;
		size_t repl_len = strlen(repl);
		if (repl_len > alias_len) {
			mrsh_buffer_reserve(&state->buf, repl_len - alias_len);
		}
		memmove(&state->buf.data[repl_len], &state->buf.data[alias_len],
			state->buf.len - alias_len);
		memcpy(state->buf.data, repl, repl_len);
		state->buf.len = repl_len + trailing_len;

		// TODO: fixup state->pos
		// TODO: if repl's last char is blank, replace next alias too

		consume_symbol(state);
		last_repl = repl;
	}
}

static bool io_here(struct mrsh_parser *state, struct mrsh_io_redirect *redir) {
	if (operator(state, DLESS, &redir->op_range)) {
		redir->op = MRSH_IO_DLESS;
	} else if (operator(state, DLESSDASH, &redir->op_range)) {
		redir->op = MRSH_IO_DLESSDASH;
	} else {
		return false;
	}

	redir->name = word(state, 0);
	if (redir->name == NULL) {
		parser_set_error(state,
			"expected a name after IO here-document redirection operator");
		return false;
	}
	// TODO: check redir->name only contains word strings and lists

	return true;
}

static struct mrsh_word *filename(struct mrsh_parser *state) {
	// TODO: Apply rule 2
	return word(state, 0);
}

static int io_redirect_op(struct mrsh_parser *state, struct mrsh_range *range) {
	if (token(state, "<", range)) {
		return MRSH_IO_LESS;
	} else if (token(state, ">", range)) {
		return MRSH_IO_GREAT;
	} else if (operator(state, LESSAND, range)) {
		return MRSH_IO_LESSAND;
	} else if (operator(state, GREATAND, range)) {
		return MRSH_IO_GREATAND;
	} else if (operator(state, DGREAT, range)) {
		return MRSH_IO_DGREAT;
	} else if (operator(state, CLOBBER, range)) {
		return MRSH_IO_CLOBBER;
	} else if (operator(state, LESSGREAT, range)) {
		return MRSH_IO_LESSGREAT;
	} else {
		return -1;
	}
}

static bool io_file(struct mrsh_parser *state,
		struct mrsh_io_redirect *redir) {
	int op = io_redirect_op(state, &redir->op_range);
	if (op < 0) {
		return false;
	}
	redir->op = op;

	redir->name = filename(state);
	if (redir->name == NULL) {
		parser_set_error(state,
			"expected a filename after IO file redirection operator");
		return false;
	}

	return true;
}

static int io_number(struct mrsh_parser *state) {
	if (!symbol(state, TOKEN)) {
		return -1;
	}

	char c = parser_peek_char(state);
	if (!isdigit(c)) {
		return -1;
	}

	char buf[2];
	parser_peek(state, buf, sizeof(buf));
	if (buf[1] != '<' && buf[1] != '>') {
		return -1;
	}

	parser_read_char(state);
	consume_symbol(state);
	return strtol(buf, NULL, 10);
}

static struct mrsh_io_redirect *io_redirect(struct mrsh_parser *state) {
	struct mrsh_io_redirect redir = {0};

	struct mrsh_position io_number_pos = state->pos;
	redir.io_number = io_number(state);
	if (redir.io_number >= 0) {
		redir.io_number_pos = io_number_pos;
	}

	redir.op_range.begin = state->pos;
	if (io_file(state, &redir)) {
		struct mrsh_io_redirect *redir_ptr =
			calloc(1, sizeof(struct mrsh_io_redirect));
		memcpy(redir_ptr, &redir, sizeof(struct mrsh_io_redirect));
		redir.op_range.end = state->pos;
		return redir_ptr;
	}
	if (io_here(state, &redir)) {
		struct mrsh_io_redirect *redir_ptr =
			calloc(1, sizeof(struct mrsh_io_redirect));
		memcpy(redir_ptr, &redir, sizeof(struct mrsh_io_redirect));
		redir.op_range.end = state->pos;
		mrsh_array_add(&state->here_documents, redir_ptr);
		return redir_ptr;
	}

	if (redir.io_number >= 0) {
		parser_set_error(state, "expected an IO redirect after IO number");
	}
	return NULL;
}

static struct mrsh_assignment *assignment_word(struct mrsh_parser *state) {
	if (!symbol(state, TOKEN)) {
		return NULL;
	}

	size_t name_len = peek_name(state, false);
	if (name_len == 0) {
		return NULL;
	}

	parser_peek(state, NULL, name_len + 1);
	if (state->buf.data[name_len] != '=') {
		return NULL;
	}

	struct mrsh_range name_range;
	char *name = read_token(state, name_len, &name_range);

	struct mrsh_position equal_pos = state->pos;
	parser_read(state, NULL, 1);

	struct mrsh_word *value = word(state, 0);
	if (value == NULL) {
		value = &mrsh_word_string_create(strdup(""), false)->word;
	}

	struct mrsh_assignment *assign = calloc(1, sizeof(struct mrsh_assignment));
	assign->name = name;
	assign->value = value;
	assign->name_range = name_range;
	assign->equal_pos = equal_pos;
	return assign;
}

static bool cmd_prefix(struct mrsh_parser *state,
		struct mrsh_simple_command *cmd) {
	struct mrsh_io_redirect *redir = io_redirect(state);
	if (redir != NULL) {
		mrsh_array_add(&cmd->io_redirects, redir);
		return true;
	}

	struct mrsh_assignment *assign = assignment_word(state);
	if (assign != NULL) {
		mrsh_array_add(&cmd->assignments, assign);
		return true;
	}

	return false;
}

static struct mrsh_word *cmd_name(struct mrsh_parser *state) {
	apply_aliases(state);

	size_t word_len = peek_word(state, 0);
	if (word_len == 0) {
		return word(state, 0);
	}

	// TODO: optimize this
	for (size_t i = 0; i < keywords_len; ++i) {
		if (strlen(keywords[i]) == word_len &&
				strncmp(state->buf.data, keywords[i], word_len) == 0) {
			return NULL;
		}
	}

	struct mrsh_range range;
	char *str = read_token(state, word_len, &range);

	struct mrsh_word_string *ws = mrsh_word_string_create(str, false);
	ws->range = range;
	return &ws->word;
}

static bool cmd_suffix(struct mrsh_parser *state,
		struct mrsh_simple_command *cmd) {
	struct mrsh_io_redirect *redir = io_redirect(state);
	if (redir != NULL) {
		mrsh_array_add(&cmd->io_redirects, redir);
		return true;
	}

	struct mrsh_word *arg = word(state, 0);
	if (arg != NULL) {
		mrsh_array_add(&cmd->arguments, arg);
		return true;
	}

	return false;
}

static struct mrsh_simple_command *simple_command(struct mrsh_parser *state) {
	struct mrsh_simple_command cmd = {0};

	bool has_prefix = false;
	while (cmd_prefix(state, &cmd)) {
		has_prefix = true;
	}

	cmd.name = cmd_name(state);
	if (cmd.name == NULL && !has_prefix) {
		return NULL;
	} else if (cmd.name != NULL) {
		while (cmd_suffix(state, &cmd)) {
			// This space is intentionally left blank
		}
	}

	return mrsh_simple_command_create(cmd.name, &cmd.arguments,
		&cmd.io_redirects, &cmd.assignments);
}

static int separator(struct mrsh_parser *state) {
	int sep = separator_op(state);
	if (sep != -1) {
		linebreak(state);
		return sep;
	}

	if (newline_list(state)) {
		return '\n';
	}

	return -1;
}

static struct mrsh_and_or_list *and_or(struct mrsh_parser *state);

static struct mrsh_command_list *term(struct mrsh_parser *state) {
	struct mrsh_and_or_list *and_or_list = and_or(state);
	if (and_or_list == NULL) {
		return NULL;
	}

	struct mrsh_command_list *cmd = mrsh_command_list_create();
	cmd->and_or_list = and_or_list;

	struct mrsh_position separator_pos = state->pos;
	int sep = separator(state);
	if (sep == '&') {
		cmd->ampersand = true;
	}
	if (sep >= 0) {
		cmd->separator_pos = separator_pos;
	}

	return cmd;
}

static bool compound_list(struct mrsh_parser *state, struct mrsh_array *cmds) {
	linebreak(state);

	struct mrsh_command_list *l = term(state);
	if (l == NULL) {
		return false;
	}
	mrsh_array_add(cmds, l);

	while (true) {
		l = term(state);
		if (l == NULL) {
			break;
		}
		mrsh_array_add(cmds, l);
	}

	return true;
}

static bool expect_compound_list(struct mrsh_parser *state,
		struct mrsh_array *cmds) {
	if (!compound_list(state, cmds)) {
		parser_set_error(state, "expected a compound list");
		return false;
	}

	return true;
}

static struct mrsh_brace_group *brace_group(struct mrsh_parser *state) {
	struct mrsh_position lbrace_pos = state->pos;
	if (!token(state, "{", NULL)) {
		return NULL;
	}

	struct mrsh_array body = {0};
	if (!expect_compound_list(state, &body)) {
		return NULL;
	}

	struct mrsh_position rbrace_pos = state->pos;
	if (!expect_token(state, "}", NULL)) {
		command_list_array_finish(&body);
		return NULL;
	}

	struct mrsh_brace_group *bg = mrsh_brace_group_create(&body);
	bg->lbrace_pos = lbrace_pos;
	bg->rbrace_pos = rbrace_pos;
	return bg;
}

static struct mrsh_subshell *subshell(struct mrsh_parser *state) {
	struct mrsh_position lparen_pos = state->pos;
	if (!token(state, "(", NULL)) {
		return NULL;
	}

	struct mrsh_array body = {0};
	if (!expect_compound_list(state, &body)) {
		return NULL;
	}

	struct mrsh_position rparen_pos = state->pos;
	if (!expect_token(state, ")", NULL)) {
		command_list_array_finish(&body);
		return NULL;
	}

	struct mrsh_subshell *s = mrsh_subshell_create(&body);
	s->lparen_pos = lparen_pos;
	s->rparen_pos = rparen_pos;
	return s;
}

static struct mrsh_command *else_part(struct mrsh_parser *state) {
	struct mrsh_range if_range = {0};
	if (token(state, "elif", &if_range)) {
		struct mrsh_array cond = {0};
		if (!expect_compound_list(state, &cond)) {
			return NULL;
		}

		struct mrsh_range then_range;
		if (!expect_token(state, "then", &then_range)) {
			command_list_array_finish(&cond);
			return NULL;
		}

		struct mrsh_array body = {0};
		if (!expect_compound_list(state, &body)) {
			command_list_array_finish(&cond);
			return NULL;
		}

		struct mrsh_command *ep = else_part(state);

		struct mrsh_if_clause *ic = mrsh_if_clause_create(&cond, &body, ep);
		ic->if_range = if_range;
		ic->then_range = then_range;
		return &ic->command;
	}

	if (token(state, "else", NULL)) {
		struct mrsh_array body = {0};
		if (!expect_compound_list(state, &body)) {
			return NULL;
		}

		// TODO: position information is missing
		struct mrsh_brace_group *bg = mrsh_brace_group_create(&body);
		return &bg->command;
	}

	return NULL;
}

static struct mrsh_if_clause *if_clause(struct mrsh_parser *state) {
	struct mrsh_range if_range;
	if (!token(state, "if", &if_range)) {
		return NULL;
	}

	struct mrsh_array cond = {0};
	if (!expect_compound_list(state, &cond)) {
		goto error_cond;
	}

	struct mrsh_range then_range;
	if (!expect_token(state, "then", &then_range)) {
		goto error_cond;
	}

	struct mrsh_array body = {0};
	if (!expect_compound_list(state, &body)) {
		goto error_body;
	}

	struct mrsh_command *ep = else_part(state);

	struct mrsh_range fi_range;
	if (!expect_token(state, "fi", &fi_range)) {
		goto error_else_part;
	}

	struct mrsh_if_clause *ic = mrsh_if_clause_create(&cond, &body, ep);
	ic->if_range = if_range;
	ic->then_range = then_range;
	ic->fi_range = fi_range;
	return ic;

error_else_part:
	mrsh_command_destroy(ep);
error_body:
	command_list_array_finish(&body);
error_cond:
	command_list_array_finish(&cond);
	return NULL;
}

static bool sequential_sep(struct mrsh_parser *state) {
	if (token(state, ";", NULL)) {
		linebreak(state);
		return true;
	}
	return newline_list(state);
}

static void wordlist(struct mrsh_parser *state,
		struct mrsh_array *words) {
	while (true) {
		struct mrsh_word *w = word(state, 0);
		if (w == NULL) {
			break;
		}
		mrsh_array_add(words, w);
	}
}

static bool expect_do_group(struct mrsh_parser *state,
		struct mrsh_array *body, struct mrsh_range *do_range,
		struct mrsh_range *done_range) {
	if (!token(state, "do", do_range)) {
		parser_set_error(state, "expected 'do'");
		return false;
	}

	if (!expect_compound_list(state, body)) {
		return false;
	}

	if (!token(state, "done", done_range)) {
		parser_set_error(state, "expected 'done'");
		command_list_array_finish(body);
		return false;
	}

	return true;
}

static struct mrsh_for_clause *for_clause(struct mrsh_parser *state) {
	struct mrsh_range for_range;
	if (!token(state, "for", &for_range)) {
		return NULL;
	}

	size_t name_len = peek_name(state, false);
	if (name_len == 0) {
		parser_set_error(state, "expected name");
		return NULL;
	}

	struct mrsh_range name_range;
	char *name = read_token(state, name_len, &name_range);

	linebreak(state);

	struct mrsh_range in_range = {0};
	bool in = token(state, "in", &in_range);

	// TODO: save sequential_sep position, if any
	struct mrsh_array words = {0};
	if (in) {
		wordlist(state, &words);

		if (!sequential_sep(state)) {
			parser_set_error(state, "expected sequential separator");
			goto error_words;
		}
	} else {
		sequential_sep(state);
	}

	struct mrsh_array body = {0};
	struct mrsh_range do_range, done_range;
	if (!expect_do_group(state, &body, &do_range, &done_range)) {
		goto error_words;
	}

	struct mrsh_for_clause *fc =
		mrsh_for_clause_create(name, in, &words, &body);
	fc->for_range = for_range;
	fc->name_range = name_range;
	fc->in_range = in_range;
	fc->do_range = do_range;
	fc->done_range = done_range;
	return fc;

error_words:
	for (size_t i = 0; i < words.len; ++i) {
		struct mrsh_word *word = words.data[i];
		mrsh_word_destroy(word);
	}
	mrsh_array_finish(&words);
	free(name);
	return NULL;
}

static struct mrsh_loop_clause *loop_clause(struct mrsh_parser *state) {
	enum mrsh_loop_type type;
	struct mrsh_range while_until_range;
	if (token(state, "while", &while_until_range)) {
		type = MRSH_LOOP_WHILE;
	} else if (token(state, "until", &while_until_range)) {
		type = MRSH_LOOP_UNTIL;
	} else {
		return NULL;
	}

	struct mrsh_array condition = {0};
	if (!expect_compound_list(state, &condition)) {
		return NULL;
	}

	struct mrsh_array body = {0};
	struct mrsh_range do_range, done_range;
	if (!expect_do_group(state, &body, &do_range, &done_range)) {
		command_list_array_finish(&condition);
		return NULL;
	}

	struct mrsh_loop_clause *fc =
		mrsh_loop_clause_create(type, &condition, &body);
	fc->while_until_range = while_until_range;
	fc->do_range = do_range;
	fc->done_range = done_range;
	return fc;
}

static struct mrsh_case_item *expect_case_item(struct mrsh_parser *state,
		bool *dsemi) {
	struct mrsh_position lparen_pos = state->pos;
	if (!token(state, "(", NULL)) {
		lparen_pos = (struct mrsh_position){0};
	}

	struct mrsh_word *w = word(state, 0);
	if (w == NULL) {
		parser_set_error(state, "expected a word");
		return NULL;
	}

	struct mrsh_array patterns = {0};
	mrsh_array_add(&patterns, w);

	while (token(state, "|", NULL)) {
		struct mrsh_word *w = word(state, 0);
		if (w == NULL) {
			parser_set_error(state, "expected a word");
			return NULL;
		}
		mrsh_array_add(&patterns, w);
	}

	struct mrsh_position rparen_pos = state->pos;
	if (!expect_token(state, ")", NULL)) {
		goto error_patterns;
	}

	// It's okay if there's no body
	struct mrsh_array body = {0};
	compound_list(state, &body);
	if (mrsh_parser_error(state, NULL)) {
		goto error_patterns;
	}

	struct mrsh_range dsemi_range = {0};
	*dsemi = operator(state, DSEMI, &dsemi_range);
	if (*dsemi) {
		linebreak(state);
	}

	struct mrsh_case_item *item = calloc(1, sizeof(struct mrsh_case_item));
	if (item == NULL) {
		goto error_body;
	}
	item->patterns = patterns;
	item->body = body;
	item->lparen_pos = lparen_pos;
	item->rparen_pos = rparen_pos;
	item->dsemi_range = dsemi_range;
	return item;

error_body:
	command_list_array_finish(&body);
error_patterns:
	for (size_t i = 0; i < patterns.len; ++i) {
		struct mrsh_word *w = patterns.data[i];
		mrsh_word_destroy(w);
	}
	mrsh_array_finish(&patterns);
	return NULL;
}

static struct mrsh_case_clause *case_clause(struct mrsh_parser *state) {
	struct mrsh_range case_range;
	if (!token(state, "case", &case_range)) {
		return NULL;
	}

	struct mrsh_word *w = word(state, 0);
	if (w == NULL) {
		parser_set_error(state, "expected a word");
		return NULL;
	}

	linebreak(state);

	struct mrsh_range in_range;
	if (!expect_token(state, "in", &in_range)) {
		goto error_word;
	}

	linebreak(state);

	bool dsemi = false;
	struct mrsh_array items = {0};
	struct mrsh_range esac_range;
	while (!token(state, "esac", &esac_range)) {
		struct mrsh_case_item *item = expect_case_item(state, &dsemi);
		if (item == NULL) {
			goto error_items;
		}
		mrsh_array_add(&items, item);

		if (!dsemi) {
			// Only the last case can omit `;;`
			if (!expect_token(state, "esac", &esac_range)) {
				goto error_items;
			}
			break;
		}
	}

	struct mrsh_case_clause *cc = mrsh_case_clause_create(w, &items);
	cc->case_range = case_range;
	cc->in_range = in_range;
	cc->esac_range = esac_range;
	return cc;

error_items:
	for (size_t i = 0; i < items.len; ++i) {
		struct mrsh_case_item *item = items.data[i];
		case_item_destroy(item);
	}
	mrsh_array_finish(&items);
error_word:
	mrsh_word_destroy(w);
	return NULL;
}

static struct mrsh_command *compound_command(struct mrsh_parser *state);

static struct mrsh_function_definition *function_definition(
		struct mrsh_parser *state) {
	size_t name_len = peek_name(state, false);
	if (name_len == 0) {
		return NULL;
	}

	size_t i = name_len;
	while (true) {
		parser_peek(state, NULL, i + 1);

		char c = state->buf.data[i];
		if (c == '(') {
			break;
		} else if (!isblank(c)) {
			return NULL;
		}

		++i;
	}

	struct mrsh_range name_range;
	char *name = read_token(state, name_len, &name_range);

	struct mrsh_position lparen_pos = state->pos;
	if (!expect_token(state, "(", NULL)) {
		return NULL;
	}

	struct mrsh_position rparen_pos = state->pos;
	if (!expect_token(state, ")", NULL)) {
		return NULL;
	}

	linebreak(state);

	struct mrsh_command *cmd = compound_command(state);
	if (cmd == NULL) {
		parser_set_error(state, "expected a compount command");
		return NULL;
	}

	// TODO: compound_command redirect_list

	struct mrsh_function_definition *fd =
		mrsh_function_definition_create(name, cmd);
	fd->name_range = name_range;
	fd->lparen_pos = lparen_pos;
	fd->rparen_pos = rparen_pos;
	return fd;
}

static struct mrsh_command *compound_command(struct mrsh_parser *state) {
	struct mrsh_brace_group *bg = brace_group(state);
	if (bg != NULL) {
		return &bg->command;
	} else if (mrsh_parser_error(state, NULL)) {
		return NULL;
	}

	struct mrsh_subshell *s = subshell(state);
	if (s != NULL) {
		return &s->command;
	} else if (mrsh_parser_error(state, NULL)) {
		return NULL;
	}

	struct mrsh_if_clause *ic = if_clause(state);
	if (ic != NULL) {
		return &ic->command;
	} else if (mrsh_parser_error(state, NULL)) {
		return NULL;
	}

	struct mrsh_for_clause *fc = for_clause(state);
	if (fc != NULL) {
		return &fc->command;
	} else if (mrsh_parser_error(state, NULL)) {
		return NULL;
	}

	struct mrsh_loop_clause *lc = loop_clause(state);
	if (lc != NULL) {
		return &lc->command;
	} else if (mrsh_parser_error(state, NULL)) {
		return NULL;
	}

	struct mrsh_case_clause *cc = case_clause(state);
	if (cc != NULL) {
		return &cc->command;
	} else if (mrsh_parser_error(state, NULL)) {
		return NULL;
	}

	struct mrsh_function_definition *fd = function_definition(state);
	if (fd != NULL) {
		return &fd->command;
	} else if (mrsh_parser_error(state, NULL)) {
		return NULL;
	}

	return NULL;
}

static struct mrsh_command *command(struct mrsh_parser *state) {
	apply_aliases(state);

	struct mrsh_command *cmd = compound_command(state);
	if (cmd != NULL || mrsh_parser_error(state, NULL)) {
		return cmd;
	}

	// TODO: compound_command redirect_list

	struct mrsh_simple_command *sc = simple_command(state);
	if (sc != NULL) {
		return &sc->command;
	}

	return NULL;
}

static struct mrsh_pipeline *pipeline(struct mrsh_parser *state) {
	struct mrsh_range bang_range = {0};
	bool bang = token(state, "!", &bang_range);
	struct mrsh_position bang_pos = bang_range.begin; // can be invalid

	struct mrsh_command *cmd = command(state);
	if (cmd == NULL) {
		return NULL;
	}

	struct mrsh_array commands = {0};
	mrsh_array_add(&commands, cmd);

	while (token(state, "|", NULL)) {
		linebreak(state);
		struct mrsh_command *cmd = command(state);
		if (cmd == NULL) {
			parser_set_error(state, "expected a command");
			goto error_commands;
		}
		mrsh_array_add(&commands, cmd);
	}

	struct mrsh_pipeline *p = mrsh_pipeline_create(&commands, bang);
	p->bang_pos = bang_pos;
	return p;

error_commands:
	for (size_t i = 0; i < commands.len; ++i) {
		mrsh_command_destroy((struct mrsh_command *)commands.data[i]);
	}
	mrsh_array_finish(&commands);
	return NULL;
}

static struct mrsh_and_or_list *and_or(struct mrsh_parser *state) {
	struct mrsh_pipeline *pl = pipeline(state);
	if (pl == NULL) {
		return NULL;
	}

	enum mrsh_binop_type binop_type;
	struct mrsh_range op_range;
	if (operator(state, AND_IF, &op_range)) {
		binop_type = MRSH_BINOP_AND;
	} else if (operator(state, OR_IF, &op_range)) {
		binop_type = MRSH_BINOP_OR;
	} else {
		return &pl->and_or_list;
	}

	linebreak(state);
	struct mrsh_and_or_list *and_or_list = and_or(state);
	if (and_or_list == NULL) {
		mrsh_and_or_list_destroy(&pl->and_or_list);
		parser_set_error(state, "expected an AND-OR list");
		return NULL;
	}

	struct mrsh_binop *binop = mrsh_binop_create(binop_type, &pl->and_or_list, and_or_list);
	binop->op_range = op_range;
	return &binop->and_or_list;
}

static struct mrsh_command_list *list(struct mrsh_parser *state) {
	struct mrsh_and_or_list *and_or_list = and_or(state);
	if (and_or_list == NULL) {
		return NULL;
	}

	struct mrsh_command_list *cmd = mrsh_command_list_create();
	cmd->and_or_list = and_or_list;

	struct mrsh_position separator_pos = state->pos;
	int sep = separator_op(state);
	if (sep == '&') {
		cmd->ampersand = true;
	}
	if (sep >= 0) {
		cmd->separator_pos = separator_pos;
	}

	return cmd;
}

/**
 * Append a new string word to `children` with the contents of `buf`, and reset
 * `buf`.
 */
static void push_buffer_word_string(struct mrsh_array *children,
		struct mrsh_buffer *buf) {
	if (buf->len == 0) {
		return;
	}

	mrsh_buffer_append_char(buf, '\0');

	char *data = mrsh_buffer_steal(buf);
	struct mrsh_word_string *ws = mrsh_word_string_create(data, false);
	mrsh_array_add(children, &ws->word);
}

static struct mrsh_word *here_document_line(struct mrsh_parser *state) {
	struct mrsh_array children = {0};
	struct mrsh_buffer buf = {0};

	while (true) {
		char c = parser_peek_char(state);
		if (c == '\0') {
			break;
		}

		if (c == '$') {
			push_buffer_word_string(&children, &buf);
			struct mrsh_word *t = expect_dollar(state);
			if (t == NULL) {
				return NULL;
			}
			mrsh_array_add(&children, t);
			continue;
		}

		if (c == '`') {
			push_buffer_word_string(&children, &buf);
			struct mrsh_word *t = back_quotes(state);
			mrsh_array_add(&children, t);
			continue;
		}

		if (c == '\\') {
			// Here-document backslash, same semantics as quoted backslash
			// except double-quotes are not special
			char next[2];
			parser_peek(state, next, sizeof(next));
			switch (next[1]) {
			case '$':
			case '`':
			case '\\':
				parser_read_char(state);
				c = next[1];
				break;
			}
		}

		parser_read_char(state);
		mrsh_buffer_append_char(&buf, c);
	}

	push_buffer_word_string(&children, &buf);
	mrsh_buffer_finish(&buf);

	if (children.len == 1) {
		struct mrsh_word *word = children.data[0];
		mrsh_array_finish(&children); // TODO: don't allocate this array
		return word;
	} else {
		struct mrsh_word_list *wl = mrsh_word_list_create(&children, false);
		return &wl->word;
	}
}

static bool is_word_quoted(struct mrsh_word *word) {
	switch (word->type) {
	case MRSH_WORD_STRING:;
		struct mrsh_word_string *ws = mrsh_word_get_string(word);
		return ws->single_quoted;
	case MRSH_WORD_LIST:;
		struct mrsh_word_list *wl = mrsh_word_get_list(word);
		if (wl->double_quoted) {
			return true;
		}
		for (size_t i = 0; i < wl->children.len; ++i) {
			struct mrsh_word *child = wl->children.data[i];
			if (is_word_quoted(child)) {
				return true;
			}
		}
		return false;
	default:
		assert(false);
	}
}

static bool expect_here_document(struct mrsh_parser *state,
		struct mrsh_io_redirect *redir, const char *delim) {
	bool trim_tabs = redir->op == MRSH_IO_DLESSDASH;
	bool expand_lines = !is_word_quoted(redir->name);

	state->continuation_line = true;

	struct mrsh_buffer buf = {0};
	while (true) {
		buf.len = 0;
		while (true) {
			char c = parser_peek_char(state);
			if (c == '\0' || c == '\n') {
				break;
			}

			mrsh_buffer_append_char(&buf, parser_read_char(state));
		}
		mrsh_buffer_append_char(&buf, '\0');

		const char *line = buf.data;
		if (trim_tabs) {
			while (line[0] == '\t') {
				++line;
			}
		}

		if (strcmp(line, delim) == 0) {
			break;
		}
		if (parser_peek_char(state) == '\0') {
			parser_set_error(state, "unterminated here-document");
			return false;
		}
		read_continuation_line(state);

		struct mrsh_word *word;
		if (expand_lines) {
			struct mrsh_parser *subparser =
				mrsh_parser_with_data(line, strlen(line));
			word = here_document_line(subparser);
			mrsh_parser_destroy(subparser);
		} else {
			struct mrsh_word_string *ws =
				mrsh_word_string_create(strdup(line), true);
			word = &ws->word;
		}

		mrsh_array_add(&redir->here_document, word);
	}
	mrsh_buffer_finish(&buf);

	return true;
}

static bool expect_complete_command(struct mrsh_parser *state,
		struct mrsh_array *cmds) {
	struct mrsh_command_list *l = list(state);
	if (l == NULL) {
		parser_set_error(state, "expected a complete command");
		return false;
	}
	mrsh_array_add(cmds, l);

	while (true) {
		l = list(state);
		if (l == NULL) {
			break;
		}
		mrsh_array_add(cmds, l);
	}

	if (state->here_documents.len > 0) {
		for (size_t i = 0; i < state->here_documents.len; ++i) {
			struct mrsh_io_redirect *redir = state->here_documents.data[i];

			if (!newline(state)) {
				parser_set_error(state,
					"expected a newline followed by a here-document");
				return false;
			}

			char *delim = mrsh_word_str(redir->name);
			bool ok = expect_here_document(state, redir, delim);
			free(delim);
			if (!ok) {
				return false;
			}
		}

		state->here_documents.len = 0;
	}

	return true;
}

static struct mrsh_program *program(struct mrsh_parser *state) {
	struct mrsh_program *prog = mrsh_program_create();
	if (prog == NULL) {
		return NULL;
	}

	linebreak(state);
	if (eof(state)) {
		return prog;
	}

	if (!expect_complete_command(state, &prog->body)) {
		mrsh_program_destroy(prog);
		return NULL;
	}

	while (newline_list(state)) {
		if (eof(state)) {
			return prog;
		}

		if (!expect_complete_command(state, &prog->body)) {
			mrsh_program_destroy(prog);
			return NULL;
		}
	}

	linebreak(state);
	return prog;
}

struct mrsh_program *mrsh_parse_line(struct mrsh_parser *state) {
	parser_begin(state);

	if (eof(state)) {
		return NULL;
	}

	struct mrsh_program *prog = mrsh_program_create();
	if (prog == NULL) {
		return NULL;
	}

	if (newline(state)) {
		return prog;
	}

	if (!expect_complete_command(state, &prog->body)) {
		goto error;
	}
	if (!eof(state) && !newline(state)) {
		parser_set_error(state, "expected a newline");
		goto error;
	}

	return prog;

error:
	mrsh_program_destroy(prog);

	// Consume the whole line
	while (true) {
		char c = parser_peek_char(state);
		if (c == '\0') {
			break;
		}

		parser_read_char(state);
		if (c == '\n') {
			break;
		}
	}

	state->has_sym = false;

	return NULL;
}

struct mrsh_program *mrsh_parse_program(struct mrsh_parser *state) {
	parser_begin(state);
	return program(state);
}