1 #include "minilang.h"
2 #include "ml_macros.h"
3 #include "sha256.h"
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <stdarg.h>
7 #include <string.h>
8 #include <stdint.h>
9 #include <gc/gc.h>
10 #include <limits.h>
11 #include <math.h>
12 #include <float.h>
13 #include <inttypes.h>
14 
15 #include "ml_compiler2.h"
16 #include "ml_runtime.h"
17 #include "ml_string.h"
18 #include "ml_method.h"
19 #include "ml_list.h"
20 #include "ml_map.h"
21 #ifdef ML_TRE
22 #include <tre/regex.h>
23 #else
24 #include <regex.h>
25 #endif
26 
27 #ifdef ML_THREADSAFE
28 #include <pthread.h>
29 #endif
30 
31 //!type
32 
33 ML_METHOD_DECL(IterateMethod, "iterate");
34 ML_METHOD_DECL(ValueMethod, "value");
35 ML_METHOD_DECL(KeyMethod, "key");
36 ML_METHOD_DECL(NextMethod, "next");
37 ML_METHOD_DECL(CompareMethod, "<>");
38 ML_METHOD_DECL(IndexMethod, "[]");
39 ML_METHOD_DECL(SymbolMethod, "::");
40 ML_METHOD_DECL(LessMethod, "<");
41 ML_METHOD_DECL(CallMethod, "()");
42 ML_METHOD_ANON(MLIterCount, "iteratable::count");
43 
rotl(uintptr_t X,unsigned int N)44 static inline uintptr_t rotl(uintptr_t X, unsigned int N) {
45 	const unsigned int Mask = (CHAR_BIT * sizeof(uintptr_t) - 1);
46 	return (X << (N & Mask)) | (X >> ((-N) & Mask ));
47 }
48 
49 // Types //
50 
51 ML_INTERFACE(MLAnyT, (), "any", .Rank = 0);
52 // Base type for all values.
53 
54 ML_INTERFACE(MLIteratableT, (), "iteratable");
55 //!iteratable
56 // The base type for any iteratable value.
57 
58 ML_INTERFACE(MLFunctionT, (), "function");
59 //!function
60 // The base type of all functions.
61 
ML_FUNCTION(MLTypeOf)62 ML_FUNCTION(MLTypeOf) {
63 //!type
64 //@type
65 //<Value
66 //>type
67 // Returns the type of :mini:`Value`.
68 	ML_CHECK_ARG_COUNT(1);
69 	return (ml_value_t *)ml_typeof(Args[0]);
70 }
71 
ml_type_hash(ml_type_t * Type)72 static long ml_type_hash(ml_type_t *Type) {
73 	return (intptr_t)Type;
74 }
75 
ml_type_call(ml_state_t * Caller,ml_type_t * Type,int Count,ml_value_t ** Args)76 static void ml_type_call(ml_state_t *Caller, ml_type_t *Type, int Count, ml_value_t **Args) {
77 	return ml_call(Caller, Type->Constructor, Count, Args);
78 }
79 
80 ML_TYPE(MLTypeT, (MLFunctionT), "type",
81 //!type
82 // Type of all types.
83 // Every type contains a set of named exports, which allows them to be used as modules.
84 	.hash = (void *)ml_type_hash,
85 	.call = (void *)ml_type_call,
86 	.Constructor = (ml_value_t *)MLTypeOf
87 );
88 
89 ML_METHOD("rank", MLTypeT) {
90 //!type
91 //<Type
92 //>integer
93 // Returns the rank of :mini:`Type`, i.e. the depth of its inheritence tree.
94 	ml_type_t *Type = (ml_type_t *)Args[0];
95 	return ml_integer(Type->Rank);
96 }
97 
ml_type_exports_fn(const char * Name,void * Value,ml_value_t * Exports)98 static int ml_type_exports_fn(const char *Name, void *Value, ml_value_t *Exports) {
99 	ml_map_insert(Exports, ml_cstring(Name), Value);
100 	return 0;
101 }
102 
103 ML_METHOD("exports", MLTypeT) {
104 //<Type
105 //>map
106 // Returns a map of all the exports from :mini:`Type`.
107 	ml_type_t *Type = (ml_type_t *)Args[0];
108 	ml_value_t *Exports = ml_map();
109 	stringmap_foreach(Type->Exports, Exports, (void *)ml_type_exports_fn);
110 	return Exports;
111 }
112 
113 #ifdef ML_GENERICS
114 
115 ML_TYPE(MLGenericTypeT, (MLTypeT), "generic-type");
116 //!internal
117 
118 struct ml_generic_rule_t {
119 	ml_generic_rule_t *Next;
120 	int NumArgs;
121 	ml_type_t *Type;
122 	uintptr_t Args[];
123 };
124 
ml_generic_fill(ml_generic_rule_t * Rule,ml_type_t ** Args2,int NumArgs,ml_type_t ** Args)125 static void ml_generic_fill(ml_generic_rule_t *Rule, ml_type_t **Args2, int NumArgs, ml_type_t **Args) {
126 	Args2[0] = Rule->Type;
127 	for (int I = 1; I < Rule->NumArgs; ++I) {
128 		uintptr_t Arg = Rule->Args[I - 1];
129 		if (Arg >> 48) {
130 			unsigned int J = Arg & 0xFFFF;
131 			Args2[I] = (J < NumArgs) ? Args[J] : MLAnyT;
132 		} else {
133 			Args2[I] = (ml_type_t *)Arg;
134 		}
135 	}
136 }
137 
ml_generic_parents(ml_value_t * Parents,int NumArgs,ml_type_t ** Args)138 static void ml_generic_parents(ml_value_t *Parents, int NumArgs, ml_type_t **Args) {
139 	ml_type_t *V = Args[0];
140 	if (Args[0] == MLTupleT) {
141 		for (int NumArgs2 = NumArgs; --NumArgs2 > 0;) {
142 			ml_type_t *Parent = ml_generic_type(NumArgs2, Args);
143 			ml_list_put(Parents, (ml_value_t *)Parent);
144 		}
145 	}
146 	for (ml_generic_rule_t *Rule = V->Rules; Rule; Rule = Rule->Next) {
147 		int NumArgs2 = Rule->NumArgs;
148 		ml_type_t *Args2[NumArgs2];
149 		ml_generic_fill(Rule, Args2, NumArgs, Args);
150 		ml_type_t *Parent = ml_generic_type(NumArgs2, Args2);
151 		ml_list_put(Parents, (ml_value_t *)Parent);
152 		ml_generic_parents(Parents, NumArgs2, Args2);
153 	}
154 }
155 
156 ML_METHOD("parents", MLGenericTypeT) {
157 //!internal
158 	ml_generic_type_t *Type = (ml_generic_type_t *)Args[0];
159 	ml_value_t *Parents = ml_list();
160 	ml_generic_parents(Parents, Type->NumArgs, Type->Args);
161 	return Parents;
162 }
163 
164 #endif
165 
166 ML_METHOD("parents", MLTypeT) {
167 //!type
168 //<Type
169 //>list
170 	ml_type_t *Type = (ml_type_t *)Args[0];
171 	ml_value_t *Parents = ml_list();
172 #ifdef ML_GENERICS
173 	ml_generic_parents(Parents, 1, &Type);
174 #endif
175 	for (int I = 0; I < Type->Parents->Size; ++I) {
176 		ml_type_t *Parent = (ml_type_t *)Type->Parents->Keys[I];
177 		if (Parent) ml_list_put(Parents, (ml_value_t *)Parent);
178 	}
179 	return Parents;
180 }
181 
ml_default_call(ml_state_t * Caller,ml_value_t * Value,int Count,ml_value_t ** Args)182 void ml_default_call(ml_state_t *Caller, ml_value_t *Value, int Count, ml_value_t **Args) {
183 	//ML_RETURN(ml_error("TypeError", "<%s> is not callable", ml_typeof(Value)->Name));
184 	ml_value_t **Args2 = ml_alloc_args(Count + 1);
185 	Args2[0] = Value;
186 	for (int I = 0; I < Count; ++I) Args2[I + 1] = Args[I];
187 	return ml_call(Caller, CallMethod, Count + 1, Args2);
188 }
189 
ml_default_hash(ml_value_t * Value,ml_hash_chain_t * Chain)190 long ml_default_hash(ml_value_t *Value, ml_hash_chain_t *Chain) {
191 	long Hash = 5381;
192 	for (const char *P = ml_typeof(Value)->Name; P[0]; ++P) Hash = ((Hash << 5) + Hash) + P[0];
193 	return Hash;
194 }
195 
ml_default_deref(ml_value_t * Ref)196 ml_value_t *ml_default_deref(ml_value_t *Ref) {
197 	return Ref;
198 }
199 
ml_default_assign(ml_value_t * Ref,ml_value_t * Value)200 ml_value_t *ml_default_assign(ml_value_t *Ref, ml_value_t *Value) {
201 	return ml_error("TypeError", "<%s> is not assignable", ml_typeof(Ref)->Name);
202 }
203 
ml_type_init(ml_type_t * Type,...)204 void ml_type_init(ml_type_t *Type, ...) {
205 	int Rank = 0;
206 	va_list Args;
207 	va_start(Args, Type);
208 	ml_type_t *Parent;
209 	while ((Parent = va_arg(Args, ml_type_t *))) {
210 		if (Parent->Rank > Rank) Rank = Parent->Rank;
211 		ml_type_add_parent(Type, Parent);
212 	}
213 	va_end(Args);
214 	if (Type != MLAnyT) Type->Rank = Rank + 1;
215 	stringmap_insert(Type->Exports, "of", Type->Constructor);
216 }
217 
ml_type(ml_type_t * Parent,const char * Name)218 ml_type_t *ml_type(ml_type_t *Parent, const char *Name) {
219 	ml_type_t *Type = new(ml_type_t);
220 	Type->Type = MLTypeT;
221 	ml_type_init(Type, Parent, NULL);
222 	Type->Name = Name;
223 	Type->hash = Parent->hash;
224 	Type->call = Parent->call;
225 	Type->deref = Parent->deref;
226 	Type->assign = Parent->assign;
227 	return Type;
228 }
229 
ml_type_name(const ml_value_t * Value)230 const char *ml_type_name(const ml_value_t *Value) {
231 	return ((ml_type_t *)Value)->Name;
232 }
233 
ml_type_add_parent(ml_type_t * Type,ml_type_t * Parent)234 void ml_type_add_parent(ml_type_t *Type, ml_type_t *Parent) {
235 	inthash_insert(Type->Parents, (uintptr_t)Parent, Parent);
236 	for (int I = 0; I < Parent->Parents->Size; ++I) {
237 		ml_type_t *Parent2 = (ml_type_t *)Parent->Parents->Keys[I];
238 		if (Parent2) ml_type_add_parent(Type, Parent2);
239 	}
240 }
241 
ml_typed_fn_get(ml_type_t * Type,void * TypedFn)242 inline void *ml_typed_fn_get(ml_type_t *Type, void *TypedFn) {
243 #ifdef ML_GENERICS
244 	if (Type->Type == MLGenericTypeT) return ml_typed_fn_get(ml_generic_type_args(Type)[0], TypedFn);
245 #endif
246 	ML_RUNTIME_LOCK();
247 	inthash_result_t Result = inthash_search2(Type->TypedFns, (uintptr_t)TypedFn);
248 	ML_RUNTIME_UNLOCK();
249 	if (Result.Present) return Result.Value;
250 	void *BestFn = NULL;
251 	int BestRank = 0;
252 	for (int I = 0; I < Type->Parents->Size; ++I) {
253 		ml_type_t *Parent = (ml_type_t *)Type->Parents->Keys[I];
254 		if (Parent && (Parent->Rank > BestRank)) {
255 			void *Fn = ml_typed_fn_get(Parent, TypedFn);
256 			if (Fn) {
257 				BestFn = Fn;
258 				BestRank = Parent->Rank;
259 			}
260 		}
261 	}
262 	ML_RUNTIME_LOCK();
263 	inthash_insert(Type->TypedFns, (uintptr_t)TypedFn, BestFn);
264 	ML_RUNTIME_UNLOCK();
265 	return BestFn;
266 }
267 
ml_typed_fn_set(ml_type_t * Type,void * TypedFn,void * Function)268 void ml_typed_fn_set(ml_type_t *Type, void *TypedFn, void *Function) {
269 	inthash_insert(Type->TypedFns, (uintptr_t)TypedFn, Function);
270 }
271 
ML_METHOD(MLStringT,MLTypeT)272 ML_METHOD(MLStringT, MLTypeT) {
273 //!type
274 //<Type
275 //>string
276 // Returns a string representing :mini:`Type`.
277 	ml_type_t *Type = (ml_type_t *)Args[0];
278 	return ml_string_format("<<%s>>", Type->Name);
279 }
280 
281 ML_METHOD("append", MLStringBufferT, MLTypeT) {
282 	ml_stringbuffer_t *Buffer = (ml_stringbuffer_t *)Args[0];
283 	ml_type_t *Type = (ml_type_t *)Args[1];
284 	ml_stringbuffer_addf(Buffer, "<<%s>>", Type->Name);
285 	return MLSome;
286 }
287 
288 ML_METHOD("::", MLTypeT, MLStringT) {
289 //!type
290 //<Type
291 //<Name
292 //>any | error
293 // Returns the value of :mini:`Name` exported from :mini:`Type`.
294 // Returns an error if :mini:`Name` is not present.
295 // This allows types to behave as modules.
296 	ml_type_t *Type = (ml_type_t *)Args[0];
297 	const char *Name = ml_string_value(Args[1]);
298 	ml_value_t *Value = stringmap_search(Type->Exports, Name);
299 	return Value ?: ml_error("ModuleError", "Symbol %s not exported from type %s", Name, Type->Name);
300 }
301 
302 #ifdef ML_GENERICS
303 
ml_generic_type(int NumArgs,ml_type_t * Args[])304 ml_type_t *ml_generic_type(int NumArgs, ml_type_t *Args[]) {
305 	static inthash_t GenericTypeCache[1] = {INTHASH_INIT};
306 	uintptr_t Hash = (uintptr_t)3541;
307 	for (int I = NumArgs; --I >= 0;) Hash = rotl(Hash, 1) ^ (uintptr_t)Args[I];
308 	ML_RUNTIME_LOCK();
309 	ml_generic_type_t *Type = (ml_generic_type_t *)inthash_search(GenericTypeCache, Hash);
310 	while (Type) {
311 		if (Type->NumArgs != NumArgs) goto next;
312 		for (int I = 0; I < NumArgs; ++I) {
313 			if (Args[I] != Type->Args[I]) goto next;
314 		}
315 		ML_RUNTIME_UNLOCK();
316 		return (ml_type_t *)Type;
317 	next:
318 		Type = Type->NextGeneric;
319 	}
320 	Type = xnew(ml_generic_type_t, NumArgs, ml_type_t *);
321 	const ml_type_t *Base = Args[0];
322 	const char *Name = Base->Name;
323 	if (NumArgs > 1) {
324 		ml_stringbuffer_t Buffer[1] = {ML_STRINGBUFFER_INIT};
325 		ml_stringbuffer_add(Buffer, Base->Name, strlen(Base->Name));
326 		ml_stringbuffer_add(Buffer, "[", 1);
327 		ml_stringbuffer_add(Buffer, Args[1]->Name, strlen(Args[1]->Name));
328 		for (int I = 2; I < NumArgs; ++I) {
329 			ml_stringbuffer_add(Buffer, ",", 1);
330 			ml_stringbuffer_add(Buffer, Args[I]->Name, strlen(Args[I]->Name));
331 		}
332 		ml_stringbuffer_add(Buffer, "]", 1);
333 		Name = ml_stringbuffer_get(Buffer);
334 	}
335 	Type->Base.Type = MLGenericTypeT;
336 	Type->Base.Name = Name;
337 	Type->Base.hash = Base->hash;
338 	Type->Base.call = Base->call;
339 	Type->Base.deref = Base->deref;
340 	Type->Base.assign = Base->assign;
341 	Type->Base.Rank = Base->Rank + 1;
342 	Type->NumArgs = NumArgs;
343 	for (int I = 0; I < NumArgs; ++I) Type->Args[I] = Args[I];
344 	Type->NextGeneric = (ml_generic_type_t *)inthash_insert(GenericTypeCache, Hash, Type);
345 	ML_RUNTIME_UNLOCK();
346 	return (ml_type_t *)Type;
347 }
348 
ml_type_add_rule(ml_type_t * T,ml_type_t * U,...)349 void ml_type_add_rule(ml_type_t *T, ml_type_t *U, ...) {
350 	int Count = 0;
351 	va_list Args;
352 	va_start(Args, U);
353 	while (va_arg(Args, uintptr_t)) ++Count;
354 	va_end(Args);
355 	ml_generic_rule_t *Rule = xnew(ml_generic_rule_t, Count, uintptr_t);
356 	Rule->Type = U;
357 	Rule->NumArgs = Count + 1;
358 	uintptr_t *RuleArgs = Rule->Args;
359 	va_start(Args, U);
360 	for (;;) {
361 		uintptr_t Arg = va_arg(Args, uintptr_t);
362 		if (!Arg) break;
363 		*RuleArgs++ = Arg;
364 	}
365 	va_end(Args);
366 	ml_generic_rule_t **Slot = &T->Rules;
367 	int Rank = U->Rank;
368 	while (Slot[0] && Slot[0]->Type->Rank > Rank) Slot = &Slot[0]->Next;
369 	Rule->Next = Slot[0];
370 	Slot[0] = Rule;
371 }
372 
373 #endif
374 
375 // Values //
376 
377 ML_TYPE(MLNilT, (MLFunctionT, MLIteratableT), "nil");
378 //!internal
379 
380 ML_TYPE(MLSomeT, (), "some");
381 //!internal
382 
ml_blank_assign(ml_value_t * Blank,ml_value_t * Value)383 static ml_value_t *ml_blank_assign(ml_value_t *Blank, ml_value_t *Value) {
384 	return Value;
385 }
386 
387 ML_TYPE(MLBlankT, (), "blank",
388 //!internal
389 	.assign = ml_blank_assign
390 );
391 
392 ML_VALUE(MLNil, MLNilT);
393 ML_VALUE(MLSome, MLSomeT);
394 ML_VALUE(MLBlank, MLBlankT);
395 
396 #ifdef ML_GENERICS
397 
ml_is_generic_subtype(int TNumArgs,ml_type_t ** TArgs,int UNumArgs,ml_type_t ** UArgs)398 static int ml_is_generic_subtype(int TNumArgs, ml_type_t **TArgs, int UNumArgs, ml_type_t **UArgs) {
399 	if (TArgs[0] == UArgs[0]) {
400 		if (UNumArgs == 1) return 1;
401 		if (UNumArgs <= TNumArgs) {
402 			for (int I = 0; I < UNumArgs; ++I) {
403 				if (!ml_is_subtype(TArgs[I], UArgs[I])) goto different;
404 			}
405 			return 1;
406 		}
407 	}
408 different:
409 	/*if (TArgs[0] == MLTupleT && TNumArgs > 1) {
410 
411 		if (ml_is_generic_subtype(TNumArgs - 1, TArgs, UNumArgs, UArgs)) return 1;
412 	}*/
413 	for (ml_generic_rule_t *Rule = TArgs[0]->Rules; Rule; Rule = Rule->Next) {
414 		int TNumArgs2 = Rule->NumArgs;
415 		ml_type_t *TArgs2[TNumArgs2];
416 		ml_generic_fill(Rule, TArgs2, TNumArgs, TArgs);
417 		if (ml_is_generic_subtype(TNumArgs2, TArgs2, UNumArgs, UArgs)) return 1;
418 	}
419 	return 0;
420 }
421 
422 #endif
423 
ml_is_subtype(ml_type_t * T,ml_type_t * U)424 int ml_is_subtype(ml_type_t *T, ml_type_t *U) {
425 	if (T == U) return 1;
426 	if (U == MLAnyT) return 1;
427 #ifdef ML_GENERICS
428 	if (T->Type == MLGenericTypeT) {
429 		ml_generic_type_t *GenericT = (ml_generic_type_t *)T;
430 		if (U->Type == MLGenericTypeT) {
431 			ml_generic_type_t *GenericU = (ml_generic_type_t *)U;
432 			return ml_is_generic_subtype(GenericT->NumArgs, GenericT->Args, GenericU->NumArgs, GenericU->Args);
433 		} else {
434 			if (GenericT->Args[0] == U) return 1;
435 			return ml_is_generic_subtype(GenericT->NumArgs, GenericT->Args, 1, &U);
436 		}
437 	} else {
438 		if (U->Type == MLGenericTypeT) {
439 			ml_generic_type_t *GenericU = (ml_generic_type_t *)U;
440 			if (ml_is_generic_subtype(1, &T, GenericU->NumArgs, GenericU->Args)) return 1;
441 		} else {
442 			if (ml_is_generic_subtype(1, &T, 1, &U)) return 1;
443 		}
444 	}
445 #endif
446 	return (uintptr_t)inthash_search(T->Parents, (uintptr_t)U);
447 }
448 
449 #ifdef ML_GENERICS
450 
ml_generic_type_max(ml_type_t * Max,int TNumArgs,ml_type_t ** TArgs,int UNumArgs,ml_type_t ** UArgs)451 static ml_type_t *ml_generic_type_max(ml_type_t *Max, int TNumArgs, ml_type_t **TArgs, int UNumArgs, ml_type_t **UArgs) {
452 	if (TArgs[0] == UArgs[0]) {
453 		if (TNumArgs > UNumArgs) {
454 			ml_type_t *Args[TNumArgs];
455 			Args[0] = TArgs[0];
456 			for (int I = 1; I < UNumArgs; ++I) Args[I] = ml_type_max(TArgs[I], UArgs[I]);
457 			for (int I = UNumArgs; I < TNumArgs; ++I) Args[I] = MLAnyT;
458 			return ml_generic_type(TNumArgs, Args);
459 		} else {
460 			ml_type_t *Args[UNumArgs];
461 			Args[0] = UArgs[0];
462 			for (int I = 1; I < TNumArgs; ++I) Args[I] = ml_type_max(TArgs[I], UArgs[I]);
463 			for (int I = TNumArgs; I < UNumArgs; ++I) Args[I] = MLAnyT;
464 			return ml_generic_type(UNumArgs, Args);
465 		}
466 	}
467 	if (TArgs[0] == MLTupleT && TNumArgs > 1) {
468 		for (ml_generic_rule_t *URule = UArgs[0]->Rules; URule; URule = URule->Next) {
469 			if (URule->Type->Rank <= Max->Rank) return Max;
470 			int UNumArgs2 = URule->NumArgs;
471 			ml_type_t *UArgs2[UNumArgs2];
472 			ml_generic_fill(URule, UArgs2, UNumArgs, UArgs);
473 			Max = ml_generic_type_max(Max, TNumArgs - 1, TArgs, UNumArgs2, UArgs2);
474 		}
475 	}
476 	for (ml_generic_rule_t *TRule = TArgs[0]->Rules; TRule; TRule = TRule->Next) {
477 		if (TRule->Type->Rank <= Max->Rank) return Max;
478 		int TNumArgs2 = TRule->NumArgs;
479 		ml_type_t *TArgs2[TNumArgs2];
480 		ml_generic_fill(TRule, TArgs2, TNumArgs, TArgs);
481 		for (ml_generic_rule_t *URule = UArgs[0]->Rules; URule; URule = URule->Next) {
482 			if (URule->Type->Rank <= Max->Rank) return Max;
483 			int UNumArgs2 = URule->NumArgs;
484 			ml_type_t *UArgs2[UNumArgs2];
485 			ml_generic_fill(URule, UArgs2, UNumArgs, UArgs);
486 			Max = ml_generic_type_max(Max, TNumArgs2, TArgs2, UNumArgs2, UArgs2);
487 		}
488 	}
489 	return Max;
490 }
491 
492 #endif
493 
ml_type_max(ml_type_t * T,ml_type_t * U)494 ml_type_t *ml_type_max(ml_type_t *T, ml_type_t *U) {
495 	ml_type_t *Max = MLAnyT;
496 	if (T->Rank < U->Rank) {
497 		if (inthash_search(U->Parents, (uintptr_t)T)) return T;
498 	} else {
499 		if (inthash_search(T->Parents, (uintptr_t)U)) return U;
500 	}
501 	for (int I = 0; I < T->Parents->Size; ++I) {
502 		ml_type_t *Parent = (ml_type_t *)T->Parents->Keys[I];
503 		if (Parent && Parent->Rank > Max->Rank) {
504 			if (inthash_search(U->Parents, (uintptr_t)Parent)) {
505 				Max = Parent;
506 			}
507 		}
508 	}
509 #ifdef ML_GENERICS
510 	if (T->Type == MLGenericTypeT) {
511 		ml_generic_type_t *GenericT = (ml_generic_type_t *)T;
512 		if (U->Type == MLGenericTypeT) {
513 			ml_generic_type_t *GenericU = (ml_generic_type_t *)U;
514 			Max = ml_generic_type_max(Max, GenericT->NumArgs, GenericT->Args, GenericU->NumArgs, GenericU->Args);
515 		} else {
516 			if (GenericT->Args[0] == U) return U;
517 			Max = ml_generic_type_max(Max, GenericT->NumArgs, GenericT->Args, 1, &U);
518 		}
519 	} else {
520 		if (U->Type == MLGenericTypeT) {
521 			ml_generic_type_t *GenericU = (ml_generic_type_t *)U;
522 			Max = ml_generic_type_max(Max, 1, &T, GenericU->NumArgs, GenericU->Args);
523 		} else {
524 			Max = ml_generic_type_max(Max, 1, &T, 1, &U);
525 		}
526 	}
527 #endif
528 	return Max;
529 }
530 
531 ML_METHOD("*", MLTypeT, MLTypeT) {
532 //<Type/1
533 //<Type/2
534 //>type
535 // Returns the closest common parent type of :mini:`Type/1` and :mini:`Type/2`.
536 	return (ml_value_t *)ml_type_max((ml_type_t *)Args[0], (ml_type_t *)Args[1]);
537 }
538 
539 ML_METHOD("<", MLTypeT, MLTypeT) {
540 //<Type/1
541 //<Type/2
542 //>type or nil
543 // Returns :mini:`Type/2` if :mini:`Type/2` is a strict parent of :mini:`Type/1`, otherwise returns :mini:`nil`.
544 	ml_type_t *Type1 = (ml_type_t *)Args[0];
545 	ml_type_t *Type2 = (ml_type_t *)Args[1];
546 	if (Type1 == Type2) return MLNil;
547 	if (ml_is_subtype(Type1, Type2)) return Args[1];
548 	return MLNil;
549 }
550 
551 ML_METHOD("<=", MLTypeT, MLTypeT) {
552 //<Type/1
553 //<Type/2
554 //>type or nil
555 // Returns :mini:`Type/2` if :mini:`Type/2` is a parent of :mini:`Type/1`, otherwise returns :mini:`nil`.
556 	ml_type_t *Type1 = (ml_type_t *)Args[0];
557 	ml_type_t *Type2 = (ml_type_t *)Args[1];
558 	if (Type1 == Type2) return Args[1];
559 	if (ml_is_subtype(Type1, Type2)) return Args[1];
560 	return MLNil;
561 }
562 
563 ML_METHOD(">", MLTypeT, MLTypeT) {
564 //<Type/1
565 //<Type/2
566 //>type or nil
567 // Returns :mini:`Type/2` if :mini:`Type/2` is a strict sub-type of :mini:`Type/1`, otherwise returns :mini:`nil`.
568 	ml_type_t *Type1 = (ml_type_t *)Args[0];
569 	ml_type_t *Type2 = (ml_type_t *)Args[1];
570 	if (Type1 == Type2) return MLNil;
571 	if (ml_is_subtype(Type2, Type1)) return Args[1];
572 	return MLNil;
573 }
574 
575 ML_METHOD(">=", MLTypeT, MLTypeT) {
576 //<Type/1
577 //<Type/2
578 //>type or nil
579 // Returns :mini:`Type/2` if :mini:`Type/2` is a sub-type of :mini:`Type/1`, otherwise returns :mini:`nil`.
580 	ml_type_t *Type1 = (ml_type_t *)Args[0];
581 	ml_type_t *Type2 = (ml_type_t *)Args[1];
582 	if (Type1 == Type2) return Args[1];
583 	if (ml_is_subtype(Type2, Type1)) return Args[1];
584 	return MLNil;
585 }
586 
587 #ifdef ML_GENERICS
588 ML_METHODVX("[]", MLTypeT, MLTypeT) {
589 //<Base
590 //<Type/1,...,Type/n
591 //>type
592 // Returns the generic type :mini:`Base[Type/1, ..., Type/n]`.
593 	for (int I = 2; I < Count; ++I) ML_CHECKX_ARG_TYPE(I, MLTypeT);
594 	ML_RETURN(ml_generic_type(Count, (ml_type_t **)Args));
595 }
596 #endif
597 
ML_TYPED_FN(ml_iterate,MLNilT,ml_state_t * Caller,ml_value_t * Value)598 static void ML_TYPED_FN(ml_iterate, MLNilT, ml_state_t *Caller, ml_value_t *Value) {
599 	ML_RETURN(Value);
600 }
601 
602 ML_METHOD("in", MLAnyT, MLTypeT) {
603 //<Value
604 //<Type
605 //>Value | nil
606 // Returns :mini:`Value` if it is an instance of :mini:`Type` or a type that inherits from :mini:`Type`.
607 // Returns :mini:`nil` otherwise.
608 	return ml_is(Args[0], (ml_type_t *)Args[1]) ? Args[0] : MLNil;
609 }
610 
611 ML_METHOD_ANON(MLCompilerSwitch, "compiler::switch");
612 
ML_METHODVX(MLCompilerSwitch,MLFunctionT)613 ML_METHODVX(MLCompilerSwitch, MLFunctionT) {
614 //!internal
615 	return ml_call(Caller, Args[0], Count - 1, Args + 1);
616 }
617 
ML_METHODVX(MLCompilerSwitch,MLTypeT)618 ML_METHODVX(MLCompilerSwitch, MLTypeT) {
619 //!internal
620 	ml_type_t *Type = (ml_type_t *)Args[0];
621 	ml_value_t *Switch = (ml_value_t *)stringmap_search(Type->Exports, "switch");
622 	if (!Switch) ML_ERROR("SwitchError", "%s does not support switch", Type->Name);
623 	return ml_call(Caller, Switch, Count - 1, Args + 1);
624 }
625 
626 typedef struct {
627 	ml_value_t *Index;
628 	ml_type_t *Type;
629 } ml_type_case_t;
630 
631 typedef struct {
632 	ml_type_t *Type;
633 	ml_type_case_t Cases[];
634 } ml_type_switch_t;
635 
ml_type_switch(ml_state_t * Caller,ml_type_switch_t * Switch,int Count,ml_value_t ** Args)636 static void ml_type_switch(ml_state_t *Caller, ml_type_switch_t *Switch, int Count, ml_value_t **Args) {
637 	ML_CHECKX_ARG_COUNT(1);
638 	ml_type_t *Type = ml_typeof(Args[0]);
639 	for (ml_type_case_t *Case = Switch->Cases;; ++Case) {
640 		if (ml_is_subtype(Type, Case->Type)) ML_RETURN(Case->Index);
641 	}
642 	ML_RETURN(MLNil);
643 }
644 
645 ML_TYPE(MLTypeSwitchT, (MLFunctionT), "type-switch",
646 //!internal
647 	.call = (void *)ml_type_switch
648 );
649 
ML_FUNCTION(MLTypeSwitch)650 ML_FUNCTION(MLTypeSwitch) {
651 //!internal
652 	int Total = 1;
653 	for (int I = 0; I < Count; ++I) {
654 		ML_CHECK_ARG_TYPE(I, MLListT);
655 		Total += ml_list_length(Args[I]);
656 	}
657 	ml_type_switch_t *Switch = xnew(ml_type_switch_t, Total, ml_type_case_t);
658 	Switch->Type = MLTypeSwitchT;
659 	ml_type_case_t *Case = Switch->Cases;
660 	for (int I = 0; I < Count; ++I) {
661 		ML_LIST_FOREACH(Args[I], Iter) {
662 			ml_value_t *Value = Iter->Value;
663 			if (ml_is(Value, MLTypeT)) {
664 				Case->Type = (ml_type_t *)Value;
665 			} else {
666 				return ml_error("ValueError", "Unsupported value in type case");
667 			}
668 			Case->Index = ml_integer(I);
669 			++Case;
670 		}
671 	}
672 	Case->Type = MLAnyT;
673 	Case->Index = ml_integer(Count);
674 	return (ml_value_t *)Switch;
675 }
676 
ml_hash_chain(ml_value_t * Value,ml_hash_chain_t * Chain)677 long ml_hash_chain(ml_value_t *Value, ml_hash_chain_t *Chain) {
678 	//Value = ml_deref(Value);
679 	for (ml_hash_chain_t *Link = Chain; Link; Link = Link->Previous) {
680 		if (Link->Value == Value) return Link->Index;
681 	}
682 	ml_hash_chain_t NewChain[1] = {{Chain, Value, Chain ? Chain->Index + 1 : 1}};
683 	return ml_typeof(Value)->hash(Value, NewChain);
684 }
685 
686 #ifdef ML_NANBOXING
687 
688 #define NegOne ml_int32(-1)
689 #define One ml_int32(1)
690 #define Zero ml_int32(0)
691 
692 #else
693 
694 static ml_integer_t One[1] = {{MLIntegerT, 1}};
695 static ml_integer_t NegOne[1] = {{MLIntegerT, -1}};
696 static ml_integer_t Zero[1] = {{MLIntegerT, 0}};
697 
698 #endif
699 
700 ML_METHOD("<>", MLAnyT, MLAnyT) {
701 //<Value/1
702 //<Value/2
703 //>integer
704 // Compares :mini:`Value/1` and :mini:`Value/2` and returns :mini:`-1`, :mini:`0` or :mini:`1`.
705 // This comparison is based on the internal addresses of :mini:`Value/1` and :mini:`Value/2` and thus only has no persistent meaning.
706 	if (Args[0] < Args[1]) return (ml_value_t *)NegOne;
707 	if (Args[0] > Args[1]) return (ml_value_t *)One;
708 	return (ml_value_t *)Zero;
709 }
710 
711 ML_METHOD("#", MLAnyT) {
712 //<Value
713 //>integer
714 // Returns a hash for :mini:`Value` for use in lookup tables, etc.
715 	ml_value_t *Value = Args[0];
716 	return ml_integer(ml_typeof(Value)->hash(Value, NULL));
717 }
718 
719 ML_METHOD("=", MLAnyT, MLAnyT) {
720 //<Value/1
721 //<Value/2
722 //>Value/2 | nil
723 // Returns :mini:`Value2` if :mini:`Value1` and :mini:`Value2` are exactly the same instance.
724 // Returns :mini:`nil` otherwise.
725 	return (Args[0] == Args[1]) ? Args[1] : MLNil;
726 }
727 
728 ML_METHOD("!=", MLAnyT, MLAnyT) {
729 //<Value/1
730 //<Value/2
731 //>Value/2 | nil
732 // Returns :mini:`Value2` if :mini:`Value1` and :mini:`Value2` are not exactly the same instance.
733 // Returns :mini:`nil` otherwise.
734 	return (Args[0] != Args[1]) ? Args[1] : MLNil;
735 }
736 
737 typedef struct {
738 	ml_state_t Base;
739 	ml_value_t *Comparison;
740 	ml_value_t **Args, **End;
741 	ml_value_t *Values[];
742 } ml_compare_state_t;
743 
ml_compare_state_run(ml_compare_state_t * State,ml_value_t * Result)744 static void ml_compare_state_run(ml_compare_state_t *State, ml_value_t *Result) {
745 	if (ml_is_error(Result)) ML_CONTINUE(State->Base.Caller, Result);
746 	if (Result == MLNil) ML_CONTINUE(State->Base.Caller, Result);
747 	State->Args[0] = Result;
748 	if (++State->Args == State->End) {
749 		return ml_call(State->Base.Caller, State->Comparison, 2, State->Args - 1);
750 	} else {
751 		return ml_call((ml_state_t *)State, State->Comparison, 2, State->Args - 1);
752 	}
753 }
754 
755 #define ml_comp_any_any_any(NAME) \
756 ML_METHODVX(NAME, MLAnyT, MLAnyT, MLAnyT) { \
757 	ml_compare_state_t *State = xnew(ml_compare_state_t, Count - 1, ml_value_t *); \
758 	State->Base.Caller = Caller; \
759 	State->Base.Context = Caller->Context; \
760 	State->Base.run = (ml_state_fn)ml_compare_state_run; \
761 	State->Comparison = ml_method(NAME); \
762 	for (int I = 2; I < Count; ++I) State->Values[I - 1] = Args[I]; \
763 	State->Args = State->Values; \
764 	State->End = State->Args + (Count - 2); \
765 	return ml_call((ml_state_t *)State, State->Comparison, 2, Args); \
766 }
767 
768 ml_comp_any_any_any("=");
769 ml_comp_any_any_any("!=");
770 ml_comp_any_any_any("<");
771 ml_comp_any_any_any("<=");
772 ml_comp_any_any_any(">");
773 ml_comp_any_any_any(">=");
774 
ML_METHOD(MLStringT,MLAnyT)775 ML_METHOD(MLStringT, MLAnyT) {
776 //<Value
777 //>string
778 // Returns a general (type name only) representation of :mini:`Value` as a string.
779 	return ml_string_format("<%s>", ml_typeof(Args[0])->Name);
780 }
781 
ml_value_set_name(ml_value_t * Value,const char * Name)782 void ml_value_set_name(ml_value_t *Value, const char *Name) {
783 	typeof(ml_value_set_name) *function = ml_typed_fn_get(ml_typeof(Value), ml_value_set_name);
784 	if (function) function(Value, Name);
785 }
786 
787 // Iterators //
788 
ml_iterate(ml_state_t * Caller,ml_value_t * Value)789 void ml_iterate(ml_state_t *Caller, ml_value_t *Value) {
790 	typeof(ml_iterate) *function = ml_typed_fn_get(ml_typeof(Value), ml_iterate);
791 	if (!function) {
792 		ml_value_t **Args = ml_alloc_args(1);
793 		Args[0] = Value;
794 		return ml_call(Caller, IterateMethod, 1, Args);
795 	}
796 	return function(Caller, Value);
797 }
798 
ml_iter_value(ml_state_t * Caller,ml_value_t * Iter)799 void ml_iter_value(ml_state_t *Caller, ml_value_t *Iter) {
800 	typeof(ml_iter_value) *function = ml_typed_fn_get(ml_typeof(Iter), ml_iter_value);
801 	if (!function) {
802 		ml_value_t **Args = ml_alloc_args(1);
803 		Args[0] = Iter;
804 		return ml_call(Caller, ValueMethod, 1, Args);
805 	}
806 	return function(Caller, Iter);
807 }
808 
ml_iter_key(ml_state_t * Caller,ml_value_t * Iter)809 void ml_iter_key(ml_state_t *Caller, ml_value_t *Iter) {
810 	typeof(ml_iter_key) *function = ml_typed_fn_get(ml_typeof(Iter), ml_iter_key);
811 	if (!function) {
812 		ml_value_t **Args = ml_alloc_args(1);
813 		Args[0] = Iter;
814 		return ml_call(Caller, KeyMethod, 1, Args);
815 	}
816 	return function(Caller, Iter);
817 }
818 
ml_iter_next(ml_state_t * Caller,ml_value_t * Iter)819 void ml_iter_next(ml_state_t *Caller, ml_value_t *Iter) {
820 	typeof(ml_iter_next) *function = ml_typed_fn_get(ml_typeof(Iter), ml_iter_next);
821 	if (!function) {
822 		ml_value_t **Args = ml_alloc_args(1);
823 		Args[0] = Iter;
824 		return ml_call(Caller, NextMethod, 1, Args);
825 	}
826 	return function(Caller, Iter);
827 }
828 
829 // Functions //
830 
831 ML_METHODX("!", MLFunctionT, MLTupleT) {
832 //!function
833 //<Function
834 //<Tuple
835 //>any
836 // Calls :mini:`Function` with the values in :mini:`Tuple` as positional arguments.
837 	ml_tuple_t *Tuple = (ml_tuple_t *)Args[1];
838 	ml_value_t *Function = Args[0];
839 	return ml_call(Caller, Function, Tuple->Size, Tuple->Values);
840 }
841 
842 ML_METHODX("!", MLFunctionT, MLListT) {
843 //!function
844 //<Function
845 //<List
846 //>any
847 // Calls :mini:`Function` with the values in :mini:`List` as positional arguments.
848 	ml_value_t *Function = Args[0];
849 	ml_value_t *List = Args[1];
850 	int Count2 = ml_list_length(List);
851 	ml_value_t **Args2 = ml_alloc_args(Count2);
852 	ml_list_to_array(List, Args2);
853 	return ml_call(Caller, Function, Count2, Args2);
854 }
855 
856 ML_METHODX("!", MLFunctionT, MLMapT) {
857 //!function
858 //<Function
859 //<Map
860 //>any
861 // Calls :mini:`Function` with the keys and values in :mini:`Map` as named arguments.
862 // Returns an error if any of the keys in :mini:`Map` is not a string or method.
863 	ml_value_t *Function = Args[0];
864 	ml_value_t *Map = Args[1];
865 	int Count2 = ml_map_size(Map) + 1;
866 	ml_value_t **Args2 = ml_alloc_args(Count2);
867 	ml_value_t *Names = ml_names();
868 	ml_value_t **Arg = Args2;
869 	*(Arg++) = Names;
ML_MAP_FOREACH(Map,Node)870 	ML_MAP_FOREACH(Map, Node) {
871 		ml_value_t *Name = Node->Key;
872 		if (ml_is(Name, MLMethodT)) {
873 			ml_names_add(Names, Name);
874 		} else if (ml_is(Name, MLStringT)) {
875 			ml_names_add(Names, ml_method(ml_string_value(Name)));
876 		} else {
877 			ML_RETURN(ml_error("TypeError", "Parameter names must be strings or methods"));
878 		}
879 		*(Arg++) = Node->Value;
880 	}
881 	return ml_call(Caller, Function, Count2, Args2);
882 }
883 
884 ML_METHODX("!", MLFunctionT, MLTupleT, MLMapT) {
885 //!function
886 //<Function
887 //<Tuple
888 //<Map
889 //>any
890 // Calls :mini:`Function` with the values in :mini:`Tuple` as positional arguments and the keys and values in :mini:`Map` as named arguments.
891 // Returns an error if any of the keys in :mini:`Map` is not a string or method.
892 	ml_value_t *Function = Args[0];
893 	ml_tuple_t *Tuple = (ml_tuple_t *)Args[1];
894 	ml_value_t *Map = Args[2];
895 	int TupleCount = Tuple->Size;
896 	int MapCount = ml_map_size(Map);
897 	int Count2 = TupleCount + MapCount + 1;
898 	ml_value_t **Args2 = ml_alloc_args(Count2);
899 	memcpy(Args2, Tuple->Values, TupleCount * sizeof(ml_value_t *));
900 	ml_value_t *Names = ml_names();
901 	ml_value_t **Arg = Args2 + TupleCount;
902 	*(Arg++) = Names;
ML_MAP_FOREACH(Map,Node)903 	ML_MAP_FOREACH(Map, Node) {
904 		ml_value_t *Name = Node->Key;
905 		if (ml_is(Name, MLMethodT)) {
906 			ml_names_add(Names, Name);
907 		} else if (ml_is(Name, MLStringT)) {
908 			ml_names_add(Names, ml_method(ml_string_value(Name)));
909 		} else {
910 			ML_RETURN(ml_error("TypeError", "Parameter names must be strings or methods"));
911 		}
912 		*(Arg++) = Node->Value;
913 	}
914 	return ml_call(Caller, Function, Count2, Args2);
915 }
916 
917 ML_METHODX("!", MLFunctionT, MLListT, MLMapT) {
918 //!function
919 //<Function
920 //<List
921 //<Map
922 //>any
923 // Calls :mini:`Function` with the values in :mini:`List` as positional arguments and the keys and values in :mini:`Map` as named arguments.
924 // Returns an error if any of the keys in :mini:`Map` is not a string or method.
925 	ml_value_t *Function = Args[0];
926 	int ListCount = ml_list_length(Args[1]);
927 	ml_value_t *Map = Args[2];
928 	int MapCount = ml_map_size(Map);
929 	int Count2 = ListCount + MapCount + 1;
930 	ml_value_t **Args2 = ml_alloc_args(Count2);
931 	ml_list_to_array(Args[1], Args2);
932 	ml_value_t *Names = ml_names();
933 	ml_value_t **Arg = Args2 + ListCount;
934 	*(Arg++) = Names;
ML_MAP_FOREACH(Map,Node)935 	ML_MAP_FOREACH(Map, Node) {
936 		ml_value_t *Name = Node->Key;
937 		if (ml_is(Name, MLMethodT)) {
938 			ml_names_add(Names, Name);
939 		} else if (ml_is(Name, MLStringT)) {
940 			ml_names_add(Names, ml_method(ml_string_value(Name)));
941 		} else {
942 			ML_RETURN(ml_error("TypeError", "Parameter names must be strings or methods"));
943 		}
944 		*(Arg++) = Node->Value;
945 	}
946 	return ml_call(Caller, Function, Count2, Args2);
947 }
948 
ml_cfunction_call(ml_state_t * Caller,ml_cfunction_t * Function,int Count,ml_value_t ** Args)949 static void ml_cfunction_call(ml_state_t *Caller, ml_cfunction_t *Function, int Count, ml_value_t **Args) {
950 	for (int I = 0; I < Count; ++I) Args[I] = ml_deref(Args[I]);
951 	ML_RETURN((Function->Callback)(Function->Data, Count, Args));
952 }
953 
954 ML_TYPE(MLCFunctionT, (MLFunctionT), "c-function",
955 //!internal
956 	.call = (void *)ml_cfunction_call
957 );
958 
ml_cfunction(void * Data,ml_callback_t Callback)959 ml_value_t *ml_cfunction(void *Data, ml_callback_t Callback) {
960 	ml_cfunction_t *Function = new(ml_cfunction_t);
961 	Function->Type = MLCFunctionT;
962 	Function->Data = Data;
963 	Function->Callback = Callback;
964 	return (ml_value_t *)Function;
965 }
966 
ml_cfunction_noderef_call(ml_state_t * Caller,ml_cfunction_t * Function,int Count,ml_value_t ** Args)967 static void ml_cfunction_noderef_call(ml_state_t *Caller, ml_cfunction_t *Function, int Count, ml_value_t **Args) {
968 	for (int I = 0; I < Count; ++I) Args[I] = ml_deref(Args[I]);
969 	ML_RETURN((Function->Callback)(Function->Data, Count, Args));
970 }
971 
972 ML_TYPE(MLCFunctionNoDerefT, (MLFunctionT), "c-function",
973 //!internal
974 	.call = (void *)ml_cfunction_noderef_call
975 );
976 
ml_cfunction_noderef(void * Data,ml_callback_t Callback)977 ml_value_t *ml_cfunction_noderef(void *Data, ml_callback_t Callback) {
978 	ml_cfunction_t *Function = new(ml_cfunction_t);
979 	Function->Type = MLCFunctionNoDerefT;
980 	Function->Data = Data;
981 	Function->Callback = Callback;
982 	return (ml_value_t *)Function;
983 }
984 
ML_TYPED_FN(ml_iterate,MLCFunctionT,ml_state_t * Caller,ml_cfunction_t * Function)985 static void ML_TYPED_FN(ml_iterate, MLCFunctionT, ml_state_t *Caller, ml_cfunction_t *Function) {
986 	ML_RETURN((Function->Callback)(Function->Data, 0, NULL));
987 }
988 
ml_cfunctionx_call(ml_state_t * Caller,ml_cfunctionx_t * Function,int Count,ml_value_t ** Args)989 static void ml_cfunctionx_call(ml_state_t *Caller, ml_cfunctionx_t *Function, int Count, ml_value_t **Args) {
990 	for (int I = 0; I < Count; ++I) Args[I] = ml_deref(Args[I]);
991 	return (Function->Callback)(Caller, Function->Data, Count, Args);
992 }
993 
994 ML_TYPE(MLCFunctionXT, (MLFunctionT), "c-functionx",
995 //!internal
996 	.call = (void *)ml_cfunctionx_call
997 );
998 
ml_cfunctionx(void * Data,ml_callbackx_t Callback)999 ml_value_t *ml_cfunctionx(void *Data, ml_callbackx_t Callback) {
1000 	ml_cfunctionx_t *Function = new(ml_cfunctionx_t);
1001 	Function->Type = MLCFunctionXT;
1002 	Function->Data = Data;
1003 	Function->Callback = Callback;
1004 	return (ml_value_t *)Function;
1005 }
1006 
ml_cfunctionz_call(ml_state_t * Caller,ml_cfunctionx_t * Function,int Count,ml_value_t ** Args)1007 static void ml_cfunctionz_call(ml_state_t *Caller, ml_cfunctionx_t *Function, int Count, ml_value_t **Args) {
1008 	return (Function->Callback)(Caller, Function->Data, Count, Args);
1009 }
1010 
1011 ML_TYPE(MLCFunctionZT, (MLFunctionT), "c-functionx",
1012 //!internal
1013 	.call = (void *)ml_cfunctionz_call
1014 );
1015 
ml_cfunctionz(void * Data,ml_callbackx_t Callback)1016 ml_value_t *ml_cfunctionz(void *Data, ml_callbackx_t Callback) {
1017 	ml_cfunctionx_t *Function = new(ml_cfunctionx_t);
1018 	Function->Type = MLCFunctionZT;
1019 	Function->Data = Data;
1020 	Function->Callback = Callback;
1021 	return (ml_value_t *)Function;
1022 }
1023 
ml_return_nil(void * Data,int Count,ml_value_t ** Args)1024 ml_value_t *ml_return_nil(void *Data, int Count, ml_value_t **Args) {
1025 	return MLNil;
1026 }
1027 
ml_identity(void * Data,int Count,ml_value_t ** Args)1028 ml_value_t *ml_identity(void *Data, int Count, ml_value_t **Args) {
1029 	return Args[0];
1030 }
1031 
1032 typedef struct ml_partial_function_t {
1033 	const ml_type_t *Type;
1034 	ml_value_t *Function;
1035 	int Count, Set;
1036 	ml_value_t *Args[];
1037 } ml_partial_function_t;
1038 
ml_partial_function_call(ml_state_t * Caller,ml_partial_function_t * Partial,int Count,ml_value_t ** Args)1039 static void ml_partial_function_call(ml_state_t *Caller, ml_partial_function_t *Partial, int Count, ml_value_t **Args) {
1040 	int CombinedCount = Count + Partial->Set;
1041 	if (CombinedCount < Partial->Count) CombinedCount = Partial->Count;
1042 	ml_value_t **CombinedArgs = ml_alloc_args(CombinedCount);
1043 	if (CombinedArgs == Args) CombinedArgs = anew(ml_value_t *, CombinedCount);
1044 	int I = 0, J = 0;
1045 	for (; I < Partial->Count; ++I) {
1046 		CombinedArgs[I] = Partial->Args[I] ?: (J < Count) ? Args[J++] : MLNil;
1047 	}
1048 	for (; I < CombinedCount; ++I) {
1049 		CombinedArgs[I] = (J < Count) ? Args[J++] : MLNil;
1050 	}
1051 	return ml_call(Caller, Partial->Function, CombinedCount, CombinedArgs);
1052 }
1053 
1054 ML_TYPE(MLPartialFunctionT, (MLFunctionT, MLIteratableT), "partial-function",
1055 //!function
1056 	.call = (void *)ml_partial_function_call
1057 );
1058 
ml_partial_function_new(ml_value_t * Function,int Count)1059 ml_value_t *ml_partial_function_new(ml_value_t *Function, int Count) {
1060 	ml_partial_function_t *Partial = xnew(ml_partial_function_t, Count, ml_value_t *);
1061 	Partial->Type = MLPartialFunctionT;
1062 	Partial->Function = Function;
1063 	Partial->Count = 0;
1064 	Partial->Set = 0;
1065 	return (ml_value_t *)Partial;
1066 }
1067 
ml_partial_function_set(ml_value_t * Partial0,size_t Index,ml_value_t * Value)1068 ml_value_t *ml_partial_function_set(ml_value_t *Partial0, size_t Index, ml_value_t *Value) {
1069 	ml_partial_function_t *Partial = (ml_partial_function_t *)Partial0;
1070 	++Partial->Set;
1071 	if (Partial->Count < Index + 1) Partial->Count = Index + 1;
1072 	return Partial->Args[Index] = Value;
1073 }
1074 
1075 ML_METHOD("count", MLPartialFunctionT) {
1076 //!function
1077 	ml_partial_function_t *Partial = (ml_partial_function_t *)Args[0];
1078 	return ml_integer(Partial->Count);
1079 }
1080 
1081 ML_METHOD("set", MLPartialFunctionT) {
1082 //!function
1083 	ml_partial_function_t *Partial = (ml_partial_function_t *)Args[0];
1084 	return ml_integer(Partial->Set);
1085 }
1086 
1087 ML_METHOD("!!", MLFunctionT, MLListT) {
1088 //!function
1089 //<Function
1090 //<List
1091 //>partialfunction
1092 // Returns a function equivalent to :mini:`fun(Args...) Function(List/1, List/2, ..., Args...)`.
1093 	ml_list_t *ArgsList = (ml_list_t *)Args[1];
1094 	ml_partial_function_t *Partial = xnew(ml_partial_function_t, ArgsList->Length, ml_value_t *);
1095 	Partial->Type = MLPartialFunctionT;
1096 	Partial->Function = Args[0];
1097 	Partial->Count = Partial->Set = ArgsList->Length;
1098 	ml_value_t **Arg = Partial->Args;
1099 	ML_LIST_FOREACH(ArgsList, Node) *Arg++ = Node->Value;
1100 	return (ml_value_t *)Partial;
1101 }
1102 
1103 ML_METHODV("$", MLFunctionT, MLAnyT) {
1104 //!function
1105 //<Function
1106 //<Values...
1107 //>partialfunction
1108 // Returns a function equivalent to :mini:`fun(Args...) Function(Values..., Args...)`.
1109 	ml_partial_function_t *Partial = xnew(ml_partial_function_t, Count - 1, ml_value_t *);
1110 	Partial->Type = MLPartialFunctionT;
1111 	Partial->Function = Args[0];
1112 	Partial->Count = Partial->Set = Count - 1;
1113 	for (int I = 1; I < Count; ++I) Partial->Args[I - 1] = Args[I];
1114 	return (ml_value_t *)Partial;
1115 }
1116 
ML_TYPED_FN(ml_iterate,MLPartialFunctionT,ml_state_t * Caller,ml_partial_function_t * Partial)1117 static void ML_TYPED_FN(ml_iterate, MLPartialFunctionT, ml_state_t *Caller, ml_partial_function_t *Partial) {
1118 	if (Partial->Set != Partial->Count) ML_ERROR("CallError", "Partial function used with missing arguments");
1119 	return ml_call(Caller, Partial->Function, Partial->Count, Partial->Args);
1120 }
1121 
1122 // Tuples //
1123 
ml_tuple_hash(ml_tuple_t * Tuple,ml_hash_chain_t * Chain)1124 static long ml_tuple_hash(ml_tuple_t *Tuple, ml_hash_chain_t *Chain) {
1125 	long Hash = 739;
1126 	for (int I = 0; I < Tuple->Size; ++I) Hash = ((Hash << 3) + Hash) + ml_hash(Tuple->Values[I]);
1127 	return Hash;
1128 }
1129 
ml_tuple_deref(ml_tuple_t * Ref)1130 static ml_value_t *ml_tuple_deref(ml_tuple_t *Ref) {
1131 	if (Ref->NoRefs) return (ml_value_t *)Ref;
1132 	for (int I = 0; I < Ref->Size; ++I) {
1133 		ml_value_t *Old = Ref->Values[I];
1134 		ml_value_t *New = ml_deref(Old);
1135 		if (Old != New) {
1136 			ml_tuple_t *Deref = xnew(ml_tuple_t, Ref->Size, ml_value_t *);
1137 			Deref->Type = MLTupleT;
1138 			Deref->Size = Ref->Size;
1139 			Deref->NoRefs = 1;
1140 			for (int J = 0; J < I; ++J) Deref->Values[J] = Ref->Values[J];
1141 			Deref->Values[I] = New;
1142 			for (int J = I + 1; J < Ref->Size; ++J) {
1143 				Deref->Values[J] = ml_deref(Ref->Values[J]);
1144 			}
1145 			return (ml_value_t *)Deref;
1146 		}
1147 	}
1148 	Ref->NoRefs = 1;
1149 	return (ml_value_t *)Ref;
1150 }
1151 
ml_tuple_assign(ml_tuple_t * Ref,ml_value_t * Values)1152 static ml_value_t *ml_tuple_assign(ml_tuple_t *Ref, ml_value_t *Values) {
1153 	int Count = Ref->Size;
1154 	for (int I = 0; I < Count; ++I) {
1155 		ml_value_t *Value = ml_deref(ml_unpack(Values, I + 1));
1156 		ml_value_t *Result = ml_assign(Ref->Values[I], Value);
1157 		if (ml_is_error(Result)) return Result;
1158 	}
1159 	return Values;
1160 }
1161 
ML_FUNCTION(MLTuple)1162 ML_FUNCTION(MLTuple) {
1163 //!tuple
1164 //@tuple
1165 //<Value/1
1166 //<:...
1167 //<Value/n
1168 //>tuple
1169 // Returns a tuple of values :mini:`Value/1, ..., Value/n`.
1170 	ml_value_t *Tuple = ml_tuple(Count);
1171 	for (int I = 0; I < Count; ++I) {
1172 		ml_value_t *Value = ml_deref(Args[I]);
1173 		//if (ml_is_error(Value)) return Value;
1174 		ml_tuple_set(Tuple, I + 1, Value);
1175 	}
1176 	return Tuple;
1177 }
1178 
1179 ML_TYPE(MLTupleT, (), "tuple",
1180 //!tuple
1181 // An immutable tuple of values.
1182 	.hash = (void *)ml_tuple_hash,
1183 	.deref = (void *)ml_tuple_deref,
1184 	.assign = (void *)ml_tuple_assign,
1185 	.Constructor = (ml_value_t *)MLTuple
1186 );
1187 
ml_tuple(size_t Size)1188 ml_value_t *ml_tuple(size_t Size) {
1189 	ml_tuple_t *Tuple = xnew(ml_tuple_t, Size, ml_value_t *);
1190 	Tuple->Type = MLTupleT;
1191 	Tuple->Size = Size;
1192 	return (ml_value_t *)Tuple;
1193 }
1194 
1195 #ifdef ML_GENERICS
1196 
ml_tuple_set(ml_value_t * Tuple0,int Index,ml_value_t * Value)1197 ml_value_t *ml_tuple_set(ml_value_t *Tuple0, int Index, ml_value_t *Value) {
1198 	ml_tuple_t *Tuple = (ml_tuple_t *)Tuple0;
1199 	Tuple->Values[Index - 1] = Value;
1200 	if (Tuple->Type == MLTupleT) {
1201 		ml_type_t *Types[Tuple->Size + 1];
1202 		Types[0] = MLTupleT;
1203 		for (int I = 0; I < Tuple->Size; ++I) {
1204 			if (!Tuple->Values[I]) return Value;
1205 			Types[I + 1] = ml_typeof(Tuple->Values[I]);
1206 		}
1207 		Tuple->Type = ml_generic_type(Tuple->Size + 1, Types);
1208 	}
1209 	return Value;
1210 }
1211 
1212 #endif
1213 
ml_unpack(ml_value_t * Value,int Index)1214 ml_value_t *ml_unpack(ml_value_t *Value, int Index) {
1215 	typeof(ml_unpack) *function = ml_typed_fn_get(ml_typeof(Value), ml_unpack);
1216 	if (!function) return ml_simple_inline(IndexMethod, 2, Value, ml_integer(Index));
1217 	return function(Value, Index);
1218 }
1219 
1220 ML_METHOD("size", MLTupleT) {
1221 //!tuple
1222 //<Tuple
1223 //>integer
1224 // Returns the number of elements in :mini:`Tuple`.
1225 	ml_tuple_t *Tuple = (ml_tuple_t *)Args[0];
1226 	return ml_integer(Tuple->Size);
1227 }
1228 
1229 ML_METHOD("[]", MLTupleT, MLIntegerT) {
1230 //!tuple
1231 //<Tuple
1232 //<Index
1233 //>any | error
1234 // Returns the :mini:`Index`-th element in :mini:`Tuple` or an error if :mini:`Index` is out of range.
1235 // Indexing starts at :mini:`1`. Negative indices count from the end, with :mini:`-1` returning the last element.
1236 	ml_tuple_t *Tuple = (ml_tuple_t *)Args[0];
1237 	long Index = ml_integer_value_fast(Args[1]);
1238 	if (--Index < 0) Index += Tuple->Size + 1;
1239 	if (Index < 0 || Index >= Tuple->Size) return ml_error("RangeError", "Tuple index out of bounds");
1240 	return Tuple->Values[Index];
1241 }
1242 
ml_tuple_fn(void * Data,int Count,ml_value_t ** Args)1243 ml_value_t *ml_tuple_fn(void *Data, int Count, ml_value_t **Args) {
1244 	ml_tuple_t *Tuple = xnew(ml_tuple_t, Count, ml_value_t *);
1245 	Tuple->Type = MLTupleT;
1246 	Tuple->Size = Count;
1247 	memcpy(Tuple->Values, Args, Count * sizeof(ml_value_t *));
1248 	return (ml_value_t *)Tuple;
1249 }
1250 
ML_METHOD(MLStringT,MLTupleT)1251 ML_METHOD(MLStringT, MLTupleT) {
1252 //!tuple
1253 //<Tuple
1254 //>string
1255 // Returns a string representation of :mini:`Tuple`.
1256 	ml_tuple_t *Tuple = (ml_tuple_t *)Args[0];
1257 	ml_stringbuffer_t Buffer[1] = {ML_STRINGBUFFER_INIT};
1258 	ml_stringbuffer_add(Buffer, "(", 1);
1259 	if (Tuple->Size) {
1260 		ml_stringbuffer_append(Buffer, Tuple->Values[0]);
1261 		for (int I = 1; I < Tuple->Size; ++I) {
1262 			ml_stringbuffer_add(Buffer, ", ", 2);
1263 			ml_stringbuffer_append(Buffer, Tuple->Values[I]);
1264 		}
1265 	}
1266 	ml_stringbuffer_add(Buffer, ")", 1);
1267 	return ml_stringbuffer_value(Buffer);
1268 }
1269 
1270 ML_METHOD("append", MLStringBufferT, MLTupleT) {
1271 //!tuple
1272 	ml_stringbuffer_t *Buffer = (ml_stringbuffer_t *)Args[0];
1273 	ml_tuple_t *Value = (ml_tuple_t *)Args[1];
1274 	ml_stringbuffer_add(Buffer, "(", 1);
1275 	if (Value->Size) {
1276 		ml_stringbuffer_append(Buffer, Value->Values[0]);
1277 		for (int I = 1; I < Value->Size; ++I) {
1278 			ml_stringbuffer_add(Buffer, ", ", 2);
1279 			ml_stringbuffer_append(Buffer, Value->Values[I]);
1280 		}
1281 	}
1282 	ml_stringbuffer_add(Buffer, ")", 1);
1283 	return MLSome;
1284 }
1285 
ML_TYPED_FN(ml_unpack,MLTupleT,ml_tuple_t * Tuple,int Index)1286 ml_value_t *ML_TYPED_FN(ml_unpack, MLTupleT, ml_tuple_t *Tuple, int Index) {
1287 	if (Index > Tuple->Size) return MLNil;
1288 	return Tuple->Values[Index - 1];
1289 }
1290 
ml_tuple_compare(ml_tuple_t * A,ml_tuple_t * B)1291 static ml_value_t *ml_tuple_compare(ml_tuple_t *A, ml_tuple_t *B) {
1292 	ml_value_t *Args[2];
1293 	ml_value_t *Result;
1294 	int N;
1295 	if (A->Size > B->Size) {
1296 		N = B->Size;
1297 		Result = (ml_value_t *)One;
1298 	} else if (A->Size < B->Size) {
1299 		N = A->Size;
1300 		Result = (ml_value_t *)NegOne;
1301 	} else {
1302 		N = A->Size;
1303 		Result = (ml_value_t *)Zero;
1304 	}
1305 	for (int I = 0; I < N; ++I) {
1306 		Args[0] = A->Values[I];
1307 		Args[1] = B->Values[I];
1308 		ml_value_t *C = ml_simple_call(CompareMethod, 2, Args);
1309 		if (ml_is_error(C)) return C;
1310 		if (ml_integer_value(C)) return C;
1311 	}
1312 	return Result;
1313 }
1314 
1315 ML_METHOD("<>", MLTupleT, MLTupleT) {
1316 //!tuple
1317 //<Tuple/1
1318 //<Tuple/2
1319 //>integer
1320 // Returns :mini:`-1`, :mini:`0` or :mini:`1` depending on whether :mini:`Tuple/1` is less than, equal to or greater than :mini:`Tuple/2` using lexicographical ordering.
1321 	return ml_tuple_compare((ml_tuple_t *)Args[0], (ml_tuple_t *)Args[1]);
1322 }
1323 
1324 #define ml_comp_tuple_tuple(NAME, NEG, ZERO, POS) \
1325 ML_METHOD(NAME, MLTupleT, MLTupleT) { \
1326 	ml_value_t *Result = ml_tuple_compare((ml_tuple_t *)Args[0], (ml_tuple_t *)Args[1]); \
1327 	if (Result == (ml_value_t *)NegOne) return NEG; \
1328 	if (Result == (ml_value_t *)Zero) return ZERO; \
1329 	if (Result == (ml_value_t *)One) return POS; \
1330 	return Result; \
1331 }
1332 
1333 ml_comp_tuple_tuple("=", MLNil, Args[1], MLNil);
1334 ml_comp_tuple_tuple("!=", Args[1], MLNil, Args[1]);
1335 ml_comp_tuple_tuple("<", Args[1], MLNil, MLNil);
1336 ml_comp_tuple_tuple("<=", Args[1], Args[1], MLNil);
1337 ml_comp_tuple_tuple(">", MLNil, MLNil, Args[1]);
1338 ml_comp_tuple_tuple(">=", MLNil, Args[1], Args[1]);
1339 
1340 #if 0
1341 ML_METHOD("<op>", MLTupleT, MLTupleT) {
1342 //!tuple
1343 //<Tuple/1
1344 //<Tuple/2
1345 //>Tuple/2 | nil
1346 // :mini:`<op>` is :mini:`=`, :mini:`!=`, :mini:`<`, :mini:`<=`, :mini:`>` or :mini:`>=`
1347 // Returns :mini:`Tuple/2` if :mini:`Tuple/2 <op> Tuple/1` is true, otherwise returns :mini:`nil`.
1348 }
1349 #endif
1350 
1351 // Boolean //
1352 
ml_boolean_hash(ml_boolean_t * Boolean,ml_hash_chain_t * Chain)1353 static long ml_boolean_hash(ml_boolean_t *Boolean, ml_hash_chain_t *Chain) {
1354 	return (long)Boolean;
1355 }
1356 
1357 ML_TYPE(MLBooleanT, (MLFunctionT), "boolean",
1358 //!boolean
1359 	.hash = (void *)ml_boolean_hash
1360 );
1361 
ml_boolean_value(const ml_value_t * Value)1362 int ml_boolean_value(const ml_value_t *Value) {
1363 	return ((ml_boolean_t *)Value)->Value;
1364 }
1365 
1366 ml_boolean_t MLFalse[1] = {{MLBooleanT, "false", 0}};
1367 ml_boolean_t MLTrue[1] = {{MLBooleanT, "true", 1}};
1368 
1369 static ml_value_t *MLBooleans[2] = {
1370 	[0] = (ml_value_t *)MLFalse,
1371 	[1] = (ml_value_t *)MLTrue
1372 };
1373 
ml_boolean(int Value)1374 ml_value_t *ml_boolean(int Value) {
1375 	return Value ? (ml_value_t *)MLTrue : (ml_value_t *)MLFalse;
1376 }
1377 
ML_METHOD(MLBooleanT,MLStringT)1378 ML_METHOD(MLBooleanT, MLStringT) {
1379 //!boolean
1380 //<String
1381 //>boolean | error
1382 // Returns :mini:`true` if :mini:`String` equals :mini:`"true"` (ignoring case).
1383 // Returns :mini:`false` if :mini:`String` equals :mini:`"false"` (ignoring case).
1384 // Otherwise returns an error.
1385 	const char *Name = ml_string_value(Args[0]);
1386 	if (!strcasecmp(Name, "true")) return (ml_value_t *)MLTrue;
1387 	if (!strcasecmp(Name, "false")) return (ml_value_t *)MLFalse;
1388 	return ml_error("ValueError", "Invalid boolean: %s", Name);
1389 }
1390 
1391 ML_METHOD("-", MLBooleanT) {
1392 //!boolean
1393 //<Bool
1394 //>boolean
1395 // Returns the logical inverse of :mini:`Bool`
1396 	return MLBooleans[1 - ml_boolean_value(Args[0])];
1397 }
1398 
1399 ML_METHOD("/\\", MLBooleanT, MLBooleanT) {
1400 //!boolean
1401 //<Bool/1
1402 //<Bool/2
1403 //>boolean
1404 // Returns the logical and of :mini:`Bool/1` and :mini:`Bool/2`.
1405 	return MLBooleans[ml_boolean_value(Args[0]) & ml_boolean_value(Args[1])];
1406 }
1407 
1408 ML_METHOD("\\/", MLBooleanT, MLBooleanT) {
1409 //!boolean
1410 //<Bool/1
1411 //<Bool/2
1412 //>boolean
1413 // Returns the logical or of :mini:`Bool/1` and :mini:`Bool/2`.
1414 	return MLBooleans[ml_boolean_value(Args[0]) | ml_boolean_value(Args[1])];
1415 }
1416 
1417 ML_METHOD("<>", MLBooleanT, MLBooleanT) {
1418 //!boolean
1419 //<Bool/1
1420 //<Bool/2
1421 //>integer
1422 // Returns :mini:`-1`, :mini:`0` or :mini:`1` depending on whether :mini:`Bool/1` is less than, equal to or greater than :mini:`Bool/2`. :mini:`true` is considered greater than :mini:`false`.
1423 	ml_boolean_t *BooleanA = (ml_boolean_t *)Args[0];
1424 	ml_boolean_t *BooleanB = (ml_boolean_t *)Args[1];
1425 	return ml_integer(BooleanA->Value - BooleanB->Value);
1426 }
1427 
1428 #define ml_comp_method_boolean_boolean(NAME, SYMBOL) \
1429 	ML_METHOD(NAME, MLBooleanT, MLBooleanT) { \
1430 		ml_boolean_t *BooleanA = (ml_boolean_t *)Args[0]; \
1431 		ml_boolean_t *BooleanB = (ml_boolean_t *)Args[1]; \
1432 		return BooleanA->Value SYMBOL BooleanB->Value ? Args[1] : MLNil; \
1433 	}
1434 
1435 ml_comp_method_boolean_boolean("=", ==);
1436 ml_comp_method_boolean_boolean("!=", !=);
1437 ml_comp_method_boolean_boolean("<", <);
1438 ml_comp_method_boolean_boolean(">", >);
1439 ml_comp_method_boolean_boolean("<=", <=);
1440 ml_comp_method_boolean_boolean(">=", >=);
1441 
1442 #if 0
1443 ML_METHOD("<op>", MLBooleanT, MLBooleanT) {
1444 //!boolean
1445 //<Bool/1
1446 //<Bool/2
1447 //>Bool/2 | nil
1448 // :mini:`<op>` is :mini:`=`, :mini:`!=`, :mini:`<`, :mini:`<=`, :mini:`>` or :mini:`>=`
1449 // Returns :mini:`Bool/2` if :mini:`Bool/2 <op> Bool/1` is true, otherwise returns :mini:`nil`.
1450 // :mini:`true` is considered greater than :mini:`false`.
1451 }
1452 #endif
1453 
1454 // Numbers //
1455 
1456 ML_TYPE(MLNumberT, (), "number");
1457 //!number
1458 // Base type for numbers.
1459 
1460 ML_TYPE(MLRealT, (MLNumberT), "real");
1461 //!number
1462 // Base type for real numbers.
1463 
1464 #ifdef ML_NANBOXING
1465 
ml_int32_hash(ml_value_t * Value,ml_hash_chain_t * Chain)1466 static long ml_int32_hash(ml_value_t *Value, ml_hash_chain_t *Chain) {
1467 	return (int32_t)(intptr_t)Value;
1468 }
1469 
ml_int32_call(ml_state_t * Caller,ml_value_t * Value,int Count,ml_value_t ** Args)1470 static void ml_int32_call(ml_state_t *Caller, ml_value_t *Value, int Count, ml_value_t **Args) {
1471 	long Index = (int32_t)(intptr_t)Value;
1472 	if (Index <= 0) Index += Count + 1;
1473 	if (Index <= 0) ML_RETURN(MLNil);
1474 	if (Index > Count) ML_RETURN(MLNil);
1475 	ML_RETURN(Args[Index - 1]);
1476 }
1477 
1478 ML_TYPE(MLIntegerT, (MLRealT, MLFunctionT), "integer");
1479 //!number
1480 
1481 ML_TYPE(MLInt32T, (MLIntegerT), "int32",
1482 //!internal
1483 	.hash = (void *)ml_int32_hash,
1484 	.call = (void *)ml_int32_call,
1485 	.NoInherit = 1
1486 );
1487 
ml_int64_hash(ml_value_t * Value,ml_hash_chain_t * Chain)1488 static long ml_int64_hash(ml_value_t *Value, ml_hash_chain_t *Chain) {
1489 	return ((ml_int64_t *)Value)->Value;
1490 }
1491 
1492 ML_TYPE(MLInt64T, (MLIntegerT), "int64",
1493 //!internal
1494 	.hash = (void *)ml_int64_hash,
1495 	.NoInherit = 1
1496 );
1497 
ml_int64(int64_t Integer)1498 ml_value_t *ml_int64(int64_t Integer) {
1499 	ml_int64_t *Value = new(ml_int64_t);
1500 	Value->Type = MLInt64T;
1501 	Value->Value = Integer;
1502 	return (ml_value_t *)Value;
1503 }
1504 
ml_integer_value(const ml_value_t * Value)1505 int64_t ml_integer_value(const ml_value_t *Value) {
1506 	int Tag = ml_tag(Value);
1507 	if (Tag == 1) return (int32_t)(intptr_t)Value;
1508 	if (Tag >= 7) return ml_to_double(Value);
1509 	if (Tag == 0) {
1510 		if (Value->Type == MLInt64T) {
1511 			return ((ml_int64_t *)Value)->Value;
1512 		}
1513 	}
1514 	return 0;
1515 }
1516 
ML_METHOD(MLRealT,MLInt32T)1517 ML_METHOD(MLRealT, MLInt32T) {
1518 //!number
1519 	return ml_real((int32_t)(intptr_t)Args[0]);
1520 }
1521 
ML_METHOD(MLRealT,MLInt64T)1522 ML_METHOD(MLRealT, MLInt64T) {
1523 //!number
1524 	return ml_real(((ml_int64_t *)Args[0])->Value);
1525 }
1526 
1527 #else
1528 
ml_integer_hash(ml_integer_t * Integer,ml_hash_chain_t * Chain)1529 static long ml_integer_hash(ml_integer_t *Integer, ml_hash_chain_t *Chain) {
1530 	return Integer->Value;
1531 }
1532 
ml_integer_call(ml_state_t * Caller,ml_integer_t * Integer,int Count,ml_value_t ** Args)1533 static void ml_integer_call(ml_state_t *Caller, ml_integer_t *Integer, int Count, ml_value_t **Args) {
1534 	long Index = Integer->Value;
1535 	if (Index <= 0) Index += Count + 1;
1536 	if (Index <= 0) ML_RETURN(MLNil);
1537 	if (Index > Count) ML_RETURN(MLNil);
1538 	ML_RETURN(Args[Index - 1]);
1539 }
1540 
1541 ML_TYPE(MLIntegerT, (MLRealT, MLFunctionT), "integer",
1542 //!number
1543 	.hash = (void *)ml_integer_hash,
1544 	.call = (void *)ml_integer_call
1545 );
1546 
ml_integer(int64_t Value)1547 ml_value_t *ml_integer(int64_t Value) {
1548 	ml_integer_t *Integer = new(ml_integer_t);
1549 	Integer->Type = MLIntegerT;
1550 	Integer->Value = Value;
1551 	return (ml_value_t *)Integer;
1552 }
1553 
1554 extern int64_t ml_integer_value_fast(const ml_value_t *Value);
1555 
ml_integer_value(const ml_value_t * Value)1556 int64_t ml_integer_value(const ml_value_t *Value) {
1557 	if (Value->Type == MLIntegerT) {
1558 		return ((ml_integer_t *)Value)->Value;
1559 	} else if (Value->Type == MLDoubleT) {
1560 		return ((ml_double_t *)Value)->Value;
1561 	} else if (ml_is(Value, MLIntegerT)) {
1562 		return ((ml_integer_t *)Value)->Value;
1563 	} else if (ml_is(Value, MLDoubleT)) {
1564 		return ((ml_double_t *)Value)->Value;
1565 	} else {
1566 		return 0;
1567 	}
1568 }
1569 
ML_METHOD(MLRealT,MLIntegerT)1570 ML_METHOD(MLRealT, MLIntegerT) {
1571 //!number
1572 	return ml_real(((ml_integer_t *)Args[0])->Value);
1573 }
1574 
1575 #endif
1576 
1577 #ifdef ML_NANBOXING
1578 
ML_METHOD(MLIntegerT,MLDoubleT)1579 ML_METHOD(MLIntegerT, MLDoubleT) {
1580 //!number
1581 	return ml_integer(ml_to_double(Args[0]));
1582 }
1583 
ml_double_hash(ml_value_t * Value,ml_hash_chain_t * Chain)1584 static long ml_double_hash(ml_value_t *Value, ml_hash_chain_t *Chain) {
1585 	return (long)ml_to_double(Value);
1586 }
1587 
1588 ML_TYPE(MLDoubleT, (MLRealT), "double",
1589 //!internal
1590 	.hash = (void *)ml_double_hash,
1591 	.NoInherit = 1
1592 );
1593 
ml_real_value(const ml_value_t * Value)1594 double ml_real_value(const ml_value_t *Value) {
1595 	int Tag = ml_tag(Value);
1596 	if (Tag == 1) return (int32_t)(intptr_t)Value;
1597 	if (Tag >= 7) return ml_to_double(Value);
1598 	if (Tag == 0) {
1599 		if (Value->Type == MLInt64T) {
1600 			return ((ml_int64_t *)Value)->Value;
1601 		}
1602 	}
1603 	return 0;
1604 }
1605 
ML_METHOD(MLDoubleT,MLInt32T)1606 ML_METHOD(MLDoubleT, MLInt32T) {
1607 //!number
1608 	return ml_real((int32_t)(intptr_t)Args[0]);
1609 }
1610 
ML_METHOD(MLDoubleT,MLInt64T)1611 ML_METHOD(MLDoubleT, MLInt64T) {
1612 //!number
1613 	return ml_real(((ml_int64_t *)Args[0])->Value);
1614 }
1615 
1616 #else
1617 
ML_METHOD(MLIntegerT,MLDoubleT)1618 ML_METHOD(MLIntegerT, MLDoubleT) {
1619 //!number
1620 //<Real
1621 //>integer
1622 // Converts :mini:`Real` to an integer (using default rounding).
1623 	return ml_integer(((ml_double_t *)Args[0])->Value);
1624 }
1625 
ml_double_hash(ml_double_t * Real,ml_hash_chain_t * Chain)1626 static long ml_double_hash(ml_double_t *Real, ml_hash_chain_t *Chain) {
1627 	return (long)Real->Value;
1628 }
1629 
1630 ML_TYPE(MLDoubleT, (MLRealT), "real",
1631 //!number
1632 	.hash = (void *)ml_double_hash,
1633 	.NoInherit = 1
1634 );
1635 
ml_real(double Value)1636 ml_value_t *ml_real(double Value) {
1637 	ml_double_t *Real = new(ml_double_t);
1638 	Real->Type = MLDoubleT;
1639 	Real->Value = Value;
1640 	return (ml_value_t *)Real;
1641 }
1642 
1643 extern double ml_double_value_fast(const ml_value_t *Value);
1644 
ml_real_value(const ml_value_t * Value)1645 double ml_real_value(const ml_value_t *Value) {
1646 	if (Value->Type == MLIntegerT) {
1647 		return ((ml_integer_t *)Value)->Value;
1648 	} else if (Value->Type == MLDoubleT) {
1649 		return ((ml_double_t *)Value)->Value;
1650 	} else if (ml_is(Value, MLIntegerT)) {
1651 		return ((ml_integer_t *)Value)->Value;
1652 	} else if (ml_is(Value, MLDoubleT)) {
1653 		return ((ml_double_t *)Value)->Value;
1654 	} else {
1655 		return 0;
1656 	}
1657 }
1658 
ML_METHOD(MLDoubleT,MLIntegerT)1659 ML_METHOD(MLDoubleT, MLIntegerT) {
1660 //!number
1661 	return ml_real(((ml_integer_t *)Args[0])->Value);
1662 }
1663 
1664 #endif
1665 
1666 #define ml_arith_method_integer(NAME, SYMBOL) \
1667 	ML_METHOD(NAME, MLIntegerT) { \
1668 		int64_t IntegerA = ml_integer_value_fast(Args[0]); \
1669 		return ml_integer(SYMBOL(IntegerA)); \
1670 	}
1671 
1672 #define ml_arith_method_integer_integer(NAME, SYMBOL) \
1673 	ML_METHOD(NAME, MLIntegerT, MLIntegerT) { \
1674 		int64_t IntegerA = ml_integer_value_fast(Args[0]); \
1675 		int64_t IntegerB = ml_integer_value_fast(Args[1]); \
1676 		return ml_integer(IntegerA SYMBOL IntegerB); \
1677 	}
1678 
1679 #define ml_arith_method_real(NAME, SYMBOL) \
1680 	ML_METHOD(NAME, MLDoubleT) { \
1681 		double RealA = ml_double_value_fast(Args[0]); \
1682 		return ml_real(SYMBOL(RealA)); \
1683 	}
1684 
1685 #define ml_arith_method_real_real(NAME, SYMBOL) \
1686 	ML_METHOD(NAME, MLDoubleT, MLDoubleT) { \
1687 		double RealA = ml_double_value_fast(Args[0]); \
1688 		double RealB = ml_double_value_fast(Args[1]); \
1689 		return ml_real(RealA SYMBOL RealB); \
1690 	}
1691 
1692 #define ml_arith_method_real_integer(NAME, SYMBOL) \
1693 	ML_METHOD(NAME, MLDoubleT, MLIntegerT) { \
1694 		double RealA = ml_double_value_fast(Args[0]); \
1695 		int64_t IntegerB = ml_integer_value_fast(Args[1]); \
1696 		return ml_real(RealA SYMBOL IntegerB); \
1697 	}
1698 
1699 #define ml_arith_method_integer_real(NAME, SYMBOL) \
1700 	ML_METHOD(NAME, MLIntegerT, MLDoubleT) { \
1701 		int64_t IntegerA = ml_integer_value_fast(Args[0]); \
1702 		double RealB = ml_double_value_fast(Args[1]); \
1703 		return ml_real(IntegerA SYMBOL RealB); \
1704 	}
1705 
1706 #ifdef ML_COMPLEX
1707 
ml_complex_hash(ml_complex_t * Complex,ml_hash_chain_t * Chain)1708 static long ml_complex_hash(ml_complex_t *Complex, ml_hash_chain_t *Chain) {
1709 	return (long)creal(Complex->Value);
1710 }
1711 
1712 ML_TYPE(MLComplexT, (MLNumberT), "complex",
1713 //!number
1714 	.hash = (void *)ml_complex_hash
1715 );
1716 
ml_complex(complex double Value)1717 ml_value_t *ml_complex(complex double Value) {
1718 	ml_complex_t *Complex = new(ml_complex_t);
1719 	Complex->Type = MLComplexT;
1720 	Complex->Value = Value;
1721 	return (ml_value_t *)Complex;
1722 }
1723 
ML_METHOD(MLComplexT,MLRealT)1724 ML_METHOD(MLComplexT, MLRealT) {
1725 //!number
1726 	return ml_complex(ml_real_value(Args[0]));
1727 }
1728 
ML_METHOD(MLRealT,MLComplexT)1729 ML_METHOD(MLRealT, MLComplexT) {
1730 //!number
1731 	return ml_real(creal(ml_complex_value(Args[0])));
1732 }
1733 
1734 extern complex double ml_complex_value_fast(const ml_value_t *Value);
1735 
ml_complex_value(const ml_value_t * Value)1736 complex double ml_complex_value(const ml_value_t *Value) {
1737 #ifdef ML_NANBOXING
1738 	int Tag = ml_tag(Value);
1739 	if (Tag == 1) return (int32_t)(intptr_t)Value;
1740 	if (Tag >= 7) return ml_to_double(Value);
1741 	if (Tag == 0) {
1742 		if (Value->Type == MLInt64T) {
1743 			return ((ml_int64_t *)Value)->Value;
1744 		} else if (Value->Type == MLComplexT) {
1745 			return ((ml_complex_t *)Value)->Value;
1746 		}
1747 	}
1748 	return 0;
1749 #else
1750 	if (Value->Type == MLIntegerT) {
1751 		return ((ml_integer_t *)Value)->Value;
1752 	} else if (Value->Type == MLDoubleT) {
1753 		return ((ml_double_t *)Value)->Value;
1754 	} else if (ml_is(Value, MLIntegerT)) {
1755 		return ((ml_integer_t *)Value)->Value;
1756 	} else if (ml_is(Value, MLDoubleT)) {
1757 		return ((ml_double_t *)Value)->Value;
1758 	} else if (ml_is(Value, MLComplexT)) {
1759 		return ((ml_complex_t *)Value)->Value;
1760 	} else {
1761 		return 0;
1762 	}
1763 #endif
1764 }
1765 
1766 #define ml_arith_method_complex(NAME, SYMBOL) \
1767 	ML_METHOD(NAME, MLComplexT) { \
1768 		complex double ComplexA = ml_complex_value_fast(Args[0]); \
1769 		complex double ComplexB = SYMBOL(ComplexA); \
1770 		if (fabs(cimag(ComplexB)) <= DBL_EPSILON) { \
1771 			return ml_real(creal(ComplexB)); \
1772 		} else { \
1773 			return ml_complex(ComplexB); \
1774 		} \
1775 	}
1776 
1777 #define ml_arith_method_complex_complex(NAME, SYMBOL) \
1778 	ML_METHOD(NAME, MLComplexT, MLComplexT) { \
1779 		complex double ComplexA = ml_complex_value_fast(Args[0]); \
1780 		complex double ComplexB = ml_complex_value_fast(Args[1]); \
1781 		complex double ComplexC = ComplexA SYMBOL ComplexB; \
1782 		if (fabs(cimag(ComplexC)) <= DBL_EPSILON) { \
1783 			return ml_real(creal(ComplexC)); \
1784 		} else { \
1785 			return ml_complex(ComplexC); \
1786 		} \
1787 	}
1788 
1789 #define ml_arith_method_complex_integer(NAME, SYMBOL) \
1790 	ML_METHOD(NAME, MLComplexT, MLIntegerT) { \
1791 		complex double ComplexA = ml_complex_value_fast(Args[0]); \
1792 		int64_t IntegerB = ml_integer_value_fast(Args[1]); \
1793 		complex double ComplexC = ComplexA SYMBOL IntegerB; \
1794 		if (fabs(cimag(ComplexC)) <= DBL_EPSILON) { \
1795 			return ml_real(creal(ComplexC)); \
1796 		} else { \
1797 			return ml_complex(ComplexC); \
1798 		} \
1799 	}
1800 
1801 #define ml_arith_method_integer_complex(NAME, SYMBOL) \
1802 	ML_METHOD(NAME, MLIntegerT, MLComplexT) { \
1803 		int64_t IntegerA = ml_integer_value_fast(Args[0]); \
1804 		complex double ComplexB = ml_complex_value_fast(Args[1]); \
1805 		complex double ComplexC = IntegerA SYMBOL ComplexB; \
1806 		if (fabs(cimag(ComplexC)) <= DBL_EPSILON) { \
1807 			return ml_real(creal(ComplexC)); \
1808 		} else { \
1809 			return ml_complex(ComplexC); \
1810 		} \
1811 	}
1812 
1813 #define ml_arith_method_complex_real(NAME, SYMBOL) \
1814 	ML_METHOD(NAME, MLComplexT, MLDoubleT) { \
1815 		complex double ComplexA = ml_complex_value_fast(Args[0]); \
1816 		double RealB = ml_double_value_fast(Args[1]); \
1817 		complex double ComplexC = ComplexA SYMBOL RealB; \
1818 		if (fabs(cimag(ComplexC)) <= DBL_EPSILON) { \
1819 			return ml_real(creal(ComplexC)); \
1820 		} else { \
1821 			return ml_complex(ComplexC); \
1822 		} \
1823 	}
1824 
1825 #define ml_arith_method_real_complex(NAME, SYMBOL) \
1826 	ML_METHOD(NAME, MLDoubleT, MLComplexT) { \
1827 		double RealA = ml_double_value_fast(Args[0]); \
1828 		complex double ComplexB = ml_complex_value_fast(Args[1]); \
1829 		complex double ComplexC = RealA SYMBOL ComplexB; \
1830 		if (fabs(cimag(ComplexC)) <= DBL_EPSILON) { \
1831 			return ml_real(creal(ComplexC)); \
1832 		} else { \
1833 			return ml_complex(ComplexC); \
1834 		} \
1835 	}
1836 
1837 ML_METHOD("r", MLComplexT) {
1838 //!number
1839 //<Z
1840 //>real
1841 // Returns the real component of :mini:`Z`.
1842 	return ml_real(creal(ml_complex_value_fast(Args[0])));
1843 }
1844 
1845 ML_METHOD("i", MLComplexT) {
1846 //!number
1847 //<Z
1848 //>real
1849 // Returns the imaginary component of :mini:`Z`.
1850 	return ml_real(cimag(ml_complex_value_fast(Args[0])));
1851 }
1852 
1853 #endif
1854 
1855 #ifdef ML_COMPLEX
1856 
1857 #define ml_arith_method_number(NAME, SYMBOL) \
1858 	ml_arith_method_integer(NAME, SYMBOL) \
1859 	ml_arith_method_real(NAME, SYMBOL) \
1860 	ml_arith_method_complex(NAME, SYMBOL)
1861 
1862 #define ml_arith_method_number_number(NAME, SYMBOL) \
1863 	ml_arith_method_integer_integer(NAME, SYMBOL) \
1864 	ml_arith_method_real_real(NAME, SYMBOL) \
1865 	ml_arith_method_real_integer(NAME, SYMBOL) \
1866 	ml_arith_method_integer_real(NAME, SYMBOL) \
1867 	ml_arith_method_complex_complex(NAME, SYMBOL) \
1868 	ml_arith_method_complex_real(NAME, SYMBOL) \
1869 	ml_arith_method_complex_integer(NAME, SYMBOL) \
1870 	ml_arith_method_integer_complex(NAME, SYMBOL) \
1871 	ml_arith_method_real_complex(NAME, SYMBOL) \
1872 
1873 #else
1874 
1875 #define ml_arith_method_number(NAME, SYMBOL) \
1876 	ml_arith_method_integer(NAME, SYMBOL) \
1877 	ml_arith_method_real(NAME, SYMBOL)
1878 
1879 #define ml_arith_method_number_number(NAME, SYMBOL) \
1880 	ml_arith_method_integer_integer(NAME, SYMBOL) \
1881 	ml_arith_method_real_real(NAME, SYMBOL) \
1882 	ml_arith_method_real_integer(NAME, SYMBOL) \
1883 	ml_arith_method_integer_real(NAME, SYMBOL)
1884 
1885 #endif
1886 
1887 ml_arith_method_number("-", -)
1888 ml_arith_method_number_number("+", +)
1889 ml_arith_method_number_number("-", -)
1890 ml_arith_method_number_number("*", *)
1891 ml_arith_method_integer_integer("shl", <<);
1892 ml_arith_method_integer_integer("shr", >>);
1893 ml_arith_method_integer_integer("and", &);
1894 ml_arith_method_integer_integer("or", |);
1895 ml_arith_method_integer_integer("xor", ^);
1896 
1897 ML_METHOD("++", MLIntegerT) {
1898 //!number
1899 //<Int
1900 //>integer
1901 // Returns :mini:`Int + 1`
1902 	return ml_integer(ml_integer_value_fast(Args[0]) + 1);
1903 }
1904 
1905 ML_METHOD("--", MLIntegerT) {
1906 //!number
1907 //<Int
1908 //>integer
1909 // Returns :mini:`Int - 1`
1910 	return ml_integer(ml_integer_value_fast(Args[0]) - 1);
1911 }
1912 
1913 ML_METHOD("++", MLDoubleT) {
1914 //!number
1915 //<Real
1916 //>real
1917 // Returns :mini:`Real + 1`
1918 	return ml_real(ml_double_value_fast(Args[0]) + 1);
1919 }
1920 
1921 ML_METHOD("--", MLDoubleT) {
1922 //!number
1923 //<Real
1924 //>real
1925 // Returns :mini:`Real - 1`
1926 	return ml_real(ml_double_value_fast(Args[0]) - 1);
1927 }
1928 
1929 ml_arith_method_real_real("/", /)
1930 ml_arith_method_real_integer("/", /)
1931 ml_arith_method_integer_real("/", /)
1932 
1933 #ifdef ML_COMPLEX
1934 
1935 ml_arith_method_complex_complex("/", /)
1936 ml_arith_method_complex_integer("/", /)
1937 ml_arith_method_integer_complex("/", /)
1938 ml_arith_method_complex_real("/", /)
1939 ml_arith_method_real_complex("/", /)
1940 ml_arith_method_complex("~", ~);
1941 
1942 #endif
1943 
1944 ML_METHOD("/", MLIntegerT, MLIntegerT) {
1945 //!number
1946 //<Int/1
1947 //<Int/2
1948 //>integer | real
1949 // Returns :mini:`Int/1 / Int/2` as an integer if the division is exact, otherwise as a real.
1950 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
1951 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
1952 	if (!IntegerB) return ml_error("ValueError", "Division by 0");
1953 	if (IntegerA % IntegerB == 0) {
1954 		return ml_integer(IntegerA / IntegerB);
1955 	} else {
1956 		return ml_real((double)IntegerA / (double)IntegerB);
1957 	}
1958 }
1959 
1960 ML_METHOD("%", MLIntegerT, MLIntegerT) {
1961 //!number
1962 //<Int/1
1963 //<Int/2
1964 //>integer
1965 // Returns the remainder of :mini:`Int/1` divided by :mini:`Int/2`.
1966 // Note: the result is calculated by rounding towards 0. In particular, if :mini:`Int/1` is negative, the result will be negative.
1967 // For a nonnegative remainder, use :mini:`Int/1 mod Int/2`.
1968 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
1969 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
1970 	if (!IntegerB) return ml_error("ValueError", "Division by 0");
1971 	return ml_integer(IntegerA % IntegerB);
1972 }
1973 
1974 ML_METHOD("|", MLIntegerT, MLIntegerT) {
1975 //!number
1976 //<Int/1
1977 //<Int/2
1978 //>integer
1979 // Returns :mini:`Int/2` if it is divisible by :mini:`Int/1` and :mini:`nil` otherwise.
1980 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
1981 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
1982 	return (IntegerB % IntegerA) ? MLNil : Args[1];
1983 }
1984 
1985 ML_METHOD("!|", MLIntegerT, MLIntegerT) {
1986 //!number
1987 //<Int/1
1988 //<Int/2
1989 //>integer
1990 // Returns :mini:`Int/2` if it is not divisible by :mini:`Int/1` and :mini:`nil` otherwise.
1991 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
1992 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
1993 	return (IntegerB % IntegerA) ? Args[1] : MLNil;
1994 }
1995 
1996 ML_METHOD("div", MLIntegerT, MLIntegerT) {
1997 //!number
1998 //<Int/1
1999 //<Int/2
2000 //>integer
2001 // Returns the quotient of :mini:`Int/1` divided by :mini:`Int/2`.
2002 // The result is calculated by rounding down in all cases.
2003 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
2004 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
2005 	if (!IntegerB) return ml_error("ValueError", "Division by 0");
2006 	long A = IntegerA;
2007 	long B = IntegerB;
2008 	long Q = A / B;
2009 	if (A < 0 && B * Q != A) {
2010 		if (B < 0) ++Q; else --Q;
2011 	}
2012 	return ml_integer(Q);
2013 }
2014 
2015 ML_METHOD("mod", MLIntegerT, MLIntegerT) {
2016 //!number
2017 //<Int/1
2018 //<Int/2
2019 //>integer
2020 // Returns the remainder of :mini:`Int/1` divided by :mini:`Int/2`.
2021 // Note: the result is calculated by rounding down in all cases. In particular, the result is always nonnegative.
2022 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
2023 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
2024 	if (!IntegerB) return ml_error("ValueError", "Division by 0");
2025 	long A = IntegerA;
2026 	long B = IntegerB;
2027 	long R = A % B;
2028 	if (R < 0) R += labs(B);
2029 	return ml_integer(R);
2030 }
2031 
2032 #define ml_comp_method_integer_integer(NAME, SYMBOL) \
2033 	ML_METHOD(NAME, MLIntegerT, MLIntegerT) { \
2034 		int64_t IntegerA = ml_integer_value_fast(Args[0]); \
2035 		int64_t IntegerB = ml_integer_value_fast(Args[1]); \
2036 		return IntegerA SYMBOL IntegerB ? Args[1] : MLNil; \
2037 	}
2038 
2039 #define ml_comp_method_real_real(NAME, SYMBOL) \
2040 	ML_METHOD(NAME, MLDoubleT, MLDoubleT) { \
2041 		double RealA = ml_double_value_fast(Args[0]); \
2042 		double RealB = ml_double_value_fast(Args[1]); \
2043 		return RealA SYMBOL RealB ? Args[1] : MLNil; \
2044 	}
2045 
2046 #define ml_comp_method_real_integer(NAME, SYMBOL) \
2047 	ML_METHOD(NAME, MLDoubleT, MLIntegerT) { \
2048 		double RealA = ml_double_value_fast(Args[0]); \
2049 		int64_t IntegerB = ml_integer_value_fast(Args[1]); \
2050 		return RealA SYMBOL IntegerB ? Args[1] : MLNil; \
2051 	}
2052 
2053 #define ml_comp_method_integer_real(NAME, SYMBOL) \
2054 	ML_METHOD(NAME, MLIntegerT, MLDoubleT) { \
2055 		int64_t IntegerA = ml_integer_value_fast(Args[0]); \
2056 		double RealB = ml_double_value_fast(Args[1]); \
2057 		return IntegerA SYMBOL RealB ? Args[1] : MLNil; \
2058 	}
2059 
2060 #define ml_comp_method_number_number(NAME, SYMBOL) \
2061 	ml_comp_method_integer_integer(NAME, SYMBOL) \
2062 	ml_comp_method_real_real(NAME, SYMBOL) \
2063 	ml_comp_method_real_integer(NAME, SYMBOL) \
2064 	ml_comp_method_integer_real(NAME, SYMBOL)
2065 
2066 ml_comp_method_number_number("=", ==)
2067 ml_comp_method_number_number("!=", !=)
2068 ml_comp_method_number_number("<", <)
2069 ml_comp_method_number_number(">", >)
2070 ml_comp_method_number_number("<=", <=)
2071 ml_comp_method_number_number(">=", >=)
2072 
2073 ML_METHOD("<>", MLIntegerT, MLIntegerT) {
2074 //!number
2075 //<Int/1
2076 //<Int/2
2077 //>integer
2078 // Returns :mini:`-1`, :mini:`0` or :mini:`1` depending on whether :mini:`Int/1` is less than, equal to or greater than :mini:`Int/2`.
2079 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
2080 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
2081 	if (IntegerA < IntegerB) return (ml_value_t *)NegOne;
2082 	if (IntegerA > IntegerB) return (ml_value_t *)One;
2083 	return (ml_value_t *)Zero;
2084 }
2085 
2086 ML_METHOD("<>", MLDoubleT, MLIntegerT) {
2087 //!number
2088 //<Real/1
2089 //<Int/2
2090 //>integer
2091 // Returns :mini:`-1`, :mini:`0` or :mini:`1` depending on whether :mini:`Real/1` is less than, equal to or greater than :mini:`Int/2`.
2092 	double RealA = ml_double_value_fast(Args[0]);
2093 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
2094 	if (RealA < IntegerB) return (ml_value_t *)NegOne;
2095 	if (RealA > IntegerB) return (ml_value_t *)One;
2096 	return (ml_value_t *)Zero;
2097 }
2098 
2099 ML_METHOD("<>", MLIntegerT, MLDoubleT) {
2100 //!number
2101 //<Int/1
2102 //<Real/2
2103 //>integer
2104 // Returns :mini:`-1`, :mini:`0` or :mini:`1` depending on whether :mini:`Int/1` is less than, equal to or greater than :mini:`Real/2`.
2105 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
2106 	double RealB = ml_double_value_fast(Args[1]);
2107 	if (IntegerA < RealB) return (ml_value_t *)NegOne;
2108 	if (IntegerA > RealB) return (ml_value_t *)One;
2109 	return (ml_value_t *)Zero;
2110 }
2111 
2112 ML_METHOD("<>", MLDoubleT, MLDoubleT) {
2113 //!number
2114 //<Real/1
2115 //<Real/2
2116 //>integer
2117 // Returns :mini:`-1`, :mini:`0` or :mini:`1` depending on whether :mini:`Real/1` is less than, equal to or greater than :mini:`Real/2`.
2118 	double RealA = ml_double_value_fast(Args[0]);
2119 	double RealB = ml_double_value_fast(Args[1]);
2120 	if (RealA < RealB) return (ml_value_t *)NegOne;
2121 	if (RealA > RealB) return (ml_value_t *)One;
2122 	return (ml_value_t *)Zero;
2123 }
2124 
2125 typedef struct ml_integer_iter_t {
2126 	const ml_type_t *Type;
2127 	long Current, Step, Limit;
2128 	long Index;
2129 } ml_integer_iter_t;
2130 
ML_TYPED_FN(ml_iter_value,MLIntegerIterT,ml_state_t * Caller,ml_integer_iter_t * Iter)2131 static void ML_TYPED_FN(ml_iter_value, MLIntegerIterT, ml_state_t *Caller, ml_integer_iter_t *Iter) {
2132 	ML_RETURN(ml_integer(Iter->Current));
2133 }
2134 
ML_TYPED_FN(ml_iter_next,MLIntegerIterT,ml_state_t * Caller,ml_integer_iter_t * Iter)2135 static void ML_TYPED_FN(ml_iter_next, MLIntegerIterT, ml_state_t *Caller, ml_integer_iter_t *Iter) {
2136 	Iter->Current += Iter->Step;
2137 	if (Iter->Step > 0) {
2138 		if (Iter->Current > Iter->Limit) ML_RETURN(MLNil);
2139 	} else if (Iter->Step < 0) {
2140 		if (Iter->Current < Iter->Limit) ML_RETURN(MLNil);
2141 	}
2142 	++Iter->Index;
2143 	ML_RETURN(Iter);
2144 }
2145 
ML_TYPED_FN(ml_iter_key,MLIntegerIterT,ml_state_t * Caller,ml_integer_iter_t * Iter)2146 static void ML_TYPED_FN(ml_iter_key, MLIntegerIterT, ml_state_t *Caller, ml_integer_iter_t *Iter) {
2147 	ML_RETURN(ml_integer(Iter->Index));
2148 }
2149 
2150 ML_TYPE(MLIntegerIterT, (), "integer-iter");
2151 //!range
2152 
2153 typedef struct ml_integer_range_t {
2154 	const ml_type_t *Type;
2155 	long Start, Limit, Step;
2156 } ml_integer_range_t;
2157 
ML_TYPED_FN(ml_iterate,MLIntegerRangeT,ml_state_t * Caller,ml_value_t * Value)2158 static void ML_TYPED_FN(ml_iterate, MLIntegerRangeT, ml_state_t *Caller, ml_value_t *Value) {
2159 	ml_integer_range_t *Range = (ml_integer_range_t *)Value;
2160 	if (Range->Step > 0 && Range->Start > Range->Limit) ML_RETURN(MLNil);
2161 	if (Range->Step < 0 && Range->Start < Range->Limit) ML_RETURN(MLNil);
2162 	ml_integer_iter_t *Iter = new(ml_integer_iter_t);
2163 	Iter->Type = MLIntegerIterT;
2164 	Iter->Index = 1;
2165 	Iter->Current = Range->Start;
2166 	Iter->Limit = Range->Limit;
2167 	Iter->Step = Range->Step;
2168 	ML_RETURN(Iter);
2169 }
2170 
2171 ML_TYPE(MLIntegerRangeT, (MLIteratableT), "integer-range");
2172 //!range
2173 
ML_METHOD(MLIterCount,MLIntegerRangeT)2174 ML_METHOD(MLIterCount, MLIntegerRangeT) {
2175 //!internal
2176 	ml_integer_range_t *Range = (ml_integer_range_t *)Args[0];
2177 	int64_t Diff = Range->Limit - Range->Start;
2178 	if (!Range->Step) {
2179 		return (ml_value_t *)Zero;
2180 	} else if (Range->Limit < Range->Start) {
2181 		return (ml_value_t *)Zero;
2182 	} else {
2183 		return ml_integer(Diff / Range->Step + 1);
2184 	}
2185 }
2186 
2187 ML_METHOD("..", MLIntegerT, MLIntegerT) {
2188 //!range
2189 //<Start
2190 //<Limit
2191 //>integerrange
2192 // Returns a range from :mini:`Start` to :mini:`Limit` (inclusive).
2193 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
2194 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
2195 	ml_integer_range_t *Range = new(ml_integer_range_t);
2196 	Range->Type = MLIntegerRangeT;
2197 	Range->Start = IntegerA;
2198 	Range->Limit = IntegerB;
2199 	Range->Step = 1;
2200 	return (ml_value_t *)Range;
2201 }
2202 
2203 ML_METHOD("by", MLIntegerT, MLIntegerT) {
2204 //!range
2205 //<Start
2206 //<Step
2207 //>integerrange
2208 // Returns a unlimited range from :mini:`Start` in steps of :mini:`Step`.
2209 	int64_t IntegerA = ml_integer_value_fast(Args[0]);
2210 	int64_t IntegerB = ml_integer_value_fast(Args[1]);
2211 	ml_integer_range_t *Range = new(ml_integer_range_t);
2212 	Range->Type = MLIntegerRangeT;
2213 	Range->Start = IntegerA;
2214 	Range->Step = IntegerB;
2215 	Range->Limit = Range->Step > 0 ? LONG_MAX : LONG_MIN;
2216 	return (ml_value_t *)Range;
2217 }
2218 
2219 ML_METHOD("by", MLIntegerRangeT, MLIntegerT) {
2220 //!range
2221 //<Range
2222 //<Step
2223 //>integerrange
2224 // Returns a range with the same limits as :mini:`Range` but with step :mini:`Step`.
2225 	ml_integer_range_t *Range0 = (ml_integer_range_t *)Args[0];
2226 	ml_integer_range_t *Range = new(ml_integer_range_t);
2227 	Range->Type = MLIntegerRangeT;
2228 	Range->Start = Range0->Start;
2229 	Range->Limit = Range0->Limit;
2230 	Range->Step = ml_integer_value_fast(Args[1]);
2231 	return (ml_value_t *)Range;
2232 }
2233 
2234 ML_METHOD("count", MLIntegerRangeT) {
2235 //!range
2236 //<X
2237 //>integer
2238 	ml_integer_range_t *Range = (ml_integer_range_t *)Args[0];
2239 	int64_t Diff = Range->Limit - Range->Start;
2240 	if (!Range->Step) {
2241 		return (ml_value_t *)Zero;
2242 	} else if (Range->Limit < Range->Start) {
2243 		return (ml_value_t *)Zero;
2244 	} else {
2245 		return ml_integer(Diff / Range->Step + 1);
2246 	}
2247 }
2248 
2249 ML_METHOD("in", MLIntegerT, MLIntegerRangeT) {
2250 //!range
2251 //<X
2252 //<Range
2253 //>X | nil
2254 	long Value = ml_integer_value_fast(Args[0]);
2255 	ml_integer_range_t *Range = (ml_integer_range_t *)Args[1];
2256 	if (Value < Range->Start) return MLNil;
2257 	if (Value > Range->Limit) return MLNil;
2258 	return Args[0];
2259 }
2260 
2261 ML_METHOD("in", MLDoubleT, MLIntegerRangeT) {
2262 //!range
2263 //<X
2264 //<Range
2265 //>X | nil
2266 	double Value = ml_double_value_fast(Args[0]);
2267 	ml_integer_range_t *Range = (ml_integer_range_t *)Args[1];
2268 	if (Value < Range->Start) return MLNil;
2269 	if (Value > Range->Limit) return MLNil;
2270 	return Args[0];
2271 }
2272 
2273 typedef struct ml_real_iter_t {
2274 	const ml_type_t *Type;
2275 	double Current, Step, Limit;
2276 	long Index, Remaining;
2277 } ml_real_iter_t;
2278 
ML_TYPED_FN(ml_iter_value,MLRealIterT,ml_state_t * Caller,ml_real_iter_t * Iter)2279 static void ML_TYPED_FN(ml_iter_value, MLRealIterT, ml_state_t *Caller, ml_real_iter_t *Iter) {
2280 	ML_RETURN(ml_real(Iter->Current));
2281 }
2282 
ML_TYPED_FN(ml_iter_next,MLRealIterT,ml_state_t * Caller,ml_real_iter_t * Iter)2283 static void ML_TYPED_FN(ml_iter_next, MLRealIterT, ml_state_t *Caller, ml_real_iter_t *Iter) {
2284 	Iter->Current += Iter->Step;
2285 	if (--Iter->Remaining <= 0) ML_RETURN(MLNil);
2286 	++Iter->Index;
2287 	ML_RETURN(Iter);
2288 }
2289 
ML_TYPED_FN(ml_iter_key,MLRealIterT,ml_state_t * Caller,ml_real_iter_t * Iter)2290 static void ML_TYPED_FN(ml_iter_key, MLRealIterT, ml_state_t *Caller, ml_real_iter_t *Iter) {
2291 	ML_RETURN(ml_integer(Iter->Index));
2292 }
2293 
2294 ML_TYPE(MLRealIterT, (), "real-iter");
2295 //!range
2296 
2297 typedef struct ml_real_range_t {
2298 	const ml_type_t *Type;
2299 	double Start, Limit, Step;
2300 	long Count;
2301 } ml_real_range_t;
2302 
ML_TYPED_FN(ml_iterate,MLRealRangeT,ml_state_t * Caller,ml_value_t * Value)2303 static void ML_TYPED_FN(ml_iterate, MLRealRangeT, ml_state_t *Caller, ml_value_t *Value) {
2304 	ml_real_range_t *Range = (ml_real_range_t *)Value;
2305 	if (Range->Step > 0 && Range->Start > Range->Limit) ML_RETURN(MLNil);
2306 	if (Range->Step < 0 && Range->Start < Range->Limit) ML_RETURN(MLNil);
2307 	ml_real_iter_t *Iter = new(ml_real_iter_t);
2308 	Iter->Type = MLRealIterT;
2309 	Iter->Index = 1;
2310 	Iter->Current = Range->Start;
2311 	Iter->Limit = Range->Limit;
2312 	Iter->Step = Range->Step;
2313 	Iter->Remaining = Range->Count;
2314 	ML_RETURN(Iter);
2315 }
2316 
2317 ML_TYPE(MLRealRangeT, (MLIteratableT), "real-range");
2318 //!range
2319 
ML_METHOD(MLIterCount,MLRealRangeT)2320 ML_METHOD(MLIterCount, MLRealRangeT) {
2321 //!internal
2322 	ml_real_range_t *Range = (ml_real_range_t *)Args[0];
2323 	return ml_integer(Range->Count);
2324 }
2325 
2326 ML_METHOD("..", MLNumberT, MLNumberT) {
2327 //!range
2328 //<Start
2329 //<Limit
2330 //>realrange
2331 	ml_real_range_t *Range = new(ml_real_range_t);
2332 	Range->Type = MLRealRangeT;
2333 	Range->Start = ml_real_value(Args[0]);
2334 	Range->Limit = ml_real_value(Args[1]);
2335 	Range->Step = 1.0;
2336 	Range->Count = floor(Range->Limit - Range->Start) + 1;
2337 	return (ml_value_t *)Range;
2338 }
2339 
2340 ML_METHOD("by", MLNumberT, MLNumberT) {
2341 //!range
2342 //<Start
2343 //<Step
2344 //>realrange
2345 	ml_real_range_t *Range = new(ml_real_range_t);
2346 	Range->Type = MLRealRangeT;
2347 	Range->Start = ml_real_value(Args[0]);
2348 	Range->Step = ml_real_value(Args[1]);
2349 	Range->Limit = Range->Step > 0.0 ? INFINITY : -INFINITY;
2350 	Range->Count = LONG_MAX;
2351 	return (ml_value_t *)Range;
2352 }
2353 
2354 ML_METHOD("by", MLRealRangeT, MLNumberT) {
2355 //!range
2356 //<Range
2357 //<Step
2358 //>realrange
2359 	ml_real_range_t *Range0 = (ml_real_range_t *)Args[0];
2360 	ml_real_range_t *Range = new(ml_real_range_t);
2361 	Range->Type = MLRealRangeT;
2362 	double Start = Range->Start = Range0->Start;
2363 	double Limit = Range->Limit = Range0->Limit;
2364 	Range->Step = ml_real_value(Args[1]);
2365 	double C = (Limit - Start) / Range->Step + 1;
2366 	if (C > LONG_MAX) C = LONG_MAX;
2367 	Range->Count = C;
2368 	return (ml_value_t *)Range;
2369 }
2370 
2371 ML_METHOD("in", MLIntegerRangeT, MLIntegerT) {
2372 //!range
2373 //<Range
2374 //<Count
2375 //>realrange
2376 	ml_integer_range_t *Range0 = (ml_integer_range_t *)Args[0];
2377 	long C = ml_integer_value_fast(Args[1]);
2378 	if (C <= 0) return ml_error("RangeError", "Invalid step count");
2379 	if ((Range0->Limit - Range0->Start) % C) {
2380 		ml_real_range_t *Range = new(ml_real_range_t);
2381 		Range->Type = MLRealRangeT;
2382 		Range->Start = Range0->Start;
2383 		Range->Limit = Range0->Limit;
2384 		Range->Step = (Range->Limit - Range->Start) / C;
2385 		Range->Count = C + 1;
2386 		return (ml_value_t *)Range;
2387 	} else {
2388 		ml_integer_range_t *Range = new(ml_integer_range_t);
2389 		Range->Type = MLIntegerRangeT;
2390 		Range->Start = Range0->Start;
2391 		Range->Limit = Range0->Limit;
2392 		Range->Step = (Range->Limit - Range->Start) / C;
2393 		return (ml_value_t *)Range;
2394 	}
2395 }
2396 
2397 ML_METHOD("in", MLRealRangeT, MLIntegerT) {
2398 //!range
2399 //<Range
2400 //<Count
2401 //>realrange
2402 	ml_real_range_t *Range0 = (ml_real_range_t *)Args[0];
2403 	long C = ml_integer_value_fast(Args[1]);
2404 	if (C <= 0) return ml_error("RangeError", "Invalid step count");
2405 	ml_real_range_t *Range = new(ml_real_range_t);
2406 	Range->Type = MLRealRangeT;
2407 	Range->Start = Range0->Start;
2408 	Range->Limit = Range0->Limit;
2409 	Range->Step = (Range->Limit - Range->Start) / C;
2410 	Range->Count = C + 1;
2411 	return (ml_value_t *)Range;
2412 }
2413 
2414 ML_METHOD("by", MLIntegerRangeT, MLDoubleT) {
2415 //!range
2416 //<Range
2417 //<Step
2418 //>realrange
2419 	ml_integer_range_t *Range0 = (ml_integer_range_t *)Args[0];
2420 	ml_real_range_t *Range = new(ml_real_range_t);
2421 	Range->Type = MLRealRangeT;
2422 	double Start = Range->Start = Range0->Start;
2423 	double Limit = Range->Limit = Range0->Limit;
2424 	double Step = Range->Step = ml_double_value_fast(Args[1]);
2425 	double C = (Limit - Start) / Step + 1;
2426 	if (C > LONG_MAX) C = LONG_MAX;
2427 	Range->Count = C;
2428 	return (ml_value_t *)Range;
2429 }
2430 
2431 ML_METHOD("bin", MLIntegerRangeT, MLIntegerT) {
2432 //!range
2433 //<Range
2434 //<Value
2435 //>integer | nil
2436 	ml_integer_range_t *Range = (ml_integer_range_t *)Args[0];
2437 	int64_t Value = ml_integer_value_fast(Args[1]);
2438 	if (Value < Range->Start) return MLNil;
2439 	if (Value > Range->Limit) return MLNil;
2440 	return ml_integer((Value - Range->Start) / Range->Step + 1);
2441 }
2442 
2443 ML_METHOD("bin", MLIntegerRangeT, MLDoubleT) {
2444 //!range
2445 //<Range
2446 //<Value
2447 //>integer | nil
2448 	ml_integer_range_t *Range = (ml_integer_range_t *)Args[0];
2449 	double Value = ml_real_value(Args[1]);
2450 	if (Value < Range->Start) return MLNil;
2451 	if (Value > Range->Limit) return MLNil;
2452 	return ml_integer(floor((Value - Range->Start) / Range->Step) + 1);
2453 }
2454 
2455 ML_METHOD("bin", MLRealRangeT, MLIntegerT) {
2456 //!range
2457 //<Range
2458 //<Value
2459 //>integer | nil
2460 	ml_real_range_t *Range = (ml_real_range_t *)Args[0];
2461 	int64_t Value = ml_integer_value_fast(Args[1]);
2462 	if (Value < Range->Start) return MLNil;
2463 	if (Value > Range->Limit) return MLNil;
2464 	return ml_integer((Value - Range->Start) / Range->Step + 1);
2465 }
2466 
2467 ML_METHOD("bin", MLRealRangeT, MLDoubleT) {
2468 //!range
2469 //<Range
2470 //<Value
2471 //>integer | nil
2472 	ml_real_range_t *Range = (ml_real_range_t *)Args[0];
2473 	double Value = ml_real_value(Args[1]);
2474 	if (Value < Range->Start) return MLNil;
2475 	if (Value > Range->Limit) return MLNil;
2476 	return ml_integer(floor((Value - Range->Start) / Range->Step) + 1);
2477 }
2478 
2479 ML_METHOD("count", MLRealRangeT) {
2480 //!range
2481 //<X
2482 //>integer
2483 	ml_real_range_t *Range = (ml_real_range_t *)Args[0];
2484 	return ml_integer(Range->Count);
2485 }
2486 
2487 ML_METHOD("in", MLIntegerT, MLRealRangeT) {
2488 //!range
2489 //<X
2490 //<Range
2491 //>X | nil
2492 	long Value = ml_integer_value_fast(Args[0]);
2493 	ml_real_range_t *Range = (ml_real_range_t *)Args[1];
2494 	if (Value < Range->Start) return MLNil;
2495 	if (Value > Range->Limit) return MLNil;
2496 	return Args[0];
2497 }
2498 
2499 ML_METHOD("in", MLDoubleT, MLRealRangeT) {
2500 //!range
2501 //<X
2502 //<Range
2503 //>X | nil
2504 	double Value = ml_double_value_fast(Args[0]);
2505 	ml_real_range_t *Range = (ml_real_range_t *)Args[1];
2506 	if (Value < Range->Start) return MLNil;
2507 	if (Value > Range->Limit) return MLNil;
2508 	return Args[0];
2509 }
2510 
2511 // Switch Functions //
2512 
2513 typedef struct {
2514 	ml_value_t *Index;
2515 	int64_t Min, Max;
2516 } ml_integer_case_t;
2517 
2518 typedef struct {
2519 	ml_type_t *Type;
2520 	ml_integer_case_t Cases[];
2521 } ml_integer_switch_t;
2522 
ml_integer_switch(ml_state_t * Caller,ml_integer_switch_t * Switch,int Count,ml_value_t ** Args)2523 static void ml_integer_switch(ml_state_t *Caller, ml_integer_switch_t *Switch, int Count, ml_value_t **Args) {
2524 	ML_CHECKX_ARG_COUNT(1);
2525 	ML_CHECKX_ARG_TYPE(0, MLNumberT);
2526 	int64_t Value = ml_integer_value(Args[0]);
2527 	for (ml_integer_case_t *Case = Switch->Cases;; ++Case) {
2528 		if (Case->Min <= Value && Value <= Case->Max) ML_RETURN(Case->Index);
2529 	}
2530 	ML_RETURN(MLNil);
2531 }
2532 
2533 ML_TYPE(MLIntegerSwitchT, (MLFunctionT), "integer-switch",
2534 //!internal
2535 	.call = (void *)ml_integer_switch
2536 );
2537 
ML_FUNCTION(MLIntegerSwitch)2538 ML_FUNCTION(MLIntegerSwitch) {
2539 //!internal
2540 	int Total = 1;
2541 	for (int I = 0; I < Count; ++I) {
2542 		ML_CHECK_ARG_TYPE(I, MLListT);
2543 		Total += ml_list_length(Args[I]);
2544 	}
2545 	ml_integer_switch_t *Switch = xnew(ml_integer_switch_t, Total, ml_integer_case_t);
2546 	Switch->Type = MLIntegerSwitchT;
2547 	ml_integer_case_t *Case = Switch->Cases;
2548 	for (int I = 0; I < Count; ++I) {
2549 		ML_LIST_FOREACH(Args[I], Iter) {
2550 			ml_value_t *Value = Iter->Value;
2551 			if (ml_is(Value, MLIntegerT)) {
2552 				Case->Min = Case->Max = ml_integer_value(Value);
2553 			} else if (ml_is(Value, MLDoubleT)) {
2554 				double Real = ml_real_value(Value), Int = floor(Real);
2555 				if (Real != Int) return ml_error("ValueError", "Non-integer value in integer case");
2556 				Case->Min = Case->Max = Int;
2557 			} else if (ml_is(Value, MLIntegerRangeT)) {
2558 				ml_integer_range_t *Range = (ml_integer_range_t *)Value;
2559 				Case->Min = Range->Start;
2560 				Case->Max = Range->Limit;
2561 			} else if (ml_is(Value, MLRealRangeT)) {
2562 				ml_real_range_t *Range = (ml_real_range_t *)Value;
2563 				Case->Min = ceil(Range->Start);
2564 				Case->Max = floor(Range->Limit);
2565 			} else {
2566 				return ml_error("ValueError", "Unsupported value in integer case");
2567 			}
2568 			Case->Index = ml_integer(I);
2569 			++Case;
2570 		}
2571 	}
2572 	Case->Min = LONG_MIN;
2573 	Case->Max = LONG_MAX;
2574 	Case->Index = ml_integer(Count);
2575 	return (ml_value_t *)Switch;
2576 }
2577 
2578 typedef struct {
2579 	ml_value_t *Index;
2580 	double Min, Max;
2581 } ml_real_case_t;
2582 
2583 typedef struct {
2584 	ml_type_t *Type;
2585 	ml_real_case_t Cases[];
2586 } ml_real_switch_t;
2587 
ml_real_switch(ml_state_t * Caller,ml_real_switch_t * Switch,int Count,ml_value_t ** Args)2588 static void ml_real_switch(ml_state_t *Caller, ml_real_switch_t *Switch, int Count, ml_value_t **Args) {
2589 	ML_CHECKX_ARG_COUNT(1);
2590 	ML_CHECKX_ARG_TYPE(0, MLNumberT);
2591 	double Value = ml_real_value(Args[0]);
2592 	for (ml_real_case_t *Case = Switch->Cases;; ++Case) {
2593 		if (Case->Min <= Value && Value <= Case->Max) ML_RETURN(Case->Index);
2594 	}
2595 	ML_RETURN(MLNil);
2596 }
2597 
2598 ML_TYPE(MLRealSwitchT, (MLFunctionT), "real-switch",
2599 //!internal
2600 	.call = (void *)ml_real_switch
2601 );
2602 
ML_FUNCTION(MLRealSwitch)2603 ML_FUNCTION(MLRealSwitch) {
2604 //!internal
2605 	int Total = 1;
2606 	for (int I = 0; I < Count; ++I) {
2607 		ML_CHECK_ARG_TYPE(I, MLListT);
2608 		Total += ml_list_length(Args[I]);
2609 	}
2610 	ml_real_switch_t *Switch = xnew(ml_real_switch_t, Total, ml_real_case_t);
2611 	Switch->Type = MLRealSwitchT;
2612 	ml_real_case_t *Case = Switch->Cases;
2613 	for (int I = 0; I < Count; ++I) {
2614 		ML_LIST_FOREACH(Args[I], Iter) {
2615 			ml_value_t *Value = Iter->Value;
2616 			if (ml_is(Value, MLIntegerT)) {
2617 				Case->Min = Case->Max = ml_integer_value(Value);
2618 			} else if (ml_is(Value, MLDoubleT)) {
2619 				Case->Min = Case->Max = ml_real_value(Value);
2620 			} else if (ml_is(Value, MLIntegerRangeT)) {
2621 				ml_integer_range_t *Range = (ml_integer_range_t *)Value;
2622 				Case->Min = Range->Start;
2623 				Case->Max = Range->Limit;
2624 			} else if (ml_is(Value, MLRealRangeT)) {
2625 				ml_real_range_t *Range = (ml_real_range_t *)Value;
2626 				Case->Min = Range->Start;
2627 				Case->Max = Range->Limit;
2628 			} else {
2629 				return ml_error("ValueError", "Unsupported value in real case");
2630 			}
2631 			Case->Index = ml_integer(I);
2632 			++Case;
2633 		}
2634 	}
2635 	Case->Min = -INFINITY;
2636 	Case->Max = INFINITY;
2637 	Case->Index = ml_integer(Count);
2638 	return (ml_value_t *)Switch;
2639 }
2640 
2641 // Modules //
2642 
2643 ML_TYPE(MLModuleT, (), "module");
2644 //!module
2645 
2646 ML_METHODX("::", MLModuleT, MLStringT) {
2647 //!module
2648 //<Module
2649 //<Name
2650 //>MLAnyT
2651 // Imports a symbol from a module.
2652 	ml_module_t *Module = (ml_module_t *)Args[0];
2653 	const char *Name = ml_string_value(Args[1]);
2654 	ml_value_t *Value = stringmap_search(Module->Exports, Name) ?: ml_error("ModuleError", "Symbol %s not exported from module %s", Name, Module->Path);
2655 	ML_RETURN(Value);
2656 }
2657 
ml_module(const char * Path,...)2658 ml_value_t *ml_module(const char *Path, ...) {
2659 	ml_module_t *Module = new(ml_module_t);
2660 	Module->Type = MLModuleT;
2661 	Module->Path = Path;
2662 	va_list Args;
2663 	va_start(Args, Path);
2664 	const char *Export;
2665 	while ((Export = va_arg(Args, const char *))) {
2666 		stringmap_insert(Module->Exports, Export, va_arg(Args, ml_value_t *));
2667 	}
2668 	va_end(Args);
2669 	return (ml_value_t *)Module;
2670 }
2671 
ml_module_path(ml_value_t * Module)2672 const char *ml_module_path(ml_value_t *Module) {
2673 	return ((ml_module_t *)Module)->Path;
2674 }
2675 
ml_module_import(ml_value_t * Module0,const char * Name)2676 ml_value_t *ml_module_import(ml_value_t *Module0, const char *Name) {
2677 	ml_module_t *Module = (ml_module_t *)Module0;
2678 	return (ml_value_t *)stringmap_search(Module->Exports, Name);
2679 }
2680 
ml_module_export(ml_value_t * Module0,const char * Name,ml_value_t * Value)2681 ml_value_t *ml_module_export(ml_value_t *Module0, const char *Name, ml_value_t *Value) {
2682 	ml_module_t *Module = (ml_module_t *)Module0;
2683 	stringmap_insert(Module->Exports, Name, Value);
2684 	return Value;
2685 }
2686 
ML_METHOD(MLStringT,MLModuleT)2687 ML_METHOD(MLStringT, MLModuleT) {
2688 //!module
2689 	ml_module_t *Module = (ml_module_t *)Args[0];
2690 	return ml_string_format("module(%s)", Module->Path);
2691 }
2692 
ml_module_exports_fn(const char * Name,void * Value,ml_value_t * Exports)2693 static int ml_module_exports_fn(const char *Name, void *Value, ml_value_t *Exports) {
2694 	ml_map_insert(Exports, ml_cstring(Name), Value);
2695 	return 0;
2696 }
2697 
2698 ML_METHOD("exports", MLModuleT) {
2699 	ml_module_t *Module = (ml_module_t *)Args[0];
2700 	ml_value_t *Exports = ml_map();
2701 	stringmap_foreach(Module->Exports, Exports, (void *)ml_module_exports_fn);
2702 	return Exports;
2703 }
2704 
2705 // Init //
2706 
ml_init()2707 void ml_init() {
2708 #ifdef ML_JIT
2709 	GC_set_pages_executable(1);
2710 #endif
2711 	GC_INIT();
2712 #include "ml_types_init.c"
2713 	stringmap_insert(MLTypeT->Exports, "switch", MLTypeSwitch);
2714 	stringmap_insert(MLIntegerT->Exports, "range", MLIntegerRangeT);
2715 	stringmap_insert(MLIntegerT->Exports, "switch", MLIntegerSwitch);
2716 	stringmap_insert(MLRealT->Exports, "range", MLRealRangeT);
2717 	stringmap_insert(MLIteratableT->Exports, "count", MLIterCount);
2718 	ml_method_by_value(MLIntegerT->Constructor, NULL, ml_identity, MLIntegerT, NULL);
2719 	ml_method_by_value(MLDoubleT->Constructor, NULL, ml_identity, MLDoubleT, NULL);
2720 	ml_method_by_value(MLRealT->Constructor, NULL, ml_identity, MLDoubleT, NULL);
2721 	stringmap_insert(MLRealT->Exports, "infinity", ml_real(INFINITY));
2722 	ml_method_by_value(MLNumberT->Constructor, NULL, ml_identity, MLNumberT, NULL);
2723 	ml_method_by_name("=", NULL, ml_return_nil, MLNilT, MLAnyT, NULL);
2724 	ml_method_by_name("!=", NULL, ml_return_nil, MLNilT, MLAnyT, NULL);
2725 	ml_method_by_name("<", NULL, ml_return_nil, MLNilT, MLAnyT, NULL);
2726 	ml_method_by_name(">", NULL, ml_return_nil, MLNilT, MLAnyT, NULL);
2727 	ml_method_by_name("<=", NULL, ml_return_nil, MLNilT, MLAnyT, NULL);
2728 	ml_method_by_name(">=", NULL, ml_return_nil, MLNilT, MLAnyT, NULL);
2729 	ml_method_by_name("=", NULL, ml_return_nil, MLAnyT, MLNilT, NULL);
2730 	ml_method_by_name("!=", NULL, ml_return_nil, MLAnyT, MLNilT, NULL);
2731 	ml_method_by_name("<", NULL, ml_return_nil, MLAnyT, MLNilT, NULL);
2732 	ml_method_by_name(">", NULL, ml_return_nil, MLAnyT, MLNilT, NULL);
2733 	ml_method_by_name("<=", NULL, ml_return_nil, MLAnyT, MLNilT, NULL);
2734 	ml_method_by_name(">=", NULL, ml_return_nil, MLAnyT, MLNilT, NULL);
2735 	ml_string_init();
2736 	ml_method_init();
2737 	ml_list_init();
2738 	ml_map_init();
2739 	ml_compiler_init();
2740 	ml_runtime_init();
2741 	ml_bytecode_init();
2742 }
2743 
ML_FUNCTIONZ(MLExchange)2744 ML_FUNCTIONZ(MLExchange) {
2745 //@exchange
2746 	ML_CHECKX_ARG_COUNT(1);
2747 	ml_value_t *New = ml_deref(Args[0]);
2748 	for (int I = Count; --I >= 0;) {
2749 		ml_value_t *Old = ml_deref(Args[I]);
2750 		ml_value_t *Error = ml_assign(Args[I], New);
2751 		if (ml_is_error(Error)) ML_RETURN(Error);
2752 		New = Old;
2753 	}
2754 	ML_RETURN(New);
2755 }
2756 
ML_FUNCTIONZ(MLReplace)2757 ML_FUNCTIONZ(MLReplace) {
2758 //@replace
2759 	ML_CHECKX_ARG_COUNT(2);
2760 	ml_value_t *New = ml_deref(Args[Count - 1]);
2761 	for (int I = Count - 1; --I >= 0;) {
2762 		ml_value_t *Old = ml_deref(Args[I]);
2763 		ml_value_t *Error = ml_assign(Args[I], New);
2764 		if (ml_is_error(Error)) ML_RETURN(Error);
2765 		New = Old;
2766 	}
2767 	ML_RETURN(New);
2768 }
2769 
ml_types_init(stringmap_t * Globals)2770 void ml_types_init(stringmap_t *Globals) {
2771 	if (Globals) {
2772 		stringmap_insert(Globals, "any", MLAnyT);
2773 		stringmap_insert(Globals, "type", MLTypeT);
2774 		stringmap_insert(Globals, "function", MLFunctionT);
2775 		stringmap_insert(Globals, "iteratable", MLIteratableT);
2776 		stringmap_insert(Globals, "boolean", MLBooleanT);
2777 		stringmap_insert(Globals, "true", MLTrue);
2778 		stringmap_insert(Globals, "false", MLFalse);
2779 		stringmap_insert(Globals, "number", MLNumberT);
2780 		stringmap_insert(Globals, "integer", MLIntegerT);
2781 		stringmap_insert(Globals, "real", MLRealT);
2782 		stringmap_insert(Globals, "double", MLDoubleT);
2783 #ifdef ML_COMPLEX
2784 		stringmap_insert(Globals, "complex", MLComplexT);
2785 		stringmap_insert(Globals, "i", ml_complex(1i));
2786 #endif
2787 		stringmap_insert(Globals, "method", MLMethodT);
2788 		stringmap_insert(Globals, "buffer", MLBufferT);
2789 		stringmap_insert(Globals, "string", MLStringT);
2790 		stringmap_insert(Globals, "stringbuffer", MLStringBufferT);
2791 		stringmap_insert(Globals, "regex", MLRegexT);
2792 		stringmap_insert(Globals, "tuple", MLTupleT);
2793 		stringmap_insert(Globals, "list", MLListT);
2794 		stringmap_insert(Globals, "names", MLNamesT);
2795 		stringmap_insert(Globals, "map", MLMapT);
2796 		stringmap_insert(Globals, "exchange", MLExchange);
2797 		stringmap_insert(Globals, "replace", MLReplace);
2798 	}
2799 }
2800