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