1 //===-- lib/Semantics/type.cpp --------------------------------------------===//
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 #include "flang/Semantics/type.h"
10 #include "check-declarations.h"
11 #include "compute-offsets.h"
12 #include "flang/Evaluate/fold.h"
13 #include "flang/Evaluate/tools.h"
14 #include "flang/Parser/characters.h"
15 #include "flang/Semantics/scope.h"
16 #include "flang/Semantics/symbol.h"
17 #include "flang/Semantics/tools.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 namespace Fortran::semantics {
21 
22 DerivedTypeSpec::DerivedTypeSpec(SourceName name, const Symbol &typeSymbol)
23     : name_{name}, typeSymbol_{typeSymbol} {
24   CHECK(typeSymbol.has<DerivedTypeDetails>());
25 }
26 DerivedTypeSpec::DerivedTypeSpec(const DerivedTypeSpec &that) = default;
27 DerivedTypeSpec::DerivedTypeSpec(DerivedTypeSpec &&that) = default;
28 
29 void DerivedTypeSpec::set_scope(const Scope &scope) {
30   CHECK(!scope_);
31   ReplaceScope(scope);
32 }
33 void DerivedTypeSpec::ReplaceScope(const Scope &scope) {
34   CHECK(scope.IsDerivedType());
35   scope_ = &scope;
36 }
37 
38 void DerivedTypeSpec::AddRawParamValue(
39     const std::optional<parser::Keyword> &keyword, ParamValue &&value) {
40   CHECK(parameters_.empty());
41   rawParameters_.emplace_back(keyword ? &*keyword : nullptr, std::move(value));
42 }
43 
44 void DerivedTypeSpec::CookParameters(evaluate::FoldingContext &foldingContext) {
45   if (cooked_) {
46     return;
47   }
48   cooked_ = true;
49   auto &messages{foldingContext.messages()};
50   if (IsForwardReferenced()) {
51     messages.Say(typeSymbol_.name(),
52         "Derived type '%s' was used but never defined"_err_en_US,
53         typeSymbol_.name());
54     return;
55   }
56 
57   // Parameters of the most deeply nested "base class" come first when the
58   // derived type is an extension.
59   auto parameterNames{OrderParameterNames(typeSymbol_)};
60   auto parameterDecls{OrderParameterDeclarations(typeSymbol_)};
61   auto nextNameIter{parameterNames.begin()};
62   RawParameters raw{std::move(rawParameters_)};
63   for (auto &[maybeKeyword, value] : raw) {
64     SourceName name;
65     common::TypeParamAttr attr{common::TypeParamAttr::Kind};
66     if (maybeKeyword) {
67       name = maybeKeyword->v.source;
68       auto it{std::find_if(parameterDecls.begin(), parameterDecls.end(),
69           [&](const Symbol &symbol) { return symbol.name() == name; })};
70       if (it == parameterDecls.end()) {
71         messages.Say(name,
72             "'%s' is not the name of a parameter for derived type '%s'"_err_en_US,
73             name, typeSymbol_.name());
74       } else {
75         // Resolve the keyword's symbol
76         maybeKeyword->v.symbol = const_cast<Symbol *>(&it->get());
77         attr = it->get().get<TypeParamDetails>().attr();
78       }
79     } else if (nextNameIter != parameterNames.end()) {
80       name = *nextNameIter++;
81       auto it{std::find_if(parameterDecls.begin(), parameterDecls.end(),
82           [&](const Symbol &symbol) { return symbol.name() == name; })};
83       if (it == parameterDecls.end()) {
84         break;
85       }
86       attr = it->get().get<TypeParamDetails>().attr();
87     } else {
88       messages.Say(name_,
89           "Too many type parameters given for derived type '%s'"_err_en_US,
90           typeSymbol_.name());
91       break;
92     }
93     if (FindParameter(name)) {
94       messages.Say(name_,
95           "Multiple values given for type parameter '%s'"_err_en_US, name);
96     } else {
97       value.set_attr(attr);
98       AddParamValue(name, std::move(value));
99     }
100   }
101 }
102 
103 void DerivedTypeSpec::EvaluateParameters(SemanticsContext &context) {
104   evaluate::FoldingContext &foldingContext{context.foldingContext()};
105   CookParameters(foldingContext);
106   if (evaluated_) {
107     return;
108   }
109   evaluated_ = true;
110   auto &messages{foldingContext.messages()};
111 
112   // Fold the explicit type parameter value expressions first.  Do not
113   // fold them within the scope of the derived type being instantiated;
114   // these expressions cannot use its type parameters.  Convert the values
115   // of the expressions to the declared types of the type parameters.
116   auto parameterDecls{OrderParameterDeclarations(typeSymbol_)};
117   for (const Symbol &symbol : parameterDecls) {
118     const SourceName &name{symbol.name()};
119     if (ParamValue * paramValue{FindParameter(name)}) {
120       if (const MaybeIntExpr & expr{paramValue->GetExplicit()}) {
121         if (auto converted{evaluate::ConvertToType(symbol, SomeExpr{*expr})}) {
122           SomeExpr folded{
123               evaluate::Fold(foldingContext, std::move(*converted))};
124           if (auto *intExpr{std::get_if<SomeIntExpr>(&folded.u)}) {
125             paramValue->SetExplicit(std::move(*intExpr));
126             continue;
127           }
128         }
129         if (!context.HasError(symbol)) {
130           evaluate::SayWithDeclaration(messages, symbol,
131               "Value of type parameter '%s' (%s) is not convertible to its"
132               " type"_err_en_US,
133               name, expr->AsFortran());
134         }
135       }
136     }
137   }
138 
139   // Default initialization expressions for the derived type's parameters
140   // may reference other parameters so long as the declaration precedes the
141   // use in the expression (10.1.12).  This is not necessarily the same
142   // order as "type parameter order" (7.5.3.2).
143   // Type parameter default value expressions are folded in declaration order
144   // within the scope of the derived type so that the values of earlier type
145   // parameters are available for use in the default initialization
146   // expressions of later parameters.
147   auto restorer{foldingContext.WithPDTInstance(*this)};
148   for (const Symbol &symbol : parameterDecls) {
149     const SourceName &name{symbol.name()};
150     if (!FindParameter(name)) {
151       const TypeParamDetails &details{symbol.get<TypeParamDetails>()};
152       if (details.init()) {
153         auto expr{evaluate::Fold(foldingContext, SomeExpr{*details.init()})};
154         AddParamValue(name,
155             ParamValue{
156                 std::move(std::get<SomeIntExpr>(expr.u)), details.attr()});
157       } else if (!context.HasError(symbol)) {
158         messages.Say(name_,
159             "Type parameter '%s' lacks a value and has no default"_err_en_US,
160             name);
161       }
162     }
163   }
164 }
165 
166 void DerivedTypeSpec::AddParamValue(SourceName name, ParamValue &&value) {
167   CHECK(cooked_);
168   auto pair{parameters_.insert(std::make_pair(name, std::move(value)))};
169   CHECK(pair.second); // name was not already present
170 }
171 
172 bool DerivedTypeSpec::MightBeParameterized() const {
173   return !cooked_ || !parameters_.empty();
174 }
175 
176 bool DerivedTypeSpec::IsForwardReferenced() const {
177   return typeSymbol_.get<DerivedTypeDetails>().isForwardReferenced();
178 }
179 
180 bool DerivedTypeSpec::HasDefaultInitialization(bool ignoreAllocatable) const {
181   DirectComponentIterator components{*this};
182   return bool{std::find_if(
183       components.begin(), components.end(), [&](const Symbol &component) {
184         return IsInitialized(component, true, ignoreAllocatable);
185       })};
186 }
187 
188 bool DerivedTypeSpec::HasDestruction() const {
189   if (!typeSymbol().get<DerivedTypeDetails>().finals().empty()) {
190     return true;
191   }
192   DirectComponentIterator components{*this};
193   return bool{std::find_if(
194       components.begin(), components.end(), [&](const Symbol &component) {
195         return IsDestructible(component, &typeSymbol());
196       })};
197 }
198 
199 ParamValue *DerivedTypeSpec::FindParameter(SourceName target) {
200   return const_cast<ParamValue *>(
201       const_cast<const DerivedTypeSpec *>(this)->FindParameter(target));
202 }
203 
204 class InstantiateHelper {
205 public:
206   InstantiateHelper(Scope &scope) : scope_{scope} {}
207   // Instantiate components from fromScope into scope_
208   void InstantiateComponents(const Scope &);
209 
210 private:
211   SemanticsContext &context() const { return scope_.context(); }
212   evaluate::FoldingContext &foldingContext() {
213     return context().foldingContext();
214   }
215   template <typename A> A Fold(A &&expr) {
216     return evaluate::Fold(foldingContext(), std::move(expr));
217   }
218   void InstantiateComponent(const Symbol &);
219   const DeclTypeSpec *InstantiateType(const Symbol &);
220   const DeclTypeSpec &InstantiateIntrinsicType(
221       SourceName, const DeclTypeSpec &);
222   DerivedTypeSpec CreateDerivedTypeSpec(const DerivedTypeSpec &, bool);
223 
224   Scope &scope_;
225 };
226 
227 static int PlumbPDTInstantiationDepth(const Scope *scope) {
228   int depth{0};
229   while (scope->IsParameterizedDerivedTypeInstantiation()) {
230     ++depth;
231     scope = &scope->parent();
232   }
233   return depth;
234 }
235 
236 // Completes component derived type instantiation and initializer folding
237 // for a non-parameterized derived type Scope.
238 static void InstantiateNonPDTScope(Scope &typeScope, Scope &containingScope) {
239   auto &context{containingScope.context()};
240   auto &foldingContext{context.foldingContext()};
241   for (auto &pair : typeScope) {
242     Symbol &symbol{*pair.second};
243     if (DeclTypeSpec * type{symbol.GetType()}) {
244       if (DerivedTypeSpec * derived{type->AsDerived()}) {
245         if (!(derived->IsForwardReferenced() &&
246                 IsAllocatableOrPointer(symbol))) {
247           derived->Instantiate(containingScope);
248         }
249       }
250     }
251     if (!IsPointer(symbol)) {
252       if (auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
253         if (MaybeExpr & init{object->init()}) {
254           auto restorer{foldingContext.messages().SetLocation(symbol.name())};
255           init = evaluate::NonPointerInitializationExpr(
256               symbol, std::move(*init), foldingContext);
257         }
258       }
259     }
260   }
261   ComputeOffsets(context, typeScope);
262 }
263 
264 void DerivedTypeSpec::Instantiate(Scope &containingScope) {
265   if (instantiated_) {
266     return;
267   }
268   instantiated_ = true;
269   auto &context{containingScope.context()};
270   auto &foldingContext{context.foldingContext()};
271   if (IsForwardReferenced()) {
272     foldingContext.messages().Say(typeSymbol_.name(),
273         "The derived type '%s' was forward-referenced but not defined"_err_en_US,
274         typeSymbol_.name());
275     context.SetError(typeSymbol_);
276     return;
277   }
278   EvaluateParameters(context);
279   const Scope &typeScope{DEREF(typeSymbol_.scope())};
280   if (!MightBeParameterized()) {
281     scope_ = &typeScope;
282     if (typeScope.derivedTypeSpec()) {
283       CHECK(*this == *typeScope.derivedTypeSpec());
284     } else {
285       Scope &mutableTypeScope{const_cast<Scope &>(typeScope)};
286       mutableTypeScope.set_derivedTypeSpec(*this);
287       InstantiateNonPDTScope(mutableTypeScope, containingScope);
288     }
289     return;
290   }
291   // New PDT instantiation.  Create a new scope and populate it
292   // with components that have been specialized for this set of
293   // parameters.
294   Scope &newScope{containingScope.MakeScope(Scope::Kind::DerivedType)};
295   newScope.set_derivedTypeSpec(*this);
296   ReplaceScope(newScope);
297   auto restorer{foldingContext.WithPDTInstance(*this)};
298   std::string desc{typeSymbol_.name().ToString()};
299   char sep{'('};
300   for (const Symbol &symbol : OrderParameterDeclarations(typeSymbol_)) {
301     const SourceName &name{symbol.name()};
302     if (typeScope.find(symbol.name()) != typeScope.end()) {
303       // This type parameter belongs to the derived type itself, not to
304       // one of its ancestors.  Put the type parameter expression value
305       // into the new scope as the initialization value for the parameter.
306       if (ParamValue * paramValue{FindParameter(name)}) {
307         const TypeParamDetails &details{symbol.get<TypeParamDetails>()};
308         paramValue->set_attr(details.attr());
309         if (MaybeIntExpr expr{paramValue->GetExplicit()}) {
310           if (auto folded{evaluate::NonPointerInitializationExpr(symbol,
311                   SomeExpr{std::move(*expr)}, foldingContext, &newScope)}) {
312             desc += sep;
313             desc += name.ToString();
314             desc += '=';
315             desc += folded->AsFortran();
316             sep = ',';
317             TypeParamDetails instanceDetails{details.attr()};
318             if (const DeclTypeSpec * type{details.type()}) {
319               instanceDetails.set_type(*type);
320             }
321             instanceDetails.set_init(
322                 std::move(DEREF(evaluate::UnwrapExpr<SomeIntExpr>(*folded))));
323             newScope.try_emplace(name, std::move(instanceDetails));
324           }
325         }
326       }
327     }
328   }
329   parser::Message *contextMessage{nullptr};
330   if (sep != '(') {
331     desc += ')';
332     contextMessage = new parser::Message{foldingContext.messages().at(),
333         "instantiation of parameterized derived type '%s'"_en_US, desc};
334     if (auto outer{containingScope.instantiationContext()}) {
335       contextMessage->SetContext(outer.get());
336     }
337     newScope.set_instantiationContext(contextMessage);
338   }
339   // Instantiate every non-parameter symbol from the original derived
340   // type's scope into the new instance.
341   newScope.AddSourceRange(typeScope.sourceRange());
342   auto restorer2{foldingContext.messages().SetContext(contextMessage)};
343   if (PlumbPDTInstantiationDepth(&containingScope) > 100) {
344     foldingContext.messages().Say(
345         "Too many recursive parameterized derived type instantiations"_err_en_US);
346   } else {
347     InstantiateHelper{newScope}.InstantiateComponents(typeScope);
348   }
349 }
350 
351 void InstantiateHelper::InstantiateComponents(const Scope &fromScope) {
352   for (const auto &pair : fromScope) {
353     InstantiateComponent(*pair.second);
354   }
355   ComputeOffsets(context(), scope_);
356 }
357 
358 void InstantiateHelper::InstantiateComponent(const Symbol &oldSymbol) {
359   auto pair{scope_.try_emplace(
360       oldSymbol.name(), oldSymbol.attrs(), common::Clone(oldSymbol.details()))};
361   Symbol &newSymbol{*pair.first->second};
362   if (!pair.second) {
363     // Symbol was already present in the scope, which can only happen
364     // in the case of type parameters.
365     CHECK(oldSymbol.has<TypeParamDetails>());
366     return;
367   }
368   newSymbol.flags() = oldSymbol.flags();
369   if (auto *details{newSymbol.detailsIf<ObjectEntityDetails>()}) {
370     if (const DeclTypeSpec * newType{InstantiateType(newSymbol)}) {
371       details->ReplaceType(*newType);
372     }
373     for (ShapeSpec &dim : details->shape()) {
374       if (dim.lbound().isExplicit()) {
375         dim.lbound().SetExplicit(Fold(std::move(dim.lbound().GetExplicit())));
376       }
377       if (dim.ubound().isExplicit()) {
378         dim.ubound().SetExplicit(Fold(std::move(dim.ubound().GetExplicit())));
379       }
380     }
381     for (ShapeSpec &dim : details->coshape()) {
382       if (dim.lbound().isExplicit()) {
383         dim.lbound().SetExplicit(Fold(std::move(dim.lbound().GetExplicit())));
384       }
385       if (dim.ubound().isExplicit()) {
386         dim.ubound().SetExplicit(Fold(std::move(dim.ubound().GetExplicit())));
387       }
388     }
389     if (MaybeExpr & init{details->init()}) {
390       // Non-pointer components with default initializers are
391       // processed now so that those default initializers can be used
392       // in PARAMETER structure constructors.
393       auto restorer{foldingContext().messages().SetLocation(newSymbol.name())};
394       init = IsPointer(newSymbol)
395           ? Fold(std::move(*init))
396           : evaluate::NonPointerInitializationExpr(
397                 newSymbol, std::move(*init), foldingContext());
398     }
399   } else if (auto *procDetails{newSymbol.detailsIf<ProcEntityDetails>()}) {
400     // We have a procedure pointer.  Instantiate its return type
401     if (const DeclTypeSpec * returnType{InstantiateType(newSymbol)}) {
402       ProcInterface &interface{procDetails->interface()};
403       if (!interface.symbol()) {
404         // Don't change the type for interfaces based on symbols
405         interface.set_type(*returnType);
406       }
407     }
408   }
409 }
410 
411 const DeclTypeSpec *InstantiateHelper::InstantiateType(const Symbol &symbol) {
412   const DeclTypeSpec *type{symbol.GetType()};
413   if (!type) {
414     return nullptr; // error has occurred
415   } else if (const DerivedTypeSpec * spec{type->AsDerived()}) {
416     return &FindOrInstantiateDerivedType(scope_,
417         CreateDerivedTypeSpec(*spec, symbol.test(Symbol::Flag::ParentComp)),
418         type->category());
419   } else if (type->AsIntrinsic()) {
420     return &InstantiateIntrinsicType(symbol.name(), *type);
421   } else if (type->category() == DeclTypeSpec::ClassStar) {
422     return type;
423   } else {
424     common::die("InstantiateType: %s", type->AsFortran().c_str());
425   }
426 }
427 
428 // Apply type parameter values to an intrinsic type spec.
429 const DeclTypeSpec &InstantiateHelper::InstantiateIntrinsicType(
430     SourceName symbolName, const DeclTypeSpec &spec) {
431   const IntrinsicTypeSpec &intrinsic{DEREF(spec.AsIntrinsic())};
432   if (evaluate::ToInt64(intrinsic.kind())) {
433     return spec; // KIND is already a known constant
434   }
435   // The expression was not originally constant, but now it must be so
436   // in the context of a parameterized derived type instantiation.
437   KindExpr copy{Fold(common::Clone(intrinsic.kind()))};
438   int kind{context().GetDefaultKind(intrinsic.category())};
439   if (auto value{evaluate::ToInt64(copy)}) {
440     if (evaluate::IsValidKindOfIntrinsicType(intrinsic.category(), *value)) {
441       kind = *value;
442     } else {
443       foldingContext().messages().Say(symbolName,
444           "KIND parameter value (%jd) of intrinsic type %s "
445           "did not resolve to a supported value"_err_en_US,
446           *value,
447           parser::ToUpperCaseLetters(EnumToString(intrinsic.category())));
448     }
449   }
450   switch (spec.category()) {
451   case DeclTypeSpec::Numeric:
452     return scope_.MakeNumericType(intrinsic.category(), KindExpr{kind});
453   case DeclTypeSpec::Logical:
454     return scope_.MakeLogicalType(KindExpr{kind});
455   case DeclTypeSpec::Character:
456     return scope_.MakeCharacterType(
457         ParamValue{spec.characterTypeSpec().length()}, KindExpr{kind});
458   default:
459     CRASH_NO_CASE;
460   }
461 }
462 
463 DerivedTypeSpec InstantiateHelper::CreateDerivedTypeSpec(
464     const DerivedTypeSpec &spec, bool isParentComp) {
465   DerivedTypeSpec result{spec};
466   result.CookParameters(foldingContext()); // enables AddParamValue()
467   if (isParentComp) {
468     // Forward any explicit type parameter values from the
469     // derived type spec under instantiation that define type parameters
470     // of the parent component to the derived type spec of the
471     // parent component.
472     const DerivedTypeSpec &instanceSpec{DEREF(foldingContext().pdtInstance())};
473     for (const auto &[name, value] : instanceSpec.parameters()) {
474       if (scope_.find(name) == scope_.end()) {
475         result.AddParamValue(name, ParamValue{value});
476       }
477     }
478   }
479   return result;
480 }
481 
482 std::string DerivedTypeSpec::AsFortran() const {
483   std::string buf;
484   llvm::raw_string_ostream ss{buf};
485   ss << name_;
486   if (!rawParameters_.empty()) {
487     CHECK(parameters_.empty());
488     ss << '(';
489     bool first = true;
490     for (const auto &[maybeKeyword, value] : rawParameters_) {
491       if (first) {
492         first = false;
493       } else {
494         ss << ',';
495       }
496       if (maybeKeyword) {
497         ss << maybeKeyword->v.source.ToString() << '=';
498       }
499       ss << value.AsFortran();
500     }
501     ss << ')';
502   } else if (!parameters_.empty()) {
503     ss << '(';
504     bool first = true;
505     for (const auto &[name, value] : parameters_) {
506       if (first) {
507         first = false;
508       } else {
509         ss << ',';
510       }
511       ss << name.ToString() << '=' << value.AsFortran();
512     }
513     ss << ')';
514   }
515   return ss.str();
516 }
517 
518 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const DerivedTypeSpec &x) {
519   return o << x.AsFortran();
520 }
521 
522 Bound::Bound(common::ConstantSubscript bound) : expr_{bound} {}
523 
524 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const Bound &x) {
525   if (x.isStar()) {
526     o << '*';
527   } else if (x.isColon()) {
528     o << ':';
529   } else if (x.expr_) {
530     x.expr_->AsFortran(o);
531   } else {
532     o << "<no-expr>";
533   }
534   return o;
535 }
536 
537 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const ShapeSpec &x) {
538   if (x.lb_.isStar()) {
539     CHECK(x.ub_.isStar());
540     o << "..";
541   } else {
542     if (!x.lb_.isColon()) {
543       o << x.lb_;
544     }
545     o << ':';
546     if (!x.ub_.isColon()) {
547       o << x.ub_;
548     }
549   }
550   return o;
551 }
552 
553 llvm::raw_ostream &operator<<(
554     llvm::raw_ostream &os, const ArraySpec &arraySpec) {
555   char sep{'('};
556   for (auto &shape : arraySpec) {
557     os << sep << shape;
558     sep = ',';
559   }
560   if (sep == ',') {
561     os << ')';
562   }
563   return os;
564 }
565 
566 ParamValue::ParamValue(MaybeIntExpr &&expr, common::TypeParamAttr attr)
567     : attr_{attr}, expr_{std::move(expr)} {}
568 ParamValue::ParamValue(SomeIntExpr &&expr, common::TypeParamAttr attr)
569     : attr_{attr}, expr_{std::move(expr)} {}
570 ParamValue::ParamValue(
571     common::ConstantSubscript value, common::TypeParamAttr attr)
572     : ParamValue(SomeIntExpr{evaluate::Expr<evaluate::SubscriptInteger>{value}},
573           attr) {}
574 
575 void ParamValue::SetExplicit(SomeIntExpr &&x) {
576   category_ = Category::Explicit;
577   expr_ = std::move(x);
578 }
579 
580 std::string ParamValue::AsFortran() const {
581   switch (category_) {
582     SWITCH_COVERS_ALL_CASES
583   case Category::Assumed:
584     return "*";
585   case Category::Deferred:
586     return ":";
587   case Category::Explicit:
588     if (expr_) {
589       std::string buf;
590       llvm::raw_string_ostream ss{buf};
591       expr_->AsFortran(ss);
592       return ss.str();
593     } else {
594       return "";
595     }
596   }
597 }
598 
599 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const ParamValue &x) {
600   return o << x.AsFortran();
601 }
602 
603 IntrinsicTypeSpec::IntrinsicTypeSpec(TypeCategory category, KindExpr &&kind)
604     : category_{category}, kind_{std::move(kind)} {
605   CHECK(category != TypeCategory::Derived);
606 }
607 
608 static std::string KindAsFortran(const KindExpr &kind) {
609   std::string buf;
610   llvm::raw_string_ostream ss{buf};
611   if (auto k{evaluate::ToInt64(kind)}) {
612     ss << *k; // emit unsuffixed kind code
613   } else {
614     kind.AsFortran(ss);
615   }
616   return ss.str();
617 }
618 
619 std::string IntrinsicTypeSpec::AsFortran() const {
620   return parser::ToUpperCaseLetters(common::EnumToString(category_)) + '(' +
621       KindAsFortran(kind_) + ')';
622 }
623 
624 llvm::raw_ostream &operator<<(
625     llvm::raw_ostream &os, const IntrinsicTypeSpec &x) {
626   return os << x.AsFortran();
627 }
628 
629 std::string CharacterTypeSpec::AsFortran() const {
630   return "CHARACTER(" + length_.AsFortran() + ',' + KindAsFortran(kind()) + ')';
631 }
632 
633 llvm::raw_ostream &operator<<(
634     llvm::raw_ostream &os, const CharacterTypeSpec &x) {
635   return os << x.AsFortran();
636 }
637 
638 DeclTypeSpec::DeclTypeSpec(NumericTypeSpec &&typeSpec)
639     : category_{Numeric}, typeSpec_{std::move(typeSpec)} {}
640 DeclTypeSpec::DeclTypeSpec(LogicalTypeSpec &&typeSpec)
641     : category_{Logical}, typeSpec_{std::move(typeSpec)} {}
642 DeclTypeSpec::DeclTypeSpec(const CharacterTypeSpec &typeSpec)
643     : category_{Character}, typeSpec_{typeSpec} {}
644 DeclTypeSpec::DeclTypeSpec(CharacterTypeSpec &&typeSpec)
645     : category_{Character}, typeSpec_{std::move(typeSpec)} {}
646 DeclTypeSpec::DeclTypeSpec(Category category, const DerivedTypeSpec &typeSpec)
647     : category_{category}, typeSpec_{typeSpec} {
648   CHECK(category == TypeDerived || category == ClassDerived);
649 }
650 DeclTypeSpec::DeclTypeSpec(Category category, DerivedTypeSpec &&typeSpec)
651     : category_{category}, typeSpec_{std::move(typeSpec)} {
652   CHECK(category == TypeDerived || category == ClassDerived);
653 }
654 DeclTypeSpec::DeclTypeSpec(Category category) : category_{category} {
655   CHECK(category == TypeStar || category == ClassStar);
656 }
657 bool DeclTypeSpec::IsNumeric(TypeCategory tc) const {
658   return category_ == Numeric && numericTypeSpec().category() == tc;
659 }
660 bool DeclTypeSpec::IsSequenceType() const {
661   if (const DerivedTypeSpec * derivedType{AsDerived()}) {
662     const auto *typeDetails{
663         derivedType->typeSymbol().detailsIf<DerivedTypeDetails>()};
664     return typeDetails && typeDetails->sequence();
665   }
666   return false;
667 }
668 
669 const NumericTypeSpec &DeclTypeSpec::numericTypeSpec() const {
670   CHECK(category_ == Numeric);
671   return std::get<NumericTypeSpec>(typeSpec_);
672 }
673 const LogicalTypeSpec &DeclTypeSpec::logicalTypeSpec() const {
674   CHECK(category_ == Logical);
675   return std::get<LogicalTypeSpec>(typeSpec_);
676 }
677 bool DeclTypeSpec::operator==(const DeclTypeSpec &that) const {
678   return category_ == that.category_ && typeSpec_ == that.typeSpec_;
679 }
680 
681 std::string DeclTypeSpec::AsFortran() const {
682   switch (category_) {
683     SWITCH_COVERS_ALL_CASES
684   case Numeric:
685     return numericTypeSpec().AsFortran();
686   case Logical:
687     return logicalTypeSpec().AsFortran();
688   case Character:
689     return characterTypeSpec().AsFortran();
690   case TypeDerived:
691     if (derivedTypeSpec()
692             .typeSymbol()
693             .get<DerivedTypeDetails>()
694             .isDECStructure()) {
695       return "RECORD" + derivedTypeSpec().typeSymbol().name().ToString();
696     } else {
697       return "TYPE(" + derivedTypeSpec().AsFortran() + ')';
698     }
699   case ClassDerived:
700     return "CLASS(" + derivedTypeSpec().AsFortran() + ')';
701   case TypeStar:
702     return "TYPE(*)";
703   case ClassStar:
704     return "CLASS(*)";
705   }
706 }
707 
708 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const DeclTypeSpec &x) {
709   return o << x.AsFortran();
710 }
711 
712 void ProcInterface::set_symbol(const Symbol &symbol) {
713   CHECK(!type_);
714   symbol_ = &symbol;
715 }
716 void ProcInterface::set_type(const DeclTypeSpec &type) {
717   CHECK(!symbol_);
718   type_ = &type;
719 }
720 
721 } // namespace Fortran::semantics
722