bootstrap.c 21.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * Cherry programming language
 * Copyright (C) 2013 Christoph Mueller
 *
 * 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 <http://www.gnu.org/licenses/>.
*/

#include "bootstrap.h"
#include <gc.h>
21
#include <getopt.h>
22
23
24
25
26
#include <stdarg.h>

// ----------------------------------------------------------------------------
// Default symbols
// ----------------------------------------------------------------------------
27
28
static struct value* global_symbollist = NULL;

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
struct value*    True = NULL;
struct value*    False = NULL;
struct value*    Emptylist = NULL;
struct value*	 Dot = NULL;
struct value*	 Quote = NULL;
struct value*	 Define = NULL;
struct value*	 Let = NULL;
struct value*	 Lambda = NULL;
struct value*	 If = NULL;

static void
failure(const byte_t* format, ...)
{
	va_list args;
	va_start(args, format);

	vfprintf(stderr, format, args);
	fprintf(stderr, "\n");

	va_end(args);

	exit(EXIT_FAILURE);
}

struct value*   
alloc_value(void)
{
	struct value* value = GC_MALLOC(sizeof(struct value));

	if(value == NULL) {
59
		failure("Boehm GC: can not allocate a value (out of memory)");
60
61
62
63
64
	}

	return value;
}

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
struct value*
alloc_symbol(const byte_t* symbol_value)
{
	size_t size = strlen(symbol_value) + 1;

	byte_t* symbol_string = GC_MALLOC(sizeof(byte_t) * size);

	if(symbol_string == NULL) 
		failure("Boehm GC: can not allocate a symbol (out of memory)");
	else 
		memcpy(symbol_string, symbol_value, size);

	struct value* value = alloc_value();
	value->tag = SYMBOL;
	value->symbol_value = symbol_string;
	return value;
}

83
84
85
struct value*   
symbol(const byte_t* symbol_value)
{
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
	struct value* node = global_symbollist;

	if(IS_NULL(node)) {
		global_symbollist = SYMBOL_ENTRY(alloc_symbol(symbol_value), Emptylist, Emptylist);
		return HEAD(global_symbollist);
	}

	while(TRUE) {
		const byte_t* current = HEAD(node)->symbol_value;

		if(strcmp(current, symbol_value) > 0) {
			if(IS_NULL(SYMBOL_LEFT(node))) {
				SYMBOL_LEFT(node) = SYMBOL_ENTRY(alloc_symbol(symbol_value), Emptylist, Emptylist);
				return HEAD(SYMBOL_LEFT(node));
			} else
				node = SYMBOL_LEFT(node);
		} else if (strcmp(current, symbol_value) < 0) {
			if(IS_NULL(SYMBOL_RIGHT(node))) {
				SYMBOL_RIGHT(node) = SYMBOL_ENTRY(alloc_symbol(symbol_value), Emptylist, Emptylist);
				return HEAD(SYMBOL_RIGHT(node));
			} else
				node = SYMBOL_RIGHT(node);
		} else {
			return HEAD(node);
		}
	}

	return Emptylist;
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
}

struct value*   
fixnum(fixnum_t fixnum_value)
{
	struct value* v = alloc_value();
	v->tag = FIXNUM;
	v->fixnum_value = fixnum_value;
	return v;
}

struct value*   
floatpoint(float_t float_value)
{
	struct value* v = alloc_value();
	v->tag = FLOAT;
	v->float_value = float_value;
	return v;
}

struct value*   
string(const byte_t* string_value)
{
	struct value* v = alloc_value();
	v->tag = STRING;
	v->string_value = string_value;
	return v;
}

struct value*   
primitive(const primitive_t fun_value)
{
	struct value* v = alloc_value();
	v->tag = PRIMITIVE;
	v->fun_value = fun_value;
	return v;
}

struct value*   
lambda(struct value* param, struct value* body)
{
	struct value* v = alloc_value();
	v->tag = LAMBDA;
	v->lambda.param = param;
	v->lambda.body = body;
	return v;
}

162
163
164
165
166
167
168
169
170
171
172

struct value*
character(unicode_t code)
{
	struct value* v = alloc_value();
	v->tag = CHARACTER;
	v->character_value = code;
	return v;
}


173
174
175
176
177
178
179
180
181
struct value*   
tuple(size_t size, ...)
{
	struct value* v = alloc_value();
	v->tag = TUPLE;
	v->tuple.size = size;
	v->tuple.data = GC_MALLOC(sizeof(struct value*) * size);

	if(v->tuple.data == NULL)
182
		failure("Boehm GC: can not allocate tuple (out of memory)");
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

	va_list args;
	va_start(args, size);

	struct value* arg = va_arg(args, struct value*);
	int i;

	for(i = 0; i < size && arg; ++i) {
		v->tuple.data[i] = arg;
		arg = va_arg(args, struct value*);
	}

	va_end(args);

	return v;
}

struct value*   
dup(struct value* value)
{
	struct value* cpy = alloc_value();
	memcpy(cpy, value, sizeof(struct value));
	return cpy;
}


struct value*   
cons(struct value* head, struct value* tail)
{
	struct value* v = alloc_value();
	v->tag = PAIR;
	HEAD(v) = head;
	TAIL(v) = tail;
	return v;
}



void
initialize(void)
{
	GC_INIT();

	True = alloc_value();
	True->tag = BOOLEAN;
	True->fixnum_value = TRUE;

	False = alloc_value();
	False->tag = BOOLEAN;
	False->fixnum_value = FALSE;

	Dot = alloc_value();
	Dot->tag = DOT;

	Emptylist = alloc_value();
	Emptylist->tag = EMPTYLIST;

240
241
	global_symbollist = Emptylist;

242
243
244
245
246
247
248
249
	Quote = symbol("quote");
	Define = symbol("define");
	Let	   = symbol("let");
	Lambda = symbol("lambda");
	If	   = symbol("If");
}

// ----------------------------------------------------------------------------
250
// Reading
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
enum token {
	TOK_EOF, TOK_ROUNDLEFTBRACE, TOK_ROUNDRIGHTBRACE, 
	TOK_SQUARELEFTBRACE, TOK_SQUARERIGHTBRACE,
	TOK_STRING, TOK_DOT, TOK_CHAR, TOK_HEX, TOK_DEC, 
	TOK_OCT, TOK_BIN, TOK_FLOAT, TOK_SYMBOL,
	TOK_QUOTE, TOK_TRUE, TOK_FALSE
};


static int 
issymbol(int ch)
{
	return isalnum(ch) || 
		ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' ||
		ch == '<' || ch == '>' || ch == '=' || ch == '!' || ch == '?' ||
		ch == '#' || ch == ':' || ch == '.' || ch == '~' || ch == '_';
}

enum number_state {
	INT_START, 
	INT_BASE, 
	INT_BIN_WAIT, 
	INT_HEX_WAIT, 
	INT_OCT_WAIT, 
	INT_BIN_READ, 
	INT_HEX_READ, 
	INT_OCT_READ, 
279
280
281
282
283
284
285
	INT_DEC_READ,
	FP_START, 
	FP_EXPONENT, 
	FP_DOT, 
	FP_DECIMAL, 
	FP_MINUSPLUS, 
	FP_FINAL
286
287
288
289
};


static enum token
290
lex_number(byte_t** src, byte_t* buffer, size_t buffer_size)
291
{
292
	byte_t* p = *src;
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
	byte_t* buf_beg = buffer;
	byte_t* buf_end = buffer + buffer_size;

	enum token token = TOK_DEC;
	enum number_state state = INT_START;

	do {
		switch(state) {
			case INT_START:
				if(*p == '0')
					state = INT_BASE;
				else
					state = INT_DEC_READ;
				break;

			case INT_BASE:
				if(*p == 'x') {
					state = INT_HEX_WAIT;
				} else if(*p == 'b') {
					state = INT_BIN_WAIT;
				} else if('0' <= *p && *p <= '7') {
					state = INT_OCT_READ;
315
316
317
318
				} else if(*p == '.') {
					state = FP_DOT;
				} else if(*p == 'e' || *p == 'E') {
					state = FP_EXPONENT;
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
				} else {
					token = TOK_DEC;
					goto RETURN_TOKEN;
				}
				break;

			case INT_HEX_WAIT:
				if(('0' > *p || *p > '9') && ('A' > *p || *p > 'F'))
					failure("Unexpected character found in hex literal");
				state = INT_HEX_READ;
				break;

			case INT_BIN_WAIT:
				if(*p != '0' && *p != '1')
					failure("Unexpected character found in binary literal");
				state = INT_BIN_READ;
				break;

			case INT_BIN_READ:
				token = TOK_BIN;
				if(*p != '0' && *p != '1')
					goto RETURN_TOKEN;
				break;

			case INT_OCT_READ:
				token = TOK_OCT;
				if('0' > *p || *p > '7')
					goto RETURN_TOKEN;
				break;

			case INT_DEC_READ:
				token = TOK_DEC;
351
352
353
354
				if(*p == '.')
					state = FP_DOT;
				else if(*p == 'e' || *p == 'E') {
					state = FP_EXPONENT;
355
356
357
358
359
360
361
362
363
364
				} else if('0' > *p || *p > '9')
					goto RETURN_TOKEN;
				break;

			case INT_HEX_READ:
				token = TOK_HEX;
				if(('0' > *p || *p > '9') && ('A' > *p || *p > 'F'))
					goto RETURN_TOKEN;
				break;

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
			case FP_EXPONENT:
				if(*p == '+' || *p == '-')
					state = FP_MINUSPLUS;
				else if('0' > *p || *p > '9') {
					failure("Unexpected character found in float literal after +/-");
				} else
					state = FP_FINAL;
				break;

			case FP_DOT:
				state = FP_DECIMAL;
				if('0' > *p || *p > '9')
					failure("Unexpected character found in float literal after dot");
				break;

			case FP_DECIMAL:
				if(*p == 'e' || *p == 'E') 
					state = FP_EXPONENT;
				else if('0' > *p || *p > '9')
					goto RETURN_TOKEN;
				break;

			case FP_MINUSPLUS:
				state = FP_FINAL;
				if('0' > *p || *p > '9')
					failure("Unexpected character found in float literal");
				break;

			case FP_FINAL:
				token = TOK_FLOAT;
				if('0' > *p || *p > '9')
					goto RETURN_TOKEN;
				break;

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
			default:
				break;

		}

		*buffer = *p;

		if(buffer + 1 < buf_end) {
			buffer++;
			p++;
		} else 
			failure("Bufferoverflow in number literal");

	} while(*p != '\0');

RETURN_TOKEN:
	*buffer = '\0';
416
	*src = p;
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439

	return token;
}




static enum token
lex_char(byte_t** begin, byte_t* buffer, size_t buffer_size)
{
	byte_t* p = *begin;
	byte_t* buf_beg = buffer;
	byte_t* buf_end = buffer + buffer_size;

	p++; // remove beginning delimeter

	while(!isspace(*p) && *p != '\0') {
		*buffer = *p;

		if(buffer + 1 < buf_end) {
			buffer++;
			p++;
		} else 
440
			failure("Bufferoverflow in character literal");
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
	}

	*buffer = '\0';
	*begin = p;

	return TOK_CHAR;
};


static enum token
lex_raw_string(byte_t** begin, byte_t* buffer, size_t buffer_size)
{
	byte_t* p = *begin;
	byte_t* buf_beg = buffer;
	byte_t* buf_end = buffer + buffer_size;

	p++; // remove beginning delimeter

	while(*p != '\0' && *p != '~') {
		if(*p == '\r' || *p == '\n')
			failure("Unexpected newline/carriage return found in raw string");

		*buffer = *p;

		if(buffer + 1 < buf_end) {
			buffer++;
			p++;
		} else 
			failure("Bufferoverflow in raw string literal");

		buffer++;
		p++;

	}

	*buffer = '\0';
	*begin = (*p != '\0') ? p : p + 1;

	return TOK_STRING;
}



static enum token
lex_symbol(byte_t** begin, byte_t* buffer, size_t buffer_size)
{
	byte_t* p = *begin;
	byte_t* buf_beg = buffer;
	byte_t* buf_end = buffer + buffer_size;

	while(issymbol(*p)) {
		*buffer = *p;
	
		if(buffer < buf_end) {
			buffer++;
			p++;
		} else
			failure("Bufferoverflow in symbol scanning");
	}

	*buffer = '\0';
	*begin = p;

	if(strcmp(buf_beg, "true") == 0)
		return TOK_TRUE;
	else if(strcmp(buf_beg, "false") == 0)
		return TOK_FALSE;
	else
		return TOK_SYMBOL;
}


enum string_state {
	STR_EAT, 
	STR_ESCAPE,
	STR_FINAL
};

static enum token
lex_string(byte_t** begin, byte_t* buffer, size_t buffer_size)
{
	byte_t* p = *begin;
	byte_t* buf_beg = buffer;
	byte_t* buf_end = buffer + buffer_size;

	enum string_state state  = STR_EAT;

	p++;

	while(*p != '\0') {
		switch(state) {
			case STR_EAT:
				if(*p == '\\') {
					state = STR_ESCAPE;
					goto NO_BUFFER_APPEND;
				} else if(*p == '\"') {
					state = STR_FINAL;
					goto NO_BUFFER_APPEND;
				} else if(*p == '\r' || *p == '\n')
					failure("Unexpected newline/carriage return found in string literal");
				break;

			case STR_ESCAPE:
				switch(*p) {
					case 'a': *buffer = '\a'; break;
					case 'b': *buffer = '\b'; break;
					case 'f': *buffer = '\f'; break;
					case 'n': *buffer = '\n'; break;
					case 'r': *buffer = '\r'; break;
					case 't': *buffer = '\t'; break; 
					case 'v': *buffer = '\v'; break;
					case '0': *buffer = '0'; break;
					case '"': *buffer = '"'; break;
					case '\\': *buffer = '\\'; break;
						state = STR_EAT;
						goto NO_BUFFER_APPEND;
					default:
						failure("Unknown escape sequence found in this string literal");
				}
				break;

			case STR_FINAL:
				goto RETURN_TOKEN;
		}

		*buffer = *p;

NO_BUFFER_APPEND:
		if(buffer < buf_end) {
			buffer++;
			p++;
		} else
573
			failure("Bufferoverflow in string scanning");
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
RETURN_TOKEN:
	if(state != STR_FINAL)
		failure("Unexpected end of file found in unclosed string");

	*begin = p;
	*buffer = '\0';

	return TOK_STRING;
}





static enum token
lex(byte_t** begin, byte_t* buffer, size_t buffer_size)
{
	byte_t* p = *begin;
	enum token tok = TOK_EOF;

	while(TRUE) {
		while(isspace(*p))
			p++;

		switch(*p) {
			case '\0':
				tok = TOK_EOF;
				goto RETURN;
			case '(':
				tok = TOK_ROUNDLEFTBRACE;
				goto RETURN_AND_INC;
			case ')':
				tok = TOK_ROUNDRIGHTBRACE;
				goto RETURN_AND_INC;
			case '.':
				tok = TOK_DOT;
				goto RETURN_AND_INC;
			case '[':
				tok = TOK_SQUARELEFTBRACE;
				goto RETURN_AND_INC;
			case ']':
				tok = TOK_SQUARERIGHTBRACE;
				goto RETURN_AND_INC;
			case '\'':
				tok = TOK_QUOTE;
				goto RETURN_AND_INC;
622

623
			case ';':
624
				while(*p != '\n' && *p != '\0')
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
					p++;
				continue;

			case '~':
				tok = lex_raw_string(&p, buffer, buffer_size);
				goto RETURN;

			case '\\':
				tok = lex_char(&p, buffer, buffer_size);
				goto RETURN;

			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9':
				tok = lex_number(&p, buffer, buffer_size);
				goto RETURN;

			case '"':
				tok = lex_string(&p, buffer, buffer_size);
				goto RETURN;

			default:
				if(issymbol(*p))
					tok = lex_symbol(&p, buffer, buffer_size);
				else
					failure("Unexpected character found in lex stream");

				goto RETURN;
		}
	}

RETURN_AND_INC:
	++p;
	*begin = p;

RETURN:
	*begin = p;

	return tok;
}


byte_t*
text(FILE* file) 
{
	size_t filesize;

	fseek(file, 0, SEEK_END);
	filesize = ftell(file);
	rewind(file);

	byte_t* data = GC_MALLOC(filesize * sizeof(byte_t));
	fread(data, sizeof(byte_t), filesize, file);
	fclose(file);

	return data;
}


static byte_t*
string_dup(const byte_t* buffer)
{
	size_t size = strlen(buffer) + 1;
	byte_t* p = GC_MALLOC(sizeof(byte_t) * size);

	if(!p) 
		failure("Boehm GC: string allocation failed (out of memory)");

	memcpy(p, buffer, size);
	return p;
}


static struct value*
cherry_read_pair(byte_t** src, byte_t* buffer, size_t buffer_size)
{
	byte_t* pos = *src;

	enum token tok = lex(src, buffer, buffer_size);
	
	if(tok == TOK_ROUNDRIGHTBRACE || tok == TOK_EOF) {
		return Emptylist;
	}

	*src = pos;

	struct value* head = cherry_read(src, buffer, buffer_size);
	struct value* tail = cherry_read_pair(src, buffer, buffer_size);

	return cons(head, tail);	
}
715
716
717


struct value*	
718
cherry_read(byte_t** src, byte_t* buffer, size_t buffer_size)
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
	struct value* last = alloc_value();
	struct value* begin = last;
	struct value* val = 0;

	enum token tok = lex(src, buffer, buffer_size);

	if (tok != TOK_EOF) {
		switch(tok) {
			case TOK_FALSE:
				val = False;
				break;

			case TOK_TRUE:
				val = True;
				break;

			case TOK_HEX:
				val = fixnum(strtol(buffer + 2, 0, 16));
				break;

			case TOK_DEC:
				val = fixnum(strtol(buffer, 0, 10));
				break;

			case TOK_OCT:
				val = fixnum(strtol(buffer + 2, 0, 8));
				break;

			case TOK_BIN:
				val = fixnum(strtol(buffer + 2, 0, 2));
				break;

			case TOK_FLOAT:
753
				val = floatpoint(strtod(buffer, 0));
754
755
756
757
				break;

			case TOK_STRING:
				val = string(string_dup(buffer));
758
				break;
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781

			case TOK_SYMBOL:
				val = symbol(string_dup(buffer));
				break;

			case TOK_CHAR:
				val = character(buffer[0]);
				break;

			case TOK_QUOTE:
				val = cons(Quote, cons(cherry_read(src, buffer, buffer_size), Emptylist));
				break;

			case TOK_ROUNDLEFTBRACE:
				val = cherry_read_pair(src, buffer, buffer_size);
				break;

			default:
				failure("Bad input token found in read");
		}
	}

	return val;
782
783
}

784
785
786
787
// ----------------------------------------------------------------------------
// runtime utils
// ----------------------------------------------------------------------------

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
struct value*
env_lookup(struct value* env, struct value* symbol)
{
	struct value *frame, *vars, *vals;

	while(!IS_NULL(env)) {
		frame = FIRST_FRAME(env);
		vars = FRAME_VARIABLES(frame);
		vals = FRAME_VALUES(frame);

		while(!IS_NULL(vars)) {
			if(symbol == HEAD(vars))
				return HEAD(vals);

			vars = TAIL(vars);
			vals = TAIL(vals);
		}

		env = PARENT_FRAMES(env);
	}

	failure("Unbound variable found for symbol %s", symbol->symbol_value);
}


struct value*
env_set(struct value* env, struct value* var, struct value* val)
{
	struct value *frame, *vars, *vals;

	while(!IS_NULL(env)) {
		frame = FIRST_FRAME(env);
		vars = FRAME_VARIABLES(frame);
		vals = FRAME_VALUES(frame);

		while(!IS_NULL(vars)) {
			if(var == HEAD(vars))
				HEAD(vals) = val;
				return True;

			vars = TAIL(vars);
			vals = TAIL(vals);
		}

		env = PARENT_FRAMES(env);
	}

	failure("Unbound variable found for symbol %s", var->symbol_value);
}

	
struct value*
env_add_binding_to_frame(struct value* frame, struct value* var, struct value* val)
{
	HEAD(frame) = cons(var, HEAD(frame));
	TAIL(frame) = cons(val, TAIL(frame));
}


struct value*
env_define(struct value* env, struct value* var, struct value* val)
{
	struct value* frame = FIRST_FRAME(env);
	struct value* vars = FRAME_VARIABLES(frame);
	struct value* vals = FRAME_VALUES(frame);

	while(!IS_NULL(vars)) {
		if(var == HEAD(vars)) {
			HEAD(vals) = val;
			return True;
		}

		vars = TAIL(vars);
		vals = TAIL(vals);
	}

	env_add_binding_to_frame(var, val, frame);
	return True;
}
867
868
869



870
871
872
873
874
875
// ----------------------------------------------------------------------------
// compile
// ----------------------------------------------------------------------------


struct closure*
876
cherry_compile(struct value* ast, struct value* env)
877
{
878

879
880
881
882
883
	return NULL;
}


struct value*
884
cherry_eval(struct closure* code)
885
886
887
888
889
890
891
892
893
{
	return EXECUTE(code);
}

// ----------------------------------------------------------------------------
// printing 
// ----------------------------------------------------------------------------

static void 
894
cherry_write_tuple(FILE* out, struct value* value)
895
896
897
898
{
	struct value** p = TUPLE_DATA(value);
	struct value** e = TUPLE_DATA(value) + TUPLE_SIZE(value);

899
	cherry_write(out, *p);
900
901
902
903
	p++;

	while(p < e) {
		fprintf(out, " ");
904
		cherry_write(out, *p);
905
906
907
908
909
		p++;
	}	
}

static void
910
cherry_write_pair(FILE* out, struct value* value)
911
912
913
914
{
	struct value* head = HEAD(value);
	struct value* tail = TAIL(value);

915
	cherry_write(out, head);
916
917
918
	
	if(IS_PAIR(tail)) {
		fprintf(out, " ");
919
		cherry_write_pair(out, tail);
920
921
922
	} else if(IS_NULL(tail)) {
		return;
	} else if(IS_DOT(tail)) {
923
		cherry_write_pair(out, tail);
924
925
926
927
928
929
	} else
		failure("Unexpected value found in write");
}


void
930
cherry_write(FILE* out, struct value* value)
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
{
	const byte_t* p;

	switch(value->tag) {
		case EMPTYLIST:
			fprintf(out, "()");
			break;

		case BOOLEAN:
			fprintf(out, (value->fixnum_value) ? "true" : "false");
			break;

		case DOT:
			fprintf(out, " . ");
			break;

		case SYMBOL:
			fprintf(out, "%s", value->symbol_value);
			break;

		case FIXNUM:
			fprintf(out, "%ld", value->fixnum_value);
			break;

		case FLOAT:
			fprintf(out, "%lf", value->float_value);
			break;

959
		case CHARACTER:
960
			fprintf(out, "\\");
961
			switch(value->character_value) {
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
				case '\0':
					fprintf(out, "null");
					break;
				case '\a':
					fprintf(out, "bell");
					break;
				case '\b':
					fprintf(out, "backspace");
					break;
				case '\f':
					fprintf(out, "formfeed");
					break;
				case '\n': 
					fprintf(out, "newline");
					break;
				case ' ':
					fprintf(out, "space");
					break;
				case '\r':
					fprintf(out, "return");
					break;
				case '\t':
					fprintf(out, "tab");
					break;
				case '\v':
					fprintf(out, "vtab");
					break;
				default:
990
					fprintf(out, "%c", (char) value->character_value);
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
			}
			break;

		case STRING:
			p = value->string_value;
			fprintf(out, "\"");
			while(*p != '\0') {
				switch(*p) {
					case '\a':
						fprintf(out, "\\a");
						break;
					case '\b':
						fprintf(out, "\\b");
						break;
					case '\f':
						fprintf(out, "\\f");
						break;
					case '\n': 
						fprintf(out, "\\n");
						break;
					case '\r':
						fprintf(out, "\\r");
						break;
					case '\t':
						fprintf(out, "\\t");
						break;
					case '\v':
						fprintf(out, "\v");
					case '"':
						fprintf(out, "\\\"");
						break;
					case '\\':
						fprintf(out, "\\");
						break;
					default:
						fprintf(out, "%c", *p);
				}
				p++;
			}
			fprintf(out, "\"");
			break;

		case PRIMITIVE:
			fprintf(out, "#primitive-procedure");
			break;

		case LAMBDA:
			fprintf(out, "#lambda-procedure");
			break;

		case PAIR:
			fprintf(out, "(");
1043
			cherry_write_pair(out, value);
1044
1045
1046
1047
1048
			fprintf(out, ")");
			break;

		case TUPLE:
			fprintf(out, "[");
1049
			cherry_write_tuple(out, value);
1050
1051
1052
1053
1054
1055
1056
			fprintf(out, "]");
			break;

		default:
			failure("cannot write an unknown value type");
	}
}
1057
1058
1059
1060
1061
1062


// ----------------------------------------------------------------------------
// main
// ----------------------------------------------------------------------------

1063
1064
#define SCANNER_BUFFERSIZE 2048

1065
1066
void cherry_main(const char* filename, const byte_t* method, struct value* args)
{
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
	FILE* port = fopen(filename, "rb");
	byte_t buffer[SCANNER_BUFFERSIZE];

	if(!port)
		failure("could not load file %s", filename);

	byte_t* p = text(port);
	struct value* exp = cherry_read(&p, buffer, SCANNER_BUFFERSIZE);

	while(exp != 0) {
		cherry_write(stdout, exp);
		fprintf(stdout, "\n");
		exp = cherry_read(&p, buffer, SCANNER_BUFFERSIZE);
	}
1081

1082
	exit(EXIT_SUCCESS);
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
}


static void 
print_usage(FILE* out, const char* prog) {
	fprintf(out, "Usage: %s [options] [file]\n");
	fprintf(out, 
		"   -h   --help			     Display this usage information.\n"
		"   -I   --loadpath=[PATH]   Specify loadpath for interpreter.\n"
		"   -M   --main=[method]	 Specify method that is executed automatically.\n");
}


int main(int argc, char** argv)
{
	static struct option options[] = {
		{"help", no_argument, 0, 'h'},
//		{"loadpath", optional_argument, 0, 'I'},
		{"main", optional_argument, 0, 'M'}
	};

	initialize();

	int ch;
	const char* filename = 0;
	const byte_t* method = 0;
	struct value* arguments = Emptylist;
	struct value* last = arguments;

	while( (ch = getopt_long(argc, argv, "hM:", options, 0)) != -1) {
		switch(ch) {
			case 'h':
				print_usage(stdout, argv[0]);
				exit(EXIT_SUCCESS);
//			case 'I':
//				cherry_ptrarray_append(load_path, optarg);
//				break;
			case 'M':
				method = optarg;
				break;
			case '?':
				print_usage(stderr, argv[0]);
				exit(EXIT_FAILURE);
			default:
				fprintf(stderr, "???");
				exit(EXIT_FAILURE);
		}
	}

	if(optind < argc)
		filename = argv[optind++];

	while(optind < argc) {
		last = TAIL(last) = cons(string(argv[optind++]), Emptylist);
	}


	if(filename)
		cherry_main(filename, method, TAIL(arguments));
	else
		failure("cherry: no input given");

	return EXIT_SUCCESS;
}