forked from gracelang/minigrace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gracelib.c
6445 lines (6360 loc) · 222 KB
/
gracelib.c
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
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdint.h>
#include <libgen.h>
#include <setjmp.h>
#include <float.h>
#include <math.h>
#include <sys/wait.h>
#include <limits.h>
#include <unistd.h>
#include <dirent.h>
#include <ctype.h>
#include "gracelib.h"
#define IN_GRACELIB 1
#include "definitions.h"
#define max(x,y) (x>y?x:y)
void debugger();
Object Float64_asString(Object, int nparts, int *argcv,
Object*, int flags);
Object Float64_asStringDecimals(Object, int nparts, int *argcv,
Object*, int flags);
Object Float64_Add(Object, int nparts, int *argcv,
Object*, int flags);
Object Object_asString(Object, int nparts, int *argcv,
Object*, int flags);
Object Singleton_asString(Object, int nparts, int *argcv,
Object*, int);
Object Object_Equals(Object, int, int*,
Object*, int flags);
Object Object_NotEquals(Object, int, int*,
Object*, int);
Object String_concat(Object, int nparts, int *argcv,
Object*, int flags);
Object String_endsWith(Object, int nparts, int *argcv,
Object*, int flags);
Object String_do(Object self, int nparts, int *argcv,
Object *args, int flags);
FILE *debugfp;
int debug_enabled = 0;
FILE *callgraph;
int track_callgraph = 0;
int callcount = 0;
int tailcount = 0;
Object String_size(Object, int, int*, Object*, int flags);
Object String_at(Object, int, int*, Object*, int flags);
Object String_replace_with(Object, int, int*, Object*, int flags);
Object String_substringFrom_to(Object, int, int*, Object*, int flags);
Object String_substringFrom_size(Object, int, int*, Object*, int flags);
Object String_startsWith(Object, int, int*, Object*, int flags);
Object String_startsWithLetter(Object, int, int*, Object*, int flags);
Object String_startsWithDigit(Object, int, int*, Object*, int flags);
Object String_startsWithSpace(Object, int, int*, Object*, int flags);
Object String_indexOf(Object, int, int*, Object*, int flags);
Object String_indexOf_ifAbsent(Object, int, int*, Object*, int flags);
Object String_indexOf_startingAt(Object, int, int*, Object*, int flags);
Object String_indexOf_startingAt_ifAbsent(Object, int, int*, Object*, int flags);
Object String_lastIndexOf_ifAbsent(Object, int, int*, Object*, int flags);
Object String_lastIndexOf_startingAt_ifAbsent(Object, int, int*, Object*, int flags);
Object String_asUpper(Object, int, int*, Object*, int flags);
Object String_asLower(Object, int, int*, Object*, int flags);
Object String_capitalized(Object, int, int*, Object*, int flags);
Object String_timesNumber(Object, int, int*, Object*, int flags);
Object String_second(Object, int, int*, Object*, int flags);
Object String_third(Object, int, int*, Object*, int flags);
Object String_fourth(Object, int, int*, Object*, int flags);
Object String_fifth(Object, int, int*, Object*, int flags);
Object String_last(Object, int, int*, Object*, int flags);
Object String_map(Object, int, int*, Object*, int flags);
Object String_filter(Object, int, int*, Object*, int flags);
Object String_fold_startingWith(Object, int, int*, Object*, int flags);
Object String_keysAndValuesDo(Object, int, int*, Object*, int flags);
Object prelude_clone(Object, int, int*, Object*, int flags);
Object makeEscapedString(char *);
Object makeQuotedString(char *);
void ConcatString__FillBuffer(Object s, char *c, int len);
Object alloc_OrPattern(Object l, Object r);
Object alloc_AndPattern(Object l, Object r);
Object alloc_ExceptionPacket(Object msg, Object exception);
Object alloc_Exception(char *name, Object parent);
int find_resource(const char *name, char *buf);
int gc_period = 100000;
int rungc();
int expand_living();
void gc_pause();
int gc_unpause();
char *grcstring(Object s);
int hash_init = 0;
Object undefined = NULL;
Object done = NULL;
Object ellipsis = NULL;
Object iomodule;
Object sysmodule;
Object BOOLEAN_TRUE = NULL;
Object BOOLEAN_FALSE = NULL;
Object FLOAT64_ZERO = NULL;
Object FLOAT64_ONE = NULL;
Object FLOAT64_TWO = NULL;
Object FLOAT64_INF = NULL;
#define FLOAT64_INTERN_MIN -10
#define FLOAT64_INTERN_MAX 10000
#define FLOAT64_INTERN_SIZE FLOAT64_INTERN_MAX-FLOAT64_INTERN_MIN
Object Float64_Interned[FLOAT64_INTERN_SIZE];
Object String_Interned_1[256];
ClassData Number;
ClassData Boolean;
ClassData String;
ClassData ConcatString;
ClassData StringIter;
ClassData Block;
ClassData Octets;
ClassData BuiltinList;
ClassData BuiltinListIter;
ClassData Lineup;
ClassData PrimitiveArray;
ClassData Undefined;
ClassData Done;
ClassData ellipsisClass;
ClassData File;
ClassData IOModule;
ClassData SysModule;
ClassData Type;
ClassData Class;
ClassData MatchResult;
ClassData OrPattern;
ClassData AndPattern;
ClassData GreaterThanPattern;
ClassData LessThanPattern;
ClassData ExceptionPacket;
ClassData ExceptionClass;
Object Dynamic;
Object ObjectType = NULL;
Object Unknown;
Object prelude = NULL; // the current prelude, i.e., the dialect
Object _prelude = NULL; // the standard prelude
struct StringObject {
OBJECT_HEADER;
int blen;
int size;
unsigned int hashcode;
int ascii;
char *flat;
char body[];
};
struct ConcatStringObject {
OBJECT_HEADER;
int blen;
int size;
unsigned int hashcode;
int ascii;
char *flat;
int depth;
Object left;
Object right;
};
struct BuiltinListObject {
OBJECT_HEADER;
int size;
int space;
Object *items;
};
struct PrimitiveArrayObject {
OBJECT_HEADER;
int size;
int space;
Object *items;
};
struct IOModuleObject {
OBJECT_HEADER;
Object _stdin;
Object _stdout;
Object _stderr;
};
struct FileObject {
OBJECT_HEADER;
char *pathname;
FILE *file;
};
struct SysModule {
int flags;
ClassData class;
Object argv;
};
struct UserClosure {
int32_t flags;
Object *vars[];
};
struct SFLinkList {
void(*func)();
struct SFLinkList *next;
};
struct BlockObject {
OBJECT_HEADER;
jmp_buf *retpoint;
Object super;
Object *data;
int ndata;
};
struct TypeObject {
OBJECT_HEADER;
char *name;
Method *methods;
int nummethods;
int methodsCapacity; // capacity of the `methods` array
};
struct ExceptionPacketObject {
OBJECT_HEADER;
Object message;
Object exception;
Object data;
char **moduleSourceLines;
int lineNumber;
int calldepth;
char **backtrace;
const char *moduleName;
};
struct ExceptionObject {
OBJECT_HEADER;
char *name;
Object parent;
};
struct SFLinkList *shutdown_functions;
int linenumber = 0;
const char *modulename;
char **moduleSourceLines;
size_t heapsize;
size_t heapcurrent;
size_t heapmax;
int objectcount = 0;
int freedcount = 0;
Object *objects_living;
int objects_living_size = 0;
int objects_living_next = 0;
int objects_living_max = 0;
struct GC_Root {
Object object;
struct GC_Root *next;
};
struct GC_Root *GC_roots;
#define FLAG_FRESH 2
#define FLAG_REACHABLE 4
#define FLAG_DEAD 8
#define FLAG_USEROBJ 16
#define FLAG_BLOCK 32
#define FLAG_MUTABLE 64
int gc_dofree = 1;
int gc_dowarn = 0;
int gc_enabled = 1;
int Strings_allocated = 0;
int start_clocks = 0;
double start_time = 0;
char **ARGV = NULL;
int stack_size = 1024;
#define STACK_SIZE stack_size
static jmp_buf error_jump;
static int error_jump_set;
static Object currentException;
static jmp_buf *exceptionHandler_stack;
static Object *finally_stack;
static int exceptionHandlerDepth;
static Object ExceptionErrorObject;
static Object BoundsErrorObject;
static Object RuntimeErrorObject;
static Object NoSuchMethodErrorObject;
static Object ProgrammingErrorObject;
static Object RequestErrorObject;
static Object ResourceExceptionObject;
static Object TypeErrorObject;
static Object EnvironmentExceptionObject;
static Object IteratorExhaustedObject;
Object ExceptionError() {
if (ExceptionErrorObject == NULL) {
ExceptionErrorObject = alloc_Exception("Exception", NULL);
gc_root(ExceptionErrorObject);
}
return ExceptionErrorObject;
}
Object ProgrammingError() {
if (ProgrammingErrorObject == NULL) {
ProgrammingErrorObject = alloc_Exception("ProgrammingError", ExceptionError());
gc_root(ProgrammingErrorObject);
}
return ProgrammingErrorObject;
}
Object RequestError() {
if (RequestErrorObject == NULL) {
RequestErrorObject = alloc_Exception("RequestError", ProgrammingError());
gc_root(RequestErrorObject);
}
return RequestErrorObject;
}
Object EnvironmentException() {
if (EnvironmentExceptionObject == NULL) {
EnvironmentExceptionObject = alloc_Exception("EnvironmentException", ProgrammingError());
gc_root(EnvironmentExceptionObject);
}
return EnvironmentExceptionObject;
}
Object IteratorExhausted() {
if (IteratorExhaustedObject == NULL) {
IteratorExhaustedObject = alloc_Exception("IteratorExhausted", ProgrammingError());
gc_root(IteratorExhaustedObject);
}
return IteratorExhaustedObject;
}
Object NoSuchMethod() {
if (NoSuchMethodErrorObject == NULL) {
NoSuchMethodErrorObject = alloc_Exception("NoSuchMethod", ProgrammingError());
gc_root(NoSuchMethodErrorObject);
}
return NoSuchMethodErrorObject;
}
Object RuntimeError() {
if (RuntimeErrorObject == NULL) {
RuntimeErrorObject = alloc_Exception("RuntimeError", ProgrammingError());
gc_root(RuntimeErrorObject);
}
return RuntimeErrorObject;
}
Object BoundsError() {
if (BoundsErrorObject == NULL) {
BoundsErrorObject = alloc_Exception("BoundsError", ProgrammingError());
gc_root(BoundsErrorObject);
}
return BoundsErrorObject;
}
Object ResourceException() {
if (ResourceExceptionObject == NULL) {
ResourceExceptionObject = alloc_Exception("ResourceException", ProgrammingError());
gc_root(ResourceExceptionObject);
}
return ResourceExceptionObject;
}
Object TypeError() {
if (TypeErrorObject == NULL) {
TypeErrorObject = alloc_Exception("TypeError", ProgrammingError());
gc_root(TypeErrorObject);
}
return TypeErrorObject;
}
static jmp_buf *return_stack;
Object return_value;
char (*callstack)[256];
int calldepth = 0;
struct StackFrameObject **frame_stack;
struct ClosureEnvObject **closure_stack;
void backtrace() {
int i;
for (i=calldepth-1; i>=0; i--) {
fprintf(stderr, " called from %s\n", callstack[i]);
}
}
void pushstackframe(struct StackFrameObject *f, char *name) {
frame_stack[calldepth-1] = f;
f->name = name;
}
void pushclosure(Object c) {
closure_stack[calldepth-1] = (struct ClosureEnvObject *)c;
}
void setframeelementname(struct StackFrameObject *f, int p, char *name) {
if (getenv("GRACE_FOO"))
fprintf(stderr, "adding name %s(%p) to slot %i of %s(%p)\n",
name, name, p, f->name, f);
f->names[p] = name;
}
void gracedie(char *msg, ...) {
va_list args;
va_start(args, msg);
if (error_jump_set) {
char buf[strlen(msg) * 4 + 1024];
vsprintf(buf, msg, args);
currentException = alloc_ExceptionPacket(alloc_String(buf),
RuntimeError());
longjmp(error_jump, 1);
}
fprintf(stderr, "RuntimeError at line %i of %s: ", linenumber, modulename);
vfprintf(stderr, msg, args);
fprintf(stderr, "\n");
backtrace();
int fl = linenumber - 2;
if (fl < 0) fl = 0;
for (; fl<linenumber+1; fl++)
if (moduleSourceLines[fl])
fprintf(stderr, " %i: %s\n", fl + 1, moduleSourceLines[fl]);
else
break;
va_end(args);
if (getenv("GRACE_DEBUGGER"))
debugger();
exit(1);
}
void graceRaise(Object exceptionKind, char *msg, ...) {
va_list args;
va_start(args, msg);
if (error_jump_set) {
char buf[strlen(msg) * 4 + 1024];
vsprintf(buf, msg, args);
currentException = alloc_ExceptionPacket(alloc_String(buf), exceptionKind);
longjmp(error_jump, 1);
}
struct ExceptionObject *ek = (struct ExceptionObject *)exceptionKind;
fprintf(stderr, "%s at line %i of %s: ", ek->name, linenumber, modulename);
vfprintf(stderr, msg, args);
fprintf(stderr, "\n");
backtrace();
int fl = linenumber - 2;
if (fl < 0) fl = 0;
for (; fl<linenumber+1; fl++)
if (moduleSourceLines[fl])
fprintf(stderr, " %i: %s\n", fl + 1, moduleSourceLines[fl]);
else
break;
va_end(args);
if (getenv("GRACE_DEBUGGER"))
debugger();
exit(1);
}
void debug(char *msg, ...) {
if (!debug_enabled)
return;
va_list args;
va_start(args, msg);
fprintf(debugfp, "%s:%i:", modulename, linenumber);
vfprintf(debugfp, msg, args);
fprintf(debugfp, "\n");
va_end(args);
}
void assertClass(Object obj, ClassData cl) {
if (obj->class != cl)
graceRaise(TypeError(), "expected instance of %s; got %s", cl->name,
obj->class->name);
}
void *glmalloc(size_t s) {
heapsize += s;
heapcurrent += s;
if (heapcurrent >= heapmax)
heapmax = heapcurrent;
void *v = calloc(1, s + sizeof(size_t));
if (v == NULL) {
fprintf(stderr, "Out of memory (line %i of %s)", linenumber, modulename);
graceRaise(EnvironmentException(), "Out of memory");
}
size_t *i = v;
*i = s;
return v + sizeof(size_t);
}
void glfree(void *p) {
size_t *i = p - sizeof(size_t);
debug("glfree: freed %p (%i)", p, *i);
heapcurrent -= *i;
memset(i, 0, *i);
free(i);
}
char* canonicalMethodName(const char *nname) {
// nname is a numeric method name, such as foo(1)bar(2);
// returns the canonical name, such as foo(_)bar(_,_).
int length = 1;
int nnLen = strlen(nname);
for (int i = 0; i < nnLen; i++) {
if (nname[i] == '(') {
int nParams = atoi(&nname[i + 1]);
length = length + (nParams * 2) + 1;
while (nname[++i] >= '0' && nname[i] <= '9') { }
}
length++;
}
char *result = glmalloc(sizeof(char) * length);
int j = 0;
for (int i = 0; i < nnLen; i++) {
if (nname[i] == '(') {
result[j] = '(';
j++;
int nParams = atoi(&nname[i + 1]);
for (int k = 0; k < nParams - 1; k++) {
result[j] = '_';
result[j + 1] = ',';
j += 2;
}
result[j] = '_';
j++;
while (nname[++i] >= '0' && nname[i] <= '9') { }
}
result[j] = nname[i];
j++;
}
result[j] = '\0';
return result;
}
char* numericMethodName(const char *cname) {
// cname is a canonical method name, such as foo(_)bar(_,_);
// returns the numeric name, such as foo(1)bar(2).
int length = strlen(cname);
char *result = glmalloc(sizeof(char) * (length + 1));
int j = 0;
for (int i = 0; i < length; i++) {
if (cname[i] == '(') {
int nParams = 1;
i++;
while (cname[++i] == ',') {
nParams++;
i++; // skip underscore
}
j = j + sprintf(&result[j], "(%d)", nParams);
} else {
result[j++] = cname[i];
}
}
result[j] = '\0';
return result;
}
void initprofiling() {
start_clocks = clock();
struct timeval ar;
gettimeofday(&ar, NULL);
start_time = ar.tv_sec + (double)ar.tv_usec / 1000000;
}
void grace_register_shutdown_function(void(*func)()) {
struct SFLinkList *nw = glmalloc(sizeof(struct SFLinkList));
nw->func = func;
nw->next = shutdown_functions;
shutdown_functions = nw;
}
void grace_run_shutdown_functions() {
while (shutdown_functions != NULL) {
shutdown_functions->func();
shutdown_functions = shutdown_functions->next;
}
}
int istrue(Object o) {
if (o == undefined)
graceRaise(RequestError(), "Undefined value used in boolean test.");
if (o == NULL || o == BOOLEAN_FALSE)
return 0;
if (o == BOOLEAN_TRUE)
return 1;
if (o->flags & FLAG_USEROBJ)
return istrue(((struct UserObject *)o)->super);
return 0;
}
int isclass(Object o, const char *class) {
return (strcmp(o->class->name, class) == 0);
}
char *cstringfromString(Object s) {
struct StringObject* so = (struct StringObject*)s;
int zs = so->blen;
zs = zs + 1;
char *c = glmalloc(zs);
if (s->class == String) {
strcpy(c, so->body);
return c;
}
grcstring(s);
ConcatString__FillBuffer(s, c, zs);
return c;
}
void bufferfromString(Object s, char *c) {
struct StringObject* so = (struct StringObject*)s;
if (s->class == String) {
strcpy(c, so->body);
return;
}
int z = so->blen;
grcstring(s);
ConcatString__FillBuffer(s, c, z);
}
int integerfromAny(Object p) {
if (p->class == Number) {
double *d = (double*)p->data;
int j = *d;
return j;
}
p = callmethod(p, "asString", 0, NULL, NULL);
char *c = grcstring(p);
int i = atoi(c);
return i;
}
Object _rangeClass = NULL;
Object grace_rangeClass() {
if (_rangeClass == NULL)
_rangeClass = callmethod(_prelude, "range", 0, NULL, NULL);
return _rangeClass;
}
Object _bindingClass = NULL;
Object grace_bindingClass() {
if (_bindingClass == NULL)
_bindingClass = callmethod(_prelude, "binding", 0, NULL, NULL);
return _bindingClass;
}
Object gracebecome(Object subObject, Object superObject) {
struct UserObject *sub = (struct UserObject *)subObject;
struct UserObject *sup = (struct UserObject *)superObject;
struct UserObject *tmpSup = sup;
ClassData subclass = sub->class;
Object *subdata = (Object *)sub->data;
sub->super = sup->super;
sup->super = subObject;
sub->class = sup->class;
sub->data = (Object *)(sup->data);
sup->class = subclass;
sup->data = subdata;
int tmpndata = sub->ndata;
sub->ndata = sup->ndata;
sup->ndata = tmpndata;
return superObject;
}
Object graceunbecome(Object topObj) {
struct UserObject *top = (struct UserObject *)topObj;
struct UserObject *extra = (struct UserObject *)top->super;
// Swap the class and data on the two objects
ClassData extraclass = top->class;
Object *extradata = (Object *)top->data;
ClassData topclass = extra->class;
Object *topdata = (Object *)extra->data;
top->class = topclass;
top->data = topdata;
extra->class = extraclass;
extra->data = extradata;
// Remove the extra object from the chain
top->super = extra->super;
return (Object)extra;
}
Method *addmethodrealflags(Object o, char *name,
Object (*func)(Object, int, int*, Object*, int), int flags) {
Method *m = add_Method(o->class, name, func);
m->flags |= flags;
return m;
}
void addmethodreal(Object o, char *name,
Object (*func)(Object, int, int*, Object*, int)) {
Method *m = add_Method(o->class, name, func);
}
void addmethod2(Object o, char *name,
Object (*func)(Object, int, int*, Object*, int)) {
Method *m = add_Method(o->class, name, func);
m->flags &= ~MFLAG_REALSELFONLY;
}
void addmethod2flags(Object o, char *name,
Object (*func)(Object, int, int*, Object*, int), int flags) {
Method *m = add_Method(o->class, name, func);
m->flags &= ~MFLAG_REALSELFONLY | flags;
}
Method *addmethod2pos(Object o, char *name,
Object (*func)(Object, int, int*, Object*, int), int pos) {
Method *m = add_Method(o->class, name, func);
m->flags &= ~MFLAG_REALSELFONLY;
m->pos = pos;
return m;
}
Object identity_function(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
return receiver;
}
Object Object_asString(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
char buf[255];
sprintf(buf, "a %s", receiver->class->name);
return alloc_String(buf);
}
Object Object_asDebugString(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
return callmethod(receiver, "asString", 0, NULL, NULL);
}
Object Singleton_asString(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
return alloc_String(receiver->class->name);
}
Object Object_bind(Object self, int nparts, int *argcv,
Object *args, int flags) {
if (nparts < 1 || (nparts >= 1 && argcv[0] < 1))
graceRaise(RequestError(), "binary operator :: requires an argument");
Object other = args[0];
Object params[2];
int partcv[] = {1, 1};
params[0] = self;
params[1] = other;
return callmethod(grace_bindingClass(), "key(1)value(1)", 2, partcv, params);
}
Object Object_concat(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
Object a = callmethod(receiver, "asString", 0, NULL, NULL);
return callmethod(a, "++(1)", 1, argcv, params);
}
Object Object_NotEquals(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
Object b = callmethod(receiver, "==(1)", 1, argcv, params);
return callmethod(b, "not", 0, NULL, NULL);
}
Object Object_Equals(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
return alloc_Boolean(receiver == params[0]);
}
Object Module_asString(Object receiver, int nparts, int *argcv,
Object* params, int flags) {
char buf[255];
sprintf(buf, "the %s module", receiver->class->name);
return alloc_String(buf);
}
Object MatchResult_result(Object self, int nparts, int *argcv,
Object *argv, int flags) {
return ((struct UserObject *)self)->data[0];
}
Object MatchResult_bindings(Object self, int nparts, int *argcv,
Object *argv, int flags) {
return ((struct UserObject *)self)->data[1];
}
Object MatchResult_asString(Object self, int nparts, int *argcv,
Object *argv, int flags) {
struct UserObject *uo = (struct UserObject *)self;
gc_pause();
Object str;
if (uo->super == BOOLEAN_TRUE)
str = alloc_String("SuccessfulMatch(result = ");
else
str = alloc_String("FailedMatch(result = ");
int partcv[] = {1};
Object tmpstr = callmethod(uo->data[0], "asString", 0, NULL, NULL);
str = callmethod(str, "++(1)", 1, partcv, &tmpstr);
tmpstr = alloc_String(", bindings = ");
str = callmethod(str, "++(1)", 1, partcv, &tmpstr);
tmpstr = callmethod(uo->data[1], "asString", 0, NULL, NULL);
str = callmethod(str, "++(1)", 1, partcv, &tmpstr);
tmpstr = alloc_String(")");
str = callmethod(str, "++(1)", 1, partcv, &tmpstr);
gc_unpause();
return str;
}
Object alloc_MatchResult(Object result, Object bindings) {
gc_pause();
if (bindings == NULL)
bindings = alloc_BuiltinList();
Object o = alloc_userobj2(3, 2, MatchResult);
if (!MatchResult) {
MatchResult = o->class;
add_Method(MatchResult, "result", &MatchResult_result);
add_Method(MatchResult, "bindings", &MatchResult_bindings);
add_Method(MatchResult, "asString", &MatchResult_asString);
}
struct UserObject *uo = (struct UserObject *)o;
uo->data[0] = result;
uo->data[1] = bindings;
gc_unpause();
return o;
}
Object alloc_SuccessfulMatch(Object result, Object bindings) {
Object o = alloc_MatchResult(result, bindings);
((struct UserObject *)o)->super = alloc_Boolean(1);
return o;
}
Object alloc_FailedMatch(Object result, Object bindings) {
Object o = alloc_MatchResult(result, bindings);
((struct UserObject *)o)->super = alloc_Boolean(0);
return o;
}
Object literal_match(Object self, int nparts, int *argcv,
Object *argv, int flags) {
if (nparts < 1 || (nparts >= 1 && argcv[0] < 1))
graceRaise(RequestError(), "match requires an argument");
Object other = argv[0];
int partcv[] = {1};
if (!istrue(callmethod(self, "==(1)", 1, partcv, argv)))
return alloc_FailedMatch(other, NULL);
return alloc_SuccessfulMatch(other, NULL);
}
Object literal_or(Object self, int nparts, int *argcv,
Object *argv, int flags) {
if (nparts < 1 || (nparts >= 1 && argcv[0] < 1))
graceRaise(RequestError(), "| requires an argument");
return alloc_OrPattern(self, argv[0]);
}
Object literal_and(Object self, int nparts, int *argcv,
Object *argv, int flags) {
if (nparts < 1 || (nparts >= 1 && argcv[0] < 1))
graceRaise(RequestError(), "& requires an argument");
return alloc_AndPattern(self, argv[0]);
}
Object AndPattern_match(Object self, int nparts, int *argcv, Object *argv,
int flags) {
Object target = argv[0];
struct UserObject *b = (struct UserObject *)self;
Object left = b->data[0];
Object right = b->data[1];
Object m = callmethod(left, "match(1)", 1, argcv, argv);
if (!istrue(m))
return m;
Object bindings = callmethod(m, "bindings", 0, NULL, NULL);
m = callmethod(right, "match(1)", 1, argcv, argv);
if (!istrue(m))
return m;
Object bindings2 = callmethod(m, "bindings", 0, NULL, NULL);
bindings = callmethod(bindings, "++(1)", 1, argcv, &bindings2);
return alloc_SuccessfulMatch(target, bindings);
}
Object OrPattern_match(Object self, int nparts, int *argcv, Object *argv,
int flags) {
Object target = argv[0];
struct UserObject *b = (struct UserObject *)self;
Object left = b->data[0];
Object right = b->data[1];
int tmp[1] = {1};
Object m = callmethod(left, "match(1)", 1, argcv, argv);
if (istrue(m))
return alloc_SuccessfulMatch(target, NULL);
m = callmethod(right, "match(1)", 1, argcv, argv);
if (istrue(m))
return alloc_SuccessfulMatch(target, NULL);
return alloc_FailedMatch(target, NULL);
}
Object alloc_OrPattern(Object l, Object r) {
Object o = alloc_userobj2(3, 2, OrPattern);
if (!OrPattern) {
OrPattern = o->class;
glfree(o->class->name);
o->class->name = "OrPattern";
add_Method(OrPattern, "|(1)", &literal_or);
add_Method(OrPattern, "&(1)", &literal_and);
add_Method(OrPattern, "match(1)", &OrPattern_match);
}
struct UserObject *b = (struct UserObject *)o;
b->data[0] = l;
b->data[1] = r;
return o;
}
Object alloc_AndPattern(Object l, Object r) {
Object o = alloc_userobj2(3, 2, AndPattern);
if (!AndPattern) {
AndPattern = o->class;
glfree(o->class->name);
o->class->name = "AndPattern";
add_Method(AndPattern, "|(1)", &literal_or);
add_Method(AndPattern, "&(1)", &literal_and);
add_Method(AndPattern, "match(1)", &AndPattern_match);
}
struct UserObject *b = (struct UserObject *)o;
b->data[0] = l;
b->data[1] = r;
return o;
}
Object LessThanPattern_match(Object self, int nparts, int *argcv, Object *argv,
int flags) {
struct UserObject *b = (struct UserObject *)self;
Object target = argv[0];
Object right = b->data[0];
int tmp[1] = {1};
Object m = callmethod(target, "<(1)", 1, argcv, &right);
if (istrue(m))
return alloc_SuccessfulMatch(target, NULL);
return alloc_FailedMatch(target, NULL);
}
Object alloc_LessThanPattern(Object r) {
Object o = alloc_userobj2(3, 2, LessThanPattern);
if (!LessThanPattern) {
LessThanPattern = o->class;
glfree(o->class->name);
o->class->name = "LessThanPattern";
add_Method(LessThanPattern, "|(1)", &literal_or);
add_Method(LessThanPattern, "&(1)", &literal_and);
add_Method(LessThanPattern, "match(1)", &LessThanPattern_match);
}
struct UserObject *b = (struct UserObject *)o;
b->data[0] = r;
return o;
}
Object GreaterThanPattern_match(Object self, int nparts, int *argcv, Object *argv,
int flags) {
struct UserObject *b = (struct UserObject *)self;
Object target = argv[0];
Object right = b->data[0];
int tmp[1] = {1};
Object m = callmethod(target, ">(1)", 1, argcv, &right);
if (istrue(m))
return alloc_SuccessfulMatch(target, NULL);
return alloc_FailedMatch(target, NULL);
}
Object alloc_GreaterThanPattern(Object r) {
Object o = alloc_userobj2(3, 2, GreaterThanPattern);
if (!GreaterThanPattern) {
GreaterThanPattern = o->class;
glfree(o->class->name);
o->class->name = "GreaterThanPattern";
add_Method(GreaterThanPattern, "|(1)", &literal_or);
add_Method(GreaterThanPattern, "&(1)", &literal_and);
add_Method(GreaterThanPattern, "match(1)", &GreaterThanPattern_match);
}
struct UserObject *b = (struct UserObject *)o;
b->data[0] = r;
return o;
}
void printExceptionBacktrace(Object o) {
struct ExceptionPacketObject *e = (struct ExceptionPacketObject *)o;
struct ExceptionObject *x = (struct ExceptionObject *)e->exception;
fprintf(stderr, "%s around line %i: %s\n", x->name, e->lineNumber,
grcstring(e->message));
for (int i=e->calldepth - 1; i >= 0; i--) {
fprintf(stderr, " called from %s\n", e->backtrace[i]);
}
int fl = e->lineNumber - 2;
if (fl < 0) fl = 0;
for (; fl<e->lineNumber+1; fl++)
if (e->moduleSourceLines[fl])
fprintf(stderr, " %i: %s\n", fl + 1, e->moduleSourceLines[fl]);
else
break;
}
void ExceptionPacket__mark(struct ExceptionPacketObject *e) {
gc_mark(e->message);
gc_mark(e->exception);
gc_mark(e->data);
}
void ExceptionPacket__release(struct ExceptionPacketObject *e) {
int i;
for (i=0; i<e->calldepth; i++) {
glfree(e->backtrace[i]);
}
glfree(e->backtrace);
}
Object ExceptionPacket_message(Object self, int argc, int *argcv, Object *argv,
int flags) {
struct ExceptionPacketObject *e = (struct ExceptionPacketObject *)self;
return e->message;
}
Object ExceptionPacket_exception(Object self, int argc, int *argcv,
Object *argv, int flags) {
struct ExceptionPacketObject *e = (struct ExceptionPacketObject *)self;
return e->exception;
}
Object ExceptionPacket_lineNumber(Object self, int argc, int *argcv,
Object *argv, int flags) {
struct ExceptionPacketObject *e = (struct ExceptionPacketObject *)self;
return alloc_Float64((double)e->lineNumber);
}
Object ExceptionPacket_moduleName(Object self, int argc, int *argcv,
Object *argv, int flags) {
struct ExceptionPacketObject *e = (struct ExceptionPacketObject *)self;
return alloc_String(e->moduleName);
}
Object ExceptionPacket_data(Object self, int argc, int *argcv,
Object *argv, int flags) {
struct ExceptionPacketObject *e = (struct ExceptionPacketObject *)self;
if (e->data)
return e->data;
return alloc_done();
}
Object ExceptionPacket_asString(Object self, int argc, int *argcv,
Object *argv, int flags) {
struct ExceptionPacketObject *e = (struct ExceptionPacketObject *)self;
struct ExceptionObject *x = (struct ExceptionObject *)e->exception;