FLANG
type.h
1//===-- include/flang/Semantics/type.h --------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef FORTRAN_SEMANTICS_TYPE_H_
10#define FORTRAN_SEMANTICS_TYPE_H_
11
12#include "flang/Common/idioms.h"
13#include "flang/Evaluate/expression.h"
14#include "flang/Parser/char-block.h"
15#include "flang/Support/Fortran.h"
16#include <algorithm>
17#include <map>
18#include <optional>
19#include <string>
20#include <variant>
21#include <vector>
22
23namespace llvm {
24class raw_ostream;
25}
26
27namespace Fortran::parser {
28struct Keyword;
29}
30
31namespace Fortran::evaluate { // avoid including all of Evaluate/tools.h
32template <typename T>
33std::optional<bool> AreEquivalentInInterface(const Expr<T> &, const Expr<T> &);
34extern template std::optional<bool>
35AreEquivalentInInterface<Type<TypeCategory::Integer>>(
38} // namespace Fortran::evaluate
39
40namespace Fortran::semantics {
41
42class Scope;
44class Symbol;
45
48using SourceName = parser::CharBlock;
49using TypeCategory = common::TypeCategory;
50using SomeExpr = evaluate::Expr<evaluate::SomeType>;
51using MaybeExpr = std::optional<SomeExpr>;
52using SomeIntExpr =
53 evaluate::Expr<evaluate::Type<common::TypeCategory::Integer>>;
54using MaybeIntExpr = std::optional<SomeIntExpr>;
55using SubscriptIntExpr = evaluate::Expr<evaluate::SubscriptInteger>;
56using MaybeSubscriptIntExpr = std::optional<SubscriptIntExpr>;
57using KindExpr = SubscriptIntExpr;
58
59KindExpr MakeKindExpr(int v);
60
61// An array spec bound: an explicit integer expression, assumed size
62// or implied shape(*), or assumed or deferred shape(:). In the absence
63// of explicit lower bounds it is not possible to distinguish assumed
64// shape bounds from deferred shape bounds without knowing whether the
65// particular symbol is an allocatable/pointer or a non-allocatable
66// non-pointer dummy; use the symbol-based predicates for those
67// determinations.
68class Bound {
69public:
70 static Bound Star() { return Bound(Category::Star); }
71 static Bound Colon() { return Bound(Category::Colon); }
72 explicit Bound(MaybeSubscriptIntExpr &&expr) : expr_{std::move(expr)} {
73 CHECK(evaluate::IsSubscriptIntegerKind(expr_));
74 }
75 explicit Bound(common::ConstantSubscript bound);
76 Bound(const Bound &) = default;
77 Bound(Bound &&) = default;
78 Bound &operator=(const Bound &) = default;
79 Bound &operator=(Bound &&) = default;
80 bool isExplicit() const { return category_ == Category::Explicit; }
81 bool isStar() const { return category_ == Category::Star; }
82 bool isColon() const { return category_ == Category::Colon; }
83 MaybeSubscriptIntExpr &GetExplicit() { return expr_; }
84 const MaybeSubscriptIntExpr &GetExplicit() const { return expr_; }
85 void SetExplicit(MaybeSubscriptIntExpr &&expr) {
86 CHECK(isExplicit());
87 CHECK(evaluate::IsSubscriptIntegerKind(expr));
88 expr_ = std::move(expr);
89 }
90
91private:
92 enum class Category { Explicit, Star, Colon };
93 Bound(Category category) : category_{category} {}
94 Bound(Category category, MaybeSubscriptIntExpr &&expr)
95 : category_{category}, expr_{std::move(expr)} {}
96 Category category_{Category::Explicit};
97 MaybeSubscriptIntExpr expr_;
98 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Bound &);
99};
100
101// A type parameter value: integer expression, assumed/implied(*),
102// or deferred(:).
103class ParamValue {
104public:
105 static ParamValue Assumed(common::TypeParamAttr attr) {
106 return ParamValue{Category::Assumed, attr};
107 }
108 static ParamValue Deferred(common::TypeParamAttr attr) {
109 return ParamValue{Category::Deferred, attr};
110 }
111 ParamValue(const ParamValue &) = default;
112 explicit ParamValue(MaybeIntExpr &&, common::TypeParamAttr);
113 explicit ParamValue(SomeIntExpr &&, common::TypeParamAttr attr);
114 explicit ParamValue(common::ConstantSubscript, common::TypeParamAttr attr);
115 bool isExplicit() const { return category_ == Category::Explicit; }
116 bool isAssumed() const { return category_ == Category::Assumed; }
117 bool isDeferred() const { return category_ == Category::Deferred; }
118 const MaybeIntExpr &GetExplicit() const { return expr_; }
119 void SetExplicit(SomeIntExpr &&);
120 bool isKind() const { return attr_ == common::TypeParamAttr::Kind; }
121 bool isLen() const { return attr_ == common::TypeParamAttr::Len; }
122 void set_attr(common::TypeParamAttr attr) { attr_ = attr; }
123 bool operator==(const ParamValue &that) const {
124 return category_ == that.category_ && expr_ == that.expr_;
125 }
126 bool operator!=(const ParamValue &that) const { return !(*this == that); }
127 bool IsEquivalentInInterface(const ParamValue &that) const {
128 return (category_ == that.category_ &&
129 expr_.has_value() == that.expr_.has_value() &&
130 (!expr_ ||
131 evaluate::AreEquivalentInInterface(*expr_, *that.expr_)
132 .value_or(false)));
133 }
134 std::string AsFortran() const;
135
136private:
137 enum class Category { Explicit, Deferred, Assumed };
138 ParamValue(Category category, common::TypeParamAttr attr)
139 : category_{category}, attr_{attr} {}
140 Category category_{Category::Explicit};
141 common::TypeParamAttr attr_{common::TypeParamAttr::Kind};
142 MaybeIntExpr expr_;
143 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ParamValue &);
144};
145
146class IntrinsicTypeSpec {
147public:
148 TypeCategory category() const { return category_; }
149 const KindExpr &kind() const { return kind_; }
150 bool operator==(const IntrinsicTypeSpec &x) const {
151 return category_ == x.category_ && kind_ == x.kind_;
152 }
153 bool operator!=(const IntrinsicTypeSpec &x) const { return !operator==(x); }
154 std::string AsFortran() const;
155
156protected:
157 IntrinsicTypeSpec(TypeCategory, KindExpr &&);
158
159private:
160 TypeCategory category_;
161 KindExpr kind_;
162 friend llvm::raw_ostream &operator<<(
163 llvm::raw_ostream &os, const IntrinsicTypeSpec &x);
164};
165
166class NumericTypeSpec : public IntrinsicTypeSpec {
167public:
168 NumericTypeSpec(TypeCategory category, KindExpr &&kind)
169 : IntrinsicTypeSpec(category, std::move(kind)) {
170 CHECK(common::IsNumericTypeCategory(category));
171 }
172};
173
174class LogicalTypeSpec : public IntrinsicTypeSpec {
175public:
176 explicit LogicalTypeSpec(KindExpr &&kind)
177 : IntrinsicTypeSpec(TypeCategory::Logical, std::move(kind)) {}
178};
179
180class CharacterTypeSpec : public IntrinsicTypeSpec {
181public:
182 CharacterTypeSpec(ParamValue &&length, KindExpr &&kind)
183 : IntrinsicTypeSpec(TypeCategory::Character, std::move(kind)),
184 length_{std::move(length)} {}
185 const ParamValue &length() const { return length_; }
186 bool operator==(const CharacterTypeSpec &that) const {
187 return kind() == that.kind() && length_ == that.length_;
188 }
189 std::string AsFortran() const;
190
191private:
192 ParamValue length_;
193 friend llvm::raw_ostream &operator<<(
194 llvm::raw_ostream &os, const CharacterTypeSpec &x);
195};
196
197class ShapeSpec {
198public:
199 // lb:ub
200 static ShapeSpec MakeExplicit(Bound &&lb, Bound &&ub) {
201 return ShapeSpec(std::move(lb), std::move(ub));
202 }
203 // 1:ub
204 static const ShapeSpec MakeExplicit(Bound &&ub) {
205 return MakeExplicit(Bound{1}, std::move(ub));
206 }
207 // 1:
208 static ShapeSpec MakeAssumedShape() {
209 return ShapeSpec(Bound{1}, Bound::Colon());
210 }
211 // lb:
212 static ShapeSpec MakeAssumedShape(Bound &&lb) {
213 return ShapeSpec(std::move(lb), Bound::Colon());
214 }
215 // :
216 static ShapeSpec MakeDeferred() {
217 return ShapeSpec(Bound::Colon(), Bound::Colon());
218 }
219 // 1:*
220 static ShapeSpec MakeImplied() { return ShapeSpec(Bound{1}, Bound::Star()); }
221 // lb:*
222 static ShapeSpec MakeImplied(Bound &&lb) {
223 return ShapeSpec(std::move(lb), Bound::Star());
224 }
225 // ..
226 static ShapeSpec MakeAssumedRank() {
227 return ShapeSpec(Bound::Star(), Bound::Star());
228 }
229
230 ShapeSpec(const ShapeSpec &) = default;
231 ShapeSpec(ShapeSpec &&) = default;
232 ShapeSpec &operator=(const ShapeSpec &) = default;
233 ShapeSpec &operator=(ShapeSpec &&) = default;
234
235 Bound &lbound() { return lb_; }
236 const Bound &lbound() const { return lb_; }
237 Bound &ubound() { return ub_; }
238 const Bound &ubound() const { return ub_; }
239
240private:
241 ShapeSpec(Bound &&lb, Bound &&ub) : lb_{std::move(lb)}, ub_{std::move(ub)} {}
242 Bound lb_;
243 Bound ub_;
244 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ShapeSpec &);
245};
246
247struct ArraySpec : public std::vector<ShapeSpec> {
248 ArraySpec() {}
249 int Rank() const { return size(); }
250 // These names are not exclusive, as some categories cannot be
251 // distinguished without knowing whether the particular symbol
252 // is allocatable, pointer, or a non-allocatable non-pointer dummy.
253 // Use the symbol-based predicates for exact results.
254 inline bool IsExplicitShape() const;
255 inline bool CanBeAssumedShape() const;
256 inline bool CanBeDeferredShape() const;
257 inline bool CanBeImpliedShape() const;
258 inline bool CanBeAssumedSize() const;
259 inline bool IsAssumedRank() const;
260 // Which bounds of this shape were declared with a rank-1 integer array
261 // (F2023 R818 explicit-shape-bounds-spec)? A constant bounds array is
262 // folded into ordinary per-dimension bounds, so the spec itself no longer
263 // shows it; the module file writer uses this to write the declared
264 // whole-array form back out.
265 bool isFromRankOneBounds() const {
266 return lboundIsRankOne_ || uboundIsRankOne_;
267 }
268 bool lboundIsRankOne() const { return lboundIsRankOne_; }
269 bool uboundIsRankOne() const { return uboundIsRankOne_; }
270 void set_rankOneBounds(bool lower, bool upper) {
271 lboundIsRankOne_ = lower;
272 uboundIsRankOne_ = upper;
273 }
274 void clear() {
275 std::vector<ShapeSpec>::clear();
276 lboundIsRankOne_ = uboundIsRankOne_ = false;
277 }
278
279private:
280 bool lboundIsRankOne_{false};
281 bool uboundIsRankOne_{false};
282 // Check non-empty and predicate is true for each element.
283 template <typename P> bool CheckAll(P predicate) const {
284 return !empty() && std::all_of(begin(), end(), predicate);
285 }
286};
287llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ArraySpec &);
288
289// Each DerivedTypeSpec has a typeSymbol that has DerivedTypeDetails.
290// The name may not match the symbol's name in case of a USE rename.
291class DerivedTypeSpec {
292public:
293 enum class Category {
294 DerivedType,
295 IntrinsicVector,
296 PairVector,
297 QuadVector,
298 EnumerationType
299 };
300
301 using RawParameter = std::pair<const parser::Keyword *, ParamValue>;
302 using RawParameters = std::vector<RawParameter>;
303 using ParameterMapType = std::map<SourceName, ParamValue>;
304 DerivedTypeSpec(SourceName, const Symbol &);
305 DerivedTypeSpec(const DerivedTypeSpec &);
306 DerivedTypeSpec(DerivedTypeSpec &&);
307
308 const SourceName &name() const { return name_; }
309 const Symbol &originalTypeSymbol() const { return originalTypeSymbol_; }
310 const Symbol &typeSymbol() const { return typeSymbol_; }
311 const Scope *scope() const { return scope_; }
312 // Return scope_ if it is set, or the typeSymbol_ scope otherwise.
313 const Scope *GetScope() const;
314 void set_scope(const Scope &);
315 void ReplaceScope(const Scope &);
316 const RawParameters &rawParameters() const { return rawParameters_; }
317 const ParameterMapType &parameters() const { return parameters_; }
318
319 bool MightBeParameterized() const;
320 bool IsForwardReferenced() const;
321 bool HasDefaultInitialization(
322 bool ignoreAllocatable = false, bool ignorePointer = true) const;
323 std::optional<std::string> // component path suitable for error messages
324 ComponentWithDefaultInitialization(
325 bool ignoreAllocatable = false, bool ignorePointer = true) const;
326 bool HasDestruction() const;
327
328 // The "raw" type parameter list is a simple transcription from the
329 // parameter list in the parse tree, built by calling AddRawParamValue().
330 // It can be used with forward-referenced derived types.
331 void AddRawParamValue(const parser::Keyword *, ParamValue &&);
332 // Checks the raw parameter list against the definition of a derived type.
333 // Converts the raw parameter list to a map, naming each actual parameter.
334 void CookParameters(evaluate::FoldingContext &);
335 // Evaluates type parameter expressions.
336 void EvaluateParameters(SemanticsContext &);
337 void ReevaluateParameters(SemanticsContext &);
338 void AddParamValue(SourceName, ParamValue &&);
339 // Creates a Scope for the type and populates it with component
340 // instantiations that have been specialized with actual type parameter
341 // values, which are cooked &/or evaluated if necessary.
342 void Instantiate(Scope &containingScope);
343 // Reset instantiation state so a copy can receive a fresh component scope
344 // (e.g. OpenACC use_device with CUDA Fortran component paths).
345 void PrepareForScopeClone();
346
347 ParamValue *FindParameter(SourceName);
348 const ParamValue *FindParameter(SourceName target) const {
349 auto iter{parameters_.find(target)};
350 if (iter != parameters_.end()) {
351 return &iter->second;
352 } else {
353 return nullptr;
354 }
355 }
356 bool operator==(const DerivedTypeSpec &that) const {
357 return RawEquals(that) && parameters_ == that.parameters_;
358 }
359 bool operator!=(const DerivedTypeSpec &that) const {
360 return !(*this == that);
361 }
362 // For TYPE IS & CLASS IS: kind type parameters must be
363 // explicit and equal, len type parameters are ignored.
364 bool MatchesOrExtends(const DerivedTypeSpec &) const;
365 std::string AsFortran() const;
366 std::string VectorTypeAsFortran() const;
367
368 Category category() const { return category_; }
369 void set_category(Category category) { category_ = category; }
370 bool IsVectorType() const {
371 return category_ == Category::IntrinsicVector ||
372 category_ == Category::PairVector || category_ == Category::QuadVector;
373 }
374 bool IsEnumerationType() const {
375 return category_ == Category::EnumerationType;
376 }
377
378private:
379 SourceName name_;
380 const Symbol &originalTypeSymbol_;
381 const Symbol &typeSymbol_; // == originalTypeSymbol_.GetUltimate()
382 const Scope *scope_{nullptr}; // same as typeSymbol_.scope() unless PDT
383 bool cooked_{false};
384 bool evaluated_{false};
385 bool instantiated_{false};
386 RawParameters rawParameters_;
387 ParameterMapType parameters_;
388 Category category_{Category::DerivedType};
389 bool RawEquals(const DerivedTypeSpec &that) const {
390 return &typeSymbol_ == &that.typeSymbol_ &&
391 &originalTypeSymbol_ == &that.originalTypeSymbol_ &&
392 cooked_ == that.cooked_ && rawParameters_ == that.rawParameters_;
393 }
394 friend llvm::raw_ostream &operator<<(
395 llvm::raw_ostream &, const DerivedTypeSpec &);
396};
397
398class DeclTypeSpec {
399public:
400 enum Category {
401 Numeric,
402 Logical,
403 Character,
404 TypeDerived,
405 ClassDerived,
406 TypeStar,
407 ClassStar
408 };
409
410 // intrinsic-type-spec or TYPE(intrinsic-type-spec), not character
411 DeclTypeSpec(NumericTypeSpec &&);
412 DeclTypeSpec(LogicalTypeSpec &&);
413 // character
414 DeclTypeSpec(const CharacterTypeSpec &);
415 DeclTypeSpec(CharacterTypeSpec &&);
416 // TYPE(derived-type-spec) or CLASS(derived-type-spec)
417 DeclTypeSpec(Category, const DerivedTypeSpec &);
418 DeclTypeSpec(Category, DerivedTypeSpec &&);
419 // TYPE(*) or CLASS(*)
420 DeclTypeSpec(Category);
421
422 bool operator==(const DeclTypeSpec &) const;
423 bool operator!=(const DeclTypeSpec &that) const { return !operator==(that); }
424
425 Category category() const { return category_; }
426 void set_category(Category category) { category_ = category; }
427 bool IsPolymorphic() const {
428 return category_ == ClassDerived || IsUnlimitedPolymorphic();
429 }
430 bool IsUnlimitedPolymorphic() const {
431 return category_ == TypeStar || category_ == ClassStar;
432 }
433 bool IsAssumedType() const { return category_ == TypeStar; }
434 bool IsNumeric(TypeCategory) const;
435 bool IsSequenceType() const;
436 const NumericTypeSpec &numericTypeSpec() const;
437 const LogicalTypeSpec &logicalTypeSpec() const;
438 const CharacterTypeSpec &characterTypeSpec() const {
439 CHECK(category_ == Character);
440 return std::get<CharacterTypeSpec>(typeSpec_);
441 }
442 const DerivedTypeSpec &derivedTypeSpec() const {
443 CHECK(category_ == TypeDerived || category_ == ClassDerived);
444 return std::get<DerivedTypeSpec>(typeSpec_);
445 }
446 DerivedTypeSpec &derivedTypeSpec() {
447 CHECK(category_ == TypeDerived || category_ == ClassDerived);
448 return std::get<DerivedTypeSpec>(typeSpec_);
449 }
450
451 inline IntrinsicTypeSpec *AsIntrinsic();
452 inline const IntrinsicTypeSpec *AsIntrinsic() const;
453 inline DerivedTypeSpec *AsDerived();
454 inline const DerivedTypeSpec *AsDerived() const;
455
456 std::string AsFortran() const;
457
458private:
459 Category category_;
460 std::variant<std::monostate, NumericTypeSpec, LogicalTypeSpec,
462 typeSpec_;
463};
464llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DeclTypeSpec &);
465
466// Define some member functions here in the header so that they can be used by
467// lib/Evaluate without link-time dependency on Semantics.
468
469inline bool ArraySpec::IsExplicitShape() const {
470 return CheckAll([](const ShapeSpec &x) { return x.ubound().isExplicit(); });
471}
472inline bool ArraySpec::CanBeAssumedShape() const {
473 return CheckAll([](const ShapeSpec &x) { return x.ubound().isColon(); });
474}
475inline bool ArraySpec::CanBeDeferredShape() const {
476 return CheckAll([](const ShapeSpec &x) {
477 return x.lbound().isColon() && x.ubound().isColon();
478 });
479}
480inline bool ArraySpec::CanBeImpliedShape() const {
481 return !IsAssumedRank() &&
482 CheckAll([](const ShapeSpec &x) { return x.ubound().isStar(); });
483}
484inline bool ArraySpec::CanBeAssumedSize() const {
485 return !empty() && !IsAssumedRank() && back().ubound().isStar() &&
486 std::all_of(begin(), end() - 1,
487 [](const ShapeSpec &x) { return x.ubound().isExplicit(); });
488}
489inline bool ArraySpec::IsAssumedRank() const {
490 return Rank() == 1 && front().lbound().isStar();
491}
492
493inline IntrinsicTypeSpec *DeclTypeSpec::AsIntrinsic() {
494 switch (category_) {
495 case Numeric:
496 return &std::get<NumericTypeSpec>(typeSpec_);
497 case Logical:
498 return &std::get<LogicalTypeSpec>(typeSpec_);
499 case Character:
500 return &std::get<CharacterTypeSpec>(typeSpec_);
501 default:
502 return nullptr;
503 }
504}
505inline const IntrinsicTypeSpec *DeclTypeSpec::AsIntrinsic() const {
506 return const_cast<DeclTypeSpec *>(this)->AsIntrinsic();
507}
508
509inline DerivedTypeSpec *DeclTypeSpec::AsDerived() {
510 switch (category_) {
511 case TypeDerived:
512 case ClassDerived:
513 return &std::get<DerivedTypeSpec>(typeSpec_);
514 default:
515 return nullptr;
516 }
517}
518inline const DerivedTypeSpec *DeclTypeSpec::AsDerived() const {
519 return const_cast<DeclTypeSpec *>(this)->AsDerived();
520}
521
522} // namespace Fortran::semantics
523#endif // FORTRAN_SEMANTICS_TYPE_H_
Definition common.h:222
Definition common.h:224
Definition type.h:68
Definition type.h:103
Definition scope.h:68
Definition semantics.h:71
Definition type.h:197
Definition symbol.h:905
Definition call.h:34
Definition ParserActions.h:24
Definition check-expression.h:19
Definition type.h:247