This repository has been archived by the owner on Mar 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
compiler.cpp
2662 lines (2370 loc) · 108 KB
/
compiler.cpp
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
// Copyright (C) 2022 Jonathan Müller and clauf contributors
// SPDX-License-Identifier: BSL-1.0
#include <clauf/compiler.hpp>
#include <dryad/symbol_table.hpp>
#include <lexy/action/parse.hpp>
#include <lexy/callback.hpp>
#include <lexy/dsl.hpp>
#include <optional>
#include <string>
#include <variant>
#include <vector>
#include <clauf/assert.hpp>
#include <clauf/ast.hpp>
#include <clauf/codegen.hpp>
#include <clauf/diagnostic.hpp>
namespace
{
class fatal_error
{};
struct scope
{
enum kind_t
{
// The global scope of the translation unit.
global,
// The local scope inside a function. Local scopes can be nested.
local,
// The local scope of an if statement.
local_if,
// The local scope of a loop; here break and continue is allowed.
local_loop,
// The scope of a struct declaration.
struct_,
} kind;
dryad::symbol_table<clauf::ast_symbol, clauf::decl*> symbols;
scope* parent;
scope(kind_t kind, scope* parent) : kind(kind), parent(parent) {}
};
struct compiler_state
{
clauf::ast ast;
dryad::unlinked_node_list<clauf::struct_decl> structs;
clauf::diagnostic_logger logger;
dryad::tree<clauf::declarator> decl_tree;
clauf::codegen codegen;
scope global_scope;
scope* current_scope;
clauf::function_decl* current_function = nullptr;
int symbol_generator_count;
compiler_state(lauf_vm* vm, clauf::file&& input)
: ast{LEXY_MOV(input)}, logger(ast.input), codegen(vm, logger, ast.input, ast.symbols),
global_scope(scope::global, nullptr), current_scope(&global_scope), symbol_generator_count(0)
{}
clauf::ast_symbol generate_symbol()
{
auto str = std::string("__clauf_anon_") + std::to_string(symbol_generator_count);
++symbol_generator_count;
return ast.symbols.intern(str.c_str(), str.size());
}
};
clauf::ast_symbol get_struct_name(compiler_state& state, clauf::ast_symbol name)
{
auto str = name.c_str(state.ast.symbols);
auto struct_name = std::string("struct ") + str;
return state.ast.symbols.intern(struct_name.c_str(), struct_name.length());
}
clauf::decl* name_lookup(compiler_state& state, bool is_struct, clauf::name name)
{
auto symbol = is_struct ? get_struct_name(state, name.symbol) : name.symbol;
clauf::decl* decl = nullptr;
for (auto scope = state.current_scope; scope != nullptr; scope = scope->parent)
{
decl = scope->symbols.lookup(symbol);
if (decl != nullptr)
break;
}
return decl;
}
void insert_new_decl(compiler_state& state, clauf::decl* decl)
{
// Check that we're allowed to add a declaration here.
if (state.current_scope->kind != scope::local && state.current_scope->kind != scope::global
&& state.current_scope->kind != scope::struct_)
{
state.logger.log(clauf::diagnostic_kind::error, "declaration not allowed in this scope")
.annotation(clauf::annotation_kind::primary, state.ast.input.location_of(decl), "here")
.finish();
}
auto name = dryad::node_has_kind<clauf::struct_decl>(decl)
? get_struct_name(state, decl->name())
: decl->name();
auto shadowed = state.current_scope->symbols.insert_or_shadow(name, decl);
if (shadowed == nullptr)
return;
// Check for duplicate definition.
if (shadowed->is_definition() && decl->is_definition())
{
auto shadowed_typedef = dryad::node_try_cast<clauf::typedef_decl>(shadowed);
auto decl_typedef = dryad::node_try_cast<clauf::typedef_decl>(decl);
if (shadowed_typedef != nullptr && decl_typedef != nullptr
&& clauf::is_same(shadowed_typedef->type(), decl_typedef->type()))
return;
auto str = name.c_str(state.ast.symbols);
state.logger
.log(clauf::diagnostic_kind::error, "duplicate %s definition '%s'",
state.current_scope->kind == scope::global ? "global" : "local", str)
.annotation(clauf::annotation_kind::secondary, state.ast.input.location_of(shadowed),
"first declaration")
.annotation(clauf::annotation_kind::primary, state.ast.input.location_of(decl),
"second declaration")
.finish();
return;
}
// The struct code assumes that we keep definitions in the symbol table.
else if (shadowed->is_definition() && !decl->is_definition())
{
// Put the definition back into the symbol table.
[[maybe_unused]] auto result
= state.current_scope->symbols.insert_or_shadow(name, shadowed);
CLAUF_ASSERT(result == decl, "decl is the one we inserted above");
}
}
void codegen_new_decl(compiler_state& state, clauf::decl* decl)
{
// Inform codegen of the new declaration if necessary.
if (auto fn = dryad::node_try_cast<clauf::function_decl>(decl))
{
state.codegen.declare_function(fn);
}
else if (auto var = dryad::node_try_cast<clauf::variable_decl>(decl))
{
if (var->storage_duration() == clauf::storage_duration::static_)
state.codegen.declare_global(var);
}
}
void check_inside_loop(compiler_state& state, clauf::location loc)
{
auto inside_loop = false;
for (auto scope = state.current_scope; scope != nullptr; scope = scope->parent)
if (scope->kind == scope::local_loop)
{
inside_loop = true;
break;
}
if (!inside_loop)
{
state.logger.log(clauf::diagnostic_kind::error, "cannot use break/continue outside loop")
.annotation(clauf::annotation_kind::primary, loc, "here")
.finish();
}
}
// If the expression has array type, convert it to a pointer to the first element.
clauf::expr* do_array_decay(compiler_state& state, clauf::location loc, clauf::expr* expr)
{
if (auto array_ty = dryad::node_try_cast<clauf::array_type>(expr->type()))
{
auto pointer_ty = state.ast.types.build([&](clauf::type_forest::node_creator creator) {
return creator.create<
clauf::pointer_type>(clauf::native_specifier::none, // expressions are never native
clauf::clone(creator, array_ty->element_type()));
});
return state.ast.create<clauf::decay_expr>(loc, pointer_ty, expr);
}
return expr;
}
// If the expression is an lvalue, creates an lvalue conversion.
clauf::expr* do_lvalue_conversion(compiler_state& state, clauf::location loc, clauf::expr* expr)
{
expr = do_array_decay(state, loc, expr);
if (clauf::is_lvalue(expr))
return state.ast.create<clauf::decay_expr>(loc, expr->type(), expr);
else
return expr;
}
// Attempts to convert the value expression to target_type by creating a cast_expr or raising an
// error.
clauf::expr* do_assignment_conversion(compiler_state& state, clauf::location loc,
clauf::assignment_op op, const clauf::type* target_type,
clauf::expr* value)
{
if (clauf::is_same_modulo_qualifiers(target_type, value->type()))
return value;
if ((clauf::is_arithmetic(target_type) && clauf::is_arithmetic(value->type()))
|| (clauf::is_pointer(target_type) && clauf::is_nullptr_constant(value)))
{
return state.ast.create<clauf::cast_expr>(loc, target_type, value);
}
else if (clauf::is_pointer(target_type) && clauf::is_pointer(value->type()))
{
auto target_pointee_type
= dryad::node_cast<clauf::pointer_type>(clauf::unqualified_type_of(target_type))
->pointee_type();
auto value_pointee_type
= dryad::node_cast<clauf::pointer_type>(clauf::unqualified_type_of(value->type()))
->pointee_type();
if (clauf::is_void(target_pointee_type) || clauf::is_void(value_pointee_type))
return state.ast.create<clauf::cast_expr>(loc, target_type, value);
auto target_qualifiers = clauf::type_qualifiers_of(target_pointee_type);
auto value_qualifiers = clauf::type_qualifiers_of(value_pointee_type);
if (clauf::is_same_modulo_qualifiers(target_pointee_type, value_pointee_type))
{
// TODO: figure out nice bit hack to do the same
auto all_qualifiers_present = true;
if ((value_qualifiers & clauf::qualified_type::const_) != 0)
all_qualifiers_present &= (target_qualifiers & clauf::qualified_type::const_) != 0;
if ((value_qualifiers & clauf::qualified_type::volatile_) != 0)
all_qualifiers_present
&= (target_qualifiers & clauf::qualified_type::volatile_) != 0;
if ((value_qualifiers & clauf::qualified_type::restrict_) != 0)
all_qualifiers_present
&= (target_qualifiers & clauf::qualified_type::restrict_) != 0;
if (all_qualifiers_present)
return state.ast.create<clauf::cast_expr>(loc, target_type, value);
}
}
else if (clauf::is_pointer(target_type) && clauf::is_integer(value->type())
&& (op == clauf::assignment_op::add || op == clauf::assignment_op::sub))
return value;
state.logger.log(clauf::diagnostic_kind::error, "cannot do implicit conversion in assignment")
.annotation(clauf::annotation_kind::primary, loc, "here")
.finish();
return value;
}
// Performs integer promotion.
clauf::expr* do_integer_promotion(compiler_state& state, clauf::location loc, clauf::expr* expr)
{
if (!clauf::is_integer(expr->type()))
return expr;
auto target_type = [&]() -> const clauf::type* {
auto kind = dryad::node_cast<clauf::builtin_type>(clauf::unqualified_type_of(expr->type()))
->type_kind();
switch (kind)
{
case clauf::builtin_type::void_:
case clauf::builtin_type::nullptr_t:
CLAUF_UNREACHABLE("not an integer");
return nullptr;
case clauf::builtin_type::char_:
case clauf::builtin_type::sint8:
case clauf::builtin_type::uint8:
case clauf::builtin_type::sint16:
case clauf::builtin_type::uint16:
case clauf::builtin_type::sint32:
case clauf::builtin_type::uint32:
return state.ast.create(clauf::builtin_type::sint64);
case clauf::builtin_type::sint64:
case clauf::builtin_type::uint64:
return expr->type();
}
}();
if (clauf::is_same(target_type, expr->type()))
return expr;
else
return state.ast.create<clauf::cast_expr>(loc, target_type, expr);
}
// Performs the usual arithmetic conversions on both operands.
const clauf::type* do_usual_arithmetic_conversions(compiler_state& state, clauf::location loc,
clauf::expr*& lhs, clauf::expr*& rhs)
{
CLAUF_PRECONDITION(clauf::is_integer(lhs->type()) && clauf::is_integer(rhs->type()));
lhs = do_integer_promotion(state, loc, lhs);
rhs = do_integer_promotion(state, loc, rhs);
if (clauf::is_same_modulo_qualifiers(lhs->type(), rhs->type()))
return lhs->type();
if (clauf::is_signed_int(lhs->type()) == clauf::is_signed_int(rhs->type()))
{
auto rank_lhs = clauf::integer_rank_of(lhs->type());
auto rank_rhs = clauf::integer_rank_of(rhs->type());
if (rank_lhs > rank_rhs)
rhs = state.ast.create<clauf::cast_expr>(loc, lhs->type(), rhs);
else
lhs = state.ast.create<clauf::cast_expr>(loc, rhs->type(), lhs);
}
else
{
auto& signed_op = clauf::is_signed_int(lhs->type()) ? lhs : rhs;
auto& unsigned_op = clauf::is_unsigned_int(lhs->type()) ? lhs : rhs;
auto signed_rank = clauf::integer_rank_of(signed_op->type());
auto unsigned_rank = clauf::integer_rank_of(unsigned_op->type());
if (unsigned_rank >= signed_rank)
{
signed_op = state.ast.create<clauf::cast_expr>(loc, unsigned_op->type(), signed_op);
}
// Since the rank is the number of bits, this compares the value range.
else if (signed_rank > unsigned_rank)
{
unsigned_op = state.ast.create<clauf::cast_expr>(loc, signed_op->type(), unsigned_op);
}
else
{
auto target_type = state.ast.types.build(
[&](auto creator) { return clauf::make_unsigned(creator, signed_op->type()); });
signed_op = state.ast.create<clauf::cast_expr>(loc, target_type, signed_op);
unsigned_op = state.ast.create<clauf::cast_expr>(loc, target_type, unsigned_op);
}
}
// We have adjusted both operands to return the same type at this point, so just return it.
return lhs->type();
}
template <typename ReturnType, typename... Callback>
constexpr auto callback(Callback... cb)
{
return lexy::bind(lexy::callback<ReturnType>(cb...), lexy::parse_state, lexy::values);
}
template <typename T>
constexpr auto construct = callback<T*>(
[](compiler_state& state, clauf::location loc, auto&& arg) {
if constexpr (std::is_same_v<std::decay_t<decltype(arg)>, lexy::nullopt>)
return state.ast.create<T>(loc);
else
return state.ast.create<T>(loc, DRYAD_FWD(arg));
},
[](compiler_state& state, clauf::location loc, auto&&... args) {
return state.ast.create<T>(loc, DRYAD_FWD(args)...);
});
} // namespace
namespace clauf::grammar
{
namespace dsl = lexy::dsl;
constexpr auto id = dsl::identifier(dsl::unicode::xid_start_underscore, dsl::unicode::xid_continue);
constexpr auto kw_nullptr = LEXY_KEYWORD("nullptr", id);
constexpr auto kw_return = LEXY_KEYWORD("return", id);
constexpr auto kw_break = LEXY_KEYWORD("break", id);
constexpr auto kw_continue = LEXY_KEYWORD("continue", id);
constexpr auto kw_if = LEXY_KEYWORD("if", id);
constexpr auto kw_else = LEXY_KEYWORD("else", id);
constexpr auto kw_while = LEXY_KEYWORD("while", id);
constexpr auto kw_do = LEXY_KEYWORD("do", id);
constexpr auto kw_type_ops = lexy::symbol_table<clauf::type_constant_expr::op_t> //
.map(LEXY_LIT("sizeof"), clauf::type_constant_expr::sizeof_)
.map(LEXY_LIT("alignof"), clauf::type_constant_expr::alignof_);
enum class simple_decl_specifier
{
//=== storage class specifiers ===//
auto_,
constexpr_,
extern_,
register_,
static_,
clauf_native,
clauf_native_string,
typedef_,
//=== type specifiers ===//
void_,
int_,
signed_,
unsigned_,
char_,
short_,
//=== type qualifiers ===//
const_,
volatile_,
restrict_,
};
using decl_specifier = std::variant<simple_decl_specifier, clauf::struct_decl*>;
constexpr auto kw_type_qualifiers
= lexy::symbol_table<simple_decl_specifier> //
.map(LEXY_LIT("const"), simple_decl_specifier::const_)
.map(LEXY_LIT("volatile"), simple_decl_specifier::volatile_)
.map(LEXY_LIT("restrict"), simple_decl_specifier::restrict_);
constexpr auto kw_decl_specifiers
= kw_type_qualifiers //
.map(LEXY_LIT("auto"), simple_decl_specifier::auto_)
.map(LEXY_LIT("constexpr"), simple_decl_specifier::constexpr_)
.map(LEXY_LIT("extern"), simple_decl_specifier::extern_)
.map(LEXY_LIT("register"), simple_decl_specifier::register_)
.map(LEXY_LIT("static"), simple_decl_specifier::static_)
.map(LEXY_LIT("__clauf_native"), simple_decl_specifier::clauf_native)
.map(LEXY_LIT("__clauf_native_string"), simple_decl_specifier::clauf_native_string)
.map(LEXY_LIT("typedef"), simple_decl_specifier::typedef_)
.map(LEXY_LIT("void"), simple_decl_specifier::void_)
.map(LEXY_LIT("int"), simple_decl_specifier::int_)
.map(LEXY_LIT("char"), simple_decl_specifier::char_)
.map(LEXY_LIT("signed"), simple_decl_specifier::signed_)
.map(LEXY_LIT("unsigned"), simple_decl_specifier::unsigned_)
.map(LEXY_LIT("short"), simple_decl_specifier::short_);
constexpr auto kw_struct = LEXY_KEYWORD("struct", id);
constexpr auto kw_builtin_exprs = lexy::symbol_table<clauf::builtin_expr::builtin_t> //
.map(LEXY_LIT("__clauf_print"), clauf::builtin_expr::print)
.map(LEXY_LIT("__clauf_assert"), clauf::builtin_expr::assert)
.map(LEXY_LIT("__clauf_malloc"), clauf::builtin_expr::malloc)
.map(LEXY_LIT("__clauf_free"), clauf::builtin_expr::free);
template <bool AllowReserved>
struct identifier
{
static constexpr auto name = "identifier";
static constexpr auto rule
= id.reserve(kw_nullptr, dsl::literal_set(kw_type_ops), kw_return, kw_break, kw_continue,
kw_if, kw_else, kw_while, kw_do, dsl::literal_set(kw_decl_specifiers),
dsl::literal_set(kw_type_qualifiers), kw_struct,
dsl::literal_set(kw_builtin_exprs));
static constexpr auto value = callback<clauf::name>([](compiler_state& state, auto lexeme) {
auto symbol = state.ast.symbols.intern(lexeme.data(), lexeme.size());
if constexpr (!AllowReserved)
{
auto symbol_str = std::string_view(symbol.c_str(state.ast.symbols));
if (symbol_str.find("__") != std::string_view::npos
|| (symbol_str.size() >= 2 && symbol_str[0] == '_' && std::isupper(symbol_str[1]))
|| (state.current_scope->kind == scope::global && symbol_str[0] == '_'))
{
state.logger
.log(clauf::diagnostic_kind::warning, "identifier '%s' is reserved",
symbol_str.data())
.annotation(clauf::annotation_kind::primary, {lexeme.begin(), lexeme.end()},
"used as declaration name here")
.finish();
}
}
return clauf::name{{lexeme.begin(), lexeme.end()}, symbol};
});
};
} // namespace clauf::grammar
//=== expression parsing ===//
namespace clauf::grammar
{
template <typename Enum = std::nullptr_t>
struct op_tag
{
clauf::location loc;
Enum op;
op_tag(clauf::location loc, Enum op) : loc(loc), op(op) {}
operator Enum()
{
return op;
}
};
template <auto Enum>
struct op_tag_for : op_tag<DRYAD_DECAY_DECLTYPE(Enum)>
{
op_tag_for(const char* pos) : op_tag<DRYAD_DECAY_DECLTYPE(Enum)>(pos, Enum) {}
};
template <auto Enum = nullptr, typename Rule>
constexpr auto op_(Rule rule)
{
return dsl::op<op_tag_for<Enum>>(rule);
}
} // namespace clauf::grammar
namespace clauf::grammar
{
struct unary_expr;
struct assignment_expr;
struct nullptr_constant_expr
{
static constexpr auto rule = dsl::position(kw_nullptr);
static constexpr auto value
= callback<clauf::nullptr_constant_expr*>([](compiler_state& state, const char* pos) {
auto type = state.ast.create(clauf::builtin_type::nullptr_t);
return state.ast.create<clauf::nullptr_constant_expr>(pos, type);
});
};
constexpr auto simple_escape_sequence = lexy::symbol_table<char> //
.map<'\''>('\'')
.map<'"'>('"')
.map<'?'>('?')
.map<'\\'>('\\')
.map<'a'>('\a')
.map<'b'>('\b')
.map<'f'>('\f')
.map<'n'>('\n')
.map<'r'>('\r')
.map<'t'>('\t')
.map<'v'>('\v');
constexpr auto escape_sequence
= dsl::backslash_escape.symbol<simple_escape_sequence>()
.rule((dsl::lit_c<'u'>) >> dsl::code_point_id<4>)
.rule((dsl::lit_c<'U'>) >> dsl::code_point_id<8>)
.rule((dsl::lit_c<'x'>) >> dsl::integer<unsigned char, dsl::hex>)
.rule(dsl::peek(dsl::digit<dsl::octal>) >> dsl::integer<unsigned char, dsl::octal>);
struct character_constant_expr
{
static constexpr auto rule = dsl::position(
dsl::single_quoted(dsl::unicode::character - dsl::unicode::control, escape_sequence));
static constexpr auto value
= lexy::as_string<std::string, lexy::utf8_char_encoding> >> callback<
clauf::integer_constant_expr*>([](compiler_state& state, const char* pos,
const std::string& str) {
auto value = str[0];
return state.ast
.create<clauf::integer_constant_expr>(pos,
state.ast.create(
clauf::builtin_type::sint64),
value);
});
};
struct string_literal_expr
{
static constexpr auto rule = dsl::position(
dsl::quoted(dsl::unicode::character - dsl::unicode::control, escape_sequence));
static constexpr auto value
= lexy::as_string<std::string, lexy::utf8_char_encoding> >> callback<
clauf::string_literal_expr*>([](compiler_state& state, const char* pos,
const std::string& str) {
auto value
= state.ast.symbols.intern(str.data(), str.length()).c_str(state.ast.symbols);
auto type = state.ast.types.build([&](clauf::type_forest::node_creator creator) {
auto element_type
= creator.create<clauf::builtin_type>(clauf::builtin_type::char_);
return creator.create<clauf::array_type>(element_type, str.length() + 1);
});
return state.ast.create<clauf::string_literal_expr>(pos, type, value);
});
};
struct integer_constant_expr
{
template <typename Base>
static constexpr auto integer
= dsl::integer<std::uint64_t>(dsl::digits<Base>.sep(dsl::digit_sep_tick));
enum suffix
{
none,
unsigned_,
};
static constexpr auto suffixes
= lexy::symbol_table<suffix>.map<'u'>(suffix::unsigned_).map<'U'>(suffix::unsigned_);
static constexpr auto rule = [] {
auto decimal_digits = integer<dsl::decimal>;
auto octal_digits = integer<dsl::octal>;
auto hex_digits = (LEXY_LIT("0x") | LEXY_LIT("0X")) >> integer<dsl::hex>;
auto binary_digits = (LEXY_LIT("0b") | LEXY_LIT("0B")) >> integer<dsl::binary>;
auto opt_suffix = dsl::opt(dsl::symbol<suffixes>);
return dsl::peek(dsl::lit_c<'0'>)
>> dsl::position + (hex_digits | binary_digits | octal_digits) + opt_suffix
| dsl::else_ >> dsl::position(decimal_digits) + opt_suffix;
}();
static constexpr auto value
= callback<clauf::integer_constant_expr*>([](compiler_state& state, clauf::location loc,
std::uint64_t value, std::optional<suffix> s) {
auto type = s == suffix::unsigned_
? state.ast.create<clauf::builtin_type>(clauf::builtin_type::uint64)
: state.ast.create<clauf::builtin_type>(clauf::builtin_type::sint64);
return state.ast.create<clauf::integer_constant_expr>(loc, type, value);
});
};
struct identifier_expr
{
static constexpr auto rule = dsl::p<identifier<true>>;
static constexpr auto value = callback<clauf::identifier_expr*>(
[](compiler_state& state, clauf::name name) -> clauf::identifier_expr* {
auto decl = name_lookup(state, false, name);
if (decl == nullptr)
{
auto str = name.symbol.c_str(state.ast.symbols);
state.logger.log(clauf::diagnostic_kind::error, "unknown identifier '%s'", str)
.annotation(clauf::annotation_kind::primary, name.loc, "used here")
.finish();
return nullptr;
}
return state.ast.create<clauf::identifier_expr>(name.loc, decl->type(), decl);
});
};
struct argument_list
{
static constexpr auto rule = dsl::terminator(LEXY_LIT(")"))
.opt_list(dsl::recurse<assignment_expr>, dsl::sep(dsl::comma));
static constexpr auto value = lexy::as_list<clauf::expr_list>;
};
template <bool Abstract = false>
struct declarator;
struct decl_specifier_list;
struct type_with_specs
{
clauf::type* type;
clauf::native_specifier native;
std::optional<clauf::linkage> linkage;
std::optional<clauf::storage_duration> storage_duration;
bool is_constexpr;
bool is_typedef;
bool is_valid_for_parameter_or_member() const
{
return (!linkage || linkage == clauf::linkage::native) && !storage_duration && !is_constexpr
&& !is_typedef;
}
bool is_valid_cast() const
{
return !linkage && !storage_duration && !is_constexpr;
}
bool is_valid_for_function() const
{
return linkage != clauf::linkage::none
&& (!storage_duration || storage_duration == clauf::storage_duration::static_)
&& !is_constexpr;
}
bool requires_declarator() const
{
return !dryad::node_has_kind<clauf::decl_type>(type);
}
};
// Parses a type name followed by a closing paren.
struct type_name_in_parens
{
static constexpr auto rule = [] {
auto type_specifiers = dsl::recurse_branch<decl_specifier_list>;
auto opt_declarator
= dsl::parenthesized.close()
| dsl::else_ >> dsl::recurse<declarator<true>> + dsl::parenthesized.close();
return dsl::position(type_specifiers) >> opt_declarator;
}();
static constexpr auto value = callback<const clauf::type*>(
[](compiler_state& state, const char* pos, type_with_specs ty_stor,
clauf::declarator* decl = nullptr) -> const clauf::type* {
if (!ty_stor.is_valid_cast())
{
state.logger
.log(clauf::diagnostic_kind::error,
"invalid use of storage class specifier in cast/sizeof/alignof")
.annotation(clauf::annotation_kind::primary, pos, "here")
.finish();
}
if (decl == nullptr)
return ty_stor.type;
auto type = clauf::get_type(state.ast.types, decl, ty_stor.native, ty_stor.type);
if (type == nullptr)
{
state.logger
.log(clauf::diagnostic_kind::error,
"invalid combination of base type and declarator")
.annotation(clauf::annotation_kind::primary, pos, "here")
.finish();
type = state.ast.create(clauf::builtin_type::sint64);
}
return type;
});
};
struct expr;
struct builtin_expr
{
static constexpr auto rule
= dsl::position(dsl::symbol<kw_builtin_exprs>) >> dsl::parenthesized(dsl::recurse<expr>);
static constexpr auto value = callback<clauf::builtin_expr*>(
[](compiler_state& state, const char* pos, clauf::builtin_expr::builtin_t builtin,
clauf::expr* child) {
child = do_lvalue_conversion(state, pos, child);
auto type = [&]() -> const clauf::type* {
if (builtin == clauf::builtin_expr::malloc)
return state.ast.types.build([&](clauf::type_forest::node_creator creator) {
auto void_
= creator.create<clauf::builtin_type>(clauf::builtin_type::void_);
return creator.create<clauf::pointer_type>(clauf::native_specifier::none,
void_);
});
else
{
return state.ast.create(clauf::builtin_type::void_);
}
}();
return state.ast.create<clauf::builtin_expr>(pos, type, builtin, child);
});
};
struct initializer;
void verify_init(compiler_state& state, clauf::location loc, const clauf::type* type,
clauf::init* init);
struct expr : lexy::expression_production
{
// primary-expression
static constexpr auto atom = [] {
auto id = dsl::p<identifier_expr>;
auto constant = dsl::p<nullptr_constant_expr> //
| dsl::p<character_constant_expr> | dsl::p<string_literal_expr> //
| dsl::else_ >> dsl::p<integer_constant_expr>;
// When we have a '(' in the beginning of an expression, it can be either (expr) or
// (type)expr. This can be distinguished by checking for a type name after the '(',
// which is not possible if cast were a regular prefix operator.
//
// We thus do it here as part of the primary-expression, even though it is not a
// primary-expression, but has lower precedence. However, no other operator matches
// before that, so it works out.
auto braced_init = dsl::peek(dsl::curly_bracketed.open()) >> dsl::recurse<initializer>;
auto cast
= dsl::p<type_name_in_parens> >> (braced_init | dsl::else_ >> dsl::recurse<unary_expr>);
auto parens = dsl::recurse<expr> + dsl::parenthesized.close();
auto paren_expr = dsl::position(dsl::parenthesized.open()) >> (cast | dsl::else_ >> parens);
// sizeof/alignof are technically unary operators, but we can't parse them here since
// their operand is a type and not an expression. It should make no difference,
// however.
//
// Parse (type-name) or (expr) as operand of sizeof.
auto type_constant_operand_parens
= dsl::parenthesized.open() >> //
(dsl::p<type_name_in_parens>
| dsl::else_ >> dsl::recurse<expr> + dsl::parenthesized.close());
auto type_constant_expr
= dsl::position(dsl::symbol<kw_type_ops>)
>> (type_constant_operand_parens | dsl::else_ >> dsl::recurse<unary_expr>);
return paren_expr | type_constant_expr | id | dsl::p<builtin_expr> | dsl::else_ >> constant;
}();
struct postfix : dsl::postfix_op
{
enum member_access
{
period,
arrow
};
static constexpr auto op = op_(LEXY_LIT("(") >> dsl::p<argument_list>)
/ op_(dsl::square_bracketed(dsl::recurse<expr>))
/ op_<period>(dsl::period >> dsl::p<identifier<false>>)
/ op_<arrow>(LEXY_LIT("->") >> dsl::p<identifier<false>>)
/ op_<clauf::unary_op::post_inc>(LEXY_LIT("++"))
/ op_<clauf::unary_op::post_dec>(LEXY_LIT("--"));
using operand = dsl::atom;
};
struct unary : dsl::prefix_op
{
static constexpr auto op = op_<clauf::unary_op::plus>(LEXY_LIT("+"))
/ op_<clauf::unary_op::neg>(LEXY_LIT("-"))
/ op_<clauf::unary_op::bnot>(LEXY_LIT("~"))
/ op_<clauf::unary_op::lnot>(LEXY_LIT("!"))
/ op_<clauf::unary_op::pre_inc>(LEXY_LIT("++"))
/ op_<clauf::unary_op::pre_dec>(LEXY_LIT("--"))
/ op_<clauf::unary_op::address>(LEXY_LIT("&"))
/ op_<clauf::unary_op::deref>(LEXY_LIT("*"));
using operand = postfix;
};
struct multiplicative : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::arithmetic_op::mul>(LEXY_LIT("*"))
/ op_<clauf::arithmetic_op::div>(LEXY_LIT("/"))
/ op_<clauf::arithmetic_op::rem>(LEXY_LIT("%"));
// Operand should be cast, but it is handled as part of the atom.
using operand = unary;
};
struct additive : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::arithmetic_op::add>(LEXY_LIT("+"))
/ op_<clauf::arithmetic_op::sub>(LEXY_LIT("-"));
using operand = multiplicative;
};
struct shift : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::arithmetic_op::shl>(LEXY_LIT("<<"))
/ op_<clauf::arithmetic_op::shr>(LEXY_LIT(">>"));
using operand = additive;
};
struct relational : dsl::infix_op_left
{
static constexpr auto op
= op_<clauf::comparison_op::lt>(dsl::not_followed_by(LEXY_LIT("<"), LEXY_LIT("<")))
/ op_<clauf::comparison_op::le>(LEXY_LIT("<="))
/ op_<clauf::comparison_op::gt>(dsl::not_followed_by(LEXY_LIT(">"), LEXY_LIT(">")))
/ op_<clauf::comparison_op::ge>(LEXY_LIT(">="));
using operand = shift;
};
struct equality : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::comparison_op::eq>(LEXY_LIT("=="))
/ op_<clauf::comparison_op::ne>(LEXY_LIT("!="));
using operand = relational;
};
struct band : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::arithmetic_op::band>(LEXY_LIT("&"));
using operand = equality;
};
struct bxor : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::arithmetic_op::bxor>(LEXY_LIT("^"));
using operand = band;
};
struct bor : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::arithmetic_op::bor>(LEXY_LIT("|"));
using operand = bxor;
};
struct land : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::sequenced_op::land>(LEXY_LIT("&&"));
using operand = bor;
};
struct lor : dsl::infix_op_left
{
static constexpr auto op = op_<clauf::sequenced_op::lor>(LEXY_LIT("||"));
using operand = land;
};
struct conditional : dsl::infix_op_right
{
static constexpr auto op = op_<0>(LEXY_LIT("?") >> dsl::recurse<expr> + LEXY_LIT(":"));
using operand = lor;
};
struct assignment : dsl::infix_op_right
{
static constexpr auto op
= op_<clauf::assignment_op::none>(LEXY_LIT("="))
/ op_<assignment_op::add>(LEXY_LIT("+=")) / op_<assignment_op::sub>(LEXY_LIT("-="))
/ op_<assignment_op::mul>(LEXY_LIT("*=")) / op_<assignment_op::div>(LEXY_LIT("/="))
/ op_<assignment_op::rem>(LEXY_LIT("%=")) / op_<assignment_op::band>(LEXY_LIT("&="))
/ op_<assignment_op::bor>(LEXY_LIT("|=")) / op_<assignment_op::bxor>(LEXY_LIT("^="))
/ op_<assignment_op::shl>(LEXY_LIT("<<=")) / op_<assignment_op::shr>(LEXY_LIT(">>="));
using operand = conditional;
};
struct operation : dsl::infix_op_left
{
static constexpr auto op = op_<sequenced_op::comma>(dsl::comma);
using operand = assignment;
};
static clauf::expr* create_unary(compiler_state& state, op_tag<clauf::unary_op> op,
clauf::expr* child)
{
auto is_valid_type = [&] {
switch (op)
{
case unary_op::plus:
case unary_op::neg:
return clauf::is_arithmetic(child->type());
case unary_op::bnot:
return clauf::is_integer(child->type());
case unary_op::lnot:
return clauf::is_scalar(child->type());
case clauf::unary_op::pre_inc:
case clauf::unary_op::pre_dec:
case clauf::unary_op::post_inc:
case clauf::unary_op::post_dec:
return (clauf::is_arithmetic(child->type())
|| clauf::is_pointer_to_complete_object_type(child->type()))
&& clauf::is_modifiable_lvalue(child);
case clauf::unary_op::address:
return clauf::is_lvalue_with_address(child);
case clauf::unary_op::deref:
return clauf::is_pointer(child->type()) || clauf::is_array(child->type());
}
}();
if (!is_valid_type)
{
state.logger.log(clauf::diagnostic_kind::error, "invalid type for unary operator")
.annotation(clauf::annotation_kind::primary, op.loc, "here")
.finish();
}
if (op == clauf::unary_op::address)
{
auto type = state.ast.types.build([&](clauf::type_forest::node_creator creator) {
return creator.create<clauf::pointer_type>(clauf::native_specifier::none,
clauf::clone(creator, child->type()));
});
return state.ast.create<clauf::unary_expr>(op.loc, type, op, child);
}
else if (op == clauf::unary_op::deref)
{
child = do_lvalue_conversion(state, op.loc, child);
auto type
= dryad::node_cast<clauf::pointer_type>(clauf::unqualified_type_of(child->type()))
->pointee_type();
return state.ast.create<clauf::unary_expr>(op.loc, type, op, child);
}
else if (op == clauf::unary_op::lnot)
{
// We need to do integer promotion as it's defined in terms of ==, which does integer
// promotion.
child = do_lvalue_conversion(state, op.loc, child);
child = do_integer_promotion(state, op.loc, child);
auto type = state.ast.create(clauf::builtin_type::sint64);
return state.ast.create<clauf::unary_expr>(op.loc, type, op, child);
}
else
{
child = do_array_decay(state, op.loc, child);
if (op != clauf::unary_op::post_inc && op != clauf::unary_op::pre_inc
&& op != clauf::unary_op::post_dec && op != clauf::unary_op::pre_dec)
child = do_lvalue_conversion(state, op.loc, child);
// For increment/decrement, we need to do the usual arithmetic conversions between
// `child` and the number 1. However, if we assume that 1 already has the correct type,
// this just does integer promotion on `child`, so we can just call that instead.
//
// For the other unary operators, integer promotion is what we need to do anyway.
child = do_integer_promotion(state, op.loc, child);
return state.ast.create<clauf::unary_expr>(op.loc, child->type(), op, child);
}
}
static constexpr auto value = callback<clauf::expr*>( //
[](const compiler_state&, clauf::expr* expr) { return expr; },
[](const compiler_state&, const char*, clauf::expr* expr) { return expr; },
[](compiler_state& state, const char* pos, clauf::type_constant_expr::op_t op,
const clauf::type* operand_ty) {
auto type = state.ast.create(clauf::builtin_type::uint64);
return state.ast.create<clauf::type_constant_expr>(pos, type, op, operand_ty);
},
[](compiler_state& state, const char* pos, clauf::type_constant_expr::op_t op,
const clauf::expr* operand_expr) {
if (op != clauf::type_constant_expr::sizeof_)
{
state.logger
.log(clauf::diagnostic_kind::error,