aboutsummaryrefslogtreecommitdiff
path: root/plugins/script
blob: 9c6239938f504fcf825e4eb139da6aa19dc4451f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
#!/usr/bin/tcc -run
//
// ZyklonB scripting plugin, using a custom stack-based language
//
// Copyright 2014 Přemysl Janouch.  All rights reserved.
// See the file LICENSE for licensing information.
//
// Just compile this file as usual (sans #!) if you don't feel like using TCC.
// It is a very basic and portable C99 application.  It's not supposed to be
// very sophisticated, for it'd get extremely big.
//
// The main influences of the language were Factor and Joy, stripped of all
// even barely complex stuff.  In its current state, it's only really useful as
// a calculator but it's got great potential for extending.
//
// If you don't like something, just change it; this is just an experiment.
//
// NOTE: it is really easy to crash and abuse.  Be careful.
//

#define _XOPEN_SOURCE 500

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <assert.h>
#include <time.h>
#include <stdbool.h>
#include <strings.h>

#if defined __GNUC__
#define ATTRIBUTE_PRINTF(x, y) __attribute__ ((format (printf, x, y)))
#else // ! __GNUC__
#define ATTRIBUTE_PRINTF(x, y)
#endif // ! __GNUC__

#define N_ELEMENTS(a) (sizeof (a) / sizeof ((a)[0]))

// --- Utilities ---------------------------------------------------------------

static char *strdup_printf (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);

static char *
strdup_printf (const char *format, ...)
{
	va_list ap;
	va_start (ap, format);
	int size = vsnprintf (NULL, 0, format, ap);
	va_end (ap);
	if (size < 0)
		return NULL;

	char buf[size + 1];
	va_start (ap, format);
	size = vsnprintf (buf, sizeof buf, format, ap);
	va_end (ap);
	if (size < 0)
		return NULL;

	return strdup (buf);
}

// --- Generic buffer ----------------------------------------------------------

struct buffer
{
	char *s;                            ///< Buffer data
	size_t alloc;                       ///< Number of bytes allocated
	size_t len;                         ///< Number of bytes used
};

#define BUFFER_INITIALIZER {NULL, 0, 0}

static void
buffer_append (struct buffer *self, const void *s, size_t n)
{
	if (!self->s)
		self->s = malloc (self->alloc = 8);
	while (self->len + n > self->alloc)
		self->s = realloc (self->s, self->alloc <<= 1);

	memcpy (self->s + self->len, s, n);
	self->len += n;
}

inline static void
buffer_append_c (struct buffer *self, char c)
{
	buffer_append (self, &c, 1);
}

// --- Data types --------------------------------------------------------------

enum item_type
{
	ITEM_STRING,
	ITEM_WORD,
	ITEM_INTEGER,
	ITEM_FLOAT,
	ITEM_LIST
};

struct item
{
#define ITEM_HEADER                                                            \
	enum item_type type;                /**< The type of this object        */ \
	struct item *next;                  /**< Next item on the list/stack    */

	ITEM_HEADER
};

struct item_string
{
	ITEM_HEADER
	size_t len;                         ///< Length of the string (sans '\0')
	char value[];                       ///< The null-terminated string value
};

#define get_string(item)                                                       \
	(assert ((item)->type == ITEM_STRING),                                     \
	 ((struct item_string *)(item))->value)

/// It looks like a string but it doesn't quack like a string
#define item_word item_string

#define get_word(item)                                                         \
	(assert ((item)->type == ITEM_WORD),                                       \
	 ((struct item_word *)(item))->value)

struct item_integer
{
	ITEM_HEADER
	long long value;                    ///< The integer value
};

#define get_integer(item)                                                      \
	(assert ((item)->type == ITEM_INTEGER),                                    \
	 ((struct item_integer *)(item))->value)

struct item_float
{
	ITEM_HEADER
	long double value;                  ///< The floating point value
};

#define get_float(item)                                                        \
	(assert ((item)->type == ITEM_FLOAT),                                      \
	 ((struct item_float *)(item))->value)

struct item_list
{
	ITEM_HEADER
	struct item *head;                  ///< The head of the list
};

#define get_list(item)                                                         \
	(assert ((item)->type == ITEM_LIST),                                       \
	 ((struct item_list *)(item))->head)

#define set_list(item, head_)                                                  \
	(assert ((item)->type == ITEM_LIST),                                       \
	 item_free_list (((struct item_list *)(item))->head),                      \
	 ((struct item_list *)(item))->head = (head_))

const char *
item_type_to_str (enum item_type type)
{
	switch (type)
	{
	case ITEM_STRING:   return "string";
	case ITEM_WORD:     return "word";
	case ITEM_INTEGER:  return "integer";
	case ITEM_FLOAT:    return "float";
	case ITEM_LIST:     return "list";
	}
	abort ();
}

// --- Item management ---------------------------------------------------------

static void item_free_list (struct item *);
static struct item *new_clone_list (const struct item *);

static void
item_free (struct item *item)
{
	if (item->type == ITEM_LIST)
		item_free_list (get_list (item));
	free (item);
}

static void
item_free_list (struct item *item)
{
	while (item)
	{
		struct item *link = item;
		item = item->next;
		item_free (link);
	}
}

static struct item *
new_clone (const struct item *item)
{
	size_t size;
	switch (item->type)
	{
	case ITEM_STRING:
	case ITEM_WORD:
	{
		const struct item_string *x = (const struct item_string *) item;
		size = sizeof *x + x->len + 1;
		break;
	}
	case ITEM_INTEGER:  size = sizeof (struct item_integer);  break;
	case ITEM_FLOAT:    size = sizeof (struct item_float);    break;
	case ITEM_LIST:     size = sizeof (struct item_list);     break;
	}

	struct item *clone = memcpy (malloc (size), item, size);
	if (item->type == ITEM_LIST)
	{
		struct item_list *x = (struct item_list *) clone;
		x->head = new_clone_list (x->head);
	}
	clone->next = NULL;
	return clone;
}

static struct item *
new_clone_list (const struct item *item)
{
	struct item *head = NULL;
	for (struct item **out = &head; item; item = item->next)
	{
		struct item *clone = *out = new_clone (item);
		clone->next = NULL;
		out = &clone->next;
	}
	return head;
}

static struct item *
new_string (const char *s, ssize_t len)
{
	if (len < 0)
		len = strlen (s);

	struct item_string *item = calloc (1, sizeof *item + len + 1);
	if (!item)
		return NULL;

	item->type = ITEM_STRING;
	item->len = len;
	memcpy (item->value, s, len);
	item->value[len] = '\0';
	return (struct item *) item;
}

static struct item *
new_word (const char *s, ssize_t len)
{
	struct item *item = new_string (s, len);
	item->type = ITEM_WORD;
	return item;
}

static struct item *
new_integer (long long value)
{
	struct item_integer *item = calloc (1, sizeof *item);
	item->type = ITEM_INTEGER;
	item->value = value;
	return (struct item *) item;
}

static struct item *
new_float (long double value)
{
	struct item_float *item = calloc (1, sizeof *item);
	item->type = ITEM_FLOAT;
	item->value = value;
	return (struct item *) item;
}

static struct item *
new_list (struct item *head)
{
	struct item_list *item = calloc (1, sizeof *item);
	item->type = ITEM_LIST;
	item->head = head;
	return (struct item *) item;
}

// --- Parsing -----------------------------------------------------------------

struct tokenizer
{
	const char *cursor;
	const char *error;
};

static bool
decode_hexa_escape (struct tokenizer *self, struct buffer *buf)
{
	int i;
	char c, code = 0;

	for (i = 0; i < 2; i++)
	{
		c = tolower (*self->cursor);
		if (c >= '0' && c <= '9')
			code = (code << 4) | (c - '0');
		else if (c >= 'a' && c <= 'f')
			code = (code << 4) | (c - 'a' + 10);
		else
			break;

		self->cursor++;
	}

	if (!i)
		return false;

	buffer_append_c (buf, code);
	return true;
}

static bool
decode_octal_escape (struct tokenizer *self, struct buffer *buf)
{
	int i;
	char c, code = 0;

	for (i = 0; i < 3; i++)
	{
		c = *self->cursor;
		if (c < '0' || c > '7')
			break;

		code = (code << 3) | (c - '0');
		self->cursor++;
	}

	if (!i)
		return false;

	buffer_append_c (buf, code);
	return true;
}

static bool
decode_escape_sequence (struct tokenizer *self, struct buffer *buf)
{
	// Support some basic escape sequences from the C language
	char c;
	switch ((c = *self->cursor))
	{
	case '\0':
		self->error = "unexpected end of input";
		return false;
	case 'x':
	case 'X':
		self->cursor++;
		if (decode_hexa_escape (self, buf))
			return true;

		self->error = "invalid hexadecimal escape sequence";
		return false;
	default:
		if (decode_octal_escape (self, buf))
			return true;

		self->cursor++;
		const char *from = "abfnrtv\"\\", *to = "\a\b\f\n\r\t\v\"\\", *x;
		if ((x = strchr (from, c)))
		{
			buffer_append_c (buf, to[x - from]);
			return true;
		}

		self->error = "unrecognized escape sequence";
		return false;
	}
}

static struct item *
parse_string (struct tokenizer *self)
{
	struct buffer buf = BUFFER_INITIALIZER;
	char c;

	while (true)
	switch ((c = *self->cursor++))
	{
	case '\0':
		self->cursor--;
		self->error = "unexpected end of input";
		goto fail;
	case '"':
	{
		struct item *item = new_string (buf.s, buf.len);
		free (buf.s);
		return item;
	}
	case '\\':
		if (!decode_escape_sequence (self, &buf))
			goto fail;
		break;
	default:
		buffer_append_c (&buf, c);
	}

fail:
	free (buf.s);
	return NULL;
}

static struct item *
try_parse_number (struct tokenizer *self)
{
	// These two standard library functions can digest a lot of various inputs,
	// including NaN and +/- infinity.  That may get a bit confusing.
	char *float_end;
	errno = 0;
	long double float_value = strtold (self->cursor, &float_end);
	int float_errno = errno;

	char *int_end;
	errno = 0;
	long long int_value = strtoll (self->cursor, &int_end, 10);
	int int_errno = errno;

	// If they both fail, then this is most probably not a number.
	if (float_end == int_end && float_end == self->cursor)
		return NULL;

	// Only use the floating point result if it parses more characters:
	if (float_end > int_end)
	{
		if (float_errno == ERANGE)
		{
			self->error = "floating point value out of range";
			return NULL;
		}
		self->cursor = float_end;
		return new_float (float_value);
	}
	else
	{
		if (int_errno == ERANGE)
		{
			self->error = "integer out of range";
			return NULL;
		}
		self->cursor = int_end;
		return new_integer (int_value);
	}
}

static struct item *
parse_word (struct tokenizer *self)
{
	struct buffer buf = BUFFER_INITIALIZER;
	char c;

	// Here we accept almost anything that doesn't break the grammar...
	while (!strchr (" []\"", (c = *self->cursor++)) && (unsigned char) c > ' ')
		buffer_append_c (&buf, c);
	self->cursor--;

	// ...so an empty word can only mean a bug within our caller.
	assert (buf.len != 0);

	struct item *item = new_word (buf.s, buf.len);
	free (buf.s);
	return item;
}

static struct item *parse_item_list (struct tokenizer *);

static struct item *
parse_list (struct tokenizer *self)
{
	struct item *list = parse_item_list (self);
	if (self->error)
	{
		assert (list == NULL);
		return NULL;
	}
	if (!*self->cursor)
	{
		self->error = "unexpected end of input";
		item_free_list (list);
		return NULL;
	}
	assert (*self->cursor == ']');
	self->cursor++;
	return new_list (list);
}

static struct item *
parse_item (struct tokenizer *self)
{
	char c;
	switch ((c = *self->cursor++))
	{
	case '[':  return parse_list (self);
	case '"':  return parse_string (self);
	default:;
	}

	self->cursor--;
	struct item *item = try_parse_number (self);
	if (!item && !self->error)
		item = parse_word (self);
	return item;
}

static struct item *
parse_item_list (struct tokenizer *self)
{
	struct item *head = NULL;
	struct item **tail = &head;

	char c;
	bool expected = true;
	while ((c = *self->cursor) && c != ']')
	{
		if (isspace (c))
		{
			self->cursor++;
			expected = true;
			continue;
		}
		else if (!expected)
		{
			self->error = "unexpected input";
			goto fail;
		}

		if (!(*tail = parse_item (self)))
			goto fail;
		tail = &(*tail)->next;
		expected = false;
	}
	return head;

fail:
	item_free_list (head);
	return NULL;
}

static struct item *
parse (const char *s, char **error)
{
	struct tokenizer self;
	self.cursor = s;
	self.error = NULL;

	struct item *list = parse_item_list (&self);
	if (!self.error && *self.cursor != '\0')
	{
		self.error = "unexpected input";
		item_free_list (list);
		list = NULL;
	}
	if (self.error && error)
		*error = strdup_printf ("at character %d: %s",
			(int) (self.cursor - s) + 1, self.error);
	return list;
}

// --- Runtime -----------------------------------------------------------------

// TODO: try to think of a _simple_ way to do preemptive multitasking

struct context
{
	struct item *stack;                 ///< The current top of the stack
	size_t stack_size;                  ///< Number of items on the stack

	size_t reduction_count;             ///< # of function calls so far
	size_t reduction_limit;             ///< The hard limit on function calls

	char *error;                        ///< Error information
	bool error_is_fatal;                ///< Whether the error can be catched

	void *user_data;                    ///< User data
};

/// Internal handler for a function
typedef bool (*handler_fn) (struct context *);

struct fn
{
	struct fn *next;                    ///< The next link in the chain

	handler_fn handler;                 ///< Internal C handler, or NULL
	struct item *script;                ///< Alternatively runtime code
	char name[];                        ///< The name of the function
};

struct fn *g_functions;                 ///< Maps words to functions

static void
context_init (struct context *ctx)
{
	ctx->stack = NULL;
	ctx->stack_size = 0;

	ctx->reduction_count = 0;
	ctx->reduction_limit = 2000;

	ctx->error = NULL;
	ctx->error_is_fatal = false;

	ctx->user_data = NULL;
}

static void
context_free (struct context *ctx)
{
	item_free_list (ctx->stack);
	ctx->stack = NULL;

	free (ctx->error);
	ctx->error = NULL;
}

static void
push (struct context *ctx, struct item *item)
{
	assert (item->next == NULL);
	item->next = ctx->stack;
	ctx->stack = item;
	ctx->stack_size++;
}

static bool
bump_reductions (struct context *ctx)
{
	if (++ctx->reduction_count >= ctx->reduction_limit)
	{
		ctx->error = strdup ("reduction limit reached");
		ctx->error_is_fatal = true;
		return false;
	}
	return true;
}

static bool execute (struct context *, struct item *);

static bool
call_function (struct context *ctx, const char *name)
{
	struct fn *iter;
	for (iter = g_functions; iter; iter = iter->next)
		if (!strcmp (name, iter->name))
			goto found;

	ctx->error = strdup_printf ("unknown function: %s", name);
	return false;

found:
	if (!bump_reductions (ctx))
		return false;

	if (iter->handler
		? iter->handler (ctx)
		: execute (ctx, iter->script))
		return true;

	// This creates some form of a stack trace
	char *error = strdup_printf ("%s -> %s", name, ctx->error);
	free (ctx->error);
	ctx->error = error;
	return false;
}

static void
unregister_function (const char *name)
{
	for (struct fn **iter = &g_functions; *iter; iter = &(*iter)->next)
		if (!strcmp ((*iter)->name, name))
		{
			struct fn *tmp = *iter;
			*iter = tmp->next;
			if (tmp->script)
				item_free_list (tmp->script);
			free (tmp);
			break;
		}
}

static struct fn *
prepend_new_fn (const char *name)
{
	struct fn *fn = calloc (1, sizeof *fn + strlen (name) + 1);
	strcpy (fn->name, name);
	fn->next = g_functions;
	return g_functions = fn;
}

static void
register_handler (const char *name, handler_fn handler)
{
	unregister_function (name);
	prepend_new_fn (name)->handler = handler;
}

static void
register_script (const char *name, struct item *script)
{
	unregister_function (name);
	prepend_new_fn (name)->script = script;
}

static bool
execute (struct context *ctx, struct item *script)
{
	for (; script; script = script->next)
	{
		if (script->type != ITEM_WORD)
		{
			if (!bump_reductions (ctx))
				return false;
			push (ctx, new_clone (script));
		}
		else if (!call_function (ctx, get_word (script)))
			return false;
	}
	return true;
}

// --- Runtime library ---------------------------------------------------------

#define defn(name) static bool name (struct context *ctx)

#define check_stack(n)                                                         \
	if (ctx->stack_size < n) {                                                 \
		ctx->error = strdup ("stack underflow");                               \
		return 0;                                                              \
	}

inline static bool
check_stack_safe (struct context *ctx, size_t n)
{
	check_stack (n);
	return true;
}

static bool
check_type (struct context *ctx, const void *item_, enum item_type type)
{
	const struct item *item = item_;
	if (item->type == type)
		return true;

	ctx->error = strdup_printf ("invalid type: expected `%s', got `%s'",
		item_type_to_str (type), item_type_to_str (item->type));
	return false;
}

static struct item *
pop (struct context *ctx)
{
	check_stack (1);
	struct item *top = ctx->stack;
	ctx->stack = top->next;
	top->next = NULL;
	ctx->stack_size--;
	return top;
}

// - - Types - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#define defn_is_type(name, item_type)                                          \
	defn (fn_is_##name) {                                                      \
		check_stack (1);                                                       \
		struct item *top = pop (ctx);                                          \
		push (ctx, new_integer (top->type == (item_type)));                    \
		item_free (top);                                                       \
		return true;                                                           \
	}

defn_is_type (string,  ITEM_STRING)
defn_is_type (word,    ITEM_WORD)
defn_is_type (integer, ITEM_INTEGER)
defn_is_type (float,   ITEM_FLOAT)
defn_is_type (list,    ITEM_LIST)

defn (fn_to_string)
{
	check_stack (1);
	struct item *item = pop (ctx);
	char *value;

	switch (item->type)
	{
	case ITEM_WORD:
		item->type = ITEM_STRING;
	case ITEM_STRING:
		push (ctx, item);
		return true;

	case ITEM_FLOAT:
		value = strdup_printf ("%Lf", get_float (item));
		break;
	case ITEM_INTEGER:
		value = strdup_printf ("%lld", get_integer (item));
		break;

	default:
		ctx->error = strdup_printf ("cannot convert `%s' to `%s'",
			item_type_to_str (item->type), item_type_to_str (ITEM_STRING));
		item_free (item);
		return false;
	}

	item_free (item);
	item = new_string (value, -1);
	free (value);

	push (ctx, item);
	return true;
}

defn (fn_to_integer)
{
	check_stack (1);
	struct item *item = pop (ctx);
	long long value;

	switch (item->type)
	{
	case ITEM_INTEGER:
		push (ctx, item);
		return true;
	case ITEM_FLOAT:
		value = get_float (item);
		break;

	case ITEM_STRING:
	{
		char *end;
		const char *s = get_string (item);
		value = strtoll (s, &end, 10);
		if (end != s && *s == '\0')
			break;

		ctx->error = strdup ("integer conversion error");
		item_free (item);
		return false;
	}

	default:
		ctx->error = strdup_printf ("cannot convert `%s' to `%s'",
			item_type_to_str (item->type), item_type_to_str (ITEM_INTEGER));
		item_free (item);
		return false;
	}

	item_free (item);
	push (ctx, new_integer (value));
	return true;
}

defn (fn_to_float)
{
	check_stack (1);
	struct item *item = pop (ctx);
	long double value;

	switch (item->type)
	{
	case ITEM_FLOAT:
		push (ctx, item);
		return true;
	case ITEM_INTEGER:
		value = get_integer (item);
		break;

	case ITEM_STRING:
	{
		char *end;
		const char *s = get_string (item);
		value = strtold (s, &end);
		if (end != s && *s == '\0')
			break;

		ctx->error = strdup ("float conversion error");
		item_free (item);
		return false;
	}

	default:
		ctx->error = strdup_printf ("cannot convert `%s' to `%s'",
			item_type_to_str (item->type), item_type_to_str (ITEM_FLOAT));
		item_free (item);
		return false;
	}

	item_free (item);
	push (ctx, new_float (value));
	return true;
}

// - - Stack operations  - - - - - - - - - - - - - - - - - - - - - - - - - - - -

defn (fn_dup)
{
	check_stack (1);
	push (ctx, new_clone (ctx->stack));
	return true;
}

defn (fn_drop)
{
	check_stack (1);
	item_free (pop (ctx));
	return true;
}

defn (fn_swap)
{
	check_stack (2);
	struct item *second = pop (ctx);
	struct item *first  = pop (ctx);
	push (ctx, second);
	push (ctx, first);
	return true;
}

defn (fn_call)
{
	check_stack (1);
	struct item *script = pop (ctx);
	bool success = check_type (ctx, script, ITEM_LIST)
		&& execute (ctx, get_list (script));
	item_free (script);
	return success;
}

defn (fn_dip)
{
	check_stack (2);
	struct item *script = pop (ctx);
	struct item *item   = pop (ctx);
	bool success = check_type (ctx, script, ITEM_LIST)
		&& execute (ctx, get_list (script));
	if (success)
		push (ctx, item);
	else
		item_free (item);
	item_free (script);
	return success;
}

defn (fn_unit)
{
	check_stack (1);
	struct item *item = pop (ctx);
	push (ctx, new_list (item));
	return true;
}

defn (fn_cons)
{
	check_stack (2);
	struct item *list = pop (ctx);
	struct item *item = pop (ctx);
	bool success = check_type (ctx, list, ITEM_LIST);
	item->next = get_list (list);
	((struct item_list *) list)->head = item;
	if (success)
		push (ctx, list);
	else
		item_free (list);
	return success;
}

defn (fn_cat)
{
	check_stack (2);
	struct item *scnd = pop (ctx);
	struct item *frst = pop (ctx);
	if (!check_type (ctx, frst, ITEM_LIST)
	 || !check_type (ctx, scnd, ITEM_LIST))
	{
		item_free (frst);
		item_free (scnd);
		return false;
	}

	// XXX: we shouldn't have to do this in O(n)
	struct item **tail = &((struct item_list *) frst)->head;
	while (*tail)
		tail = &(*tail)->next;
	*tail = get_list (scnd);
	push (ctx, frst);

	((struct item_list *) scnd)->head = NULL;
	item_free (scnd);
	return true;
}

// - - Logical - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool
to_boolean (struct context *ctx, struct item *item)
{
	switch (item->type)
	{
	case ITEM_STRING:
		return *get_string (item) != '\0';
	case ITEM_INTEGER:
		return get_integer (item) != 0;
	case ITEM_FLOAT:
		return get_float   (item) != 0.;
	default:
		ctx->error = strdup_printf ("cannot convert `%s' to boolean",
			item_type_to_str (item->type));
		return false;
	}
}

defn (fn_not)
{
	check_stack (1);
	struct item *item = pop (ctx);
	bool result = !to_boolean (ctx, item);
	item_free (item);
	if (ctx->error)
		return false;
	push (ctx, new_integer (result));
	return true;
}

defn (fn_and)
{
	check_stack (2);
	struct item *op1 = pop (ctx);
	struct item *op2 = pop (ctx);
	bool result = to_boolean (ctx, op1) && to_boolean (ctx, op2);
	item_free (op1);
	item_free (op2);
	push (ctx, new_integer (result));
	return !ctx->error;
}

defn (fn_or)
{
	check_stack (2);
	struct item *op1 = pop (ctx);
	struct item *op2 = pop (ctx);
	bool result = to_boolean (ctx, op1) || ctx->error || to_boolean (ctx, op2);
	item_free (op1);
	item_free (op2);
	if (ctx->error)
		return false;
	push (ctx, new_integer (result));
	return true;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

defn (fn_if)
{
	check_stack (3);
	struct item *else_ = pop (ctx);
	struct item *then_ = pop (ctx);
	struct item *cond_ = pop (ctx);

	bool condition = to_boolean (ctx, cond_);
	item_free (cond_);

	bool success = false;
	if (!ctx->error
	 && check_type (ctx, then_, ITEM_LIST)
	 && check_type (ctx, else_, ITEM_LIST))
		success = execute (ctx, condition
			? get_list (then_)
			: get_list (else_));

	item_free (then_);
	item_free (else_);
	return success;
}

defn (fn_try)
{
	check_stack (2);
	struct item *catch   = pop (ctx);
	struct item *try     = pop (ctx);
	bool success = false;
	if (!check_type (ctx, try,     ITEM_LIST)
	 || !check_type (ctx, catch,   ITEM_LIST))
		goto fail;

	if (!execute (ctx, get_list (try)))
	{
		if (ctx->error_is_fatal)
			goto fail;

		push (ctx, new_string (ctx->error, -1));
		free (ctx->error);
		ctx->error = NULL;

		if (!execute (ctx, get_list (catch)))
			goto fail;
	}
	success = true;

fail:
	item_free (try);
	item_free (catch);
	return success;
}

defn (fn_map)
{
	check_stack (2);
	struct item *fn   = pop (ctx);
	struct item *list = pop (ctx);
	if (!check_type (ctx, fn,   ITEM_LIST)
	 || !check_type (ctx, list, ITEM_LIST))
	{
		item_free (fn);
		item_free (list);
		return false;
	}

	bool success = false;
	struct item *result = NULL, **tail = &result;
	for (struct item *iter = get_list (list); iter; iter = iter->next)
	{
		push (ctx, new_clone (iter));
		if (!execute (ctx, get_list (fn))
		 || !check_stack_safe (ctx, 1))
			goto fail;

		struct item *item = pop (ctx);
		*tail = item;
		tail = &item->next;
	}
	success = true;

fail:
	set_list (list, result);
	if (success)
		push (ctx, list);
	else
		item_free (list);

	item_free (fn);
	return success;
}

defn (fn_filter)
{
	check_stack (2);
	struct item *fn   = pop (ctx);
	struct item *list = pop (ctx);
	if (!check_type (ctx, fn,   ITEM_LIST)
	 || !check_type (ctx, list, ITEM_LIST))
	{
		item_free (fn);
		item_free (list);
		return false;
	}

	bool success = false;
	struct item *result = NULL, **tail = &result;
	for (struct item *iter = get_list (list); iter; iter = iter->next)
	{
		push (ctx, new_clone (iter));
		if (!execute (ctx, get_list (fn))
		 || !check_stack_safe (ctx, 1))
			goto fail;

		struct item *item = pop (ctx);
		bool survived = to_boolean (ctx, item);
		item_free (item);
		if (ctx->error)
			goto fail;

		if (!survived)
			continue;

		item = new_clone (iter);
		*tail = item;
		tail = &item->next;
	}
	success = true;

fail:
	set_list (list, result);
	if (success)
		push (ctx, list);
	else
		item_free (list);

	item_free (fn);
	return success;
}

defn (fn_fold)
{
	check_stack (3);
	struct item *op   = pop (ctx);
	struct item *null = pop (ctx);
	struct item *list = pop (ctx);
	bool success = false;
	if (!check_type (ctx, op,   ITEM_LIST)
	 || !check_type (ctx, list, ITEM_LIST))
	{
		item_free (null);
		goto fail;
	}

	push (ctx, null);
	for (struct item *iter = get_list (list); iter; iter = iter->next)
	{
		push (ctx, new_clone (iter));
		if (!execute (ctx, get_list (op)))
			goto fail;
	}
	success = true;

fail:
	item_free (op);
	item_free (list);
	return success;
}

defn (fn_each)
{
	check_stack (2);
	struct item *op   = pop (ctx);
	struct item *list = pop (ctx);
	bool success = false;
	if (!check_type (ctx, op,   ITEM_LIST)
	 || !check_type (ctx, list, ITEM_LIST))
		goto fail;

	for (struct item *iter = get_list (list); iter; iter = iter->next)
	{
		push (ctx, new_clone (iter));
		if (!execute (ctx, get_list (op)))
			goto fail;
	}
	success = true;

fail:
	item_free (op);
	item_free (list);
	return success;
}

// - - Arithmetic  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// XXX: why not a `struct item_string *` argument?
static bool
push_repeated_string (struct context *ctx, struct item *op1, struct item *op2)
{
	struct item_string  *string = (struct item_string  *) op1;
	struct item_integer *repeat = (struct item_integer *) op2;
	assert (string->type == ITEM_STRING);
	assert (repeat->type == ITEM_INTEGER);

	if (repeat->value < 0)
	{
		ctx->error = strdup ("cannot multiply a string by a negative value");
		return false;
	}

	char *buf = NULL;
	size_t len = string->len * repeat->value;
	if (len < string->len && repeat->value != 0)
		goto allocation_fail;

	buf = malloc (len);
	if (!buf)
		goto allocation_fail;

	for (size_t i = 0; i < len; i += string->len)
		memcpy (buf + i, string->value, string->len);
	struct item *item = new_string (buf, len);
	free (buf);
	if (!item)
		goto allocation_fail;

	push (ctx, item);
	return true;

allocation_fail:
	// TODO: resolve the memory issues correctly, watch _all_ allocations
	ctx->error = strdup ("memory allocation failed");
	return false;
}

defn (fn_times)
{
	check_stack (2);
	struct item *op1 = pop (ctx);
	struct item *op2 = pop (ctx);
	bool success = true;

	if      (op1->type == ITEM_INTEGER && op2->type == ITEM_INTEGER)
		push (ctx, new_integer (get_integer (op1) * get_integer (op2)));
	else if (op1->type == ITEM_INTEGER && op2->type == ITEM_FLOAT)
		push (ctx, new_float   (get_integer (op1) * get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_FLOAT)
		push (ctx, new_float   (get_float   (op1) * get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_INTEGER)
		push (ctx, new_float   (get_float   (op1) * get_integer (op2)));
	else if (op1->type == ITEM_INTEGER && op2->type == ITEM_STRING)
		success = push_repeated_string (ctx, op2, op1);
	else if (op1->type == ITEM_STRING  && op2->type == ITEM_INTEGER)
		success = push_repeated_string (ctx, op1, op2);
	else
	{
		ctx->error = strdup_printf ("cannot multiply `%s' and `%s'",
			item_type_to_str (op1->type), item_type_to_str (op2->type));
		success = false;
	}

	item_free (op1);
	item_free (op2);
	return success;
}

static bool
push_concatenated_string (struct context *ctx,
	struct item *op1, struct item *op2)
{
	struct item_string *s1 = (struct item_string *) op1;
	struct item_string *s2 = (struct item_string *) op2;
	assert (s1->type == ITEM_STRING);
	assert (s2->type == ITEM_STRING);

	char *buf = NULL;
	size_t len = s1->len + s2->len;
	if (len < s1->len || len < s2->len)
		goto allocation_fail;

	buf = malloc (len);
	if (!buf)
		goto allocation_fail;

	memcpy (buf,           s1->value, s1->len);
	memcpy (buf + s1->len, s2->value, s2->len);
	struct item *item = new_string (buf, len);
	free (buf);
	if (!item)
		goto allocation_fail;

	push (ctx, item);
	return true;

allocation_fail:
	// TODO: resolve the memory issues correctly, watch _all_ allocations
	ctx->error = strdup ("memory allocation failed");
	return false;

}

defn (fn_plus)
{
	check_stack (2);
	struct item *op1 = pop (ctx);
	struct item *op2 = pop (ctx);
	bool success = true;

	if      (op1->type == ITEM_INTEGER && op2->type == ITEM_INTEGER)
		push (ctx, new_integer (get_integer (op1) + get_integer (op2)));
	else if (op1->type == ITEM_INTEGER && op2->type == ITEM_FLOAT)
		push (ctx, new_float   (get_integer (op1) + get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_FLOAT)
		push (ctx, new_float   (get_float   (op1) + get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_INTEGER)
		push (ctx, new_float   (get_float   (op1) + get_integer (op2)));
	else if (op1->type == ITEM_STRING  && op2->type == ITEM_STRING)
		success = push_concatenated_string (ctx, op2, op1);
	else
	{
		ctx->error = strdup_printf ("cannot add `%s' and `%s'",
			item_type_to_str (op1->type), item_type_to_str (op2->type));
		success = false;
	}

	item_free (op1);
	item_free (op2);
	return success;
}

// - - Comparison  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
compare_strings (struct item_string *s1, struct item_string *s2)
{
	// XXX: not entirely correct wrt. null bytes
	size_t len = (s1->len < s2->len ? s1->len : s2->len) + 1;
	return memcmp (s1->value, s2->value, len);
}

static bool compare_lists (struct item *, struct item *);

static bool
compare_list_items (struct item *op1, struct item *op2)
{
	if (op1->type != op2->type)
		return false;

	switch (op1->type)
	{
	case ITEM_STRING:
	case ITEM_WORD:
		return !compare_strings ((struct item_string *) op1,
			(struct item_string *) op2);
	case ITEM_FLOAT:
		return get_float (op1) == get_float (op2);
	case ITEM_INTEGER:
		return get_integer (op1) == get_integer (op2);
	case ITEM_LIST:
		return compare_lists (get_list (op1), get_list (op2));
	}
	abort ();
}

static bool
compare_lists (struct item *op1, struct item *op2)
{
	while (op1 && op2)
	{
		if (!compare_list_items (op1, op2))
			return false;

		op1 = op1->next;
		op2 = op2->next;
	}
	return !op1 && !op2;
}

defn (fn_eq)
{
	check_stack (2);
	struct item *op2 = pop (ctx);
	struct item *op1 = pop (ctx);
	bool success = true;

	if      (op1->type == ITEM_INTEGER && op2->type == ITEM_INTEGER)
		push (ctx, new_integer (get_integer (op1) == get_integer (op2)));
	else if (op1->type == ITEM_INTEGER && op2->type == ITEM_FLOAT)
		push (ctx, new_integer (get_integer (op1) == get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_FLOAT)
		push (ctx, new_integer (get_float   (op1) == get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_INTEGER)
		push (ctx, new_integer (get_float   (op1) == get_integer (op2)));
	else if (op1->type == ITEM_LIST    && op2->type == ITEM_LIST)
		push (ctx, new_integer (compare_lists
			(get_list (op1), get_list (op2))));
	else if (op1->type == ITEM_STRING  && op2->type == ITEM_STRING)
		push (ctx, new_integer (compare_strings
			((struct item_string *)(op1), (struct item_string *)(op2)) == 0));
	else
	{
		ctx->error = strdup_printf ("cannot compare `%s' and `%s'",
			item_type_to_str (op1->type), item_type_to_str (op2->type));
		success = false;
	}

	item_free (op1);
	item_free (op2);
	return success;
}

defn (fn_lt)
{
	check_stack (2);
	struct item *op2 = pop (ctx);
	struct item *op1 = pop (ctx);
	bool success = true;

	if      (op1->type == ITEM_INTEGER && op2->type == ITEM_INTEGER)
		push (ctx, new_integer (get_integer (op1) < get_integer (op2)));
	else if (op1->type == ITEM_INTEGER && op2->type == ITEM_FLOAT)
		push (ctx, new_integer (get_integer (op1) < get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_FLOAT)
		push (ctx, new_integer (get_float   (op1) < get_float   (op2)));
	else if (op1->type == ITEM_FLOAT   && op2->type == ITEM_INTEGER)
		push (ctx, new_integer (get_float   (op1) < get_integer (op2)));
	else if (op1->type == ITEM_STRING  && op2->type == ITEM_STRING)
		push (ctx, new_integer (compare_strings
			((struct item_string *)(op1), (struct item_string *)(op2)) < 0));
	else
	{
		ctx->error = strdup_printf ("cannot compare `%s' and `%s'",
			item_type_to_str (op1->type), item_type_to_str (op2->type));
		success = false;
	}

	item_free (op1);
	item_free (op2);
	return success;
}

// - - Utilities - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

defn (fn_rand)
{
	push (ctx, new_float ((long double) rand ()
		/ ((long double) RAND_MAX + 1)));
	return true;
}

defn (fn_time)
{
	push (ctx, new_integer (time (NULL)));
	return true;
}

// XXX: this is a bit too constrained; combines strftime() with gmtime()
defn (fn_strftime)
{
	check_stack (2);
	struct item *format = pop (ctx);
	struct item *time_  = pop (ctx);
	bool success = false;
	if (!check_type (ctx, time_,  ITEM_INTEGER)
	 || !check_type (ctx, format, ITEM_STRING))
		goto fail;

	if (get_integer (time_) < 0)
	{
		ctx->error = strdup ("invalid time value");
		goto fail;
	}

	char buf[128];
	time_t time__ = get_integer (time_);
	struct tm tm;
	gmtime_r (&time__, &tm);
	buf[strftime (buf, sizeof buf, get_string (format), &tm)] = '\0';
	push (ctx, new_string (buf, -1));
	success = true;

fail:
	item_free (time_);
	item_free (format);
	return success;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void item_list_to_str (const struct item *, struct buffer *);

static void
string_to_str (const struct item_string *string, struct buffer *buf)
{
	buffer_append_c (buf, '"');
	for (size_t i = 0; i < string->len; i++)
	{
		char c = string->value[i];
		if      (c == '\n')  buffer_append (buf, "\\\n", 2);
		else if (c == '\r')  buffer_append (buf, "\\\r", 2);
		else if (c == '\t')  buffer_append (buf, "\\\t", 2);
		else if (!isprint (c))
		{
			char tmp[8];
			snprintf (tmp, sizeof tmp, "\\x%02x", (unsigned char) c);
			buffer_append (buf, tmp, strlen (tmp));
		}
		else if (c == '\\')  buffer_append (buf, "\\\\", 2);
		else if (c == '"')   buffer_append (buf, "\\\"", 2);
		else                 buffer_append_c (buf, c);
	}
	buffer_append_c (buf, '"');
}

static void
item_to_str (const struct item *item, struct buffer *buf)
{
	switch (item->type)
	{
		char *x;
	case ITEM_STRING:
		string_to_str ((struct item_string *) item, buf);
		break;
	case ITEM_WORD:
	{
		struct item_word *word = (struct item_word *) item;
		buffer_append (buf, word->value, word->len);
		break;
	}
	case ITEM_INTEGER:
		x = strdup_printf ("%lld", get_integer (item));
		buffer_append (buf, x, strlen (x));
		free (x);
		break;
	case ITEM_FLOAT:
		x = strdup_printf ("%Lf", get_float (item));
		buffer_append (buf, x, strlen (x));
		free (x);
		break;
	case ITEM_LIST:
		buffer_append_c (buf, '[');
		item_list_to_str (get_list (item), buf);
		buffer_append_c (buf, ']');
		break;
	}
}

static void
item_list_to_str (const struct item *script, struct buffer *buf)
{
	bool first = true;
	for (; script; script = script->next)
	{
		if (!first)
			buffer_append_c (buf, ' ');
		item_to_str (script, buf);
		first = false;
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// TODO: implement more functions; try to avoid writing it in C
//
//   join { list delim -- string } -- string join -> script this
//
//   -, /, %, ** -- arithmetic
//   >, !=, <=, >= -- comparison
//   first -- first character of a string, first element in a list
//   rest -- [1:] of a string, the "tail" in a list
//   at { value index -- sub-value } -- get n-th subvalue of a string/list
//   <each> step { value program } -- foreach

static void
init_runtime_library (void)
{
	// Type detection
	register_handler ("string?",  fn_is_string);
	register_handler ("word?",    fn_is_word);
	register_handler ("integer?", fn_is_integer);
	register_handler ("float?",   fn_is_float);
	register_handler ("list?",    fn_is_list);

	// Type conversion
	register_handler (">string",  fn_to_string);
	register_handler (">integer", fn_to_integer);
	register_handler (">float",   fn_to_float);

	// Basic stack manipulation
	register_handler ("dup",      fn_dup);
	register_handler ("drop",     fn_drop);
	register_handler ("swap",     fn_swap);

	// Calling stuff
	register_handler ("call",     fn_call);
	register_handler ("dip",      fn_dip);

	// Control flow
	register_handler ("if",       fn_if);
	register_handler ("try",      fn_try);

	// List processing
	register_handler ("map",      fn_map);
	register_handler ("filter",   fn_filter);
	register_handler ("fold",     fn_fold);
	register_handler ("each",     fn_each);

	// List manipulation
	register_handler ("unit",     fn_unit);
	register_handler ("cons",     fn_cons);
	register_handler ("cat",      fn_cat);

	// Arithmetic operations
	register_handler ("*",        fn_times);
	register_handler ("+",        fn_plus);

	// Comparison
	register_handler ("=",        fn_eq);
	register_handler ("<",        fn_lt);

	// Logical operations
	register_handler ("not",      fn_not);
	register_handler ("and",      fn_and);
	register_handler ("or",       fn_or);

	// Utilities
	register_handler ("rand",     fn_rand);
	register_handler ("time",     fn_time);
	register_handler ("strftime", fn_strftime);
}

// --- IRC protocol ------------------------------------------------------------

struct message
{
	char *prefix;                       ///< Message prefix
	char *command;                      ///< IRC command
	char *params[16];                   ///< Command parameters (0-terminated)
	size_t n_params;                    ///< Number of parameters present
};

inline static char *
cut_word (char **s)
{
	char *start = *s, *end = *s + strcspn (*s, " ");
	*s = end + strspn (end, " ");
	*end = '\0';
	return start;
}

static bool
parse_message (char *s, struct message *msg)
{
	memset (msg, 0, sizeof *msg);

	// Ignore IRC 3.2 message tags, if present
	if (*s == '@')
	{
		s += strcspn (s, " ");
		s += strspn (s, " ");
	}

	// Prefix
	if (*s == ':')
		msg->prefix = cut_word (&s) + 1;

	// Command
	if (!*(msg->command = cut_word (&s)))
		return false;

	// Parameters
	while (*s)
	{
		size_t n = msg->n_params++;
		if (msg->n_params >= N_ELEMENTS (msg->params))
			return false;
		if (*s == ':')
		{
			msg->params[n] = ++s;
			break;
		}
		msg->params[n] = cut_word (&s);
	}
	return true;
}

static struct message *
read_message (void)
{
	static bool discard = false;
	static char buf[1025];
	static struct message msg;

	bool discard_this;
	do
	{
		if (!fgets (buf, sizeof buf, stdin))
			exit (EXIT_SUCCESS);
		size_t len = strlen (buf);

		// Just to be on the safe side, if the line overflows our buffer,
		// ignore everything up until the next line.
		discard_this = discard;
		if (len >= 2 && !strcmp (buf + len - 2, "\r\n"))
		{
			buf[len -= 2] = '\0';
			discard = false;
		}
		else
			discard = true;
	}
	// Invalid messages are silently ignored
	while (discard_this || !parse_message (buf, &msg));
	return &msg;
}

// --- Interfacing with the bot ------------------------------------------------

#define BOT_PRINT "ZYKLONB print :script: "

static const char *
get_config (const char *key)
{
	printf ("ZYKLONB get_config :%s\r\n", key);
	struct message *msg = read_message ();
	if (msg->n_params <= 0)
		exit (EXIT_FAILURE);
	return msg->params[0];
}

// --- Function database -------------------------------------------------------

// TODO: a global variable storing the various procedures (db)
// XXX: defining procedures would ideally need some kind of an ACL

static void
read_db (void)
{
	// TODO
}

static void
write_db (void)
{
	// TODO
}

// --- Main --------------------------------------------------------------------

static char *g_prefix;

struct user_info
{
	char *ctx;                          ///< Context: channel or user
	char *ctx_quote;                    ///< Reply quotation
};

defn (fn_dot)
{
	check_stack (1);
	struct item *item = pop (ctx);
	struct user_info *info = ctx->user_data;

	struct buffer buf = BUFFER_INITIALIZER;
	item_to_str (item, &buf);
	item_free (item);
	buffer_append_c (&buf, '\0');
	printf ("PRIVMSG %s :%s%s\r\n", info->ctx, info->ctx_quote, buf.s);
	free (buf.s);
	return true;
}

static void
process_message (struct message *msg)
{
	if (strcasecmp (msg->command, "PRIVMSG") || msg->n_params < 2)
		return;
	char *line = msg->params[1];

	// Filter out only our commands
	size_t prefix_len = strlen (g_prefix);
	if (strncmp (line, g_prefix, prefix_len))
		return;
	line += prefix_len;

	char *command = cut_word (&line);
	if (strcasecmp (command, "script"))
		return;

	// Retrieve information on how to respond back
	char *msg_ctx = msg->prefix, *x;
	if ((x = strchr (msg_ctx, '!')))
		*x = '\0';

	char *msg_ctx_quote;
	if (strchr ("#+&!", *msg->params[0]))
	{
		msg_ctx_quote = strdup_printf ("%s: ", msg_ctx);
		msg_ctx = msg->params[0];
	}
	else
		msg_ctx_quote = strdup ("");

	struct user_info info;
	info.ctx = msg_ctx;
	info.ctx_quote = msg_ctx_quote;

	// Finally parse and execute the macro
	char *error = NULL;
	struct item *script = parse (line, &error);
	if (error)
	{
		printf ("PRIVMSG %s :%s%s: %s\r\n",
			msg_ctx, msg_ctx_quote, "parse error", error);
		free (error);
		goto end;
	}

	struct context ctx;
	context_init (&ctx);
	ctx.user_data = &info;
	execute (&ctx, script);
	item_free_list (script);
	if (ctx.error)
		printf ("PRIVMSG %s :%s%s: %s\r\n",
			msg_ctx, msg_ctx_quote, "runtime error", ctx.error);
	context_free (&ctx);
end:
	free (msg_ctx_quote);
}

int
main (int argc, char *argv[])
{
	freopen (NULL, "rb", stdin);   setvbuf (stdin,  NULL, _IOLBF, BUFSIZ);
	freopen (NULL, "wb", stdout);  setvbuf (stdout, NULL, _IOLBF, BUFSIZ);

	read_db ();
	init_runtime_library ();
	register_handler (".", fn_dot);

	g_prefix = strdup (get_config ("prefix"));
	printf ("ZYKLONB register\r\n");
	while (true)
	{
		struct message *msg = read_message ();
		process_message (msg);
	}
	return 0;
}