bootstrap.c 24.6 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
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;
38
struct value*	 Begin = NULL;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

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) {
60
		failure("Boehm GC: can not allocate a value (out of memory)");
61
62
63
64
65
	}

	return value;
}

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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;
}

84
85
86
struct value*   
symbol(const byte_t* symbol_value)
{
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
	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;
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
}

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

153
154
155
156
157
158
159
160
161
struct value*
foreign(pointer_t value)
{
	struct value* v = alloc_value();
	v->tag = FOREIGN;
	v->foreign_value = value;
	return v;
}

162
struct value*   
163
procedure(struct value* env, struct value* param, struct value* body)
164
165
{
	struct value* v = alloc_value();
166
167
168
169
	v->tag = PROCEDURE;
	v->procedure.env = env;
	v->procedure.param = param;
	v->procedure.body = body;
170
171
172
	return v;
}

173
174
175
176
177
178
179
180
181
182
183

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


184
185
186
187
188
189
190
191
192
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)
193
		failure("Boehm GC: can not allocate tuple (out of memory)");
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

	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;

251
252
	global_symbollist = Emptylist;

253
	Quote  = symbol("quote");
254
255
	Let	   = symbol("let");
	Lambda = symbol("lambda");
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
	If	   = symbol("if");
	Define = symbol("define");
	Begin  = symbol("begin");
}

static struct value*
core_environment(void)
{
	struct value* env = INITIAL_ENV; 

#define proc_to_env(ENV, STR, FUN) \
	env_let(ENV, symbol(STR), primitive(FUN))

	proc_to_env(env, "println", core_println);

	return env;
}

// ----------------------------------------------------------------------------
// Primitives
// ----------------------------------------------------------------------------

struct value*   
core_println(struct value* env, struct value* args)
{
	struct value* v;

	while(!IS_NULL(args)) {
		v = HEAD(args);

		switch(v->tag) {
			case BOOLEAN:
				if(IS_TRUE(v))
					printf("true");
				else
					printf("false");
				break;

			case STRING:
				printf("%s", v->string_value);
				break;
			case SYMBOL:
				printf("%s", v->symbol_value);
				break;
			case FIXNUM:
				printf("%ld", v->fixnum_value);
				break;
			case FLOAT:
				printf("%lf", v->float_value);
				break;
			default:
				failure("cherry.core.println: Argument not accepted");
				break;
		}

		args = TAIL(args);
	}

	printf("\n");

	return True;
317
318
319
}

// ----------------------------------------------------------------------------
320
// Reading
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
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, 
349
350
351
352
353
354
355
	INT_DEC_READ,
	FP_START, 
	FP_EXPONENT, 
	FP_DOT, 
	FP_DECIMAL, 
	FP_MINUSPLUS, 
	FP_FINAL
356
357
358
359
};


static enum token
360
lex_number(byte_t** src, byte_t* buffer, size_t buffer_size)
361
{
362
	byte_t* p = *src;
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
	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;
385
386
387
388
				} else if(*p == '.') {
					state = FP_DOT;
				} else if(*p == 'e' || *p == 'E') {
					state = FP_EXPONENT;
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
				} 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;
421
422
423
424
				if(*p == '.')
					state = FP_DOT;
				else if(*p == 'e' || *p == 'E') {
					state = FP_EXPONENT;
425
426
427
428
429
430
431
432
433
434
				} 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;

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
			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;

469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
			default:
				break;

		}

		*buffer = *p;

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

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

RETURN_TOKEN:
	*buffer = '\0';
486
	*src = p;
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509

	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 
510
			failure("Read: Bufferoverflow in character scanning");
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
	}

	*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 != '~') {
530
531
532
		printf("STREAM %s\n", p);
		fflush(stdout);

533
534
535
536
537
538
539
540
541
		if(*p == '\r' || *p == '\n')
			failure("Unexpected newline/carriage return found in raw string");

		*buffer = *p;

		if(buffer + 1 < buf_end) {
			buffer++;
			p++;
		} else 
542
			failure("Read: Bufferoverflow in raw string scanning");
543
544
545
	}

	*buffer = '\0';
546
	*begin = (*p != '\0') ? p + 1 : p;
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

	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;
636
637
638
639
		if(buffer < buf_end)
			buffer++;
		else 
			failure("Read: Bufferoverflow in string scanning");
640
641

NO_BUFFER_APPEND:
642
		p++;
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
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;
691

692
			case ';':
693
				while(*p != '\n' && *p != '\0')
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
					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);	
}
784
785
786


struct value*	
787
cherry_read(byte_t** src, byte_t* buffer, size_t buffer_size)
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
	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:
822
				val = floatpoint(strtod(buffer, 0));
823
824
825
826
				break;

			case TOK_STRING:
				val = string(string_dup(buffer));
827
				break;
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850

			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;
851
852
}

853
854
855
856
// ----------------------------------------------------------------------------
// runtime utils
// ----------------------------------------------------------------------------

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
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)) {
893
			if(var == HEAD(vars)) {
894
895
				HEAD(vals) = val;
				return True;
896
			}
897
898
899
900
901
902
903
904
905
906
907
908
909
910

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

		env = PARENT_FRAMES(env);
	}

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

	

struct value*
911
env_let(struct value* env, struct value* var, struct value* val)
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
{
	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);
	}

927
928
929
	HEAD(frame) = cons(var, HEAD(frame));
	TAIL(frame) = cons(val, TAIL(frame));

930
931
	return True;
}
932
933
934



935
936
937
938
// ----------------------------------------------------------------------------
// compile
// ----------------------------------------------------------------------------

939
940
static struct value*
eval_values(struct value* env, struct value* args)
941
{
942
943
	struct value* last = Emptylist;
	struct value* begin = last;
944

945
946
947
948
	while(!IS_NULL(args)) {
		last = TAIL(last) = cons(cherry_eval(env, HEAD(args)), Emptylist);
		args = TAIL(args);
	}
949

950
951
	return TAIL(begin);
}
952
953

struct value*
954
cherry_eval(struct value* env, struct value* value)
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
	while(TRUE) {
		if(IS_SELF_EVALUATING(value))
			return value;
		else if(IS_VARIABLE(value))
			return env_lookup(env, value);
			
		struct value* fn = HEAD(value);
		struct value* args = TAIL(value);

		if(fn == Let) {
			return env_let(env, HEAD(args), cherry_eval(env, HEAD(TAIL(args))));

		} else if(fn == Quote) {
			return HEAD(args);
		
		} else if(fn == Lambda) {
			return procedure(env, HEAD(args), TAIL(args)); 

		} else if(fn == Begin) {
			while(!IS_NULL(TAIL(args))) {
				cherry_eval(env, HEAD(args));
				args = TAIL(args);
			}
			value = HEAD(args);

		} else if(fn == If) {
			value = IS_TRUE(cherry_eval(env, HEAD(args)))
					? HEAD(TAIL(args))
					: HEAD(TAIL(TAIL(args)));

		} else if(IS_SYMBOL(fn)) { 
			fn = cherry_eval(env, fn);
			args = eval_values(env, args);

			if(IS_PRIMITIVE(fn)) 
				value = (fn->fun_value)(env, args);
			else if(IS_PROCEDURE(fn)) {
				env = EXTEND_ENV(fn->procedure.env, fn->procedure.param, args);
				value = cons(Begin, fn->procedure.body);							
			} else
				failure("Eval: Unknown procedure type found");

		} else
			failure("Eval: no proper cherry operation found");
	}

1002
1003
1004
1005
1006
1007
1008
}

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

static void 
1009
cherry_write_tuple(FILE* out, struct value* value)
1010
1011
1012
1013
{
	struct value** p = TUPLE_DATA(value);
	struct value** e = TUPLE_DATA(value) + TUPLE_SIZE(value);

1014
	cherry_write(out, *p);
1015
1016
1017
1018
	p++;

	while(p < e) {
		fprintf(out, " ");
1019
		cherry_write(out, *p);
1020
1021
1022
1023
1024
		p++;
	}	
}

static void
1025
cherry_write_pair(FILE* out, struct value* value)
1026
1027
1028
1029
{
	struct value* head = HEAD(value);
	struct value* tail = TAIL(value);

1030
	cherry_write(out, head);
1031
1032
1033
	
	if(IS_PAIR(tail)) {
		fprintf(out, " ");
1034
		cherry_write_pair(out, tail);
1035
1036
1037
	} else if(IS_NULL(tail)) {
		return;
	} else if(IS_DOT(tail)) {
1038
		cherry_write_pair(out, tail);
1039
1040
1041
1042
1043
	} else
		failure("Unexpected value found in write");
}


1044
1045
1046
1047
1048
1049
1050
1051
void
cherry_writeln(FILE* out, struct value* value)
{
	cherry_write(out, value);
	fprintf(out, "\n");
	fflush(out);
}

1052
void
1053
cherry_write(FILE* out, struct value* value)
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
{
	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;

1082
		case CHARACTER:
1083
			fprintf(out, "\\");
1084
			switch(value->character_value) {
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
				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:
1113
					fprintf(out, "%c", (char) value->character_value);
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
			}
			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;

1156
1157
1158
1159
		case FOREIGN:
			fprintf(out, "#foreign");
			break;

1160
		case PRIMITIVE:
1161
			fprintf(out, "#primitive");
1162
1163
			break;

1164
1165
		case PROCEDURE:
			fprintf(out, "#procedure");
1166
1167
1168
1169
			break;

		case PAIR:
			fprintf(out, "(");
1170
			cherry_write_pair(out, value);
1171
1172
1173
1174
1175
			fprintf(out, ")");
			break;

		case TUPLE:
			fprintf(out, "[");
1176
			cherry_write_tuple(out, value);
1177
1178
1179
1180
1181
1182
			fprintf(out, "]");
			break;

		default:
			failure("cannot write an unknown value type");
	}
1183
1184
1185

	fprintf(out, "\n");
	fflush(out);
1186
}
1187
1188
1189
1190
1191
1192


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

1193
1194
#define SCANNER_BUFFERSIZE 2048

1195
1196
void cherry_main(const char* filename, const byte_t* method, struct value* args)
{
1197
1198
1199
1200
1201
1202
1203
1204
	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);
1205
	struct value* env = core_environment();
1206
1207

	while(exp != 0) {
1208
		cherry_eval(env, exp);
1209
1210
		exp = cherry_read(&p, buffer, SCANNER_BUFFERSIZE);
	}
1211

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


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