aboutsummaryrefslogtreecommitdiffhomepage
path: root/src-cslul/main.c
blob: 2ce33d5f8a565c83e3b76f0321db67b115ac01f0 (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

/*

  main.c -- Entry point for CSLUL compiler

  Copyright © 2020-2024 Samuel Lidén Borell <samuel@kodafritt.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include "cslul.h"
#include "defaults.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <stdio.h>
#include <limits.h>

#ifdef CSLUL_WINDOWS
#define NO_GETTEXT
#endif

#ifndef NO_GETTEXT
#    include <locale.h>
#    include <libintl.h>
#    define _(x) gettext(x)
#else
#    define gettext(x) (x)
#    define _(x) (x)
#endif
/* () in array initializers give a warning */
#define TR(x) x

static const char *progname;
static struct CSlulConfig *cfg;
static int reported_error = 0;
static int error_limit = 1;
static int errors_left = 50;
static int accept_errors = 0;
static int errout_set;
static FILE *errout;

static const char levels[][13] = {
    TR("fatal error"), TR("error"), TR("warning"), TR("hint"), TR("style remark")
};

static const char supported_attrs[] =
"        \\slul \\name \\type \\version \\repo \\repo.mirror \\website\n"
"        \\license \\license.text \\license.list \\depends\n"
"        \\interface_depends \\api_def \\source\n";

static const char supported_apidef_flags[] =
"        retracted\n";

static struct {
    unsigned bad_attr_name : 1;
    unsigned attr_order : 1;
    unsigned too_many_attr_params : 1;
    unsigned depflag_order : 1;
    /* TODO bad dep/ifacedep flag */
    unsigned specwithsource : 1;
    unsigned bad_arch_format : 1;
    unsigned string_too_long : 1;
    unsigned escape_too_long : 1;
    unsigned bad_number_type : 1;
    unsigned bad_expr_token : 1;
    unsigned repeated_case : 1;
    unsigned unsupported_langver : 1;
    unsigned langver_syntax : 1;
    unsigned attr_char : 1;
    unsigned optional_non_ref : 1;
    unsigned bad_param_type : 1;
    unsigned bad_tldata_qual : 1;
    unsigned ambiguous_ident : 1;
    unsigned ambiguouos_expr_type : 1;
    unsigned bad_apidef_flag : 1;
    unsigned no_goto_predecessor : 1;
    unsigned invalid_start_token : 1;
    unsigned versioned_closed_type : 1;
    unsigned no_since : 1;
    unsigned repeated_since : 1;
    unsigned method_constr : 1;
    unsigned ml_comment_not_closed : 1;
    unsigned ident_later_but_lower : 1;
    unsigned slulapp_main_missing : 1;
    unsigned cant_access_optional : 1;
} shown_hint;

/** Counts the number of parameters in a format string */
static int num_fmt_params(const char *fmt)
{
    const char *s = fmt;
    int count = 0;
    while (*s) {
        s += strcspn(s, "%");
        if (!*s) break;
        s++;
        if (*s != '%') count++;
        else s++;
    }
    return count;
}

static int endswith_path(const char *filename, const char *end)
{
    size_t endlen = strlen(end);
    size_t pathlen = strlen(filename);
    return pathlen >= endlen &&
        !strcmp(end, &filename[pathlen-endlen]) &&
        (pathlen == endlen ||
            filename[pathlen-endlen-1] == '/' ||
            filename[pathlen-endlen-1] == '\\');
}

static void report_system_err(int saved_errno, const char *msgtext)
{
    errno = saved_errno;
    perror(msgtext);
}

static void msghandler(const struct CSlulState *st)
{
    /* XXX if we add multi-threaded compilation, then this function requires
           a lock for stderr so messages don't get intertwined */
    /* FIXME stderr is unbuffered, so this can still cause intertwined
             messages if multiple processes write to the terminal/file
             that stderr uses. */
    const char *filename = st->locs[0].filename;
    const char *level;
    enum CSlulErrorCode errcode = st->errorcode;
    const char *msgtext;
    int saved_errno = errno;

    if (errcode == CSLUL_E_OPENFILE && !strcmp(filename, "main.slul")) {
        fprintf(errout, "%s\n%s",
            _("No 'main.slul' file was found in the current directory"),
#if 0
            _("See 'man main.slul' for documentation.\n")
#else
            ""
#endif
            );
        goto error_printed;
    }

    level = gettext(levels[st->level]);
    msgtext = gettext(cslul_lookup_message(errcode));
    /* Print "filename:line.column: errorlevel: " */
    if (filename) {
        fprintf(errout, "%s:%.0d%s%.0d%s %s: ", filename,
                st->locs[0].line, st->locs[0].line?".":"", st->locs[0].column,
                st->locs[0].line?":":"", level);
    } else {
        fprintf(errout, "%s: ", level);
    }
    /* Print main error message */
    if (errcode == CSLUL_E_OPENFILE) {
        /* no need to also say that the open operation failed */
        report_system_err(saved_errno, NULL);
    } else if (errcode == CSLUL_E_OUTOFMEMORY) {
        /* no point in calling perror here */
        fprintf(errout, "%s\n", msgtext);
    } else if (CSLUL_IS_SYSTEM_ERR(errcode)) {
        report_system_err(saved_errno, msgtext);
    } else if (CSLUL_IS_INTERNAL_ERR(errcode)) {
        /* Message is a format string */
        fprintf(errout, _("Internal compiler error: %s_%02x\n"),
                msgtext, CSLUL_GET_INTERR_MINOR_CODE(errcode));
        #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
        abort();
        #endif
    } else {
        int num_fmt = num_fmt_params(msgtext);
        int i;
        assert(num_fmt <= CSLUL_MAX_LOCATIONS);
        switch (num_fmt) {
        case 0:
            fputs(msgtext, errout);
            break;
        case 1:
            fprintf(errout, msgtext, st->locs[0].length, st->locs[0].text);
            break;
        case 2:
            fprintf(errout, msgtext, st->locs[0].length, st->locs[0].text,
                    st->locs[1].length, st->locs[1].text);
            break;
        case 3:
            fprintf(errout, msgtext, st->locs[0].length, st->locs[0].text,
                    st->locs[1].length, st->locs[1].text,
                    st->locs[2].length, st->locs[2].text);
            break;
        case 4:
            fprintf(errout, msgtext, st->locs[0].length, st->locs[0].text,
                    st->locs[1].length, st->locs[1].text,
                    st->locs[2].length, st->locs[2].text,
                    st->locs[3].length, st->locs[3].text);
            break;
        case 5:
            fprintf(errout, msgtext, st->locs[0].length, st->locs[0].text,
                    st->locs[1].length, st->locs[1].text,
                    st->locs[2].length, st->locs[2].text,
                    st->locs[3].length, st->locs[3].text,
                    st->locs[4].length, st->locs[4].text);
            break;
        default:
            assert(0);
        }
        fputc('\n', errout);
        i = num_fmt > 1 ? num_fmt : 1;
        for (; i < CSLUL_MAX_LOCATIONS; i++) {
            const struct CSlulLocation *loc = &st->locs[i];
            static const char loctype_texts[][18] = {
                /* CSLUL_LT_INVALID */     "",
                /* CSLUL_LT_MAIN */        TR("main location"),
                /* CSLUL_LT_MAINTEXT */    TR("main location"),
                /* CSLUL_LT_DEFINITION */  TR("definition"),
                /* CSLUL_LT_DEFINED IN */  TR("defined in"),
                /* CSLUL_LT_DEPENDENCY */  TR("depends on"),
                /* CSLUL_LT_MINIMUM */     TR("minimum"),
                /* CSLUL_LT_INSTALLED */   TR("installed version"),
                /* CSLUL_LT_DUPLICATE */   TR("other definition"),
                /* CSLUL_LT_EXPR_LEFT */   TR("left expression"),
                /* CSLUL_LT_EXPR_RIGHT */  TR("right expression"),
                /* CSLUL_LT_TYPE_SOURCE */ TR("source type"),
                /* CSLUL_LT_TYPE_TARGET */ TR("target type")
            };
            const char *typetext;
            if (loc->type == CSLUL_LT_INVALID) break;
            typetext = gettext(loctype_texts[loc->type]);
            fprintf(errout, "%s:%.0d%s%.0d%s <-- %s%s %.*s\n", loc->filename,
                loc->line, loc->line?".":"", loc->column,
                loc->line?":":"", typetext,
                loc->text?":":"",
                loc->text?loc->length:0, loc->text?loc->text:"");
        }
    }

    switch ((int)errcode) {
    case CSLUL_E_BADATTRNAME:
        if (!shown_hint.bad_attr_name) {
            shown_hint.bad_attr_name = 1;
            fprintf(errout, _("        The following attributes are supported:\n"));
            fprintf(errout, supported_attrs);
        }
        break;
    case CSLUL_E_WRONGATTRORDER:
        if (!shown_hint.attr_order) {
            shown_hint.attr_order = 1;
            fprintf(errout, _("        Attributes should come in this order:\n"));
            fprintf(errout, supported_attrs);
        }
        break;
    case CSLUL_E_TOOMANYATTRPARAMS:
        if (!shown_hint.too_many_attr_params) {
            shown_hint.too_many_attr_params = 1;
            fprintf(errout, _(
"        Note that the values may not contain spaces\n"));
        }
        break;
    case CSLUL_E_DEPFLAGSORDER:
    case CSLUL_E_IFACEDEPFLAGSORDER:
        if (!shown_hint.depflag_order) {
            shown_hint.depflag_order = 1;
            fprintf(errout, _("        The flags should come in this order:\n"));
            /* TODO remove/revise the bundled and optional flags? */
            fprintf(errout,
"        bundled -> unstable -> optional -> nestedonly\n");
        }
        break;
    case CSLUL_E_MAXSOURCEFILES:
        fprintf(errout, _(
"        Please try to divide the module into smaller modules.\n"
"        This limitation is here to prevent editors and other tools from\n"
"        encountering problems when working with the 'main.slul' file.\n"));
        break;
    case CSLUL_E_SPECWITHSOURCE:
        if (!shown_hint.specwithsource) {
            shown_hint.specwithsource = 1;
            fprintf(errout, _(
"        Modules of these types should not contain any implementation.\n"));
        }
        break;
    case CSLUL_E_BADARCHFORMAT:
        if (!shown_hint.bad_arch_format) {
            shown_hint.bad_arch_format = 1;
            fprintf(errout, _(
"        Please use a multiarch triple: cpu-syscalltype-abitype\n"
"        For example: x86_64-linux-gnu\n"
"        To build for several target systems, separate them with commas.\n"));
        }
        break;
    case CSLUL_E_STRINGTOOLONG:
        if (!shown_hint.string_too_long) {
            shown_hint.string_too_long = 1;
            fprintf(errout, _(
"        Please break into multiple pieces:\n"
"        \"like\"\n"
"        \"this\"\n"));
        }
        break;
    case CSLUL_E_ESCAPETOOLONG:
        if (!shown_hint.escape_too_long) {
            shown_hint.escape_too_long = 1;
            fprintf(errout, _(
"        If you want any of the characters 0-9, A-F, a-f to follow a hex\n"
"        escape sequence, please split the string. For example:\n"
"        \"...\\xFF\" \"F...\"\n"));
        }
        break;
    case CSLUL_E_BADNUMBERTYPE:
        if (!shown_hint.bad_number_type) {
            shown_hint.bad_number_type = 1;
            fprintf(errout, _(
"        The syntax for numbers is: (_ is an optional separator)\n"
"        123_456_789 - for decimal (base 10)\n" /* TODO floating point */
"        0x1234_ABCD - for hexadecimal (base 16)\n"
"        0b1010_1111 - for binary (base 2)\n"));
        }
        break;
    case CSLUL_E_BADEXPRTOKEN:
        if (!shown_hint.bad_expr_token) {
            shown_hint.bad_expr_token = 1;
            fprintf(errout, _(
"        This can happen if a line break is missing\n"));
        }
        break;
    case CSLUL_E_REPEATEDCASE:
        if (!shown_hint.repeated_case) {
            shown_hint.repeated_case = 1;
            fprintf(errout, _(
"        To match multiple values, use comma:\n"
"            case 123, 456:\n"
"        To have an empty case, use an empty block:\n"
"            case 123: {}\n"));
        }
        break;
    case CSLUL_E_UNSUPPORTEDLANGVER:
    case CSLUL_E_UNSUPPORTEDIMPLLANGVER:
        if (!shown_hint.unsupported_langver) {
            shown_hint.unsupported_langver = 1;
            fprintf(errout, _(
"        The supported language versions are:\n"));
            fprintf(errout, _(
"        %s\n"), cslul_supported_langver());
        }
        break;
    case CSLUL_E_BADLANGVERSYNTAX:
        if (!shown_hint.langver_syntax) {
            shown_hint.langver_syntax = 1;
            fprintf(errout, _(
"        The syntax is \"\\slul MINIMUM-VERSION impl IMPL-VER upto MAX-VER\".\n"
"        Only the \"\\slul MINIMUM-VERSION\" part is mandatory.\n"));
        }
        break;
    case CSLUL_E_BADATTRCHAR:
        if (!shown_hint.attr_char) {
            shown_hint.attr_char = 1;
            fprintf(errout, _(
"        Use spaces to separate attribute names and values.\n"));
        }
        break;
    case CSLUL_E_OPTIONALNONREF:
        if (!shown_hint.optional_non_ref) {
            shown_hint.optional_non_ref = 1;
            fprintf(errout, _(
"        These are written as ?ref, ?arena and ?own\n"));
        }
        break;
    case CSLUL_E_BADPARAMTYPE:
        if (!shown_hint.bad_param_type) {
            shown_hint.bad_param_type = 1;
            fprintf(errout, _(
"        Type parameters must specify one of the following types:\n"
"        ref T, arena T, own T or enum T\n"));
        }
        break;
    case CSLUL_E_BADTLDATAQUAL:
        if (!shown_hint.bad_tldata_qual) {
            shown_hint.bad_tldata_qual = 1;
            fprintf(errout, _(
"        Top level data objects are always const and non-shared.\n"));
        }
        break;
    case CSLUL_E_AMBIGUOUSIDENT:
        if (!shown_hint.ambiguous_ident) {
            shown_hint.ambiguous_ident = 1;
            /* TODO actually implement the \rename attribute */
/*            fprintf(errout, _(
"        Add \\rename in the module header to rename one of the identifiers.\n"
"        The syntax is \\rename MODULENAME FROM TO\n"));*/
        }
        break;
    case CSLUL_E_AMBIGUOUSEXPRTYPE:
        if (!shown_hint.ambiguouos_expr_type) {
            shown_hint.ambiguouos_expr_type = 1;
            fprintf(errout, _(
            /* TODO for == and !=, the/an expr with known type should come on the left side */
            /* FIXME how to make e.g. x<y+1 convenient to use? */
"        You can put the value in a variable to explicitly set the type.\n"));
        }
        break;
    case CSLUL_E_BADAPIDEFFLAG:
        if (!shown_hint.bad_apidef_flag) {
            shown_hint.bad_apidef_flag = 1;
            fprintf(errout, _(
"        Supported flags are:\n"));
            fprintf(errout, supported_apidef_flags);
        }
        break;
    case CSLUL_E_NOGOTOPREDECESSOR:
        if (!shown_hint.no_goto_predecessor) {
            shown_hint.no_goto_predecessor = 1;
            fprintf(errout, _(
"        A goto target must have either of the following:\n"
"          1. a preceeding statement that continues to the target,\n"
"          2. a goto to it anywhere before it,\n"
"          3. or, it can be the first statement in a function.\n"
"        This is necessary to infer the states of the variables.\n"));
        }
        break;
    case CSLUL_E_BADTOPLEVELTOKEN:
        if (!shown_hint.invalid_start_token) {
            shown_hint.invalid_start_token = 1;
            /* FIXME "since" is valid too, but only in (versioned) interfaces */
            fprintf(errout, _(
"        Valid start tokens are: type, data, func.\n"));
        }
        break;
    case CSLUL_E_VERSIONEDCLOSEDTYPE:
        if (!shown_hint.versioned_closed_type) {
            shown_hint.versioned_closed_type = 1;
            fprintf(errout, _(
"        Closed types cannot change if they are exported, so it does not\n"
"        make sense to put since-versions inside them.\n"));
        }
        break;
    case CSLUL_E_NOSINCE:
    case CSLUL_E_MISSINGVERWITHAPIDEF:
        if (!shown_hint.no_since) {
            shown_hint.no_since = 1;
            fprintf(errout, _(
"        If you are working on an unstable version, please set \"\\version ... unstable\".\n"));
        }
        break;
    case CSLUL_E_REPEATEDSINCE:
        if (!shown_hint.repeated_since) {
            shown_hint.repeated_since = 1;
            fprintf(errout, _(
"        To specify multiple versions (e.g. for backports),\n"
"        use syntax like this: \"since { 1.0 1.2 }\"\n"));
        }
        break;
    case CSLUL_E_METHODCONSTR:
        if (!shown_hint.method_constr) {
            shown_hint.method_constr = 1;
            fprintf(errout, _(
"        Call constructors like this \"Type obj = .new()\".\n"));
        }
        break;
    case CSLUL_E_MLCOMMENTNOTCLOSED:
        if (!shown_hint.ml_comment_not_closed) {
            shown_hint.ml_comment_not_closed = 1;
            fprintf(errout, _(
"        The closing #}} must be placed at the start of a line.\n"));
        }
        break;
    case CSLUL_E_TLTYPELATERLOWER:
    case CSLUL_E_TLIDENTLATERLOWER:
        if (!shown_hint.ident_later_but_lower) {
            shown_hint.ident_later_but_lower = 1;
            fprintf(errout, _(
"        There's no higher \\abi_def after the lower (but more recent)\n"
"        \\api_def in the dependency.\n"));
        }
        break;
    case CSLUL_E_APPWITHOUTMAIN:
    case CSLUL_E_MAINMALFORMED:
        if (!shown_hint.slulapp_main_missing) {
            shown_hint.slulapp_main_missing = 1;
            /* TODO the SlulApp object should have the "arena" qualifier,
                    but that isn't implemented yet. */
            fprintf(errout, _(
"        The definition should look like this:\n"
"        func SlulApp.main() -> SlulExitStatus\n"));
        }
        break;
    case CSLUL_E_CANTACCESSOPTIONAL:
        if (!shown_hint.cant_access_optional) {
            shown_hint.cant_access_optional = 1;
            fprintf(errout, _(
"        Put the subexpression value in a ?ref variable, check that it\n"
"        isn't 'none', and then access the value via the variable.\n"));
        }
        break;
    default:;
    }
  error_printed:
    if (st->level <= CSLUL_L_ERROR && error_limit && !errors_left--) {
        exit(EXIT_FAILURE);
    }
    if (CSLUL_IS_INTERNAL_ERR(errcode) || errcode == CSLUL_E_OUTOFMEMORY) {
        exit(EXIT_FAILURE);
    }
}

static void show_help(void)
{
    printf(_("usage: %s [OPTION]... [MODULE-ROOT]\n"
"\n"
"C-SLUL: A compiler for SLUL implemented in C.\n"
"\n"
"Without arguments, the module in the current directory is compiled.\n"
"Or, optionally, a path for one or more modules may be specified.\n"
"\n"
"Options:\n\n"), progname);
    puts(_(
"  --outdir DIR  Write output files to this directory instead of the source\n"
"                directory."));
    puts(_(
"  -t TYPE       Override the type of output to generate from the module\n"
"                ('-t help' for list)"));
    puts(_(
"  --target NAME Cross-compile to other target platforms. The platform names\n"
"                should be multiarch triples, e.g. x86_64-linux-gnu,\n"
"                separated by comma."));
    printf(_(
"  -I DIRECTORY  Use an alternative directory with interface files.\n"
"                Specify '-I -' to skip the default ones, which are:\n"
"                %s%s%s%s\n"),
#ifdef NO_DEFAULT_IFACEDIRS
SLULIFACEDIR, "","",""
#elif defined(CSLUL_WINDOWS)
/* TODO "%APPDATA%\\slul-interfaces, %CommonProgramFiles%\\slul-interfaces, "*/
"%APPROOT%\\slul-interfaces", "","",""
#else
"~/.local/share/slul-interfaces",
(sizeof(SLULIFACEDIR) > 1 ?
    ", " SLULIFACEDIR : ""),
(sizeof(USRLOCAL_SLULIFACEDIR) > 1 &&
    strcmp(USRLOCAL_SLULIFACEDIR, SLULIFACEDIR) ?
    ", " USRLOCAL_SLULIFACEDIR : ""),
(sizeof(USR_SLULIFACEDIR) > 1 &&
    strcmp(USR_SLULIFACEDIR, SLULIFACEDIR) ?
    ", " USR_SLULIFACEDIR : "")
#endif
        );
    puts(_(
"  --error-limit=N Stop after N errors (0=no limit. Default: 50)."));
    puts(_(
"  --error-output=FILE Redirect compiler errors to a file (\"-\" for stdout)"));
    puts(_(
"  -q            Hide all warnings. For more fine-grained control,\n"
"                use: --message-level=fatal/error/warning/notice/style\n"
"                and --no-hints"));
    puts(_(
"  -V, --version Shows the compiler version, and the supported SLUL language\n"
"                versions."));
    printf("\n");
/* TODO
"\n"
"For help type 'man cslul' or visit https://slul.kodafritt.se/\n"
*/
}

static void show_outtype_help(void)
{
    puts(_(
"List of choices for -t:\n"
"  auto     - Automatically select based on module type (default).\n"
"  check    - Just perform checks (doesn't generate any output files).\n"
"  objfile  - Generate an object file (a single one for the whole module).\n"
"  library  - Generate dynamic and static libraries.\n"
"  dynlib   - Generate a dynamic library only.\n"
"  statlib  - Generate a static library only.\n"
"  header   - Generate a C header file.\n"
"  plugin   - Generate a plugin (for some other application)."));
    puts(_(
"  exe      - Generate an application executable.\n"
"\n"
"Not all kinds of outputs are possible for all modules types.\n"
));
}

static void show_version(void)
{
    const char *langvers = cslul_supported_langver();
    printf(_("cslul compiler version: %s\n"
             "\n"
             "Supported SLUL language versions:\n"
             "%s\n"),
             CSLUL_VERSION_STR,
             langvers);
}

static void invalid_option(const char *arg)
{
    fprintf(stderr, _("%s: invalid option: %s\n"), progname, arg);
}

static int process_module(char *path)
{
    struct CSlul *cslul;
    int ok;
    if (path && endswith_path(path, "main.slul")) {
        size_t len = strlen(path);
        if (len >= 10) { /* ends with /main.slul */
            path[len-9] = '\0';
        } else { /* is exactly main.slul */
            path = NULL; /* = current directory */
        }
    }
    cslul = cslul_create(cfg);
    if (!cslul) return 0;

    ok = cslul_build(cslul, path);
    cslul_free(cslul);
    return ok;
}

static int process_modules(int argc, char **argv)
{
    int optparse = 1;
    int has_args = 0;
    int argleft;
    int ok = 1;
    char **argp;

    /* Loop through all filename arguments */
    optparse = 1;
    for (argleft = argc-1, argp = argv+1; argleft>0; argleft--, argp++) {
        char *arg = *argp;
        if (arg[0] == '-') {
            if (arg[1] == '\0') {
                /* TODO best way to implement this?
                    - mocking open function could be tricky (it is already passed into cfg.prms at this point).
                    - perhaps a function could be added in cslul.h:
                        cslul_set_single_file(struct CSlul *ctx, CSlulFile file, const char *filename);
                    - such files cannot be libraries, and cannot have \source references
                    - the file should be closed also.
                    - should this also run the program? or only compile it? or interpret it?
                    - use something similar to readline?
                      or better, simply let users who want readline use a
                      wrapper such as rlfe, rlwrap, ledit
                    - allow even \slul to be skipped?
                    - how about Windows? winlibc.c does not have a stdin variable/file
                      (but that would be easy to add)
                    - can line-based input be done easily? that should
                      only be done for the main "file", not for interfaces.
                ---> Alternative solution: Add a low level "pipe mode",
                     plus a separate program, that can use readline and/or
                     allow editing (maybe even a full IDE, with a "quick
                     one file compilation" mode?)
                     - The client needs to initiate the requests.
                     - A "memory snapshot" function could be useful for IDEs
                     - Input should be raw UTF-8, even on Windows. */
                fprintf(stderr, _("%s: parsing from standard in is currently not supported\n"), progname);
                return 0;
            } else if (optparse) {
                if (arg[1] == '-') {
                    if (arg[2] == '\0') optparse = 0;
                } else if (arg[1] == '=') { /* modified by option parser */
                    argleft--;
                    argp++;
                }
                continue;
            }
        }
        if (!*arg) {
            fprintf(stderr, _("%s: empty string given as module root directory\n"), progname);
        } else if (!process_module(arg)) {
            if (!strcmp(arg, "/?")) {
                fprintf(stderr, _("Type \"%s --help\" for help.\n"), progname);
            }
            if (error_limit && !errors_left) return 0;
            ok = 0;
        }
        has_args = 1;
    }

    if (!has_args) {
        return process_module(NULL);
    }
    return ok;
}

static int check_duplicate_arg(const char *argname, int *statusflag)
{
    if (*statusflag) {
        fprintf(stderr, _("%s: Parameter --%s may only be specified once\n"),
                progname, argname);
        reported_error = 1;
        return 0;
    } else {
        *statusflag = 1;
        return 1;
    }
}

static int set_msglevel(const char *value)
{
    enum CSlulMessageLevel msglevel;
    if (!strcmp(value, "fatal")) msglevel = CSLUL_L_FATAL;
    else if (!strcmp(value, "error")) msglevel = CSLUL_L_ERROR;
    else if (!strcmp(value, "warning")) msglevel = CSLUL_L_WARNING;
    else if (!strcmp(value, "notice")) msglevel = CSLUL_L_NOTICE;
    else if (!strcmp(value, "style")) msglevel = CSLUL_L_STYLE;
    else {
        return 0;
    }
    cslul_config_set_message_level(cfg, msglevel);
    return 1;
}

static int set_default_arch(void)
{
    const char *target = getenv("SLUL_TARGET");
    if (target && *target) {
        if (!cslul_config_add_arches(cfg, target)) {
            /* An error is already reported */
            fprintf(stderr, _(
                "Please check the 'SLUL_TARGET' environment variable.\n"));
            return 0;
        }
    } else {
        if (!cslul_config_add_host_arch(cfg)) {
            fprintf(stderr, _("Could not determine output architecture.\n"));
            return 0;
        }
    }
    return 1;
}

/**
 * Converts a positive decimal number in a string to an integer.
 * Unlike strtol, this function does not allow any spaces or +/- sign.
 * Returns 1 if the number is valid, or 0 on error.
 */
static int str2posint(const char *value, int *result)
{
    int r = 0;
    const char *p = value;

    if (!*p) return 0;
    for (;;) {
        char c = *(p++);
        if (!c) break;
        if (c < '0' || c > '9' || r >= INT_MAX/10) return 0;
        r = 10*r + (c - '0');
    }
    *result = r;
    return 1;
}

int main(int argc, char **argv)
{
    int optparse = 1;
    int ok;
    int argleft;
    char *arg, **argp;
    int bad_arg = 0;
    const char *invalid_opt = NULL;
    const char *invalid_opt_value = NULL;
    const char *invalid_outtype = NULL;
    enum CSlulOutputType outtype = CSLUL_OT_AUTO;
    int has_outdir = 0;
    int should_show_version = 0;
    int overridden_ifacedirs = 0;
    int overridden_target = 0;

#ifndef NO_GETTEXT
    setlocale(LC_ALL, "");
    bindtextdomain("cslul", LOCALEDIR);
    textdomain("cslul");
#endif
    progname = argv[0];

    errno = 0;
    cfg = cslul_config_create(NULL);
    if (!cfg) {
        perror(_("Internal error. Cannot start compiler."));
        return EXIT_FAILURE;
    }
    cslul_config_set_message_handler(cfg, &msghandler);
    errout = stderr;
    errout_set = 0;

    /* Parse option arguments (and skip filename arguments) */
    for (argleft = argc-1, argp = argv+1; argleft>0; argleft--, argp++) {
        arg = *argp;
        if (arg[0] == '-') {
            if (arg[1] == '\0' || !optparse) continue; /* stdin/filename argument */
            if (arg[1] == '-') {
                /* Long option */
                if (arg[2] == '\0') { optparse = 0; }
                else if (!strcmp(arg+2, "help")) {
                    show_help();
                    return EXIT_SUCCESS;
                } else if (!strcmp(arg+2, "version")) {
                    should_show_version = 1;
                } else if (!strcmp(arg+2, "no-hints")) {
                    memset(&shown_hint, UCHAR_MAX, sizeof(shown_hint));
                } else if (!strcmp(arg+2, "accept-errors")) {
                    accept_errors = 1;
                } else if (!strncmp(arg+2, "help=", 5) ||
                           !strncmp(arg+2, "version=", 8) ||
                           !strncmp(arg+2, "no-hints=", 9) ||
                           !strncmp(arg+2, "accept-errors=", 14)) {
                    invalid_opt = arg;
                } else {
                    char *value = strchr(arg, '=');
                    int has_equals;
                    if (value) {
                        *value = '\0';
                        value++;
                        has_equals = 1;
                    } else {
                        if (--argleft) {
                            value = *(++argp);
                        } else {
                            value = NULL;
                        }
                        has_equals = 0;
                    }
                    arg += 2;
                    if (!strcmp(arg, "target")) {
                        if (!value) goto missing_arg;
                        /* TODO check for errors? */
                        cslul_config_add_arches(cfg, value);
                        overridden_target = 1;
                    } else if (!strcmp(arg, "outdir")) {
                        if (!check_duplicate_arg(arg, &has_outdir)) continue;
                        if (!value) goto missing_arg;
                        cslul_config_set_output_directory(cfg, value);
                    } else if (!strcmp(arg, "message-level")) {
                        if (!value) goto missing_arg;
                        if (!set_msglevel(value)) {
                            invalid_opt = arg-2;
                            invalid_opt_value = value;
                        }
                    } else if (!strcmp(arg, "error-limit")) {
                        int num;
                        if (!value) goto missing_arg;
                        if (str2posint(value, &num)) {
                            error_limit = errors_left = num;
                        } else {
                            invalid_opt = arg-2;
                            invalid_opt_value = value;
                        }
                    } else if (!strcmp(arg, "error-output")) {
                        FILE *f;
                        if (!value) goto missing_arg;
                        if (*value == '-' && value[1] == '\0') {
                            errout = stdout;
                        } else if ((f = fopen(value, "w")) != NULL) {
                            errout = f;
                            errout_set = 1;
                        } else {
                            perror(value);
                            reported_error = 1;
                        }
                    } else {
                        if (!invalid_opt) invalid_opt = arg-2;
                    }
                    /* Hack to prevent option arguments from being
                       parsed as module filenames. */
                    if (!invalid_opt && !has_equals) arg[-1] = '=';
                }
            } else if (arg[2] != '\0') {
                if (!strcmp(arg, "-help")) {
                    show_help();
                    return EXIT_SUCCESS;
                } else {
                    /* Long option with only one dash (or a combination of
                       multiple short options, but that is not supported) */
                    if (!invalid_opt) invalid_opt = arg;
                }
            } else {
                /* Short option */
                switch (arg[1]) {
                case '?':
                case 'h':
                    show_help();
                    return EXIT_SUCCESS;
                case 'I': {
                    const char *value;
                    if (!--argleft) goto missing_arg;
                    value = *(++argp);
                    if (value[0] == '-' && !value[1]) {
                        overridden_ifacedirs = 1;
                    } else {
                        cslul_config_add_iface_dir(cfg, value);
                    }
                    arg[1] = '=';
                    break; }
                case 'q':
                    cslul_config_set_message_level(cfg, CSLUL_L_ERROR);
                    break;
                case 't': {
                    const char *value;
                    if (!--argleft) goto missing_arg;
                    value = *(++argp);
                    if (!strcmp(value, "auto")) outtype = CSLUL_OT_AUTO;
                    else if (!strcmp(value, "check")) outtype = CSLUL_OT_CHECK;
                    else if (!strcmp(value, "objfile")) outtype = CSLUL_OT_OBJFILE;
                    else if (!strcmp(value, "library")) outtype = CSLUL_OT_LIBRARY;
                    else if (!strcmp(value, "dynlib")) outtype = CSLUL_OT_DYNLIB;
                    else if (!strcmp(value, "statlib")) outtype = CSLUL_OT_STATLIB;
                    else if (!strcmp(value, "header")) outtype = CSLUL_OT_HEADER;
                    else if (!strcmp(value, "plugin")) outtype = CSLUL_OT_PLUGIN;
                    else if (!strcmp(value, "exe")) outtype = CSLUL_OT_EXE;
                    else if (!strcmp(value, "help")) {
                        show_outtype_help();
                        return EXIT_SUCCESS;
                    } else {
                        bad_arg = 1;
                        invalid_outtype = value;
                    }
                    arg[1] = '=';
                    break; }
                case 'V':
                    should_show_version = 1;
                    break;
                default:
                    if (!invalid_opt) invalid_opt = arg;
                }
            }
        }
    }

    if (invalid_opt_value) {
        fprintf(stderr, _("Invalid value '%s' for option '%s'\n"),
                        invalid_opt_value, invalid_opt);
        return 2;
    } else if (invalid_opt) {
        invalid_option(invalid_opt);
        return 2;
    } else if (bad_arg) {
        if (invalid_outtype) {
            fprintf(stderr, _("Invalid output type (-t option): %s\n"
                    "Run '%s -t help' for a list of valid types.\n"),
                    invalid_outtype, progname);
        }
        return 2;
    } else if (reported_error) {
        return 2;
    } else if (should_show_version) {
        show_version();
        return EXIT_SUCCESS;
    }

    if (!overridden_ifacedirs) {
        /* TODO allow default slul-includes directories to be overridden?
        * note that ~/.local/share/slul-interfaces is included by default *
        const char *ifacepath = getenv("SLUL_INTERFACES_PATH");
        ...
        */
        /* TODO related: allow rpath to be overridden in executables built by cslul? */
        if (!cslul_config_add_default_iface_dirs(cfg)) {
            fprintf(stderr, _("Could not determine default search path for interface files.\n"));
            return EXIT_FAILURE;
        }
    }
    if (!overridden_target) {
        if (!set_default_arch()) return EXIT_FAILURE;
    }
    cslul_config_set_output_type(cfg, outtype);
    if (cslul_config_has_errors(cfg)) return EXIT_FAILURE;
    ok = process_modules(argc, argv);
    cslul_config_free(cfg);
    if (errout_set) fclose(errout);

    return ok || accept_errors ? EXIT_SUCCESS : EXIT_FAILURE;
  missing_arg:
    fprintf(stderr, _("%s: option '%s' requires a parameter value\n"), progname, arg);
    return 2;
}