-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathgentree.cpp
More file actions
2463 lines (2117 loc) · 84.7 KB
/
gentree.cpp
File metadata and controls
2463 lines (2117 loc) · 84.7 KB
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
// Compiler for PHP (aka KPHP)
// Copyright (c) 2020 LLC «V Kontakte»
// Distributed under the GPL v3 License, see LICENSE.notice.txt
#include "compiler/gentree.h"
#include "common/algorithms/contains.h"
#include "common/algorithms/find.h"
#include "common/php-functions.h"
#include "compiler/compiler-core.h"
#include "compiler/data/class-data.h"
#include "compiler/data/define-data.h"
#include "compiler/data/function-data.h"
#include "compiler/data/lib-data.h"
#include "compiler/data/src-file.h"
#include "compiler/data/generics-mixins.h"
#include "compiler/lambda-utils.h"
#include "compiler/lexer.h"
#include "compiler/name-gen.h"
#include "compiler/phpdoc.h"
#include "compiler/stage.h"
#include "compiler/type-hint.h"
#include "compiler/utils/string-utils.h"
#include "compiler/vertex.h"
#include "compiler/vertex-util.h"
#define CE(x) if (!(x)) {return {};}
GenTree::GenTree(std::vector<Token> tokens, SrcFilePtr file, DataStream<FunctionPtr> &os) :
tokens(std::move(tokens)),
parsed_os(os),
cur(this->tokens.begin()),
end(this->tokens.end()),
processing_file(file) { // = stage::get_file()
kphp_assert (cur != end);
end--;
kphp_assert (end->type() == tok_end);
line_num = cur->line_num;
stage::set_line(line_num);
}
void GenTree::next_cur() {
if (cur != end) {
cur++;
if (cur->line_num != -1) {
line_num = cur->line_num;
stage::set_line(line_num);
}
}
}
#define expect_msg(msg) ({ \
fmt_format ("Expected {}, found '{}'", msg, cur == end ? "END OF FILE" : cur->to_str().c_str()); \
})
#define expect(tp, msg) ({ \
bool res__;\
if (kphp_error (test_expect (tp), expect_msg(msg))) {\
res__ = false;\
} else {\
next_cur();\
res__ = true;\
}\
res__; \
})
#define expect2(tp1, tp2, msg) ({ \
kphp_error (test_expect (tp1) || test_expect (tp2), expect_msg(msg)); \
if (cur != end) {next_cur();} \
1;\
})
VertexAdaptor<op_var> GenTree::get_var_name() {
auto location = auto_location();
if (cur->type() != tok_var_name) {
return {};
}
auto var = VertexAdaptor<op_var>::create();
var->str_val = static_cast<std::string>(cur->str_val);
next_cur();
return var.set_location(location);
}
VertexPtr GenTree::get_foreach_value() {
if (cur->type() == tok_list) {
return get_func_call<op_list_ce, op_lvalue_null>();
}
if (cur->type() == tok_opbrk) {
return get_short_array();
}
return get_var_name_ref();
}
VertexAdaptor<op_var> GenTree::get_function_use_var_name_ref() {
auto result = get_var_name_ref();
kphp_error(result, fmt_format("function use list: expected varname, found {}", cur->str_val));
kphp_error(!result->ref_flag, "references to variables in `use` block are forbidden in lambdas");
return result;
}
VertexAdaptor<op_var> GenTree::get_var_name_ref() {
bool ref_flag = false;
if (cur->type() == tok_and) {
next_cur();
ref_flag = true;
}
auto name = get_var_name();
if (name) {
name->ref_flag = ref_flag;
}
return name;
}
int GenTree::open_parent() {
if (cur->type() == tok_oppar) {
next_cur();
return 1;
}
return 0;
}
inline void GenTree::skip_phpdoc_tokens() {
// consider the phpdocs in unexpected locations like array or return to be an ordinary comment
// (usually such phpdocs contain @see or some text, they don't have @var annotations)
while (cur->type() == tok_phpdoc) {
//kphp_error(cur->str_val.find("@var") == std::string::npos, "@var would not be analyzed");
next_cur();
}
// phpdoc comments that need to be analyzed don't come here: see op_phpdoc_var
}
template<Operation EmptyOp, class FuncT, class ResultType>
bool GenTree::gen_list(std::vector<ResultType> *res, FuncT f, TokenType delim) {
//Do not clear res. Result must be appended to it.
bool prev_delim = false;
bool next_delim = true;
while (next_delim) {
ResultType v = (this->*f)();
next_delim = cur->type() == delim;
if (!v) {
if (EmptyOp != op_err && (prev_delim || next_delim)) {
if (EmptyOp == op_none) {
break;
}
if constexpr (EmptyOp != op_none && EmptyOp != op_err) {
v = VertexAdaptor<EmptyOp>::create();
}
} else if (prev_delim) {
// TODO: do not emit this error for funcs like var_name_ref() as
// they return falsy vertex in case of the parse failure.
// If we give "expecting something after ," error it will be
// misleading as there might be something after a comma,
// we just happen to get a failed parsing.
kphp_error(0, "Expected something after ','");
return false;
} else {
break;
}
}
res->push_back(v);
prev_delim = true;
if (next_delim) {
next_cur();
}
}
if (EmptyOp == op_lvalue_null && !res->empty() && res->back()->type() == op_lvalue_null) {
res->pop_back();
}
return true;
}
template<Operation Op>
VertexAdaptor<Op> GenTree::get_conv() {
auto location = auto_location();
next_cur();
VertexPtr converted_expression = get_expression();
CE (!kphp_error(converted_expression, "get_conv failed"));
return VertexAdaptor<Op>::create(converted_expression).set_location(location);
}
VertexAdaptor<op_require> GenTree::get_require(bool once) {
auto location = auto_location();
next_cur();
const bool is_opened = open_parent();
auto require = VertexAdaptor<op_require>::create(GenTree::get_expression());
require->once = once;
require->builtin = processing_file->is_from_functions_file;
if (is_opened) {
CE(expect(tok_clpar, "')'"));
}
return require.set_location(location);
}
template<Operation Op, Operation EmptyOp>
VertexAdaptor<Op> GenTree::get_func_call() {
auto location = auto_location();
std::string name{cur->str_val};
next_cur();
GenericsInstantiationPhpComment *commentTs{nullptr};
if constexpr (Op == op_func_call) {
if (test_expect(tok_commentTs)) { // f/*<...>*/(args)
commentTs = parse_php_commentTs(cur->str_val);
next_cur();
}
}
CE (expect(tok_oppar, "'('"));
skip_phpdoc_tokens();
std::vector<VertexPtr> next;
bool ok_next = gen_list<EmptyOp>(&next, &GenTree::get_expression, tok_comma);
CE (!kphp_error(ok_next, "get argument list failed"));
CE (expect(tok_clpar, "')'"));
auto call = VertexAdaptor<Op>::create_vararg(next).set_location(location);
if (call->has_get_string()) {
call->set_string(name);
}
if constexpr (Op == op_func_call) {
if (commentTs != nullptr) {
call->reifiedTs = new GenericsInstantiationMixin(call->location);
call->reifiedTs->commentTs = commentTs;
cur_function->has_commentTs_inside = true;
}
}
return call;
}
VertexAdaptor<op_array> GenTree::get_short_array() {
auto location = auto_location();
next_cur();
std::vector<VertexPtr> arr_elements;
bool ok_next = gen_list<op_lvalue_null>(&arr_elements, &GenTree::get_expression, tok_comma);
CE (!kphp_error(ok_next, "get short array failed"));
CE (expect(tok_clbrk, "']'"));
return VertexAdaptor<op_array>::create(arr_elements).set_location(location);
}
VertexAdaptor<op_string> GenTree::get_string() {
auto str = VertexAdaptor<op_string>::create().set_location(auto_location());
str->str_val = static_cast<std::string>(cur->str_val);
next_cur();
return str;
}
VertexAdaptor<op_string_build> GenTree::get_string_build() {
auto sb_location = auto_location();
next_cur();
std::vector<VertexPtr> strings;
bool after_simple_expression = false;
while (cur != end && cur->type() != tok_str_end) {
CE (vk::any_of_equal(cur->type(), tok_str, tok_expr_begin)); // make sure we handle all possible tokens
if (cur->type() == tok_str) {
strings.push_back(get_string());
if (after_simple_expression) {
auto last = strings.back().as<op_string>();
if (!last->str_val.empty() && last->str_val[0] == '[') {
kphp_warning("Simple string expressions with [] can work wrong. Use more {}");
}
}
after_simple_expression = false;
} else if (cur->type() == tok_expr_begin) {
// simple expressions produce artificial tok_expr_begin/tok_expr_end without
// having associated '{' and '}' inside the source code
after_simple_expression = cur->debug_str.empty();
next_cur();
VertexPtr add = get_expression();
CE (!kphp_error(add, "Bad expression in string"));
strings.push_back(add);
CE (expect(tok_expr_end, "'}'"));
}
}
CE (expect(tok_str_end, "'\"'"));
return VertexAdaptor<op_string_build>::create(strings).set_location(sb_location);
}
VertexPtr GenTree::get_postfix_expression(VertexPtr res, bool parenthesized) {
//postfix operators x++, x--, x[] and x{}, x->y, x()
bool need = true;
while (need && cur != end) {
auto op = cur;
TokenType tp = op->type();
need = false;
if (tp == tok_inc) {
auto v = VertexAdaptor<op_postfix_inc>::create(res).set_location(auto_location());
res = v;
need = true;
next_cur();
CE (!kphp_error(!parenthesized, "Expected variable, found parenthesized expression"));
} else if (tp == tok_dec) {
auto v = VertexAdaptor<op_postfix_dec>::create(res).set_location(auto_location());
res = v;
need = true;
next_cur();
CE (!kphp_error(!parenthesized, "Expected variable, found parenthesized expression"));
} else if (tp == tok_opbrk || tp == tok_opbrc) {
auto location = auto_location();
next_cur();
VertexPtr i = get_expression();
if (tp == tok_opbrk) {
CE (expect(tok_clbrk, "']'"));
} else {
CE (expect(tok_clbrc, "'}'"));
}
//TODO: it should be to separate operations
if (!i) {
auto v = VertexAdaptor<op_index>::create(res);
res = v;
} else {
auto v = VertexAdaptor<op_index>::create(res, i);
res = v;
}
res.set_location(location);
need = true;
} else if (tp == tok_arrow) {
auto location = auto_location();
next_cur();
VertexPtr rhs = get_expr_top(true);
CE (!kphp_error(rhs, "Failed to parse right argument of '->'"));
res = process_arrow(res, rhs);
CE(res);
res.set_location(location);
need = true;
} else if (tp == tok_oppar) {
auto location = auto_location();
next_cur();
skip_phpdoc_tokens();
std::vector<VertexPtr> next;
next.emplace_back(res);
bool ok_next = gen_list<op_none>(&next, &GenTree::get_expression, tok_comma);
CE (!kphp_error(ok_next, "get argument list failed"));
CE (expect(tok_clpar, "')'"));
res = VertexAdaptor<op_invoke_call>::create(next).set_location(location);
need = true;
}
}
return res;
}
void GenTree::check_and_remove_num_separators(std::string &s) {
bool was_separator = false;
for (const char &c : s) {
if (c == '_') {
if (was_separator) {
kphp_error_return(false, "Bad numeric constant, several '_' in a row are prohibited");
}
was_separator = true;
} else {
was_separator = false;
}
}
// if all ok
s.erase(std::remove_if(s.begin(), s.end(), [](char symbol) { return symbol == '_'; }), s.end());
}
VertexPtr GenTree::get_op_num_const() {
auto get_vertex_with_str_val = [this] (auto vertex, std::string val) {
auto res = decltype(vertex)::create();
res.set_location(auto_location());
res->str_val = std::move(val);
return res;
};
if (cur->type() == tok_int_const) {
return get_vertex_with_str_val(VertexAdaptor<op_int_const>{}, static_cast<std::string>(cur->str_val));
}
if (cur->type() == tok_float_const) {
return get_vertex_with_str_val(VertexAdaptor<op_float_const>{}, static_cast<std::string>(cur->str_val));
}
if (cur->type() == tok_int_const_sep) {
std::string val = static_cast<std::string>(cur->str_val);
check_and_remove_num_separators(val);
return get_vertex_with_str_val(VertexAdaptor<op_int_const>{}, val);
}
if (cur->type() == tok_float_const_sep) {
std::string val = static_cast<std::string>(cur->str_val);
check_and_remove_num_separators(val);
return get_vertex_with_str_val(VertexAdaptor<op_float_const>{}, val);
}
return VertexPtr{};
}
VertexPtr GenTree::get_expr_top(bool was_arrow, const PhpDocComment *phpdoc) {
auto op = cur;
VertexPtr res, first_node;
TokenType type = op->type();
auto get_vertex_with_str_val = [this] (auto vertex, std::string val) {
auto res = decltype(vertex)::create();
res.set_location(auto_location());
res->str_val = std::move(val);
return res;
};
bool return_flag = true; // whether to stop parsing without trying to parse expr as postfix expr
bool parenthesized = false;
switch (type) {
case tok_line_c: {
res = get_vertex_with_str_val(VertexAdaptor<op_int_const>{}, std::to_string(stage::get_line()));
next_cur();
break;
}
case tok_file_c: {
res = get_vertex_with_str_val(VertexAdaptor<op_string>{}, processing_file->file_name);
next_cur();
break;
}
case tok_file_relative_c: {
res = get_vertex_with_str_val(VertexAdaptor<op_string>{}, processing_file->relative_file_name);
next_cur();
break;
}
case tok_class_c: {
res = get_vertex_with_str_val(VertexAdaptor<op_string>{}, cur_class ? cur_class->name : "");
next_cur();
break;
}
case tok_dir_c: {
res = get_vertex_with_str_val(VertexAdaptor<op_string>{}, processing_file->file_name.substr(0, processing_file->file_name.rfind('/')));
next_cur();
break;
}
case tok_method_c: {
std::string fun_name;
if (cur_function->is_lambda()) {
fun_name = "{closure}";
} else if (!cur_function->is_main_function()) {
fun_name = cur_class
? cur_class->name + "::" + cur_function->name.substr(cur_function->name.rfind('$') + 1)
: cur_function->name;
}
res = get_vertex_with_str_val(VertexAdaptor<op_string>{}, fun_name);
next_cur();
break;
}
case tok_namespace_c: {
res = get_vertex_with_str_val(VertexAdaptor<op_string>{}, processing_file->namespace_name);
next_cur();
break;
}
case tok_func_c: {
std::string fun_name;
if (cur_function->is_lambda()) {
fun_name = "{closure}";
} else if (!cur_function->is_main_function()) {
fun_name = cur_function->name.substr(cur_function->name.rfind('$') + 1);
}
res = get_vertex_with_str_val(VertexAdaptor<op_string>{}, fun_name);
next_cur();
break;
}
case tok_int_const_sep: {
res = get_op_num_const();
next_cur();
break;
}
case tok_int_const: {
res = get_op_num_const();
next_cur();
break;
}
case tok_nan: {
res = get_vertex_with_str_val(VertexAdaptor<op_float_const>{}, "NAN");
next_cur();
break;
}
case tok_inf: {
res = get_vertex_with_str_val(VertexAdaptor<op_float_const>{}, "std::numeric_limits<double>::infinity()");
next_cur();
break;
}
case tok_float_const_sep: {
res = get_op_num_const();
next_cur();
break;
}
case tok_float_const: {
res = get_op_num_const();
next_cur();
break;
}
case tok_null: {
res = VertexAdaptor<op_null>::create().set_location(auto_location());
next_cur();
break;
}
case tok_false: {
res = VertexAdaptor<op_false>::create().set_location(auto_location());
next_cur();
break;
}
case tok_true: {
res = VertexAdaptor<op_true>::create().set_location(auto_location());
next_cur();
break;
}
case tok_var_name: {
res = get_var_name();
if (cur->type() == tok_double_colon) { // $class::method(), $class::$field, $class::CONST
res = get_member_by_name_after_var(res.as<op_var>());
}
return_flag = false;
break;
}
case tok_varg: {
auto prev_tok_type = std::prev(cur)->type();
bool good_prefix = cur != tokens.begin() && vk::any_of_equal(prev_tok_type, tok_comma, tok_oppar, tok_opbrk);
CE (!kphp_error(good_prefix, "It's not allowed using `...` in this place"));
next_cur();
auto next_tok_type = cur->type(); // next relative to tok_varg
res = get_expression();
// since the argument for the spread operator can be anything,
// we do not check the type of the expression here
if (res) {
res = VertexAdaptor<op_varg>::create(res).set_location(res);
} else {
if (prev_tok_type == tok_oppar && next_tok_type == tok_clpar) { // f(...) - only this syntax is possible
res = VertexAdaptor<op_ellipsis>::create();
kphp_error(0, "First class callable syntax is not supported");
} else {
kphp_error(0, "Сan not parse first class callable syntax");
}
}
break;
}
case tok_str:
res = get_string();
return_flag = false; // string is a valid postfix expr operand
break;
case tok_conv_int:
res = get_conv<op_conv_int>();
break;
case tok_conv_bool:
res = get_conv<op_conv_bool>();
break;
case tok_conv_float:
res = get_conv<op_conv_float>();
break;
case tok_conv_string:
res = get_conv<op_conv_string>();
break;
case tok_conv_array:
res = get_conv<op_conv_array>();
break;
case tok_print: {
auto location = auto_location();
next_cur();
first_node = get_expression();
CE (!kphp_error(first_node, "Failed to get print argument"));
auto print = VertexAdaptor<op_func_call>::create(first_node).set_location(location);
print->str_val = "print";
res = print;
break;
}
case tok_require:
res = get_require(false);
break;
case tok_require_once:
res = get_require(true);
break;
case tok_new: {
next_cur();
if (test_expect(tok_func_name)) { // 'new A()' / 'new \Some\Class($args)'
auto func_call = get_func_call<op_func_call, op_none>();
// Hack to be more compatible with php
if (func_call->str_val == "Memcache") {
func_call->set_string("McMemcache");
}
res = gen_constructor_call_with_args(func_call->str_val, func_call->get_next(), func_call->location);
CE(res);
} else if (test_expect(tok_var_name)) { // 'new $class_name' / 'new $class_name(...$args)'
res = get_by_name_construct();
CE(res);
} else {
CE(!kphp_error(0, "Expected class name after new"));
}
break;
}
case tok_func_name: {
cur++;
if (!test_expect(tok_oppar) && !test_expect(tok_commentTs)) {
if (!was_arrow && vk::any_of_equal(op->str_val, "die", "exit")) { // can be called without "()"
res = get_vertex_with_str_val(VertexAdaptor<op_func_call>{}, static_cast<std::string>(op->str_val));
} else {
res = get_vertex_with_str_val(VertexAdaptor<op_func_name>{}, static_cast<std::string>(op->str_val));
}
return_flag = was_arrow;
break;
}
cur--;
// we don't support namespaces for functions yet, but we
// permit \func() syntax and interpret it as func();
// this logic is compatible with what we'll get after the
// function namespaces will be implemented
auto func_call = get_func_call<op_func_call, op_none>();
if (func_call && func_call->str_val[0] == '\\' && !vk::contains(func_call->str_val, "::")) {
func_call->str_val.erase(0, 1);
}
res = func_call;
return_flag = was_arrow;
break;
}
case tok_yield: {
next_cur();
res = get_yield();
kphp_error(false, "yield isn't supported");
break;
}
case tok_static:
next_cur();
res = get_lambda_function(phpdoc, FunctionModifiers::static_lambda());
break;
case tok_function:
case tok_fn:
res = get_lambda_function(phpdoc, FunctionModifiers::nonmember());
break;
case tok_phpdoc: { // /** ... */ before expression (not before a statement)
vk::string_view phpdoc_str = cur->str_val;
next_cur();
return get_expr_top(was_arrow, new PhpDocComment(phpdoc_str));
}
case tok_isset: {
auto temp = get_multi_call<op_isset, op_none>(&GenTree::get_expression, true);
CE (!kphp_error(temp->size(), "isset function requires at least one argument"));
res = VertexPtr{};
for (auto right : temp->args()) {
res = res ? VertexPtr(VertexAdaptor<op_log_and>::create(res, right)) : right;
}
res.set_location(temp->location);
break;
}
case tok_declare:
// see GenTree::parse_declare_at_top_of_file
kphp_error(0, "strict_types declaration must be the very first statement in the script");
break;
case tok_array:
res = get_func_call<op_array, op_none>();
return_flag = false; // array is valid postfix expression operand
break;
case tok_tuple:
res = get_func_call<op_tuple, op_none>();
CE (!kphp_error(res.as<op_tuple>()->size(), "tuple() must have at least one argument"));
break;
case tok_shape:
res = get_shape();
break;
case tok_opbrk:
res = get_short_array();
return_flag = false; // array is valid postfix expression operand
break;
case tok_list:
res = get_func_call<op_list_ce, op_lvalue_null>();
break;
case tok_defined:
res = get_func_call<op_defined, op_err>();
break;
case tok_oppar:
next_cur();
res = get_expression();
CE (!kphp_error(res, "Failed to parse expression after '('"));
CE (expect(tok_clpar, "')'"));
return_flag = false; // expression inside '()' is valid postfix expression operand
parenthesized = true;
break;
case tok_str_begin:
res = get_string_build();
break;
case tok_clone: {
next_cur();
res = VertexAdaptor<op_clone>::create(get_expr_top(false)).set_location(auto_location());
break;
}
case tok_throw: {
auto location = auto_location();
next_cur();
auto throw_expr = get_expression();
CE (!kphp_error(throw_expr, "Empty expression in throw"));
res = VertexAdaptor<op_throw>::create(throw_expr).set_location(location);
break;
}
default:
return {};
}
if (return_flag) {
return res;
}
return get_postfix_expression(res, parenthesized);
}
VertexAdaptor<op_ternary> GenTree::create_ternary_op_vertex(VertexPtr condition, VertexPtr true_expr, VertexPtr false_expr) {
if (true_expr) {
return VertexAdaptor<op_ternary>::create(condition, true_expr, false_expr);
}
auto cond_var = VertexUtil::create_superlocal_var("shorthand_ternary_cond", cur_function).set_location(condition);
auto cond = VertexUtil::create_conv_to(tp_bool, VertexAdaptor<op_set>::create(cond_var, condition));
auto left_var_move = VertexAdaptor<op_move>::create(cond_var.clone());
return VertexAdaptor<op_ternary>::create(cond, left_var_move, false_expr);
}
VertexPtr GenTree::get_unary_op(int op_priority_cur, Operation unary_op_tp, bool till_ternary) {
auto location = auto_location();
next_cur();
VertexPtr left = get_binary_op(op_priority_cur, till_ternary);
if (!left) {
return {};
}
if (unary_op_tp == op_log_not) {
left = VertexUtil::create_conv_to(tp_bool, left);
}
if (unary_op_tp == op_not) {
left = VertexUtil::create_conv_to(tp_int, left);
}
VertexPtr expr = create_vertex(unary_op_tp, left).set_location(location);
if (expr->type() == op_minus || expr->type() == op_plus) {
VertexPtr maybe_num = expr.as<meta_op_unary>()->expr();
if (auto num = maybe_num.try_as<meta_op_num>()) {
// keep the +N as is, but turn -N into a constant (but if N starts with minus, then make it "N" so we can parse `- - -7`)
if (expr->type() == op_minus) {
num->str_val = num->str_val[0] == '-' ? num->str_val.substr(1) : "-" + num->str_val;
}
return num;
}
}
return expr;
}
TokenType transform_compare_operation_token(TokenType token) noexcept {
switch (token) {
case tok_gt:
return tok_lt;
case tok_ge:
return tok_le;
case tok_neq_lg:
case tok_neq2:
return tok_eq2;
case tok_neq3:
return tok_eq3;
default:
return token;
}
}
VertexPtr GenTree::get_binary_op(int op_priority_cur, bool till_ternary) {
if (op_priority_cur >= OpInfo::op_priority_end) {
return get_expr_top(false);
}
if (cur != end) {
const Operation unary_op_tp = OpInfo::tok_to_unary_op[cur->type()];
if (unary_op_tp != op_err && OpInfo::priority(unary_op_tp) <= op_priority_cur) {
return get_unary_op(op_priority_cur, unary_op_tp, till_ternary);
}
}
const bool ternary = op_priority_cur == OpInfo::ternaryP;
VertexPtr left = get_binary_op(op_priority_cur + 1, till_ternary);
if (!left || (ternary && till_ternary)) {
return left;
}
while (cur != end) {
const TokenType origin_token = cur->type();
const TokenType token = transform_compare_operation_token(origin_token);
const Operation binary_op_tp = OpInfo::tok_to_binary_op[token];
if (binary_op_tp == op_err || OpInfo::priority(binary_op_tp) != op_priority_cur) {
break;
}
auto expr_location = auto_location();
const bool left_to_right = OpInfo::fixity(binary_op_tp) == left_opp;
next_cur();
VertexPtr right = ternary
? get_expression()
: get_binary_op(op_priority_cur + left_to_right,
till_ternary && op_priority_cur >= OpInfo::ternaryP);
if (!right && !ternary) {
kphp_error (0, fmt_format("Failed to parse second argument in [{}]", OpInfo::str(binary_op_tp)));
return {};
}
VertexPtr third;
if (ternary) {
CE (expect(tok_colon, "':'"));
third = get_expression_impl(true);
if (!third) {
kphp_error (0, fmt_format("Failed to parse third argument in [{}]", OpInfo::str(binary_op_tp)));
return {};
}
if (right) {
left = VertexUtil::create_conv_to(tp_bool, left);
}
}
if (vk::any_of_equal(binary_op_tp, op_log_or, op_log_and, op_log_or_let, op_log_and_let, op_log_xor_let)) {
left = VertexUtil::create_conv_to(tp_bool, left);
right = VertexUtil::create_conv_to(tp_bool, right);
}
if (vk::any_of_equal(binary_op_tp, op_set_or, op_set_and, op_set_xor, op_set_shl, op_set_shr)) {
right = VertexUtil::create_conv_to(tp_int, right);
}
if (vk::any_of_equal(binary_op_tp, op_or, op_and, op_xor)) {
left = VertexUtil::create_conv_to(tp_int, left);
right = VertexUtil::create_conv_to(tp_int, right);
}
if (vk::any_of_equal(origin_token, tok_gt, tok_ge)) {
std::swap(left, right);
}
if (ternary) {
left = create_ternary_op_vertex(left, right, third);
} else {
left = create_vertex(binary_op_tp, left, right);
}
left.set_location(expr_location);
if (vk::any_of_equal(origin_token, tok_neq2, tok_neq_lg, tok_neq3)) {
left = VertexAdaptor<op_log_not>::create(left).set_location(expr_location);
}
if (!(left_to_right || ternary)) {
break;
}
}
return left;
}
VertexPtr GenTree::get_expression_impl(bool till_ternary) {
return get_binary_op(OpInfo::op_priority_begin, till_ternary);
}
VertexPtr GenTree::get_expression() {
skip_phpdoc_tokens();
return get_expression_impl(false);
}
VertexPtr GenTree::get_def_value() {
VertexPtr val;
if (cur->type() == tok_eq1) {
next_cur();
val = get_expression();
kphp_error (val, "Cannot parse function parameter");
}
return val;
}
VertexAdaptor<op_func_param> GenTree::get_func_param() {
auto location = auto_location();
const TypeHint *type_hint = get_typehint();
bool is_varg = false;
// if the argument is vararg and has a type hint — e.g. int ...$a — then cur points to $a, as ... were consumed by the type lexer
if (type_hint && std::prev(cur, 1)->type() == tok_varg) {
is_varg = true;
} else if (test_expect(tok_varg)) {
next_cur();
is_varg = true;
}
if (is_varg) {
kphp_error(!cur_function->has_variadic_param, "Function can not have ...$variadic more than once");
cur_function->has_variadic_param = true;
}
VertexAdaptor<op_var> name = get_var_name_ref();
if (!name) {
kphp_error(!type_hint, "Syntax error: missing varname after typehint");
return {};
}
bool is_cast_param = false;
if (cur->type() == tok_triple_colon) { // $x ::: string — a cast param
is_cast_param = true;
next_cur();
type_hint = get_typehint();
}
VertexPtr def_val = get_def_value();
VertexAdaptor<op_func_param> v;
if (def_val) {
kphp_error(!is_varg, "Variadic argument can not have a default value");
v = VertexAdaptor<op_func_param>::create(name, def_val).set_location(location);
} else {
v = VertexAdaptor<op_func_param>::create(name).set_location(location);
}
if (is_varg) {
v->extra_type = op_ex_param_variadic;
}
if (type_hint) {
// if "T $a = null" (default argument null), then type of $a is ?T (strange, but PHP works this way)
if (def_val && def_val->type() == op_null) {
type_hint = TypeHintOptional::create(type_hint, true, false);
}
v->type_hint = type_hint;
}
v->is_cast_param = is_cast_param;
return v;
}
std::pair<VertexAdaptor<op_foreach_param>, VertexPtr> GenTree::get_foreach_param() {
auto location = auto_location();
VertexPtr array_expression = get_expression();
CE (!kphp_error(array_expression, ""));
CE (expect(tok_as, "'as'"));
skip_phpdoc_tokens();
VertexAdaptor<op_var> key;
VertexAdaptor<op_var> value;
VertexPtr value_expr = get_foreach_value();
VertexPtr list;
// This error message is given for both key/value parts
// as we can't easily distinguish $k=>$v from just $v if
// get_var_name_ref failed to parse a variable.
auto tok = *cur;
CE (!kphp_error(value_expr, fmt_format("Expected a var name, ref or list, found {}", tok.str_val)));
if (vk::any_of_equal(value_expr->type(), op_list_ce, op_array)) {
value = VertexUtil::create_superlocal_var("list", cur_function);
list = value_expr;
} else {
value = value_expr.as<op_var>();
}
if (cur->type() == tok_double_arrow) {
next_cur();
key = value;
tok = *cur;
value = get_var_name_ref();
CE (!kphp_error(value, fmt_format("Expected a var name, ref or list as a foreach value, found {}", tok.str_val)));
}
VertexPtr temp_var;
if (value->ref_flag) {
temp_var = VertexAdaptor<op_empty>::create();
} else {
temp_var = VertexUtil::create_superlocal_var("tmp_expr", cur_function);
}
auto param = key ? VertexAdaptor<op_foreach_param>::create(array_expression, value, temp_var, key).set_location(location)
: VertexAdaptor<op_foreach_param>::create(array_expression, value, temp_var).set_location(location);
return {param, list};
}
VertexPtr GenTree::get_call_arg_for_param(VertexAdaptor<op_func_call> call, VertexAdaptor<op_func_param> param, int param_i) {
if (param_i < call->args().size()) {
return call->args()[param_i];
}