File: varbrace.d

package info (click to toggle)
clisp 1:2.27-0.5
  • links: PTS
  • area: main
  • in suites: woody
  • size: 49,860 kB
  • ctags: 20,752
  • sloc: ansic: 123,781; lisp: 67,533; asm: 19,633; xml: 11,766; sh: 9,788; fortran: 8,307; makefile: 3,570; objc: 2,481; perl: 1,744; java: 341; yacc: 318; sed: 117
file content (1416 lines) | stat: -rw-r--r-- 37,320 bytes parent folder | download
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
# VARBRACE - CLISP source preprocessor
# Bruno Haible 15.8.1999

# This preprocessor adds braces to source code, so that variable declarations
# (introduced with the pseudo-keyword `var') can be used within blocks, like
# in C++.
# Example:
#   {
#     var decl1;
#     statement1;
#     var decl2;
#     statement2;
#   }
# becomes
#   {
#     {var decl1;
#     statement1;
#     {var decl2;
#     statement2;
#    }}
#   }

# Restrictions and caveats:
# - The last line in the input file should be terminated with a newline.
# - #line lines should not be separated into multiple lines using
#   backslash-newline.
# - No multi-line comments should start in a preprocessor line.
# - Closing braces should not be enclosed in #if conditionals.
# - #if conditions are assumed to be constant from the `var' declaration to
#   the closing brace.


#define local static
#define global
#define var
#define loop  while (1)
#define until(exp)  while (!(exp))
typedef unsigned char  uintB;
typedef unsigned short  uintW;
typedef unsigned long  uintL;
typedef int  boolean;
#define FALSE 0
#define TRUE 1

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>

#ifndef NULL
#define NULL ((void*)0)
#endif

#ifdef __cplusplus
extern "C" void exit(int);
#endif

#if !(defined(__GNUC__) && !defined(__STRICT_ANSI__))
#define inline
#endif


# Memory utilities.

local char* xmalloc (uintL count)
{
  var char* tmp = (char*)malloc(count);
  if (!tmp) {
    fprintf(stderr,"Virtual memory exhausted.\n");
    exit(1);
  }
  return tmp;
}

local char* xrealloc (void* data, uintL count)
{
  var char* tmp = (char*)realloc(data,count);
  if (!tmp) {
    fprintf(stderr,"Virtual memory exhausted.\n");
    exit(1);
  }
  return tmp;
}

local inline void xfree (void* ptr)
{
  free((char*)ptr);
}


# Character utilities.

# Determine whether a character (not newline) is whitespace.
local inline boolean is_whitespace (char c)
{
  return (c == ' ') || (c == '\t');
}

# Determine whether a charater is a digit (locale independent).
local inline boolean is_digit (char c)
{
  return (c >= '0') && (c <= '9');
}


# String utilities.

# Returns the freshly allocated copy of a strings.
local char* concat1 (const char* str1)
{
  var uintL len1 = strlen(str1);
  var char* result = xmalloc(len1+1);
  memcpy(result+0,str1,len1+1);
  return result;
}

# Returns the freshly allocated contenation of 2 strings.
local char* concat2 (const char* str1, const char* str2)
{
  var uintL len1 = strlen(str1);
  var uintL len2 = strlen(str2);
  var char* result = xmalloc(len1+len2+1);
  memcpy(result+0,str1,len1);
  memcpy(result+len1,str2,len2+1);
  return result;
}

# Returns the freshly allocated contenation of 3 strings.
local char* concat3 (const char* str1, const char* str2, const char* str3)
{
  var uintL len1 = strlen(str1);
  var uintL len2 = strlen(str2);
  var uintL len3 = strlen(str3);
  var char* result = xmalloc(len1+len2+len3+1);
  memcpy(result+0,str1,len1);
  memcpy(result+len1,str2,len2);
  memcpy(result+len1+len2,str3,len3+1);
  return result;
}

#ifdef unused
# Returns the freshly allocated contenation of 4 strings.
local char* concat4 (const char* str1, const char* str2, const char* str3, const char* str4)
{
  var uintL len1 = strlen(str1);
  var uintL len2 = strlen(str2);
  var uintL len3 = strlen(str3);
  var uintL len4 = strlen(str4);
  var char* result = xmalloc(len1+len2+len3+len4+1);
  memcpy(result+0,str1,len1);
  memcpy(result+len1,str2,len2);
  memcpy(result+len1+len2,str3,len3);
  memcpy(result+len1+len2+len3,str4,len4+1);
  return result;
}
#endif

# Returns a freshly allocated substring.
local char* substring (const char* str, uintL index1, uintL index2)
{
  if (!(index1 <= index2)) abort();
  if (!(index2 <= strlen(str))) abort();
  { var uintL len = index2-index1;
    var char* result = xmalloc(len+1);
    if (len > 0) memcpy(result,str+index1,len);
    result[len] = '\0';
    return result;
} }

#ifdef unused
# Returns a freshly allocated substring.
local char* substring_from_to (const char* p1, const char* p2)
{
  var uintL length = p2 - p1;
  var char* result = (char*) xmalloc(length+1);
  memcpy(result,p1,length);
  result[length] = '\0';
  return result;
}
#endif

# Compares two strings for equality.
local inline boolean String_equals (const char* str1, const char* str2)
{
  return !strcmp(str1,str2);
}

#ifdef unused
# Compares two strings for case-insensitive equality.
local boolean String_equalsIgnoreCase (const char* str1, const char* str2)
{
  while (*str1 != '\0' && *str2 != '\0') {
    var unsigned char c1 = (unsigned char)(*str1++);
    var unsigned char c2 = (unsigned char)(*str2++);
    if (c1 < 0x80) /* isascii(c1) */
      c1 = toupper(c1);
    if (c2 < 0x80) /* isascii(c2) */
      c2 = toupper(c2);
    if (c1 != c2)
      return FALSE;
  }
  # Now *str1 == '\0' || *str2 == '\0'.
  return (*str1 == *str2);
}
#endif


# Extensible vectors.

typedef struct {
  uintL index;
  uintL size;
  const void* * data;
} Vector;

local inline void Vector_init (Vector* v)
{
  v->size = 5;
  v->data = (const void* *) xmalloc(v->size * sizeof(const void*));
  v->index = 0;
}

local inline uintL Vector_length (const Vector* v)
{
  return v->index;
}

local void Vector_add (Vector* v, const void* elt)
{
  if (v->index >= v->size) {
    v->size = 2 * v->size;
    v->data = (const void* *) xrealloc(v->data, v->size * sizeof(const void*));
  }
  v->data[v->index++] = elt;
}

local const void * Vector_element (const Vector* v, uintL i)
{
  if (!(i < v->index)) {
    fprintf(stderr,"vector index out of bounds");
    abort();
  }
  return v->data[i];
}

local void Vector_set_element (Vector* v, uintL i, const void* elt)
{
  if (!(i < v->index)) {
    fprintf(stderr,"vector index out of bounds");
    abort();
  }
  v->data[i] = elt;
}

#ifdef unused
local void Vector_remove_element (Vector* v, uintL i)
{
  if (!(i < v->index)) {
    fprintf(stderr,"vector index out of bounds");
    abort();
  }
  v->index--;
  for (; i < v->index; i++)
    v->data[i] = v->data[i+1];
}
#endif

#ifdef unused
local void Vector_init_clone (Vector* w, const Vector* v)
{
  w->size = (v->size < 5 ? 5 : v->size);
  w->data = (const void* *) xmalloc(w->size * sizeof(const void*));
  memcpy(w->data,v->data,v->size * sizeof(const void*));
  w->index = v->size;
}
#endif

#ifdef unused
local Vector* Vector_clone (const Vector* v)
{
  var Vector* w = (Vector*) xmalloc(sizeof(Vector));
  Vector_init_clone(w,v);
  return w;
}
#endif


# A vector of strings.

typedef struct {
  Vector rep;
} VectorString;

local inline void VectorString_init (VectorString* v)
{
  Vector_init(&v->rep);
}

local VectorString* make_VectorString ()
{
  var VectorString* v = (VectorString*) xmalloc(sizeof(VectorString));
  VectorString_init(v);
  return v;
}

local inline uintL VectorString_length (const VectorString* v)
{
  return Vector_length(&v->rep);
}

local inline void VectorString_add (VectorString* v, const char* elt)
{
  Vector_add(&v->rep,elt);
}

local inline const char* VectorString_element (const VectorString* v, uintL i)
{
  return (const char*) Vector_element(&v->rep,i);
}

local inline void VectorString_set_element (VectorString* v, uintL i, const char* elt)
{
  Vector_set_element(&v->rep,i,elt);
}

#ifdef unused
local inline void VectorString_init_clone (VectorString* w, const VectorString* v)
{
  Vector_init_clone(&w->rep,&v->rep);
}
#endif

#ifdef unused
local VectorString* VectorString_clone (const VectorString* v)
{
  var VectorString* w = (VectorString*) xmalloc(sizeof(VectorString));
  VectorString_init_clone(w,v);
  return w;
}
#endif

# Tests whether v equals w.
local boolean VectorString_equals (const VectorString* v, const VectorString* w)
{
  var uintL n = VectorString_length(v);
  if (VectorString_length(w) == n) {
    var uintL i;
    for (i = 0; i < n; i++)
      if (!String_equals(VectorString_element(v,i),VectorString_element(w,i)))
        return FALSE;
    return TRUE;
  }
  return FALSE;
}

#ifdef unused
# Tests whether v starts with w.
local boolean VectorString_startsWith (const VectorString* v, const VectorString* w)
{
  var uintL n = VectorString_length(w);
  if (VectorString_length(v) >= n) {
    var uintL i;
    for (i = 0; i < n; i++)
      if (!String_equals(VectorString_element(v,i),VectorString_element(w,i)))
        return FALSE;
    return TRUE;
  }
  return FALSE;
}
#endif


# A vector of vectors of strings.

typedef struct {
  Vector rep;
} VectorVectorString;

local inline void VectorVectorString_init (VectorVectorString* v)
{
  Vector_init(&v->rep);
}

local VectorVectorString* make_VectorVectorString ()
{
  var VectorVectorString* v = (VectorVectorString*) xmalloc(sizeof(VectorVectorString));
  VectorVectorString_init(v);
  return v;
}

local inline uintL VectorVectorString_length (const VectorVectorString* v)
{
  return Vector_length(&v->rep);
}

local inline void VectorVectorString_add (VectorVectorString* v, const VectorString* elt)
{
  Vector_add(&v->rep,elt);
}

local inline const VectorString* VectorVectorString_element (const VectorVectorString* v, uintL i)
{
  return (const VectorString*) Vector_element(&v->rep,i);
}

#ifdef unused
local inline void VectorVectorString_set_element (VectorVectorString* v, uintL i, const VectorString* elt)
{
  Vector_set_element(&v->rep,i,elt);
}
#endif

#ifdef unused
local inline void VectorVectorString_init_clone (VectorVectorString* w, const VectorVectorString* v)
{
  Vector_init_clone(&w->rep,&v->rep);
}
#endif

#ifdef unused
local VectorVectorString* VectorVectorString_clone (const VectorVectorString* v)
{
  var VectorVectorString* w = (VectorVectorString*) xmalloc(sizeof(VectorVectorString));
  VectorVectorString_init_clone(w,v);
  return w;
}
#endif


# A stack of vectors of strings.

typedef struct {
  Vector rep;
} StackVectorString;

local inline void StackVectorString_init (StackVectorString* v)
{
  Vector_init(&v->rep);
}

local StackVectorString* make_StackVectorString ()
{
  var StackVectorString* v = (StackVectorString*) xmalloc(sizeof(StackVectorString));
  StackVectorString_init(v);
  return v;
}

local inline uintL StackVectorString_length (const StackVectorString* v)
{
  return Vector_length(&v->rep);
}

#ifdef unused
local inline boolean StackVectorString_is_empty (const StackVectorString* v)
{
  return StackVectorString_length(v) == 0;
}
#endif

local inline void StackVectorString_push (StackVectorString* v, const VectorString* elt)
{
  Vector_add(&v->rep,elt);
}

local inline VectorString* StackVectorString_element (const StackVectorString* v, uintL i)
{
  return (VectorString*) Vector_element(&v->rep,i);
}

local VectorString* StackVectorString_peek (StackVectorString* v)
{
  var uintL n = StackVectorString_length(v);
  if (n == 0) { fprintf(stderr,"stack empty\n"); exit(1); }
  return StackVectorString_element(v,n-1);
}

local VectorString* StackVectorString_pop (StackVectorString* v)
{
  var uintL n = StackVectorString_length(v);
  if (n == 0) { fprintf(stderr,"stack empty\n"); exit(1); }
  { var VectorString* result = StackVectorString_element(v,n-1);
    v->rep.index -= 1;
    return result;
} }

#ifdef unused
# Push elt, and optimize: elt can be removed if is starts with an already
# present string sequence. If another element starts with elt, that one can
# be removed.
local void StackVectorString_push_optimize (StackVectorString* v, const VectorString* elt)
{
  var uintL n = StackVectorString_length(v);
  var uintL i;
  for (i = 0; i < n; i++)
    if (VectorString_startsWith(elt,StackVectorString_element(v,i)))
      return;
  for (i = 0; i < n; )
    if (VectorString_startsWith(StackVectorString_element(v,i),elt)) {
      Vector_remove_element(&v->rep,i);
      n--;
    } else
      i++;
  Vector_add(&v->rep,elt);
}
#endif


# The #if[def] stack. All the conditions are implicitly combined by &&.
# For every #if we start a new entry in the stack, which is popped when we
# see the corresponding #endif. This is a stack of vector of string, not a
# stack of string, because when a #elif is seen, we add an element to the
# stack without popping the previous one.

local StackVectorString* ifdef_stack;

# Operations on the #if[def] stack.

local void do_if (const char * condition)
{
  var VectorString* v = make_VectorString();
  VectorString_add(v,condition);
  StackVectorString_push(ifdef_stack,v);
}

local void do_else ()
{
  var VectorString* v = StackVectorString_peek(ifdef_stack);
  var uintL i = VectorString_length(v) - 1;
  var const char* lastcondition = VectorString_element(v,i);
  lastcondition = concat3("!(",lastcondition,")");
  VectorString_set_element(v,i,lastcondition);
}

local void do_elif (const char * condition)
{
  var VectorString* v = StackVectorString_peek(ifdef_stack);
  var uintL i = VectorString_length(v) - 1;
  var const char* lastcondition = VectorString_element(v,i);
  lastcondition = concat3("!(",lastcondition,")");
  VectorString_set_element(v,i,lastcondition);
  VectorString_add(v,condition);
}

local void do_endif ()
{
  StackVectorString_pop(ifdef_stack);
}

# Returns the current #if condition.
# It is a vector of strings, implicitly combined by &&.
# The vector is freshly constructed, but the strings are shared.

local VectorString* current_condition ()
{
  var VectorString* result = make_VectorString();
  var uintL n = StackVectorString_length(ifdef_stack);
  var uintL i;
  for (i = 0; i < n; i++) {
    var const VectorString* v = StackVectorString_element(ifdef_stack,i);
    var uintL m = VectorString_length(v);
    var uintL j;
    for (j = 0; j < m; j++)
      VectorString_add(result,VectorString_element(v,j));
  }
  return result;
}

# Reduces a condition modulo the current condition, i.e. removes all
# && clauses which are already implied in the current condition.

local const VectorString* modulo_current_condition (const VectorString* condition)
{
  # Quick and dirty: Just remove the start segment:
  # condition[0]==current_condition[0], ... condition[n]==current_condition[n].
  var VectorString* current = current_condition();
  var uintL i;
  for (i = 0; i < VectorString_length(current) && i < VectorString_length(condition); i++)
    if (!String_equals(VectorString_element(current,i),VectorString_element(condition,i)))
      break;
  if (i == 0)
    return condition;
  else {
    var VectorString* new_condition = make_VectorString();
    for (; i < VectorString_length(condition); i++)
      VectorString_add(new_condition,VectorString_element(condition,i));
    return new_condition;
  }
}


# Parsing of #if/#else/#elif/#endif lines.

local const char* is_if (const char* line)
{
  var uintL n = strlen(line);
  var uintL i = 0;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Parse a '#'.
  if (i < n && line[i] == '#')
    i++;
  else
    return NULL;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Check for "if".
  if (i+2 < n
      && line[i+0] == 'i'
      && line[i+1] == 'f'
      && is_whitespace(line[i+2])) {
    i += 3;
    for (; i < n && is_whitespace(line[i]); i++);
    for (; n > i && is_whitespace(line[n-1]); n--);
    return substring(line,i,n);
  }
  # Check for "ifdef".
  if (i+5 < n
      && line[i+0] == 'i'
      && line[i+1] == 'f'
      && line[i+2] == 'd'
      && line[i+3] == 'e'
      && line[i+4] == 'f'
      && is_whitespace(line[i+5])) {
    i += 6;
    for (; i < n && is_whitespace(line[i]); i++);
    for (; n > i && is_whitespace(line[n-1]); n--);
    { var char* term = substring(line,i,n);
      var const char* result = concat3("defined(",term,")");
      xfree(term);
      return result;
  } }
  # Check for "ifndef".
  if (i+6 < n
      && line[i+0] == 'i'
      && line[i+1] == 'f'
      && line[i+2] == 'n'
      && line[i+3] == 'd'
      && line[i+4] == 'e'
      && line[i+5] == 'f'
      && is_whitespace(line[i+6])) {
    i += 7;
    for (; i < n && is_whitespace(line[i]); i++);
    for (; n > i && is_whitespace(line[n-1]); n--);
    { var char* term = substring(line,i,n);
      var const char* result = concat3("!defined(",term,")");
      xfree(term);
      return result;
  } }
  return NULL;
}

local boolean is_else (const char* line)
{
  var uintL n = strlen(line);
  var uintL i = 0;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Parse a '#'.
  if (i < n && line[i] == '#')
    i++;
  else
    return FALSE;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Check for "else".
  if (i+4 <= n
      && line[i+0] == 'e'
      && line[i+1] == 'l'
      && line[i+2] == 's'
      && line[i+3] == 'e'
      && (i+4 == n || is_whitespace(line[i+4]))) {
    return TRUE;
  }
  return FALSE;
}

local const char* is_elif (const char* line)
{
  var uintL n = strlen(line);
  var uintL i = 0;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Parse a '#'.
  if (i < n && line[i] == '#')
    i++;
  else
    return NULL;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Check for "elif".
  if (i+4 < n
      && line[i+0] == 'e'
      && line[i+1] == 'l'
      && line[i+2] == 'i'
      && line[i+3] == 'f'
      && is_whitespace(line[i+4])) {
    i += 5;
    for (; i < n && is_whitespace(line[i]); i++);
    for (; n > i && is_whitespace(line[n-1]); n--);
    return substring(line,i,n);
  }
  return NULL;
}

local boolean is_endif (const char* line)
{
  var uintL n = strlen(line);
  var uintL i = 0;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Parse a '#'.
  if (i < n && line[i] == '#')
    i++;
  else
    return FALSE;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Check for "endif".
  if (i+5 <= n
      && line[i+0] == 'e'
      && line[i+1] == 'n'
      && line[i+2] == 'd'
      && line[i+3] == 'i'
      && line[i+4] == 'f'
      && (i+5 == n || is_whitespace(line[i+5]))) {
    return TRUE;
  }
  return FALSE;
}


# Print a list (cond1 && cond2 && ...) to a stream.
local void print_condition_part (FILE* stream, const VectorString* condition)
{
  var uintL n = VectorString_length(condition);
  if (n == 0) {
    fprintf(stream,"1");
    return;
  }
  if (n == 1) {
    fprintf(stream,"%s",VectorString_element(condition,0));
    return;
  }
  {
    var uintL i;
    for (i = 0; i < n; i++) {
      if (i > 0)
        fprintf(stream," && ");
      fprintf(stream,"(%s)",VectorString_element(condition,i));
    }
  }
}

# Tests whether a condition is equivalent to 1 (true).
local inline boolean is_true_condition_part (const VectorString* condition)
{
  var uintL n = VectorString_length(condition);
  return (n == 0);
}

#ifdef unused
# Print a list of lists (cond1 || cond2 || ...) to a stream.
local void print_condition (FILE* stream, const VectorVectorString* condition)
{
  var uintL n = VectorVectorString_length(condition);
  if (n == 0) {
    fprintf(stream,"0");
    return;
  }
  if (n == 1) {
    print_condition_part(stream,VectorVectorString_element(condition,0));
    return;
  }
  {
    var uintL i;
    for (i = 0; i < n; i++) {
      if (i > 0)
        fprintf(stream," || ");
      fprintf(stream,"(");
      print_condition_part(stream,VectorVectorString_element(condition,i));
      fprintf(stream,")");
    }
  }
}
#endif

#ifdef unused
# Tests whether a condition is equivalent to 0 (false).
local inline boolean is_false_condition (const VectorVectorString* condition)
{
  var uintL n = VectorVectorString_length(condition);
  return (n == 0);
}
#endif

#ifdef unused
# Tests whether a condition is equivalent to 1 (true).
local boolean is_true_condition (const VectorVectorString* condition)
{
  var uintL n = VectorVectorString_length(condition);
  var uintL i;
  for (i = 0; i < n; i++)
    if (is_true_condition_part(VectorVectorString_element(condition,i)))
      return TRUE;
  return FALSE;
}
#endif


#ifdef unused
# Read a line, or NULL if EOF is encountered.
local char* get_line (FILE* fp)
{
  var int len = 1;
  var char* line = (char*) xmalloc(len);
  var int index = 0;
  loop {
    var int c = getc(fp);
    if (c==EOF) { if (index>0) break; else { xfree(line); return NULL; } }
    if (c=='\n') break;
    if (index >= len-1) {
      len = 2*len;
      line = (char*) xrealloc(line,len);
    }
    line[index++] = c;
  }
  line[index] = '\0';
  return line;
}
#endif


# ================================== INPUT ==================================

local FILE* infile;

local const char* input_filename = "(stdin)";

local uintL input_line;

local int in_char (void)
{
  var int c = getc(infile);
  if (c=='\n')
    input_line++;
  return c;
}

local int peek_char (void)
{
  var int c = getc(infile);
  if (c != EOF)
    ungetc(c,infile);
  return c;
}


# Decode a #line directive. If the line represents a #line directive,
# return the line number. Else return -1.

local int decode_line_directive (const char* line)
{
  var uintL n = strlen(line);
  var uintL i = 0;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Parse a '#'.
  if (i < n && line[i] == '#')
    i++;
  else
    return -1;
  # Skip whitespace.
  for (; i < n && is_whitespace(line[i]); i++);
  # Check for "line".
  if (i+4 < n
      && line[i+0] == 'l'
      && line[i+1] == 'i'
      && line[i+2] == 'n'
      && line[i+3] == 'e'
      && is_whitespace(line[i+4])) {
    i += 4;
    for (; i < n && is_whitespace(line[i]); i++);
  }
  # Check for a digit.
  if (!(i < n && is_digit(line[i])))
    return -1;
  { var uintL i1 = i;
    for (; i < n && is_digit(line[i]); i++);
    { var uintL i2 = i;
      # Convert digit string to a `long'.
      var char* digits = substring(line,i1,i2);
      errno = 0;
      { var long result = strtol(digits,NULL,10);
        xfree(digits);
        if (errno != 0) return -1;
        if (result < 0) abort();
        # Check for a source file name.
        for (; i < n && is_whitespace(line[i]); i++);
        if (i < n && line[i] == '"') {
          var uintL i3;
          i++;
          i3 = i;
          for (; i < n && line[i] != '"'; i++);
          if (i < n && line[i] == '"') {
            var uintL i4 = i;
            input_filename = substring(line,i3,i4);
          }
        }
        return result;
} } } }


# ================================== OUTPUT =================================

local FILE* outfile;

# Output can be buffered for a while.
enum out_mode { direct, buffered };
#define MAXHEADERLEN  5000
local struct {
  enum out_mode mode;
  uintB buffer[MAXHEADERLEN];
  uintL buffindex;
} out;

local inline void char_out (uintB c)
{
  putc(c,outfile);
}

# Turn off output buffering.
local void outbuffer_off (void)
{
  if (out.mode==buffered) {
    var uintL index = 0;
    while (index < out.buffindex) {
      char_out(out.buffer[index]); index++;
    }
    out.mode = direct;
  }
}

# Turn off output buffering, inserting a string at a given place.
local void outbuffer_off_insert (uintL insertpoint, char* insert)
{
  if (out.mode==buffered) {
    var uintL index = 0;
    loop {
      if (index==insertpoint) {
        while (!(*insert==0)) {
          char_out(*insert++);
        }
      }
      if (index == out.buffindex)
        break;
      char_out(out.buffer[index]); index++;
    }
    out.mode = direct;
  }
}

# Turn on output buffering.
local void outbuffer_on (void)
{
  if (out.mode==direct) {
    out.buffindex = 0;
    out.mode = buffered;
  }
}

# Output a character.
local void out_char (int c)
{
  if (out.mode==buffered) {
    if (out.buffindex < MAXHEADERLEN)
      out.buffer[out.buffindex++] = c;
    else {
      # Buffer full -> turn it off
      outbuffer_off(); char_out(c);
    }
  } else {
    char_out(c);
  }
}

# Output a line.
local void out_line (const char* line)
{
  for (; *line != '\0'; line++)
    out_char(*line);
  out_char('\n');
}


# =============================== MAIN PROGRAM ==============================

local int next_char (void)
{
  var int c = in_char();
  if (c != EOF)
    out_char(c);
  return c;
}

local char* next_line (void)
{
  var int len = 1;
  var char* line = (char*) xmalloc(len);
  var int index = 0;
  loop {
    var int c = next_char();
    if (c==EOF) { if (index>0) break; else { xfree(line); return NULL; } }
    if (c=='\n') break;
    if (index >= len-1) {
      len = 2*len;
      line = (char*) xrealloc(line,len);
    }
    line[index++] = c;
  }
  line[index] = '\0';
  return line;
}


# Sadly, #line directives output during a skipped portion of #if are ignored
# by the C preprocessor. Therefore we must re-output them after every
# #else/#elif/#endif line that belongs to a #if that was in effect when the
# line directive was seen.

# The maximum #if level that needs repeated #line directives.
# This is always <= StackVectorString_length(ifdef_stack).
local uintL ifdef_line_repeat;

# Emit a #line note after the line number in the outfile has changed
# differently from the line number in the infile.
local inline void line_emit (void)
{
  fprintf(outfile,"#line %ld\n",input_line);
  if (ifdef_line_repeat < StackVectorString_length(ifdef_stack))
    ifdef_line_repeat = StackVectorString_length(ifdef_stack);
}

# #line treatment for the #if[def] stack.

local inline void line_repeat_else ()
{
  if (ifdef_line_repeat == StackVectorString_length(ifdef_stack)) {
    char buf[20];
    sprintf(buf,"#line %ld",input_line);
    out_line(buf);
  }
}

local inline void line_repeat_endif ()
{
  if (ifdef_line_repeat > StackVectorString_length(ifdef_stack)) {
    char buf[20];
    sprintf(buf,"#line %ld",input_line);
    out_line(buf);
    ifdef_line_repeat--;
  }
}


enum token_type { eof, ident, number, charconst, stringconst, sep, expr };
typedef struct {
  enum token_type type;
  # if buffered:
  uintL startindex;
  uintL endindex;
  # if type==sep (operator or separator):
  uintB ch;
} Token;

local Token next_token (void)
{
  var Token token;
 restart:
  outbuffer_off();
  outbuffer_on();
  token.startindex = out.buffindex;
  {
    var int c = next_char();
    switch (c) {
      case EOF:
        # EOF
        token.type = eof;
        goto done;
      case ' ': case '\v': case '\t': case '\n':
        # whitespace, ignore
        goto restart;
      case '\\':
        if (peek_char()=='\n') {
          # backslash newline, ignore
          next_char();
          goto restart;
        }
        goto separator;
      case '/':
        if (peek_char() == '*') {
          # Comment
          next_char();
          loop {
            c = next_char();
            if (c==EOF) {
              fprintf(stderr,"Unfinished comment\n");
              break;
            }
            if ((c=='*') && (peek_char()=='/')) {
              next_char();
              break;
            }
          }
          goto restart;
        }
        goto separator;
      case '*':
        if (peek_char() == '/')
          fprintf(stderr,"End of comment outside comment in line %lu\n",input_line);
        goto separator;
      case '#':
        # preprocessor directive
        {
          var char* line = next_line();
          if (line) {
            var char* old_line = line;
            line = concat2("#",line);
            xfree(old_line);
          } else
            line = concat1("#");
          while (line[strlen(line)-1] == '\\') {
            var char* continuation_line = next_line();
            line[strlen(line)-1] = '\0';
            if (continuation_line) {
              var char* old_line = line;
              line = concat2(line,continuation_line);
              xfree(old_line);
              xfree(continuation_line);
            }
          }
          {
            var const char* condition;
            var long line_directive;
            if ((condition = is_if(line)) != NULL) {
              do_if(condition);
            } else if (is_else(line)) {
              do_else();
              line_repeat_else();
            } else if ((condition = is_elif(line)) != NULL) {
              do_elif(condition);
              line_repeat_else();
            } else if (is_endif(line)) {
              do_endif();
              line_repeat_endif();
            } else if ((line_directive = decode_line_directive(line)) >= 0)
              input_line = line_directive;
          }
          xfree(line);
        }
        goto separator;
      case '.':
        c = peek_char();
        if (!(((c>='0') && (c<='9')) || (c=='.')))
          goto separator;
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        # Digit. Continue reading as long as alphanumeric or '.'.
        loop {
          c = peek_char();
          if (((c>='0') && (c<='9')) || ((c>='A') && (c<='Z')) || ((c>='a') && (c<='z')) || (c=='.'))
            next_char();
          else
            break;
        }
        token.type = number;
        goto done;
      case '\'':
        # Character constant
        loop {
          c = next_char();
          if (c==EOF) {
            fprintf(stderr,"Unterminated character constant\n");
            break;
          }
          if (c=='\'')
            break;
          if (c=='\\')
            c = next_char();
        }
        token.type = charconst;
        goto done;
      case '\"':
        # String constant
        loop {
          c = next_char();
          if (c==EOF) {
            fprintf(stderr,"Unterminated string constant\n");
            break;
          }
          if (c=='\"')
            break;
          if (c=='\\')
            c = next_char();
        }
        token.type = stringconst;
        goto done;
      case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
      case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
      case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
      case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
      case 'Y': case 'Z':
      case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
      case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
      case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
      case 's': case 't': case 'u': case 'v': case 'w': case 'x':
      case 'y': case 'z':
      case '_':
        # Identifier.
        loop {
          c = peek_char();
          if (((c>='0') && (c<='9')) || ((c>='A') && (c<='Z')) || ((c>='a') && (c<='z')) || (c=='_'))
            next_char();
          else
            break;
        }
        token.type = ident;
        goto done;
      default:
      separator:
        token.type = sep;
        token.ch = c;
        goto done;
    }
  }
 done:
  token.endindex = out.buffindex;
  return token;
}

#define MAXBRACES 1000
local struct {
  uintL count;
  struct {
    uintB brace_type;
    uintL input_line;
    VectorString* condition;
    VectorVectorString* pending_conditions;
  } opening[MAXBRACES];
} open_braces;

void convert (FILE* infp, FILE* outfp, const char* infilename)
{
  # Initialize input variables.
  infile = infp;
  input_line = 1;
  # Initialize output variables.
  outfile = outfp;
  # Initialize other variables.
  ifdef_stack = make_StackVectorString();
  ifdef_line_repeat = 0;
  # Go!
  if (infilename != NULL)
    fprintf(outfile,"#line 1 \"%s\"\n",infilename);
 {var boolean last_token_was_ident = FALSE;
  loop {
    var Token token = next_token();
    switch (token.type) {
      case eof:
        if (open_braces.count > 0) {
          if (open_braces.count <= MAXBRACES) {
            fprintf(stderr,"Unclosed '%c' in line %lu\n",
                           open_braces.opening[open_braces.count-1].brace_type,
                           open_braces.opening[open_braces.count-1].input_line
                   );
          } else
            fprintf(stderr,"Unclosed '(' or '{' or '['\n");
        }
        return;
      case sep:
        switch (token.ch) {
          case '(': case '{': case '[':
            if (open_braces.count < MAXBRACES) {
              open_braces.opening[open_braces.count].brace_type = token.ch;
              open_braces.opening[open_braces.count].input_line = input_line;
              if (token.ch == '{') {
                open_braces.opening[open_braces.count].condition = current_condition();
                open_braces.opening[open_braces.count].pending_conditions = make_VectorVectorString();
              }
            }
            open_braces.count++;
            break;
          case ')': case '}': case ']':
            if (open_braces.count > 0) {
              open_braces.count--;
              if (open_braces.count < MAXBRACES) {
                var uintL opening_line = open_braces.opening[open_braces.count].input_line;
                var uintL closing_line = input_line;
                var uintB opening_ch = open_braces.opening[open_braces.count].brace_type;
                var uintB closing_ch = token.ch;
                if (!(   ((opening_ch == '(') && (closing_ch == ')'))
                      || ((opening_ch == '{') && (closing_ch == '}'))
                      || ((opening_ch == '[') && (closing_ch == ']'))
                   ) )
                  fprintf(stderr,"Opening delimiter '%c' in line %lu\n and closing delimiter '%c' in line %lu\n don't match.\n",
                                 opening_ch,opening_line,
                                 closing_ch,closing_line
                         );
                if ((opening_ch == '{') && (closing_ch == '}')) {
                  var const VectorString* opening_condition = open_braces.opening[open_braces.count].condition;
                  var const VectorString* closing_condition = current_condition();
                  if (VectorString_equals(opening_condition,closing_condition)) {
                    var const VectorVectorString* conditions = open_braces.opening[open_braces.count].pending_conditions;
                    var boolean did_newline = FALSE;
                    var boolean in_fresh_line = FALSE;
                    var uintL i;
                    for (i = VectorVectorString_length(conditions); i > 0; ) {
                      var const VectorString* condition = VectorVectorString_element(conditions,--i);
                      condition = modulo_current_condition(condition);
                      if (!is_true_condition_part(condition)) {
                        if (!in_fresh_line) {
                          fprintf(outfile,"\n");
                          in_fresh_line = TRUE;
                        }
                        fprintf(outfile,"#if ");
                        print_condition_part(outfile,condition);
                        fprintf(outfile,"\n}\n#endif\n");
                        did_newline = TRUE;
                      } else {
                        fprintf(outfile,"}");
                        in_fresh_line = FALSE;
                      }
                    }
                    if (did_newline) {
                      if (!in_fresh_line) {
                        fprintf(outfile,"\n");
                        in_fresh_line = TRUE;
                      }
                      line_emit();
                    }
                  } else {
                    fprintf(stderr,"Opening brace '%c' in line %lu: #if ",opening_ch,opening_line);
                    print_condition_part(stderr,opening_condition);
                    fprintf(stderr,"\n and closing brace '%c' in line %lu: #if ",closing_ch,closing_line);
                    print_condition_part(stderr,closing_condition);
                    fprintf(stderr,"\n don't match.\n");
                  }
                }
              }
            } else {
              fprintf(stderr,"No opening delimiter for closing delimiter '%c' in line %lu\n",
                             token.ch,input_line
                     );
            }
            break;
          default:
            break;
        }
        break;
      case ident:
        if (!last_token_was_ident # to avoid cases like "local var x = ...;"
            && (token.endindex - token.startindex == 3)
            && (out.buffer[token.startindex  ] == 'v')
            && (out.buffer[token.startindex+1] == 'a')
            && (out.buffer[token.startindex+2] == 'r')
           ) {
          var uintL braceindex;
          for (braceindex = open_braces.count; braceindex > 0; ) {
            braceindex--;
            if (open_braces.opening[braceindex].brace_type == '{') {
              VectorVectorString_add(open_braces.opening[braceindex].pending_conditions,current_condition());
              outbuffer_off_insert(token.startindex,"{");
              break;
            }
          }
        }
        break;
      default:
        break;
    }
    outbuffer_off();
    last_token_was_ident = (token.type == ident);
  }
}}

int main (int argc, char* argv[])
{
  var char* infilename;
  var FILE* infile;
  var FILE* outfile;
  # Argument parsing.
  if (argc == 2) {
    infilename = argv[1];
    infile = fopen(infilename,"r");
    if (infile == NULL)
      exit(1);
    input_filename = infilename;
  } else if (argc == 1) {
    infilename = NULL;
    infile = stdin;
  } else
    exit(1);
  outfile = stdout;
  # Main job.
  convert(infile,outfile,infilename);
  # Clean up.
  if (ferror(infile) || ferror(outfile)) {
    fclose(infile);
    fclose(outfile);
    exit(1);
  }
  fclose(infile);
  fclose(outfile);
  exit(0);
}