1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
|
// Copyright (c) Herb Sutter
// SPDX-License-Identifier: CC-BY-NC-ND-4.0
// 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.
//===========================================================================
// Reflection and meta
//===========================================================================
#include "parse.h"
cpp2: namespace = {
meta: namespace = {
//-----------------------------------------------------------------------
//
// Compiler services
//
//-----------------------------------------------------------------------
//
compiler_services: @polymorphic_base @copyable type =
{
// Common data members
//
errors : *std::vector<error_entry>;
errors_original_size : int;
generated_tokens : *std::deque<token>;
parser : cpp2::parser;
metafunction_name : std::string = ();
metafunction_args : std::vector<std::string> = ();
metafunctions_used : bool = false;
// Constructor
//
operator=: (
out this,
errors_ : *std::vector<error_entry>,
generated_tokens_: *std::deque<token>
)
= {
errors = errors_;
errors_original_size = cpp2::unsafe_narrow<int>(std::ssize(errors*));
generated_tokens = generated_tokens_;
parser = errors*;
}
// Common API
//
set_metafunction_name: (inout this, name: std::string_view, args: std::vector<std::string>) = {
metafunction_name = name;
metafunction_args = args;
metafunctions_used = args.empty();
}
get_metafunction_name: (this) -> std::string_view = metafunction_name;
get_argument: (inout this, index: int) -> std::string = {
metafunctions_used = true;
if (0 <= index < metafunction_args.ssize()) {
return metafunction_args[index];
}
return "";
}
get_arguments: (inout this) -> std::vector<std::string> = {
metafunctions_used = true;
return metafunction_args;
}
arguments_were_used: (this) -> bool = metafunctions_used;
protected parse_statement: (
inout this,
copy source: std::string_view
)
-> (ret: std::unique_ptr<statement_node>)
= {
original_source := source;
generated_lines.push_back( std::vector<source_line>() );
lines := generated_lines.back()&;
add_line := :(s: std::string_view) = {
_ = lines$*.emplace_back( s, source_line::category::cpp2 );
};
// First split this string into source_lines
//
(copy newline_pos := source.find('\n'))
if source.ssize() > 1
&& newline_pos != source.npos
{
while newline_pos != std::string_view::npos
{
add_line( source.substr(0, newline_pos) );
source.remove_prefix( newline_pos+1 );
newline_pos = source.find('\n');
}
}
if !source.empty() {
add_line( source );
}
// Now lex this source fragment to generate
// a single grammar_map entry, whose .second
// is the vector of tokens
_ = generated_lexers.emplace_back( errors* );
tokens := generated_lexers.back()&;
tokens*.lex( lines*, true );
assert( std::ssize(tokens* .get_map()) == 1 );
// Now parse this single declaration from
// the lexed tokens
ret = parser.parse_one_declaration(
tokens*.get_map().begin()*.second,
generated_tokens*
);
if !ret {
error( "parse failed - the source string is not a valid statement:\n(original_source)$");
}
}
position: (virtual this)
-> source_position
= {
return ();
}
// Error diagnosis and handling, integrated with compiler output
// Unlike a contract violation, .requires continues further processing
//
require:(
this,
b : bool,
msg : std::string_view
)
= {
if !b {
error( msg );
}
}
error: (this, msg: std::string_view)
= {
message := msg as std::string;
if !metafunction_name.empty() {
message = "while applying @(metafunction_name)$ - (message)$";
}
_ = errors*.emplace_back( position(), message);
}
// Enable custom contracts on this object, integrated with compiler output
// Unlike .requires, a contract violation stops further processing
//
report_violation: (this, msg) = {
error(msg);
throw( std::runtime_error(" ==> programming bug found in metafunction @(metafunction_name)$ - contract violation - see previous errors") );
}
has_handler:(this) true;
}
/*
//-----------------------------------------------------------------------
//
// Type IDs
//
//-----------------------------------------------------------------------
//
// All type_ids are wrappers around a pointer to node
//
type_id: @polymorphic_base @copyable type =
{
this: compiler_services = ();
n: *type_id_node;
protected operator=: (
out this,
n_: *type_id_node,
s : compiler_services
)
= {
compiler_services = s;
n = n_;
assert( n, "a meta::type_id must point to a valid type_id_node, not null" );
}
is_wildcard : (this) -> bool = n*.is_wildcard();
is_pointer_qualified: (this) -> bool = n*.is_pointer_qualified();
template_args_count : (this) -> int = n*.template_arguments().ssize();
to_string : (this) -> std::string = n*.to_string();
position: (override this) -> source_position = n*.position();
}
*/
//-----------------------------------------------------------------------
//
// Declarations
//
//-----------------------------------------------------------------------
//
// All declarations are wrappers around a pointer to node
//
declaration_base: @polymorphic_base @copyable type =
{
this: compiler_services = ();
protected n: *declaration_node;
protected operator=: (
out this,
n_: *declaration_node,
s : compiler_services
)
= {
compiler_services = s;
n = n_;
assert( n, "a meta::declaration must point to a valid declaration_node, not null" );
}
position: (override this) -> source_position = n*.position();
print: (this) -> std::string = n*.pretty_print_visualize(0);
}
//-----------------------------------------------------------------------
// All declarations
//
declaration: @polymorphic_base @copyable type =
{
this: declaration_base = ();
operator=: (
out this,
n_: *declaration_node,
s : compiler_services
)
= {
declaration_base = (n_, s);
}
is_public : (this) -> bool = n*.is_public();
is_protected : (this) -> bool = n*.is_protected();
is_private : (this) -> bool = n*.is_private();
is_default_access: (this) -> bool = n*.is_default_access();
default_to_public : (inout this) = _ = n*.make_public();
default_to_protected: (inout this) = _ = n*.make_protected();
default_to_private : (inout this) = _ = n*.make_private();
make_public : (inout this) -> bool = n*.make_public();
make_protected : (inout this) -> bool = n*.make_protected();
make_private : (inout this) -> bool = n*.make_private();
has_name : (this) -> bool = n*.has_name();
has_name : (this, s: std::string_view) -> bool = n*.has_name(s);
name: (this) -> std::string_view = {
if has_name() { return n*.name()*.as_string_view(); }
else { return ""; }
}
has_initializer: (this) -> bool = n*.has_initializer();
is_global : (this) -> bool = n*.is_global();
is_function : (this) -> bool = n*.is_function();
is_object : (this) -> bool = n*.is_object();
is_base_object : (this) -> bool = n*.is_base_object();
is_member_object : (this) -> bool = n*.is_member_object();
is_type : (this) -> bool = n*.is_type();
is_namespace : (this) -> bool = n*.is_namespace();
is_alias : (this) -> bool = n*.is_alias();
is_type_alias : (this) -> bool = n*.is_type_alias();
is_namespace_alias : (this) -> bool = n*.is_namespace_alias();
is_object_alias : (this) -> bool = n*.is_object_alias();
is_function_expression : (this) -> bool = n*.is_function_expression();
as_function : (this) -> function_declaration = function_declaration(n, this);
as_object : (this) -> object_declaration = object_declaration(n, this);
as_type : (this) -> type_declaration = type_declaration(n, this);
as_alias : (this) -> alias_declaration = alias_declaration(n, this);
get_parent : (this) -> declaration = declaration(n*.parent_declaration, this);
parent_is_function : (this) -> bool = n*.parent_is_function();
parent_is_object : (this) -> bool = n*.parent_is_object();
parent_is_type : (this) -> bool = n*.parent_is_type();
parent_is_namespace : (this) -> bool = n*.parent_is_namespace();
parent_is_alias : (this) -> bool = n*.parent_is_alias();
parent_is_type_alias : (this) -> bool = n*.parent_is_type_alias();
parent_is_namespace_alias : (this) -> bool = n*.parent_is_namespace_alias();
parent_is_object_alias : (this) -> bool = n*.parent_is_object_alias();
parent_is_polymorphic: (this) -> bool = n*.parent_is_polymorphic();
mark_for_removal_from_enclosing_type: (inout this)
pre<Type>( parent_is_type() ) // this precondition should be sufficient ...
= {
test := n*.type_member_mark_for_removal();
assert( test ); // ... to ensure this assert is true
}
}
//-----------------------------------------------------------------------
// Function declarations
//
function_declaration: @copyable type =
{
this: declaration = ();
operator=: (
out this,
n_: *declaration_node,
s : compiler_services
) =
{
declaration = (n_, s);
assert( n*.is_function() );
}
index_of_parameter_named : (this, s: std::string_view) -> int = n*.index_of_parameter_named(s);
has_parameter_named : (this, s: std::string_view) -> bool = n*.has_parameter_named(s);
has_in_parameter_named : (this, s: std::string_view) -> bool = n*.has_in_parameter_named(s);
has_out_parameter_named : (this, s: std::string_view) -> bool = n*.has_out_parameter_named(s);
has_move_parameter_named : (this, s: std::string_view) -> bool = n*.has_move_parameter_named(s);
first_parameter_name : (this) -> std::string = n*.first_parameter_name();
has_parameter_with_name_and_pass: (this, s: std::string_view, pass: passing_style) -> bool
= n*.has_parameter_with_name_and_pass(s, pass);
is_function_with_this : (this) -> bool = n*.is_function_with_this();
is_virtual : (this) -> bool = n*.is_virtual_function();
is_defaultable : (this) -> bool = n*.is_defaultable_function();
is_constructor : (this) -> bool = n*.is_constructor();
is_default_constructor : (this) -> bool = n*.is_default_constructor();
is_move : (this) -> bool = n*.is_move();
is_swap : (this) -> bool = n*.is_swap();
is_constructor_with_that : (this) -> bool = n*.is_constructor_with_that();
is_constructor_with_in_that : (this) -> bool = n*.is_constructor_with_in_that();
is_constructor_with_move_that: (this) -> bool = n*.is_constructor_with_move_that();
is_assignment : (this) -> bool = n*.is_assignment();
is_assignment_with_that : (this) -> bool = n*.is_assignment_with_that();
is_assignment_with_in_that : (this) -> bool = n*.is_assignment_with_in_that();
is_assignment_with_move_that : (this) -> bool = n*.is_assignment_with_move_that();
is_destructor : (this) -> bool = n*.is_destructor();
is_copy_or_move : (this) -> bool = is_constructor_with_that() || is_assignment_with_that();
has_declared_return_type : (this) -> bool = n*.has_declared_return_type();
has_deduced_return_type : (this) -> bool = n*.has_deduced_return_type();
has_bool_return_type : (this) -> bool = n*.has_bool_return_type();
has_non_void_return_type : (this) -> bool = n*.has_non_void_return_type();
unnamed_return_type : (this) -> std::string = n*.unnamed_return_type_to_string();
get_parameters: (this)
-> std::vector<object_declaration>
= {
ret: std::vector<object_declaration> = ();
for n*.get_function_parameters() do (param) {
_ = ret.emplace_back( param*.declaration*&, this );
}
return ret;
}
is_binary_comparison_function: (this) -> bool = n*.is_binary_comparison_function();
default_to_virtual : (inout this) = _ = n*.make_function_virtual();
make_virtual : (inout this) -> bool = n*.make_function_virtual();
add_initializer: (inout this, source: std::string_view)
pre<this> (!has_initializer(), "cannot add an initializer to a function that already has one")
pre<this> (parent_is_type(), "cannot add an initializer to a function that isn't in a type scope")
= {
//require( !has_initializer(),
// "cannot add an initializer to a function that already has one");
//require( parent_is_type(),
// "cannot add an initializer to a function that isn't in a type scope");
stmt := parse_statement(source);
if !(stmt as bool) {
error( "cannot add an initializer that is not a valid statement");
return;
}
require (n*.add_function_initializer(stmt),
std::string("unexpected error while attempting to add initializer"));
}
}
//-----------------------------------------------------------------------
// Object declarations
//
object_declaration: @copyable type =
{
this: declaration = ();
operator=: (
out this,
n_: *declaration_node,
s : compiler_services
) =
{
declaration = (n_, s);
assert( n*.is_object() );
}
is_const : (this) -> bool = n*.is_const();
has_wildcard_type: (this) -> bool = n*.has_wildcard_type();
type: (this) -> std::string = {
ret := n*.object_type();
require( !contains(ret, "(*ERROR*)"),
"cannot to_string this type: " + ret);
return ret;
}
initializer: (this) -> std::string = {
ret := n*.object_initializer();
require( !contains(ret, "(*ERROR*)"),
"cannot to_string this initializer: " + ret);
return ret;
}
}
//-----------------------------------------------------------------------
// Type declarations
//
type_declaration: @copyable type =
{
this: declaration = ();
operator=: (
out this,
n_: *declaration_node,
s : compiler_services
) =
{
declaration = (n_, s);
assert( n*.is_type() );
}
reserve_names: (this, name: std::string_view, forward etc...) =
{ // etc is not declared ':string_view' for compatibility with GCC 10.x
for get_members()
do (m) {
m.require( !m.has_name( name ),
"in a '(get_metafunction_name())$' type, the name '(name)$' is reserved for use by the '(get_metafunction_name())$' implementation");
}
if constexpr !CPP2_PACK_EMPTY(etc) {
reserve_names( etc... );
}
}
is_polymorphic: (this) -> bool = n*.is_polymorphic();
is_final : (this) -> bool = n*.is_type_final();
make_final : (inout this) -> bool = n*.make_type_final();
get_member_functions: (this)
-> std::vector<function_declaration>
= {
ret: std::vector<function_declaration> = ();
for n*.get_type_scope_declarations(declaration_node::functions)
do (d) {
_ = ret.emplace_back( d, this );
}
return ret;
}
get_member_functions_needing_initializer: (this)
-> std::vector<function_declaration>
= {
ret: std::vector<function_declaration> = ();
for n*.get_type_scope_declarations(declaration_node::functions)
do (d)
if !d*.has_initializer()
&& !d*.is_virtual_function()
&& !d*.is_defaultable_function()
{
_ = ret.emplace_back( d, this );
}
return ret;
}
get_member_objects: (this)
-> std::vector<object_declaration>
= {
ret: std::vector<object_declaration> = ();
for n*.get_type_scope_declarations(declaration_node::objects) do (d) {
_ = ret.emplace_back( d, this );
}
return ret;
}
get_member_types: (this)
-> std::vector<type_declaration>
= {
ret: std::vector<type_declaration> = ();
for n*.get_type_scope_declarations(declaration_node::types) do (d) {
_ = ret.emplace_back( d, this );
}
return ret;
}
get_member_aliases: (this)
-> std::vector<alias_declaration>
= {
ret: std::vector<alias_declaration> = ();
for n*.get_type_scope_declarations(declaration_node::aliases) do (d) {
_ = ret.emplace_back( d, this );
}
return ret;
}
get_members: (this)
-> std::vector<declaration>
= {
ret: std::vector<declaration> = ();
for n*.get_type_scope_declarations(declaration_node::all) do (d) {
_ = ret.emplace_back( d, this );
}
return ret;
}
query_declared_value_set_functions: (this)
-> (
out_this_in_that : bool,
out_this_move_that : bool,
inout_this_in_that : bool,
inout_this_move_that : bool
)
= {
declared := n*.find_declared_value_set_functions();
out_this_in_that = declared.out_this_in_that != nullptr;
out_this_move_that = declared.out_this_move_that != nullptr;
inout_this_in_that = declared.inout_this_in_that != nullptr;
inout_this_move_that = declared.inout_this_move_that != nullptr;
}
add_member: (inout this, source: std::string_view)
= {
decl := parse_statement(source);
if !(decl as bool) {
error("the provided source string is not a valid statement");
return;
}
if !decl*.is_declaration() {
error("cannot add a member that is not a declaration");
}
require( n*.add_type_member(decl),
std::string("unexpected error while attempting to add member:\n") + source );
}
remove_marked_members: (inout this) = n*.type_remove_marked_members();
remove_all_members : (inout this) = n*.type_remove_all_members();
disable_member_function_generation: (inout this) = n*.type_disable_member_function_generation();
}
//-----------------------------------------------------------------------
// Alias declarations
//
alias_declaration: @copyable type =
{
this: declaration = ();
operator=: (
out this,
n_: *declaration_node,
s : compiler_services
) =
{
declaration = (n_, s);
assert( n*.is_alias() );
}
}
//-----------------------------------------------------------------------
//
// Metafunctions - these are hardwired for now until we get to the
// step of writing a Cpp2 interpreter to run inside the compiler
//
//-----------------------------------------------------------------------
//
//-----------------------------------------------------------------------
// Some common metafunction helpers (metafunctions are just functions,
// so they can be factored as usual)
//
add_virtual_destructor: (inout t: meta::type_declaration) =
{
t.add_member( "operator=: (virtual move this) = { }");
}
//-----------------------------------------------------------------------
//
// "... an abstract base class defines an interface ..."
//
// -- Stroustrup (The Design and Evolution of C++, 12.3.1)
//
//-----------------------------------------------------------------------
//
// interface
//
// an abstract base class having only pure virtual functions
//
interface: (inout t: meta::type_declaration) =
{
has_dtor := false;
for t.get_members() do (inout m)
{
m.require( !m.is_object(),
"interfaces may not contain data objects");
if m.is_function() {
mf := m.as_function();
mf.require( !mf.is_copy_or_move(),
"interfaces may not copy or move; consider a virtual clone() instead");
mf.require( !mf.has_initializer(),
"interface functions must not have a function body; remove the '=' initializer");
mf.require( mf.make_public(),
"interface functions must be public");
mf.default_to_virtual();
has_dtor |= mf.is_destructor();
}
}
if !has_dtor {
t.add_virtual_destructor();
}
}
//-----------------------------------------------------------------------
//
// "C.35: A base class destructor should be either public and
// virtual, or protected and non-virtual."
//
// "[C.43] ... a base class should not be copyable, and so does not
// necessarily need a default constructor."
//
// -- Stroustrup, Sutter, et al. (C++ Core Guidelines)
//
//-----------------------------------------------------------------------
//
// polymorphic_base
//
// A pure polymorphic base type that is not copyable, and whose
// destructor is either public and virtual or protected and nonvirtual.
//
// Unlike an interface, it can have nonpublic and nonvirtual functions.
//
polymorphic_base: (inout t: meta::type_declaration) =
{
has_dtor := false;
for t.get_member_functions() do (inout mf)
{
if mf.is_default_access() {
mf.default_to_public();
}
mf.require( !mf.is_copy_or_move(),
"polymorphic base types may not copy or move; consider a virtual clone() instead");
if mf.is_destructor() {
has_dtor = true;
mf.require( ((mf.is_public() || mf.is_default_access()) && mf.is_virtual())
|| (mf.is_protected() && !mf.is_virtual()),
"a polymorphic base type destructor must be public and virtual, or protected and nonvirtual");
}
}
if !has_dtor {
t.add_virtual_destructor();
}
}
//-----------------------------------------------------------------------
//
// "... A totally ordered type ... requires operator<=> that
// returns std::strong_ordering. If the function is not
// user-written, a lexicographical memberwise implementation
// is generated by default..."
//
// -- P0707R4, section 3
//
// Note: This feature derived from Cpp2 was already adopted
// into Standard C++ via paper P0515, so most of the
// heavy lifting is done by the Cpp1 C++20/23 compiler,
// including the memberwise default semantics
// (In contrast, cppfront has to do the work itself for
// default memberwise semantics for operator= assignment
// as those aren't yet part of Standard C++)
//
//-----------------------------------------------------------------------
//
ordered_impl: (
inout t: meta::type_declaration,
ordering: std::string_view // must be "strong_ordering" etc.
) =
{
has_spaceship := false;
for t.get_member_functions() do (inout mf)
{
if mf.has_name("operator<=>") {
has_spaceship = true;
return_name := mf.unnamed_return_type();
if return_name.find(ordering) == return_name.npos
{
mf.error( "operator<=> must return std::" + ordering as std::string );
}
}
}
if !has_spaceship {
t.add_member( "operator<=>: (this, that) -> std::" + (ordering as std::string) + ";" );
}
}
//-----------------------------------------------------------------------
// ordered - a totally ordered type
//
// Note: the ordering that should be encouraged as default gets the nice name
//
ordered: (inout t: meta::type_declaration) =
{
ordered_impl( t, "strong_ordering" );
}
//-----------------------------------------------------------------------
// weakly_ordered - a weakly ordered type
//
weakly_ordered: (inout t: meta::type_declaration) =
{
ordered_impl( t, "weak_ordering" );
}
//-----------------------------------------------------------------------
// partially_ordered - a partially ordered type
//
partially_ordered: (inout t: meta::type_declaration) =
{
ordered_impl( t, "partial_ordering" );
}
//-----------------------------------------------------------------------
//
// "A value is ... a regular type. It must have all public
// default construction, copy/move construction/assignment,
// and destruction, all of which are generated by default
// if not user-written; and it must not have any protected
// or virtual functions (including the destructor)."
//
// -- P0707R4, section 3
//
//-----------------------------------------------------------------------
//
// copyable
//
// A type with (copy and move) x (construction and assignment)
//
copyable: (inout t: meta::type_declaration) =
{
// If the user explicitly wrote any of the copy/move functions,
// they must also have written the most general one - we can't
// assume we can safely generate it for them since they've opted
// into customized semantics
smfs := t.query_declared_value_set_functions();
if !smfs.out_this_in_that
&& (
smfs.out_this_move_that
|| smfs.inout_this_in_that
|| smfs.inout_this_move_that
)
{
t.error( "this type is partially copyable/movable - when you provide any of the more-specific operator= signatures, you must also provide the one with the general signature (out this, that); alternatively, consider removing all the operator= functions and let them all be generated for you with default memberwise semantics" );
}
else if !smfs.out_this_in_that {
t.add_member( "operator=: (out this, that) = { }");
}
}
//-----------------------------------------------------------------------
//
// basic_value
//
// A regular type: copyable, plus has public default construction
// and no protected or virtual functions
//
basic_value: (inout t: meta::type_declaration) =
{
t.copyable();
has_default_ctor := false;
for t.get_member_functions() do (inout mf) {
has_default_ctor |= mf.is_default_constructor();
mf.require( !mf.is_protected() && !mf.is_virtual(),
"a value type may not have a protected or virtual function");
mf.require( !mf.is_destructor() || mf.is_public() || mf.is_default_access(),
"a value type may not have a non-public destructor");
}
if !has_default_ctor {
t.add_member( "operator=: (out this) = { }");
}
}
//-----------------------------------------------------------------------
//
// "A 'value' is a totally ordered basic_value..."
//
// -- P0707R4, section 3
//
// value - a value type that is totally ordered
//
// Note: the ordering that should be encouraged as default gets the nice name
//
value: (inout t: meta::type_declaration) =
{
t.ordered();
t.basic_value();
}
weakly_ordered_value: (inout t: meta::type_declaration) =
{
t.weakly_ordered();
t.basic_value();
}
partially_ordered_value: (inout t: meta::type_declaration) =
{
t.partially_ordered();
t.basic_value();
}
//-----------------------------------------------------------------------
//
// "By definition, a `struct` is a `class` in which members
// are by default `public`; that is,
//
// struct s { ...
//
// is simply shorthand for
//
// class s { public: ...
//
// ... Which style you use depends on circumstances and taste.
// I usually prefer to use `struct` for classes that have all
// data `public`."
//
// -- Stroustrup (The C++ Programming Language, 3rd ed., p. 234)
//
//-----------------------------------------------------------------------
//
// struct
//
// a type with only public bases, objects, and functions,
// no virtual functions, and no user-defined constructors
// (i.e., no invariants) or assignment or destructors.
//
struct: (inout t: meta::type_declaration) =
{
for t.get_members() do (inout m)
{
m.require( m.make_public(),
"all struct members must be public");
if m.is_function() {
mf := m.as_function();
t.require( !mf.is_virtual(),
"a struct may not have a virtual function");
t.require( !mf.has_name("operator="),
"a struct may not have a user-defined operator=");
}
}
t.disable_member_function_generation();
}
//-----------------------------------------------------------------------
//
// "C enumerations constitute a curiously half-baked concept. ...
// the cleanest way out was to deem each enumeration a separate type."
//
// -- Stroustrup (The Design and Evolution of C++, 11.7)
//
// "An enumeration is a distinct type ... with named constants"
//
// -- ISO C++ Standard
//
//-----------------------------------------------------------------------
//
// basic_enum
//
// a type together with named constants that are its possible values
//
value_member_info: @struct type = {
name : std::string;
type : std::string;
value : std::string;
}
basic_enum: (
inout t : meta::type_declaration,
nextval ,
bitwise : bool
)
= {
enumerators : std::vector<value_member_info> = ();
min_value : i64 = ();
max_value : i64 = ();
underlying_type : std::string;
t.reserve_names( "operator=", "operator<=>" );
if bitwise {
t.reserve_names( "has", "set", "clear", "to_string", "get_raw_value", "none" );
}
// 1. Gather: The names of all the user-written members, and find/compute the type
underlying_type = t.get_argument(0); // use the first template argument, if there was one
found_non_numeric := false;
(copy value: std::string = "-1")
for t.get_members()
do (m)
if m.is_member_object()
{
m.require( m.is_public() || m.is_default_access(),
"an enumerator cannot be protected or private");
mo := m.as_object();
if !mo.has_wildcard_type() {
mo.error( "an explicit underlying type should be specified as a template argument to the metafunction - try 'enum<u16>' or 'flag_enum<u64>'");
}
init := mo.initializer();
is_default_or_numeric := is_empty_or_a_decimal_number(init);
found_non_numeric |= !init.empty() && !is_default_or_numeric;
m.require( !is_default_or_numeric || !found_non_numeric || mo.has_name("none"),
"(mo.name())$: enumerators with non-numeric values must come after all default and numeric values");
nextval( value, init );
v := std::strtoll(value[0]&, nullptr, 10); // for non-numeric values we'll just get 0 which is okay for now
if v < min_value {
min_value = v;
}
if v > max_value {
max_value = v;
}
// Adding local variable 'e' to work around a Clang warning
e: value_member_info = ( mo.name() as std::string, "", value );
enumerators.push_back( e );
mo.mark_for_removal_from_enclosing_type();
}
if (enumerators.empty()) {
t.error( "an enumeration must contain at least one enumerator value");
return;
}
// Compute the default underlying type, if it wasn't explicitly specified
if underlying_type == ""
{
t.require( !found_non_numeric,
"if you write an enumerator with a non-numeric-literal value, you must specify the enumeration's underlying type");
if !bitwise {
if min_value >= std::numeric_limits<i8>::min() && max_value <= std::numeric_limits<i8>::max() {
underlying_type = "i8";
}
else if min_value >= std::numeric_limits<i16>::min() && max_value <= std::numeric_limits<i16>::max() {
underlying_type = "i16";
}
else if min_value >= std::numeric_limits<i32>::min() && max_value <= std::numeric_limits<i32>::max() {
underlying_type = "i32";
}
else if min_value >= std::numeric_limits<i64>::min() && max_value <= std::numeric_limits<i64>::max() {
underlying_type = "i64";
}
else {
t.error( "values are outside the range representable by the largest supported underlying signed type (i64)" );
}
}
else {
umax := max_value * 2 as u64;
if umax <= std::numeric_limits<u8>::max() {
underlying_type = "u8";
}
else if umax <= std::numeric_limits<u16>::max() {
underlying_type = "u16";
}
else if umax <= std::numeric_limits<u32>::max() {
underlying_type = "u32";
}
else {
underlying_type = "u64";
}
}
}
// 2. Replace: Erase the contents and replace with modified contents
//
// Note that most values and functions are declared as '==' compile-time values, i.e. Cpp1 'constexpr'
t.remove_marked_members();
// Generate the 'none' value if appropriate, and use that or
// else the first enumerator as the default-constructed value
default_value := enumerators[0].name;
if bitwise{
default_value = "none";
e: value_member_info = ( "none", "", "0");
enumerators.push_back( e );
}
// Generate all the private implementation
t.add_member( " _value : (underlying_type)$;");
t.add_member( " private operator= : (implicit out this, _val: i64) == _value = cpp2::unsafe_narrow<(underlying_type)$>(_val);");
// Generate the bitwise operations
if bitwise {
t.add_member( " operator|=: ( inout this, that ) == _value |= that._value;");
t.add_member( " operator&=: ( inout this, that ) == _value &= that._value;");
t.add_member( " operator^=: ( inout this, that ) == _value ^= that._value;");
t.add_member( " operator| : ( this, that ) -> (t.name())$ == _value | that._value;");
t.add_member( " operator& : ( this, that ) -> (t.name())$ == _value & that._value;");
t.add_member( " operator^ : ( this, that ) -> (t.name())$ == _value ^ that._value;");
t.add_member( " has : ( inout this, that ) -> bool == _value & that._value;");
t.add_member( " set : ( inout this, that ) == _value |= that._value;");
t.add_member( " clear : ( inout this, that ) == _value &= that._value~;");
}
// Add the enumerators
for enumerators do (e) {
t.add_member( " (e.name)$ : (t.name())$ == (e.value)$;");
}
// Generate the common functions
t.add_member( " get_raw_value : (this) -> (underlying_type)$ == _value;");
t.add_member( " operator= : (out this) == { _value = (default_value)$._value; }");
t.add_member( " operator= : (out this, that) == { }");
t.add_member( " operator<=> : (this, that) -> std::strong_ordering;");
// Provide a 'to_string' function to print enumerator name(s)
(copy to_string: std::string = " to_string: (this) -> std::string = { \n")
{
if bitwise {
to_string += " _ret : std::string = \"(\";\n";
to_string += " _comma : std::string = ();\n";
to_string += " if this == none { return \"(none)\"; }\n";
}
for enumerators
do (e) {
if e.name != "_" { // ignore unnamed values
if bitwise {
if e.name != "none" {
to_string += " if (this & (e.name)$) == (e.name)$ { _ret += _comma + \"(e.name)$\"; _comma = \", \"; }\n";
}
}
else {
to_string += " if this == (e.name)$ { return \"(e.name)$\"; }\n";
}
}
}
if bitwise {
to_string += " return _ret+\")\";\n}\n";
}
else {
to_string += " return \"invalid (t.name())$ value\";\n}\n";
}
t.add_member( to_string );
}
}
//-----------------------------------------------------------------------
//
// "An enum[...] is a totally ordered value type that stores a
// value of its enumerators's type, and otherwise has only public
// member variables of its enumerator's type, all of which are
// naturally scoped because they are members of a type."
//
// -- P0707R4, section 3
//
enum: (inout t: meta::type_declaration) =
{
// Let basic_enum do its thing, with an incrementing value generator
t.basic_enum(
:(inout value: std::string, specified_value: std::string) = {
if !specified_value.empty() {
value = specified_value;
} else {
v := std::strtoll(value[0]&, nullptr, 10);
value = (v + 1) as std::string;
}
},
false // disable bitwise operations
);
}
//-----------------------------------------------------------------------
//
// "flag_enum expresses an enumeration that stores values
// corresponding to bitwise-or'd enumerators. The enumerators must
// be powers of two, and are automatically generated [...] A none
// value is provided [...] Operators | and & are provided to
// combine and extract values."
//
// -- P0707R4, section 3
//
flag_enum: (inout t: meta::type_declaration) =
{
// Let basic_enum do its thing, with a power-of-two value generator
t.basic_enum(
:(inout value: std::string, specified_value: std::string) = {
if !specified_value.empty() {
value = specified_value;
} else {
v := std::strtoll(value[0]&, nullptr, 10);
if v < 1 {
value = "1";
}
else {
value = (v * 2) as std::string;
}
}
},
true // enable bitwise operations
);
}
//-----------------------------------------------------------------------
//
// "As with void*, programmers should know that unions [...] are
// inherently dangerous, should be avoided wherever possible,
// and should be handled with special care when actually needed."
//
// -- Stroustrup (The Design and Evolution of C++, 14.3.4.1)
//
// "C++17 needs a type-safe union... The implications of the
// consensus `variant` design are well understood and have been
// explored over several LEWG discussions, over a thousand emails,
// a joint LEWG/EWG session, and not to mention 12 years of
// experience with Boost and other libraries."
//
// -- Axel Naumann, in P0088 (wg21.link/p0088),
// the adopted proposal for C++17 std::variant
//
//-----------------------------------------------------------------------
//
// union
//
// a type that contains exactly one of a fixed set of values at a time
//
union: (inout t : meta::type_declaration)
= {
alternatives : std::vector<value_member_info> = ();
// 1. Gather: All the user-written members, and find/compute the max size
(copy value := 0)
for t.get_members()
next value++
do (m)
if m.is_member_object()
{
m.require( m.is_public() || m.is_default_access(),
"a union alternative cannot be protected or private");
m.require( !m.name().starts_with("is_")
&& !m.name().starts_with("set_"),
"a union alternative's name cannot start with 'is_' or 'set_' - that could cause user confusion with the 'is_alternative' and 'set_alternative' generated functions");
mo := m.as_object();
mo.require( mo.initializer().empty(),
"a union alternative cannot have an initializer");
// Adding local variable 'e' to work around a Clang warning
e: value_member_info = ( mo.name() as std::string, mo.type(), value as std::string );
alternatives.push_back( e );
mo.mark_for_removal_from_enclosing_type();
}
discriminator_type: std::string = ();
if alternatives.ssize() < std::numeric_limits<i8>::max() {
discriminator_type = "i8";
}
else if alternatives.ssize() < std::numeric_limits<i16>::max() {
discriminator_type = "i16";
}
else if alternatives.ssize() < std::numeric_limits<i32>::max() {
discriminator_type = "i32";
}
else {
discriminator_type = "i64";
}
// 2. Replace: Erase the contents and replace with modified contents
t.remove_marked_members();
// Provide storage
(copy storage: std::string = " _storage: cpp2::aligned_storage<cpp2::max( ")
{
(copy comma: std::string = "")
for alternatives
next comma = ", "
do (e) {
storage += comma + "sizeof((e.type)$)";
}
storage += "), cpp2::max( ";
(copy comma: std::string = "")
for alternatives
next comma = ", "
do (e) {
storage += comma + "alignof((e.type)$)";
}
storage += " )> = ();\n";
t.add_member( storage );
}
// Provide discriminator
t.add_member( " _discriminator: (discriminator_type)$ = -1;\n");
// Add the alternatives: is_alternative, get_alternative, and set_alternative
for alternatives
do (a)
{
t.add_member( " is_(a.name)$: (this) -> bool = _discriminator == (a.value)$;\n");
t.add_member( " (a.name)$: (this) -> forward (a.type)$ pre(is_(a.name)$()) = reinterpret_cast<* const (a.type)$>(_storage&)*;\n");
t.add_member( " (a.name)$: (inout this) -> forward (a.type)$ pre(is_(a.name)$()) = reinterpret_cast<*(a.type)$>(_storage&)*;\n");
t.add_member( " set_(a.name)$: (inout this, _value: (a.type)$) = { if !is_(a.name)$() { _destroy(); std::construct_at( reinterpret_cast<*(a.type)$>(_storage&), _value); } else { reinterpret_cast<*(a.type)$>(_storage&)* = _value; } _discriminator = (a.value)$; }\n");
t.add_member( " set_(a.name)$: (inout this, forward _args...: _) = { if !is_(a.name)$() { _destroy(); std::construct_at( reinterpret_cast<*(a.type)$>(_storage&), _args...); } else { reinterpret_cast<*(a.type)$>(_storage&)* = :(a.type)$ = (_args...); } _discriminator = (a.value)$; }\n");
}
// Add destroy
(copy destroy: std::string = " private _destroy: (inout this) = {\n")
{
for alternatives
do (a) {
destroy += " if _discriminator == (a.value)$ { std::destroy_at( reinterpret_cast<*(a.type)$>(_storage&) ); }\n";
}
destroy += " _discriminator = -1;\n";
destroy += " }\n";
t.add_member( destroy );
}
// Add the destructor
t.add_member( " operator=: (move this) = { _destroy(); }" );
// Add default constructor
t.add_member( " operator=: (out this) = { }" );
// Add copy/move construction and assignment
(copy value_set: std::string = "")
{
for alternatives
do (a) {
value_set += " if that.is_(a.name)$() { set_(a.name)$( that.(a.name)$() ); }\n";
}
value_set += " }\n";
t.add_member( std::string(" operator=: (out this, that) = {\n")
+ " _storage = ();\n"
+ " _discriminator = -1;\n"
+ value_set
);
t.add_member( std::string(" operator=: (inout this, that) = {\n")
+ " _storage = _;\n"
+ " _discriminator = _;\n"
+ value_set
);
}
}
//-----------------------------------------------------------------------
//
// print - output a pretty-printed visualization of t
//
print: (t: meta::type_declaration) =
{
std::cout << t.print() << "\n";
}
//-----------------------------------------------------------------------
//
// apply_metafunctions
//
apply_metafunctions: (
inout n : declaration_node,
inout rtype : type_declaration,
error
)
-> bool
= {
assert( n.is_type() );
// Check for _names reserved for the metafunction implementation
for rtype.get_members()
do (m)
{
m.require( !m.name().starts_with("_") || m.name().ssize() > 1,
"a type that applies a metafunction cannot have a body that declares a name that starts with '_' - those names are reserved for the metafunction implementation");
}
// For each metafunction, apply it
for n.metafunctions
do (meta)
{
// Convert the name and any template arguments to strings
// and record that in rtype
name := meta*.to_string();
name = name.substr(0, name.find('<'));
args: std::vector<std::string> = ();
for meta*.template_arguments()
do (arg)
args.push_back( arg.to_string() );
rtype.set_metafunction_name( name, args );
// Dispatch
//
if name == "interface" {
interface( rtype );
}
else if name == "polymorphic_base" {
polymorphic_base( rtype );
}
else if name == "ordered" {
ordered( rtype );
}
else if name == "weakly_ordered" {
weakly_ordered( rtype );
}
else if name == "partially_ordered" {
partially_ordered( rtype );
}
else if name == "copyable" {
copyable( rtype );
}
else if name == "basic_value" {
basic_value( rtype );
}
else if name == "value" {
value( rtype );
}
else if name == "weakly_ordered_value" {
weakly_ordered_value( rtype );
}
else if name == "partially_ordered_value" {
partially_ordered_value( rtype );
}
else if name == "struct" {
cpp2_struct( rtype );
}
else if name == "enum" {
cpp2_enum( rtype );
}
else if name == "flag_enum" {
flag_enum( rtype );
}
else if name == "union" {
cpp2_union( rtype );
}
else if name == "print" {
print( rtype );
}
else {
error( "unrecognized metafunction name: " + name );
error( "(temporary alpha limitation) currently the supported names are: interface, polymorphic_base, ordered, weakly_ordered, partially_ordered, copyable, basic_value, value, weakly_ordered_value, partially_ordered_value, struct, enum, flag_enum, union, print" );
return false;
}
if (
!args.empty()
&& !rtype.arguments_were_used()
)
{
error( name + " did not use its template arguments - did you mean to write '" + name + " <" + args[0] + "> type' (with the spaces)?");
return false;
}
}
return true;
}
}
}
|