forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 334
/
Copy pathexpression.cpp
5058 lines (4839 loc) · 192 KB
/
expression.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
//===-- lib/Semantics/expression.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "flang/Semantics/expression.h"
#include "check-call.h"
#include "pointer-assignment.h"
#include "resolve-names-utils.h"
#include "resolve-names.h"
#include "flang/Common/idioms.h"
#include "flang/Common/type-kinds.h"
#include "flang/Evaluate/common.h"
#include "flang/Evaluate/fold.h"
#include "flang/Evaluate/tools.h"
#include "flang/Parser/characters.h"
#include "flang/Parser/dump-parse-tree.h"
#include "flang/Parser/parse-tree-visitor.h"
#include "flang/Parser/parse-tree.h"
#include "flang/Semantics/scope.h"
#include "flang/Semantics/semantics.h"
#include "flang/Semantics/symbol.h"
#include "flang/Semantics/tools.h"
#include "flang/Support/Fortran.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <functional>
#include <optional>
#include <set>
#include <vector>
// Typedef for optional generic expressions (ubiquitous in this file)
using MaybeExpr =
std::optional<Fortran::evaluate::Expr<Fortran::evaluate::SomeType>>;
// Much of the code that implements semantic analysis of expressions is
// tightly coupled with their typed representations in lib/Evaluate,
// and appears here in namespace Fortran::evaluate for convenience.
namespace Fortran::evaluate {
using common::LanguageFeature;
using common::NumericOperator;
using common::TypeCategory;
static inline std::string ToUpperCase(std::string_view str) {
return parser::ToUpperCaseLetters(str);
}
struct DynamicTypeWithLength : public DynamicType {
explicit DynamicTypeWithLength(const DynamicType &t) : DynamicType{t} {}
std::optional<Expr<SubscriptInteger>> LEN() const;
std::optional<Expr<SubscriptInteger>> length;
};
std::optional<Expr<SubscriptInteger>> DynamicTypeWithLength::LEN() const {
if (length) {
return length;
} else {
return GetCharLength();
}
}
static std::optional<DynamicTypeWithLength> AnalyzeTypeSpec(
const std::optional<parser::TypeSpec> &spec, FoldingContext &context) {
if (spec) {
if (const semantics::DeclTypeSpec *typeSpec{spec->declTypeSpec}) {
// Name resolution sets TypeSpec::declTypeSpec only when it's valid
// (viz., an intrinsic type with valid known kind or a non-polymorphic
// & non-ABSTRACT derived type).
if (const semantics::IntrinsicTypeSpec *intrinsic{
typeSpec->AsIntrinsic()}) {
TypeCategory category{intrinsic->category()};
if (auto optKind{ToInt64(intrinsic->kind())}) {
int kind{static_cast<int>(*optKind)};
if (category == TypeCategory::Character) {
const semantics::CharacterTypeSpec &cts{
typeSpec->characterTypeSpec()};
const semantics::ParamValue &len{cts.length()};
if (len.isAssumed() || len.isDeferred()) {
context.messages().Say(
"A length specifier of '*' or ':' may not appear in the type of an array constructor"_err_en_US);
}
DynamicTypeWithLength type{DynamicType{kind, len}};
if (auto lenExpr{type.LEN()}) {
type.length = Fold(context,
AsExpr(Extremum<SubscriptInteger>{Ordering::Greater,
Expr<SubscriptInteger>{0}, std::move(*lenExpr)}));
}
return type;
} else {
return DynamicTypeWithLength{DynamicType{category, kind}};
}
}
} else if (const semantics::DerivedTypeSpec *derived{
typeSpec->AsDerived()}) {
return DynamicTypeWithLength{DynamicType{*derived}};
}
}
}
return std::nullopt;
}
// Utilities to set a source location, if we have one, on an actual argument,
// when it is statically present.
static void SetArgSourceLocation(ActualArgument &x, parser::CharBlock at) {
x.set_sourceLocation(at);
}
static void SetArgSourceLocation(
std::optional<ActualArgument> &x, parser::CharBlock at) {
if (x) {
x->set_sourceLocation(at);
}
}
static void SetArgSourceLocation(
std::optional<ActualArgument> &x, std::optional<parser::CharBlock> at) {
if (x && at) {
x->set_sourceLocation(*at);
}
}
class ArgumentAnalyzer {
public:
explicit ArgumentAnalyzer(ExpressionAnalyzer &context)
: context_{context}, source_{context.GetContextualMessages().at()},
isProcedureCall_{false} {}
ArgumentAnalyzer(ExpressionAnalyzer &context, parser::CharBlock source,
bool isProcedureCall = false)
: context_{context}, source_{source}, isProcedureCall_{isProcedureCall} {}
bool fatalErrors() const { return fatalErrors_; }
ActualArguments &&GetActuals() {
CHECK(!fatalErrors_);
return std::move(actuals_);
}
const Expr<SomeType> &GetExpr(std::size_t i) const {
return DEREF(actuals_.at(i).value().UnwrapExpr());
}
Expr<SomeType> &&MoveExpr(std::size_t i) {
return std::move(DEREF(actuals_.at(i).value().UnwrapExpr()));
}
void Analyze(const common::Indirection<parser::Expr> &x) {
Analyze(x.value());
}
void Analyze(const parser::Expr &x) {
actuals_.emplace_back(AnalyzeExpr(x));
SetArgSourceLocation(actuals_.back(), x.source);
fatalErrors_ |= !actuals_.back();
}
void Analyze(const parser::Variable &);
void Analyze(const parser::ActualArgSpec &, bool isSubroutine);
void ConvertBOZ(std::optional<DynamicType> *thisType, std::size_t,
std::optional<DynamicType> otherType);
bool IsIntrinsicRelational(
RelationalOperator, const DynamicType &, const DynamicType &) const;
bool IsIntrinsicLogical() const;
bool IsIntrinsicNumeric(NumericOperator) const;
bool IsIntrinsicConcat() const;
bool CheckConformance();
bool CheckAssignmentConformance();
bool CheckForNullPointer(const char *where = "as an operand here");
bool CheckForAssumedRank(const char *where = "as an operand here");
// Find and return a user-defined operator or report an error.
// The provided message is used if there is no such operator.
// If a definedOpSymbolPtr is provided, the caller must check
// for its accessibility.
MaybeExpr TryDefinedOp(
const char *, parser::MessageFixedText, bool isUserOp = false);
template <typename E>
MaybeExpr TryDefinedOp(E opr, parser::MessageFixedText msg) {
return TryDefinedOp(
context_.context().languageFeatures().GetNames(opr), msg);
}
// Find and return a user-defined assignment
std::optional<ProcedureRef> TryDefinedAssignment();
std::optional<ProcedureRef> GetDefinedAssignmentProc();
std::optional<DynamicType> GetType(std::size_t) const;
void Dump(llvm::raw_ostream &);
private:
MaybeExpr TryDefinedOp(
const std::vector<const char *> &, parser::MessageFixedText);
MaybeExpr TryBoundOp(const Symbol &, int passIndex);
std::optional<ActualArgument> AnalyzeExpr(const parser::Expr &);
std::optional<ActualArgument> AnalyzeVariable(const parser::Variable &);
MaybeExpr AnalyzeExprOrWholeAssumedSizeArray(const parser::Expr &);
bool AreConformable() const;
const Symbol *FindBoundOp(parser::CharBlock, int passIndex,
const Symbol *&generic, bool isSubroutine);
void AddAssignmentConversion(
const DynamicType &lhsType, const DynamicType &rhsType);
bool OkLogicalIntegerAssignment(TypeCategory lhs, TypeCategory rhs);
int GetRank(std::size_t) const;
bool IsBOZLiteral(std::size_t i) const {
return evaluate::IsBOZLiteral(GetExpr(i));
}
void SayNoMatch(const std::string &, bool isAssignment = false);
std::string TypeAsFortran(std::size_t);
bool AnyUntypedOrMissingOperand();
ExpressionAnalyzer &context_;
ActualArguments actuals_;
parser::CharBlock source_;
bool fatalErrors_{false};
const bool isProcedureCall_; // false for user-defined op or assignment
};
// Wraps a data reference in a typed Designator<>, and a procedure
// or procedure pointer reference in a ProcedureDesignator.
MaybeExpr ExpressionAnalyzer::Designate(DataRef &&ref) {
const Symbol &last{ref.GetLastSymbol()};
const Symbol &specific{BypassGeneric(last)};
const Symbol &symbol{specific.GetUltimate()};
if (semantics::IsProcedure(symbol)) {
if (symbol.attrs().test(semantics::Attr::ABSTRACT)) {
Say("Abstract procedure interface '%s' may not be used as a designator"_err_en_US,
last.name());
}
if (auto *component{std::get_if<Component>(&ref.u)}) {
if (!CheckDataRef(ref)) {
return std::nullopt;
}
return Expr<SomeType>{ProcedureDesignator{std::move(*component)}};
} else if (!std::holds_alternative<SymbolRef>(ref.u)) {
DIE("unexpected alternative in DataRef");
} else if (!symbol.attrs().test(semantics::Attr::INTRINSIC)) {
if (symbol.has<semantics::GenericDetails>()) {
Say("'%s' is not a specific procedure"_err_en_US, last.name());
} else if (IsProcedurePointer(specific)) {
// For procedure pointers, retain associations so that data accesses
// from client modules will work.
return Expr<SomeType>{ProcedureDesignator{specific}};
} else {
return Expr<SomeType>{ProcedureDesignator{symbol}};
}
} else if (auto interface{context_.intrinsics().IsSpecificIntrinsicFunction(
symbol.name().ToString())};
interface && !interface->isRestrictedSpecific) {
SpecificIntrinsic intrinsic{
symbol.name().ToString(), std::move(*interface)};
intrinsic.isRestrictedSpecific = interface->isRestrictedSpecific;
return Expr<SomeType>{ProcedureDesignator{std::move(intrinsic)}};
} else {
Say("'%s' is not an unrestricted specific intrinsic procedure"_err_en_US,
last.name());
}
return std::nullopt;
} else if (MaybeExpr result{AsGenericExpr(std::move(ref))}) {
return result;
} else if (semantics::HadUseError(
context_, GetContextualMessages().at(), &symbol)) {
return std::nullopt;
} else {
if (!context_.HasError(last) && !context_.HasError(symbol)) {
AttachDeclaration(
Say("'%s' is not an object that can appear in an expression"_err_en_US,
last.name()),
symbol);
context_.SetError(last);
}
return std::nullopt;
}
}
// Returns false if any dimension could be empty (e.g. A(1:0)) or has an error
static bool FoldSubscripts(semantics::SemanticsContext &context,
const Symbol &arraySymbol, std::vector<Subscript> &subscripts, Shape &lb,
Shape &ub) {
FoldingContext &foldingContext{context.foldingContext()};
lb = GetLBOUNDs(foldingContext, NamedEntity{arraySymbol});
CHECK(lb.size() >= subscripts.size());
ub = GetUBOUNDs(foldingContext, NamedEntity{arraySymbol});
CHECK(ub.size() >= subscripts.size());
bool anyPossiblyEmptyDim{false};
int dim{0};
for (Subscript &ss : subscripts) {
if (Triplet * triplet{std::get_if<Triplet>(&ss.u)}) {
auto expr{Fold(foldingContext, triplet->stride())};
auto stride{ToInt64(expr)};
triplet->set_stride(std::move(expr));
std::optional<ConstantSubscript> lower, upper;
if (auto expr{triplet->lower()}) {
*expr = Fold(foldingContext, std::move(*expr));
lower = ToInt64(*expr);
triplet->set_lower(std::move(*expr));
} else {
lower = ToInt64(lb[dim]);
}
if (auto expr{triplet->upper()}) {
*expr = Fold(foldingContext, std::move(*expr));
upper = ToInt64(*expr);
triplet->set_upper(std::move(*expr));
} else {
upper = ToInt64(ub[dim]);
}
if (stride) {
if (*stride == 0) {
foldingContext.messages().Say(
"Stride of triplet must not be zero"_err_en_US);
return false; // error
}
if (lower && upper) {
if (*stride > 0) {
anyPossiblyEmptyDim |= *lower > *upper;
} else {
anyPossiblyEmptyDim |= *lower < *upper;
}
} else {
anyPossiblyEmptyDim = true;
}
} else { // non-constant stride
if (lower && upper && *lower == *upper) {
// stride is not relevant
} else {
anyPossiblyEmptyDim = true;
}
}
} else { // not triplet
auto &expr{std::get<IndirectSubscriptIntegerExpr>(ss.u).value()};
expr = Fold(foldingContext, std::move(expr));
anyPossiblyEmptyDim |= expr.Rank() > 0; // vector subscript
}
++dim;
}
return !anyPossiblyEmptyDim;
}
static void ValidateSubscriptValue(parser::ContextualMessages &messages,
const Symbol &symbol, ConstantSubscript val,
std::optional<ConstantSubscript> lb, std::optional<ConstantSubscript> ub,
int dim, const char *co = "") {
std::optional<parser::MessageFixedText> msg;
std::optional<ConstantSubscript> bound;
if (lb && val < *lb) {
msg =
"%ssubscript %jd is less than lower %sbound %jd for %sdimension %d of array"_err_en_US;
bound = *lb;
} else if (ub && val > *ub) {
msg =
"%ssubscript %jd is greater than upper %sbound %jd for %sdimension %d of array"_err_en_US;
bound = *ub;
if (dim + 1 == symbol.Rank() && IsDummy(symbol) && *bound == 1) {
// Old-school overindexing of a dummy array isn't fatal when
// it's on the last dimension and the extent is 1.
msg->set_severity(parser::Severity::Warning);
}
}
if (msg) {
AttachDeclaration(
messages.Say(std::move(*msg), co, static_cast<std::intmax_t>(val), co,
static_cast<std::intmax_t>(bound.value()), co, dim + 1),
symbol);
}
}
static void ValidateSubscripts(semantics::SemanticsContext &context,
const Symbol &arraySymbol, const std::vector<Subscript> &subscripts,
const Shape &lb, const Shape &ub) {
int dim{0};
for (const Subscript &ss : subscripts) {
auto dimLB{ToInt64(lb[dim])};
auto dimUB{ToInt64(ub[dim])};
if (dimUB && dimLB && *dimUB < *dimLB) {
AttachDeclaration(
context.Warn(common::UsageWarning::SubscriptedEmptyArray,
context.foldingContext().messages().at(),
"Empty array dimension %d should not be subscripted as an element or non-empty array section"_err_en_US,
dim + 1),
arraySymbol);
break;
}
std::optional<ConstantSubscript> val[2];
int vals{0};
if (auto *triplet{std::get_if<Triplet>(&ss.u)}) {
auto stride{ToInt64(triplet->stride())};
std::optional<ConstantSubscript> lower, upper;
if (const auto *lowerExpr{triplet->GetLower()}) {
lower = ToInt64(*lowerExpr);
} else if (lb[dim]) {
lower = ToInt64(*lb[dim]);
}
if (const auto *upperExpr{triplet->GetUpper()}) {
upper = ToInt64(*upperExpr);
} else if (ub[dim]) {
upper = ToInt64(*ub[dim]);
}
if (lower) {
val[vals++] = *lower;
if (upper && *upper != lower && (stride && *stride != 0)) {
// Normalize upper bound for non-unit stride
// 1:10:2 -> 1:9:2, 10:1:-2 -> 10:2:-2
val[vals++] = *lower + *stride * ((*upper - *lower) / *stride);
}
}
} else {
val[vals++] =
ToInt64(std::get<IndirectSubscriptIntegerExpr>(ss.u).value());
}
for (int j{0}; j < vals; ++j) {
if (val[j]) {
ValidateSubscriptValue(context.foldingContext().messages(), arraySymbol,
*val[j], dimLB, dimUB, dim);
}
}
++dim;
}
}
static void CheckSubscripts(
semantics::SemanticsContext &context, ArrayRef &ref) {
const Symbol &arraySymbol{ref.base().GetLastSymbol()};
Shape lb, ub;
if (FoldSubscripts(context, arraySymbol, ref.subscript(), lb, ub)) {
ValidateSubscripts(context, arraySymbol, ref.subscript(), lb, ub);
}
}
static void CheckSubscripts(
semantics::SemanticsContext &context, CoarrayRef &ref) {
const Symbol &coarraySymbol{ref.GetBase().GetLastSymbol()};
Shape lb, ub;
if (FoldSubscripts(context, coarraySymbol, ref.subscript(), lb, ub)) {
ValidateSubscripts(context, coarraySymbol, ref.subscript(), lb, ub);
}
FoldingContext &foldingContext{context.foldingContext()};
int dim{0};
for (auto &expr : ref.cosubscript()) {
expr = Fold(foldingContext, std::move(expr));
if (auto val{ToInt64(expr)}) {
ValidateSubscriptValue(foldingContext.messages(), coarraySymbol, *val,
ToInt64(GetLCOBOUND(coarraySymbol, dim)),
ToInt64(GetUCOBOUND(coarraySymbol, dim)), dim, "co");
}
++dim;
}
}
// Some subscript semantic checks must be deferred until all of the
// subscripts are in hand.
MaybeExpr ExpressionAnalyzer::CompleteSubscripts(ArrayRef &&ref) {
const Symbol &symbol{ref.GetLastSymbol().GetUltimate()};
int symbolRank{symbol.Rank()};
int subscripts{static_cast<int>(ref.size())};
if (subscripts == 0) {
return std::nullopt; // error recovery
} else if (subscripts != symbolRank) {
if (symbolRank != 0) {
Say("Reference to rank-%d object '%s' has %d subscripts"_err_en_US,
symbolRank, symbol.name(), subscripts);
}
return std::nullopt;
} else if (symbol.has<semantics::ObjectEntityDetails>() ||
symbol.has<semantics::AssocEntityDetails>()) {
// C928 & C1002
if (Triplet * last{std::get_if<Triplet>(&ref.subscript().back().u)}) {
if (!last->upper() && IsAssumedSizeArray(symbol)) {
Say("Assumed-size array '%s' must have explicit final subscript upper bound value"_err_en_US,
symbol.name());
return std::nullopt;
}
}
} else {
// Shouldn't get here from Analyze(ArrayElement) without a valid base,
// which, if not an object, must be a construct entity from
// SELECT TYPE/RANK or ASSOCIATE.
CHECK(symbol.has<semantics::AssocEntityDetails>());
}
if (!semantics::IsNamedConstant(symbol) && !inDataStmtObject_) {
// Subscripts of named constants are checked in folding.
// Subscripts of DATA statement objects are checked in data statement
// conversion to initializers.
CheckSubscripts(context_, ref);
}
return Designate(DataRef{std::move(ref)});
}
// Applies subscripts to a data reference.
MaybeExpr ExpressionAnalyzer::ApplySubscripts(
DataRef &&dataRef, std::vector<Subscript> &&subscripts) {
if (subscripts.empty()) {
return std::nullopt; // error recovery
}
return common::visit(common::visitors{
[&](SymbolRef &&symbol) {
return CompleteSubscripts(
ArrayRef{symbol, std::move(subscripts)});
},
[&](Component &&c) {
return CompleteSubscripts(
ArrayRef{std::move(c), std::move(subscripts)});
},
[&](auto &&) -> MaybeExpr {
DIE("bad base for ArrayRef");
return std::nullopt;
},
},
std::move(dataRef.u));
}
// C919a - only one part-ref of a data-ref may have rank > 0
bool ExpressionAnalyzer::CheckRanks(const DataRef &dataRef) {
return common::visit(
common::visitors{
[this](const Component &component) {
const Symbol &symbol{component.GetLastSymbol()};
if (int componentRank{symbol.Rank()}; componentRank > 0) {
if (int baseRank{component.base().Rank()}; baseRank > 0) {
Say("Reference to whole rank-%d component '%s' of rank-%d array of derived type is not allowed"_err_en_US,
componentRank, symbol.name(), baseRank);
return false;
}
} else {
return CheckRanks(component.base());
}
return true;
},
[this](const ArrayRef &arrayRef) {
if (const auto *component{arrayRef.base().UnwrapComponent()}) {
int subscriptRank{0};
for (const Subscript &subscript : arrayRef.subscript()) {
subscriptRank += subscript.Rank();
}
if (subscriptRank > 0) {
if (int componentBaseRank{component->base().Rank()};
componentBaseRank > 0) {
Say("Subscripts of component '%s' of rank-%d derived type array have rank %d but must all be scalar"_err_en_US,
component->GetLastSymbol().name(), componentBaseRank,
subscriptRank);
return false;
}
} else {
return CheckRanks(component->base());
}
}
return true;
},
[](const SymbolRef &) { return true; },
[](const CoarrayRef &) { return true; },
},
dataRef.u);
}
// C911 - if the last name in a data-ref has an abstract derived type,
// it must also be polymorphic.
bool ExpressionAnalyzer::CheckPolymorphic(const DataRef &dataRef) {
if (auto type{DynamicType::From(dataRef.GetLastSymbol())}) {
if (type->category() == TypeCategory::Derived && !type->IsPolymorphic()) {
const Symbol &typeSymbol{
type->GetDerivedTypeSpec().typeSymbol().GetUltimate()};
if (typeSymbol.attrs().test(semantics::Attr::ABSTRACT)) {
AttachDeclaration(
Say("Reference to object with abstract derived type '%s' must be polymorphic"_err_en_US,
typeSymbol.name()),
typeSymbol);
return false;
}
}
}
return true;
}
bool ExpressionAnalyzer::CheckDataRef(const DataRef &dataRef) {
// Always check both, don't short-circuit
bool ranksOk{CheckRanks(dataRef)};
bool polyOk{CheckPolymorphic(dataRef)};
return ranksOk && polyOk;
}
// Parse tree correction after a substring S(j:k) was misparsed as an
// array section. Fortran substrings must have a range, not a
// single index.
static std::optional<parser::Substring> FixMisparsedSubstringDataRef(
parser::DataRef &dataRef) {
if (auto *ae{
std::get_if<common::Indirection<parser::ArrayElement>>(&dataRef.u)}) {
// ...%a(j:k) and "a" is a character scalar
parser::ArrayElement &arrElement{ae->value()};
if (arrElement.subscripts.size() == 1) {
if (auto *triplet{std::get_if<parser::SubscriptTriplet>(
&arrElement.subscripts.front().u)}) {
if (!std::get<2 /*stride*/>(triplet->t).has_value()) {
if (const Symbol *symbol{
parser::GetLastName(arrElement.base).symbol}) {
const Symbol &ultimate{symbol->GetUltimate()};
if (const semantics::DeclTypeSpec *type{ultimate.GetType()}) {
if (ultimate.Rank() == 0 &&
type->category() == semantics::DeclTypeSpec::Character) {
// The ambiguous S(j:k) was parsed as an array section
// reference, but it's now clear that it's a substring.
// Fix the parse tree in situ.
return arrElement.ConvertToSubstring();
}
}
}
}
}
}
}
return std::nullopt;
}
// When a designator is a misparsed type-param-inquiry of a misparsed
// substring -- it looks like a structure component reference of an array
// slice -- fix the substring and then convert to an intrinsic function
// call to KIND() or LEN(). And when the designator is a misparsed
// substring, convert it into a substring reference in place.
MaybeExpr ExpressionAnalyzer::FixMisparsedSubstring(
const parser::Designator &d) {
auto &mutate{const_cast<parser::Designator &>(d)};
if (auto *dataRef{std::get_if<parser::DataRef>(&mutate.u)}) {
if (auto *sc{std::get_if<common::Indirection<parser::StructureComponent>>(
&dataRef->u)}) {
parser::StructureComponent &structComponent{sc->value()};
parser::CharBlock which{structComponent.component.source};
if (which == "kind" || which == "len") {
if (auto substring{
FixMisparsedSubstringDataRef(structComponent.base)}) {
// ...%a(j:k)%kind or %len and "a" is a character scalar
mutate.u = std::move(*substring);
if (MaybeExpr substringExpr{Analyze(d)}) {
return MakeFunctionRef(which,
ActualArguments{ActualArgument{std::move(*substringExpr)}});
}
}
}
} else if (auto substring{FixMisparsedSubstringDataRef(*dataRef)}) {
mutate.u = std::move(*substring);
}
}
return std::nullopt;
}
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Designator &d) {
auto restorer{GetContextualMessages().SetLocation(d.source)};
if (auto substringInquiry{FixMisparsedSubstring(d)}) {
return substringInquiry;
}
// These checks have to be deferred to these "top level" data-refs where
// we can be sure that there are no following subscripts (yet).
MaybeExpr result{Analyze(d.u)};
if (result) {
std::optional<DataRef> dataRef{ExtractDataRef(std::move(result))};
if (!dataRef) {
dataRef = ExtractDataRef(std::move(result), /*intoSubstring=*/true);
}
if (!dataRef) {
dataRef = ExtractDataRef(std::move(result),
/*intoSubstring=*/false, /*intoComplexPart=*/true);
}
if (dataRef) {
if (!CheckDataRef(*dataRef)) {
result.reset();
} else if (ExtractCoarrayRef(*dataRef).has_value()) {
if (auto dyType{result->GetType()};
dyType && dyType->category() == TypeCategory::Derived) {
if (!std::holds_alternative<CoarrayRef>(dataRef->u) &&
dyType->IsPolymorphic()) { // F'2023 C918
Say("The base of a polymorphic object may not be coindexed"_err_en_US);
}
if (const auto *derived{GetDerivedTypeSpec(*dyType)}) {
if (auto bad{FindPolymorphicAllocatablePotentialComponent(
*derived)}) { // F'2023 C917
Say("A coindexed designator may not have a type with the polymorphic potential subobject component '%s'"_err_en_US,
bad.BuildResultDesignatorName());
}
}
}
}
}
}
return result;
}
// A utility subroutine to repackage optional expressions of various levels
// of type specificity as fully general MaybeExpr values.
template <typename A> common::IfNoLvalue<MaybeExpr, A> AsMaybeExpr(A &&x) {
return AsGenericExpr(std::move(x));
}
template <typename A> MaybeExpr AsMaybeExpr(std::optional<A> &&x) {
if (x) {
return AsMaybeExpr(std::move(*x));
}
return std::nullopt;
}
// Type kind parameter values for literal constants.
int ExpressionAnalyzer::AnalyzeKindParam(
const std::optional<parser::KindParam> &kindParam, int defaultKind) {
if (!kindParam) {
return defaultKind;
}
std::int64_t kind{common::visit(
common::visitors{
[](std::uint64_t k) { return static_cast<std::int64_t>(k); },
[&](const parser::Scalar<
parser::Integer<parser::Constant<parser::Name>>> &n) {
if (MaybeExpr ie{Analyze(n)}) {
return ToInt64(*ie).value_or(defaultKind);
}
return static_cast<std::int64_t>(defaultKind);
},
},
kindParam->u)};
if (kind != static_cast<int>(kind)) {
Say("Unsupported type kind value (%jd)"_err_en_US,
static_cast<std::intmax_t>(kind));
kind = defaultKind;
}
return static_cast<int>(kind);
}
// Common handling of parser::IntLiteralConstant, SignedIntLiteralConstant,
// and UnsignedLiteralConstant
template <typename TYPES, TypeCategory CAT> struct IntTypeVisitor {
using Result = MaybeExpr;
using Types = TYPES;
template <typename T> Result Test() {
if (T::kind >= kind) {
const char *p{digits.begin()};
using Int = typename T::Scalar;
typename Int::ValueWithOverflow num{0, false};
const char *typeName{
CAT == TypeCategory::Integer ? "INTEGER" : "UNSIGNED"};
if (isNegated) {
auto unsignedNum{Int::Read(p, 10, false /*unsigned*/)};
num.value = unsignedNum.value.Negate().value;
num.overflow = unsignedNum.overflow ||
(CAT == TypeCategory::Integer && num.value > Int{0});
if (!num.overflow && num.value.Negate().overflow) {
analyzer.Warn(LanguageFeature::BigIntLiterals, digits,
"negated maximum INTEGER(KIND=%d) literal"_port_en_US, T::kind);
}
} else {
num = Int::Read(p, 10, /*isSigned=*/CAT == TypeCategory::Integer);
}
if (num.overflow) {
if constexpr (CAT == TypeCategory::Unsigned) {
analyzer.Warn(common::UsageWarning::UnsignedLiteralTruncation,
"Unsigned literal too large for UNSIGNED(KIND=%d); truncated"_warn_en_US,
kind);
return Expr<SomeType>{
Expr<SomeKind<CAT>>{Expr<T>{Constant<T>{std::move(num.value)}}}};
}
} else {
if (T::kind > kind) {
if (!isDefaultKind ||
!analyzer.context().IsEnabled(LanguageFeature::BigIntLiterals)) {
return std::nullopt;
} else {
analyzer.Warn(LanguageFeature::BigIntLiterals, digits,
"Integer literal is too large for default %s(KIND=%d); "
"assuming %s(KIND=%d)"_port_en_US,
typeName, kind, typeName, T::kind);
}
}
return Expr<SomeType>{
Expr<SomeKind<CAT>>{Expr<T>{Constant<T>{std::move(num.value)}}}};
}
}
return std::nullopt;
}
ExpressionAnalyzer &analyzer;
parser::CharBlock digits;
std::int64_t kind;
bool isDefaultKind;
bool isNegated;
};
template <typename TYPES, TypeCategory CAT, typename PARSED>
MaybeExpr ExpressionAnalyzer::IntLiteralConstant(
const PARSED &x, bool isNegated) {
const auto &kindParam{std::get<std::optional<parser::KindParam>>(x.t)};
bool isDefaultKind{!kindParam};
int kind{AnalyzeKindParam(kindParam, GetDefaultKind(CAT))};
const char *typeName{CAT == TypeCategory::Integer ? "INTEGER" : "UNSIGNED"};
if (CheckIntrinsicKind(CAT, kind)) {
auto digits{std::get<parser::CharBlock>(x.t)};
if (MaybeExpr result{common::SearchTypes(IntTypeVisitor<TYPES, CAT>{
*this, digits, kind, isDefaultKind, isNegated})}) {
return result;
} else if (isDefaultKind) {
Say(digits,
"Integer literal is too large for any allowable kind of %s"_err_en_US,
typeName);
} else {
Say(digits, "Integer literal is too large for %s(KIND=%d)"_err_en_US,
typeName, kind);
}
}
return std::nullopt;
}
MaybeExpr ExpressionAnalyzer::Analyze(
const parser::IntLiteralConstant &x, bool isNegated) {
auto restorer{
GetContextualMessages().SetLocation(std::get<parser::CharBlock>(x.t))};
return IntLiteralConstant<IntegerTypes, TypeCategory::Integer>(x, isNegated);
}
MaybeExpr ExpressionAnalyzer::Analyze(
const parser::SignedIntLiteralConstant &x) {
auto restorer{GetContextualMessages().SetLocation(x.source)};
return IntLiteralConstant<IntegerTypes, TypeCategory::Integer>(x);
}
MaybeExpr ExpressionAnalyzer::Analyze(
const parser::UnsignedLiteralConstant &x) {
parser::CharBlock at{std::get<parser::CharBlock>(x.t)};
auto restorer{GetContextualMessages().SetLocation(at)};
if (!context().IsEnabled(common::LanguageFeature::Unsigned) &&
!context().AnyFatalError()) {
context().Say(
at, "-funsigned is required to enable UNSIGNED constants"_err_en_US);
}
return IntLiteralConstant<UnsignedTypes, TypeCategory::Unsigned>(x);
}
template <typename TYPE>
Constant<TYPE> ReadRealLiteral(
parser::CharBlock source, FoldingContext &context) {
const char *p{source.begin()};
auto valWithFlags{
Scalar<TYPE>::Read(p, context.targetCharacteristics().roundingMode())};
CHECK(p == source.end());
RealFlagWarnings(context, valWithFlags.flags, "conversion of REAL literal");
auto value{valWithFlags.value};
if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
value = value.FlushSubnormalToZero();
}
return {value};
}
struct RealTypeVisitor {
using Result = std::optional<Expr<SomeReal>>;
using Types = RealTypes;
RealTypeVisitor(int k, parser::CharBlock lit, FoldingContext &ctx)
: kind{k}, literal{lit}, context{ctx} {}
template <typename T> Result Test() {
if (kind == T::kind) {
return {AsCategoryExpr(ReadRealLiteral<T>(literal, context))};
}
return std::nullopt;
}
int kind;
parser::CharBlock literal;
FoldingContext &context;
};
// Reads a real literal constant and encodes it with the right kind.
MaybeExpr ExpressionAnalyzer::Analyze(const parser::RealLiteralConstant &x) {
// Use a local message context around the real literal for better
// provenance on any messages.
auto restorer{GetContextualMessages().SetLocation(x.real.source)};
// If a kind parameter appears, it defines the kind of the literal and the
// letter used in an exponent part must be 'E' (e.g., the 'E' in
// "6.02214E+23"). In the absence of an explicit kind parameter, any
// exponent letter determines the kind. Otherwise, defaults apply.
auto &defaults{context_.defaultKinds()};
int defaultKind{defaults.GetDefaultKind(TypeCategory::Real)};
const char *end{x.real.source.end()};
char expoLetter{' '};
std::optional<int> letterKind;
for (const char *p{x.real.source.begin()}; p < end; ++p) {
if (parser::IsLetter(*p)) {
expoLetter = *p;
switch (expoLetter) {
case 'e':
letterKind = defaults.GetDefaultKind(TypeCategory::Real);
break;
case 'd':
letterKind = defaults.doublePrecisionKind();
break;
case 'q':
letterKind = defaults.quadPrecisionKind();
break;
default:
Say("Unknown exponent letter '%c'"_err_en_US, expoLetter);
}
break;
}
}
if (letterKind) {
defaultKind = *letterKind;
}
// C716 requires 'E' as an exponent.
// Extension: allow exponent-letter matching the kind-param.
auto kind{AnalyzeKindParam(x.kind, defaultKind)};
if (letterKind && expoLetter != 'e') {
if (kind != *letterKind) {
Warn(common::LanguageFeature::ExponentMatchingKindParam,
"Explicit kind parameter on real constant disagrees with exponent letter '%c'"_warn_en_US,
expoLetter);
} else if (x.kind) {
Warn(common::LanguageFeature::ExponentMatchingKindParam,
"Explicit kind parameter together with non-'E' exponent letter is not standard"_port_en_US);
}
}
auto result{common::SearchTypes(
RealTypeVisitor{kind, x.real.source, GetFoldingContext()})};
if (!result) { // C717
Say("Unsupported REAL(KIND=%d)"_err_en_US, kind);
}
return AsMaybeExpr(std::move(result));
}
MaybeExpr ExpressionAnalyzer::Analyze(
const parser::SignedRealLiteralConstant &x) {
if (auto result{Analyze(std::get<parser::RealLiteralConstant>(x.t))}) {
auto &realExpr{std::get<Expr<SomeReal>>(result->u)};
if (auto sign{std::get<std::optional<parser::Sign>>(x.t)}) {
if (sign == parser::Sign::Negative) {
return AsGenericExpr(-std::move(realExpr));
}
}
return result;
}
return std::nullopt;
}
MaybeExpr ExpressionAnalyzer::Analyze(
const parser::SignedComplexLiteralConstant &x) {
auto result{Analyze(std::get<parser::ComplexLiteralConstant>(x.t))};
if (!result) {
return std::nullopt;
} else if (std::get<parser::Sign>(x.t) == parser::Sign::Negative) {
return AsGenericExpr(-std::move(std::get<Expr<SomeComplex>>(result->u)));
} else {
return result;
}
}
MaybeExpr ExpressionAnalyzer::Analyze(const parser::ComplexPart &x) {
return Analyze(x.u);
}
MaybeExpr ExpressionAnalyzer::Analyze(const parser::ComplexLiteralConstant &z) {
return AnalyzeComplex(Analyze(std::get<0>(z.t)), Analyze(std::get<1>(z.t)),
"complex literal constant");
}
// CHARACTER literal processing.
MaybeExpr ExpressionAnalyzer::AnalyzeString(std::string &&string, int kind) {
if (!CheckIntrinsicKind(TypeCategory::Character, kind)) {
return std::nullopt;
}
switch (kind) {
case 1:
return AsGenericExpr(Constant<Type<TypeCategory::Character, 1>>{
parser::DecodeString<std::string, parser::Encoding::LATIN_1>(
string, true)});
case 2:
return AsGenericExpr(Constant<Type<TypeCategory::Character, 2>>{
parser::DecodeString<std::u16string, parser::Encoding::UTF_8>(
string, true)});
case 4:
return AsGenericExpr(Constant<Type<TypeCategory::Character, 4>>{
parser::DecodeString<std::u32string, parser::Encoding::UTF_8>(
string, true)});
default:
CRASH_NO_CASE;
}
}
MaybeExpr ExpressionAnalyzer::Analyze(const parser::CharLiteralConstant &x) {
int kind{
AnalyzeKindParam(std::get<std::optional<parser::KindParam>>(x.t), 1)};
auto value{std::get<std::string>(x.t)};
return AnalyzeString(std::move(value), kind);
}
MaybeExpr ExpressionAnalyzer::Analyze(
const parser::HollerithLiteralConstant &x) {
int kind{GetDefaultKind(TypeCategory::Character)};
auto result{AnalyzeString(std::string{x.v}, kind)};
if (auto *constant{UnwrapConstantValue<Ascii>(result)}) {
constant->set_wasHollerith(true);
}
return result;
}
// .TRUE. and .FALSE. of various kinds
MaybeExpr ExpressionAnalyzer::Analyze(const parser::LogicalLiteralConstant &x) {
auto kind{AnalyzeKindParam(std::get<std::optional<parser::KindParam>>(x.t),
GetDefaultKind(TypeCategory::Logical))};
bool value{std::get<bool>(x.t)};
auto result{common::SearchTypes(
TypeKindVisitor<TypeCategory::Logical, Constant, bool>{
kind, std::move(value)})};
if (!result) {
Say("unsupported LOGICAL(KIND=%d)"_err_en_US, kind); // C728
}
return result;
}