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() const { 181 DirectComponentIterator components{*this}; 182 return bool{std::find_if(components.begin(), components.end(), 183 [&](const Symbol &component) { return IsInitialized(component); })}; 184 } 185 186 bool DerivedTypeSpec::HasDestruction() const { 187 if (!typeSymbol().get<DerivedTypeDetails>().finals().empty()) { 188 return true; 189 } 190 DirectComponentIterator components{*this}; 191 return bool{std::find_if( 192 components.begin(), components.end(), [&](const Symbol &component) { 193 return IsDestructible(component, &typeSymbol()); 194 })}; 195 } 196 197 ParamValue *DerivedTypeSpec::FindParameter(SourceName target) { 198 return const_cast<ParamValue *>( 199 const_cast<const DerivedTypeSpec *>(this)->FindParameter(target)); 200 } 201 202 // Objects of derived types might be assignment compatible if they are equal 203 // with respect to everything other than their instantiated type parameters 204 // and their constant instantiated type parameters have the same values. 205 bool DerivedTypeSpec::MightBeAssignmentCompatibleWith( 206 const DerivedTypeSpec &that) const { 207 if (!RawEquals(that)) { 208 return false; 209 } 210 return AreTypeParamCompatible(*this, that); 211 } 212 213 class InstantiateHelper { 214 public: 215 InstantiateHelper(Scope &scope) : scope_{scope} {} 216 // Instantiate components from fromScope into scope_ 217 void InstantiateComponents(const Scope &); 218 219 private: 220 SemanticsContext &context() const { return scope_.context(); } 221 evaluate::FoldingContext &foldingContext() { 222 return context().foldingContext(); 223 } 224 template <typename A> A Fold(A &&expr) { 225 return evaluate::Fold(foldingContext(), std::move(expr)); 226 } 227 void InstantiateComponent(const Symbol &); 228 const DeclTypeSpec *InstantiateType(const Symbol &); 229 const DeclTypeSpec &InstantiateIntrinsicType( 230 SourceName, const DeclTypeSpec &); 231 DerivedTypeSpec CreateDerivedTypeSpec(const DerivedTypeSpec &, bool); 232 233 Scope &scope_; 234 }; 235 236 static int PlumbPDTInstantiationDepth(const Scope *scope) { 237 int depth{0}; 238 while (scope->IsParameterizedDerivedTypeInstantiation()) { 239 ++depth; 240 scope = &scope->parent(); 241 } 242 return depth; 243 } 244 245 // Completes component derived type instantiation and initializer folding 246 // for a non-parameterized derived type Scope. 247 static void InstantiateNonPDTScope(Scope &typeScope, Scope &containingScope) { 248 auto &context{containingScope.context()}; 249 auto &foldingContext{context.foldingContext()}; 250 for (auto &pair : typeScope) { 251 Symbol &symbol{*pair.second}; 252 if (DeclTypeSpec * type{symbol.GetType()}) { 253 if (DerivedTypeSpec * derived{type->AsDerived()}) { 254 if (!(derived->IsForwardReferenced() && 255 IsAllocatableOrPointer(symbol))) { 256 derived->Instantiate(containingScope); 257 } 258 } 259 } 260 if (!IsPointer(symbol)) { 261 if (auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { 262 if (MaybeExpr & init{object->init()}) { 263 auto restorer{foldingContext.messages().SetLocation(symbol.name())}; 264 init = evaluate::NonPointerInitializationExpr( 265 symbol, std::move(*init), foldingContext); 266 } 267 } 268 } 269 } 270 ComputeOffsets(context, typeScope); 271 } 272 273 void DerivedTypeSpec::Instantiate(Scope &containingScope) { 274 if (instantiated_) { 275 return; 276 } 277 instantiated_ = true; 278 auto &context{containingScope.context()}; 279 auto &foldingContext{context.foldingContext()}; 280 if (IsForwardReferenced()) { 281 foldingContext.messages().Say(typeSymbol_.name(), 282 "The derived type '%s' was forward-referenced but not defined"_err_en_US, 283 typeSymbol_.name()); 284 context.SetError(typeSymbol_); 285 return; 286 } 287 EvaluateParameters(context); 288 const Scope &typeScope{DEREF(typeSymbol_.scope())}; 289 if (!MightBeParameterized()) { 290 scope_ = &typeScope; 291 if (typeScope.derivedTypeSpec()) { 292 CHECK(*this == *typeScope.derivedTypeSpec()); 293 } else { 294 Scope &mutableTypeScope{const_cast<Scope &>(typeScope)}; 295 mutableTypeScope.set_derivedTypeSpec(*this); 296 InstantiateNonPDTScope(mutableTypeScope, containingScope); 297 } 298 return; 299 } 300 // New PDT instantiation. Create a new scope and populate it 301 // with components that have been specialized for this set of 302 // parameters. 303 Scope &newScope{containingScope.MakeScope(Scope::Kind::DerivedType)}; 304 newScope.set_derivedTypeSpec(*this); 305 ReplaceScope(newScope); 306 auto restorer{foldingContext.WithPDTInstance(*this)}; 307 std::string desc{typeSymbol_.name().ToString()}; 308 char sep{'('}; 309 for (const Symbol &symbol : OrderParameterDeclarations(typeSymbol_)) { 310 const SourceName &name{symbol.name()}; 311 if (typeScope.find(symbol.name()) != typeScope.end()) { 312 // This type parameter belongs to the derived type itself, not to 313 // one of its ancestors. Put the type parameter expression value 314 // into the new scope as the initialization value for the parameter. 315 if (ParamValue * paramValue{FindParameter(name)}) { 316 const TypeParamDetails &details{symbol.get<TypeParamDetails>()}; 317 paramValue->set_attr(details.attr()); 318 if (MaybeIntExpr expr{paramValue->GetExplicit()}) { 319 if (auto folded{evaluate::NonPointerInitializationExpr(symbol, 320 SomeExpr{std::move(*expr)}, foldingContext, &newScope)}) { 321 desc += sep; 322 desc += name.ToString(); 323 desc += '='; 324 desc += folded->AsFortran(); 325 sep = ','; 326 TypeParamDetails instanceDetails{details.attr()}; 327 if (const DeclTypeSpec * type{details.type()}) { 328 instanceDetails.set_type(*type); 329 } 330 instanceDetails.set_init( 331 std::move(DEREF(evaluate::UnwrapExpr<SomeIntExpr>(*folded)))); 332 newScope.try_emplace(name, std::move(instanceDetails)); 333 } 334 } 335 } 336 } 337 } 338 parser::Message *contextMessage{nullptr}; 339 if (sep != '(') { 340 desc += ')'; 341 contextMessage = new parser::Message{foldingContext.messages().at(), 342 "instantiation of parameterized derived type '%s'"_en_US, desc}; 343 if (auto outer{containingScope.instantiationContext()}) { 344 contextMessage->SetContext(outer.get()); 345 } 346 newScope.set_instantiationContext(contextMessage); 347 } 348 // Instantiate every non-parameter symbol from the original derived 349 // type's scope into the new instance. 350 newScope.AddSourceRange(typeScope.sourceRange()); 351 auto restorer2{foldingContext.messages().SetContext(contextMessage)}; 352 if (PlumbPDTInstantiationDepth(&containingScope) > 100) { 353 foldingContext.messages().Say( 354 "Too many recursive parameterized derived type instantiations"_err_en_US); 355 } else { 356 InstantiateHelper{newScope}.InstantiateComponents(typeScope); 357 } 358 } 359 360 void InstantiateHelper::InstantiateComponents(const Scope &fromScope) { 361 for (const auto &pair : fromScope) { 362 InstantiateComponent(*pair.second); 363 } 364 ComputeOffsets(context(), scope_); 365 } 366 367 void InstantiateHelper::InstantiateComponent(const Symbol &oldSymbol) { 368 auto pair{scope_.try_emplace( 369 oldSymbol.name(), oldSymbol.attrs(), common::Clone(oldSymbol.details()))}; 370 Symbol &newSymbol{*pair.first->second}; 371 if (!pair.second) { 372 // Symbol was already present in the scope, which can only happen 373 // in the case of type parameters. 374 CHECK(oldSymbol.has<TypeParamDetails>()); 375 return; 376 } 377 newSymbol.flags() = oldSymbol.flags(); 378 if (auto *details{newSymbol.detailsIf<ObjectEntityDetails>()}) { 379 if (const DeclTypeSpec * newType{InstantiateType(newSymbol)}) { 380 details->ReplaceType(*newType); 381 } 382 for (ShapeSpec &dim : details->shape()) { 383 if (dim.lbound().isExplicit()) { 384 dim.lbound().SetExplicit(Fold(std::move(dim.lbound().GetExplicit()))); 385 } 386 if (dim.ubound().isExplicit()) { 387 dim.ubound().SetExplicit(Fold(std::move(dim.ubound().GetExplicit()))); 388 } 389 } 390 for (ShapeSpec &dim : details->coshape()) { 391 if (dim.lbound().isExplicit()) { 392 dim.lbound().SetExplicit(Fold(std::move(dim.lbound().GetExplicit()))); 393 } 394 if (dim.ubound().isExplicit()) { 395 dim.ubound().SetExplicit(Fold(std::move(dim.ubound().GetExplicit()))); 396 } 397 } 398 if (MaybeExpr & init{details->init()}) { 399 // Non-pointer components with default initializers are 400 // processed now so that those default initializers can be used 401 // in PARAMETER structure constructors. 402 auto restorer{foldingContext().messages().SetLocation(newSymbol.name())}; 403 init = IsPointer(newSymbol) 404 ? Fold(std::move(*init)) 405 : evaluate::NonPointerInitializationExpr( 406 newSymbol, std::move(*init), foldingContext()); 407 } 408 } else if (auto *procDetails{newSymbol.detailsIf<ProcEntityDetails>()}) { 409 // We have a procedure pointer. Instantiate its return type 410 if (const DeclTypeSpec * returnType{InstantiateType(newSymbol)}) { 411 ProcInterface &interface{procDetails->interface()}; 412 if (!interface.symbol()) { 413 // Don't change the type for interfaces based on symbols 414 interface.set_type(*returnType); 415 } 416 } 417 } 418 } 419 420 const DeclTypeSpec *InstantiateHelper::InstantiateType(const Symbol &symbol) { 421 const DeclTypeSpec *type{symbol.GetType()}; 422 if (!type) { 423 return nullptr; // error has occurred 424 } else if (const DerivedTypeSpec * spec{type->AsDerived()}) { 425 return &FindOrInstantiateDerivedType(scope_, 426 CreateDerivedTypeSpec(*spec, symbol.test(Symbol::Flag::ParentComp)), 427 type->category()); 428 } else if (type->AsIntrinsic()) { 429 return &InstantiateIntrinsicType(symbol.name(), *type); 430 } else if (type->category() == DeclTypeSpec::ClassStar) { 431 return type; 432 } else { 433 common::die("InstantiateType: %s", type->AsFortran().c_str()); 434 } 435 } 436 437 // Apply type parameter values to an intrinsic type spec. 438 const DeclTypeSpec &InstantiateHelper::InstantiateIntrinsicType( 439 SourceName symbolName, const DeclTypeSpec &spec) { 440 const IntrinsicTypeSpec &intrinsic{DEREF(spec.AsIntrinsic())}; 441 if (evaluate::ToInt64(intrinsic.kind())) { 442 return spec; // KIND is already a known constant 443 } 444 // The expression was not originally constant, but now it must be so 445 // in the context of a parameterized derived type instantiation. 446 KindExpr copy{Fold(common::Clone(intrinsic.kind()))}; 447 int kind{context().GetDefaultKind(intrinsic.category())}; 448 if (auto value{evaluate::ToInt64(copy)}) { 449 if (evaluate::IsValidKindOfIntrinsicType(intrinsic.category(), *value)) { 450 kind = *value; 451 } else { 452 foldingContext().messages().Say(symbolName, 453 "KIND parameter value (%jd) of intrinsic type %s " 454 "did not resolve to a supported value"_err_en_US, 455 *value, 456 parser::ToUpperCaseLetters(EnumToString(intrinsic.category()))); 457 } 458 } 459 switch (spec.category()) { 460 case DeclTypeSpec::Numeric: 461 return scope_.MakeNumericType(intrinsic.category(), KindExpr{kind}); 462 case DeclTypeSpec::Logical: 463 return scope_.MakeLogicalType(KindExpr{kind}); 464 case DeclTypeSpec::Character: 465 return scope_.MakeCharacterType( 466 ParamValue{spec.characterTypeSpec().length()}, KindExpr{kind}); 467 default: 468 CRASH_NO_CASE; 469 } 470 } 471 472 DerivedTypeSpec InstantiateHelper::CreateDerivedTypeSpec( 473 const DerivedTypeSpec &spec, bool isParentComp) { 474 DerivedTypeSpec result{spec}; 475 result.CookParameters(foldingContext()); // enables AddParamValue() 476 if (isParentComp) { 477 // Forward any explicit type parameter values from the 478 // derived type spec under instantiation that define type parameters 479 // of the parent component to the derived type spec of the 480 // parent component. 481 const DerivedTypeSpec &instanceSpec{DEREF(foldingContext().pdtInstance())}; 482 for (const auto &[name, value] : instanceSpec.parameters()) { 483 if (scope_.find(name) == scope_.end()) { 484 result.AddParamValue(name, ParamValue{value}); 485 } 486 } 487 } 488 return result; 489 } 490 491 std::string DerivedTypeSpec::AsFortran() const { 492 std::string buf; 493 llvm::raw_string_ostream ss{buf}; 494 ss << name_; 495 if (!rawParameters_.empty()) { 496 CHECK(parameters_.empty()); 497 ss << '('; 498 bool first = true; 499 for (const auto &[maybeKeyword, value] : rawParameters_) { 500 if (first) { 501 first = false; 502 } else { 503 ss << ','; 504 } 505 if (maybeKeyword) { 506 ss << maybeKeyword->v.source.ToString() << '='; 507 } 508 ss << value.AsFortran(); 509 } 510 ss << ')'; 511 } else if (!parameters_.empty()) { 512 ss << '('; 513 bool first = true; 514 for (const auto &[name, value] : parameters_) { 515 if (first) { 516 first = false; 517 } else { 518 ss << ','; 519 } 520 ss << name.ToString() << '=' << value.AsFortran(); 521 } 522 ss << ')'; 523 } 524 return ss.str(); 525 } 526 527 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const DerivedTypeSpec &x) { 528 return o << x.AsFortran(); 529 } 530 531 Bound::Bound(common::ConstantSubscript bound) : expr_{bound} {} 532 533 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const Bound &x) { 534 if (x.isAssumed()) { 535 o << '*'; 536 } else if (x.isDeferred()) { 537 o << ':'; 538 } else if (x.expr_) { 539 x.expr_->AsFortran(o); 540 } else { 541 o << "<no-expr>"; 542 } 543 return o; 544 } 545 546 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const ShapeSpec &x) { 547 if (x.lb_.isAssumed()) { 548 CHECK(x.ub_.isAssumed()); 549 o << ".."; 550 } else { 551 if (!x.lb_.isDeferred()) { 552 o << x.lb_; 553 } 554 o << ':'; 555 if (!x.ub_.isDeferred()) { 556 o << x.ub_; 557 } 558 } 559 return o; 560 } 561 562 llvm::raw_ostream &operator<<( 563 llvm::raw_ostream &os, const ArraySpec &arraySpec) { 564 char sep{'('}; 565 for (auto &shape : arraySpec) { 566 os << sep << shape; 567 sep = ','; 568 } 569 if (sep == ',') { 570 os << ')'; 571 } 572 return os; 573 } 574 575 ParamValue::ParamValue(MaybeIntExpr &&expr, common::TypeParamAttr attr) 576 : attr_{attr}, expr_{std::move(expr)} {} 577 ParamValue::ParamValue(SomeIntExpr &&expr, common::TypeParamAttr attr) 578 : attr_{attr}, expr_{std::move(expr)} {} 579 ParamValue::ParamValue( 580 common::ConstantSubscript value, common::TypeParamAttr attr) 581 : ParamValue(SomeIntExpr{evaluate::Expr<evaluate::SubscriptInteger>{value}}, 582 attr) {} 583 584 void ParamValue::SetExplicit(SomeIntExpr &&x) { 585 category_ = Category::Explicit; 586 expr_ = std::move(x); 587 } 588 589 std::string ParamValue::AsFortran() const { 590 switch (category_) { 591 SWITCH_COVERS_ALL_CASES 592 case Category::Assumed: 593 return "*"; 594 case Category::Deferred: 595 return ":"; 596 case Category::Explicit: 597 if (expr_) { 598 std::string buf; 599 llvm::raw_string_ostream ss{buf}; 600 expr_->AsFortran(ss); 601 return ss.str(); 602 } else { 603 return ""; 604 } 605 } 606 } 607 608 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const ParamValue &x) { 609 return o << x.AsFortran(); 610 } 611 612 IntrinsicTypeSpec::IntrinsicTypeSpec(TypeCategory category, KindExpr &&kind) 613 : category_{category}, kind_{std::move(kind)} { 614 CHECK(category != TypeCategory::Derived); 615 } 616 617 static std::string KindAsFortran(const KindExpr &kind) { 618 std::string buf; 619 llvm::raw_string_ostream ss{buf}; 620 if (auto k{evaluate::ToInt64(kind)}) { 621 ss << *k; // emit unsuffixed kind code 622 } else { 623 kind.AsFortran(ss); 624 } 625 return ss.str(); 626 } 627 628 std::string IntrinsicTypeSpec::AsFortran() const { 629 return parser::ToUpperCaseLetters(common::EnumToString(category_)) + '(' + 630 KindAsFortran(kind_) + ')'; 631 } 632 633 llvm::raw_ostream &operator<<( 634 llvm::raw_ostream &os, const IntrinsicTypeSpec &x) { 635 return os << x.AsFortran(); 636 } 637 638 std::string CharacterTypeSpec::AsFortran() const { 639 return "CHARACTER(" + length_.AsFortran() + ',' + KindAsFortran(kind()) + ')'; 640 } 641 642 llvm::raw_ostream &operator<<( 643 llvm::raw_ostream &os, const CharacterTypeSpec &x) { 644 return os << x.AsFortran(); 645 } 646 647 DeclTypeSpec::DeclTypeSpec(NumericTypeSpec &&typeSpec) 648 : category_{Numeric}, typeSpec_{std::move(typeSpec)} {} 649 DeclTypeSpec::DeclTypeSpec(LogicalTypeSpec &&typeSpec) 650 : category_{Logical}, typeSpec_{std::move(typeSpec)} {} 651 DeclTypeSpec::DeclTypeSpec(const CharacterTypeSpec &typeSpec) 652 : category_{Character}, typeSpec_{typeSpec} {} 653 DeclTypeSpec::DeclTypeSpec(CharacterTypeSpec &&typeSpec) 654 : category_{Character}, typeSpec_{std::move(typeSpec)} {} 655 DeclTypeSpec::DeclTypeSpec(Category category, const DerivedTypeSpec &typeSpec) 656 : category_{category}, typeSpec_{typeSpec} { 657 CHECK(category == TypeDerived || category == ClassDerived); 658 } 659 DeclTypeSpec::DeclTypeSpec(Category category, DerivedTypeSpec &&typeSpec) 660 : category_{category}, typeSpec_{std::move(typeSpec)} { 661 CHECK(category == TypeDerived || category == ClassDerived); 662 } 663 DeclTypeSpec::DeclTypeSpec(Category category) : category_{category} { 664 CHECK(category == TypeStar || category == ClassStar); 665 } 666 bool DeclTypeSpec::IsNumeric(TypeCategory tc) const { 667 return category_ == Numeric && numericTypeSpec().category() == tc; 668 } 669 bool DeclTypeSpec::IsSequenceType() const { 670 if (const DerivedTypeSpec * derivedType{AsDerived()}) { 671 const auto *typeDetails{ 672 derivedType->typeSymbol().detailsIf<DerivedTypeDetails>()}; 673 return typeDetails && typeDetails->sequence(); 674 } 675 return false; 676 } 677 678 const NumericTypeSpec &DeclTypeSpec::numericTypeSpec() const { 679 CHECK(category_ == Numeric); 680 return std::get<NumericTypeSpec>(typeSpec_); 681 } 682 const LogicalTypeSpec &DeclTypeSpec::logicalTypeSpec() const { 683 CHECK(category_ == Logical); 684 return std::get<LogicalTypeSpec>(typeSpec_); 685 } 686 bool DeclTypeSpec::operator==(const DeclTypeSpec &that) const { 687 return category_ == that.category_ && typeSpec_ == that.typeSpec_; 688 } 689 690 std::string DeclTypeSpec::AsFortran() const { 691 switch (category_) { 692 SWITCH_COVERS_ALL_CASES 693 case Numeric: 694 return numericTypeSpec().AsFortran(); 695 case Logical: 696 return logicalTypeSpec().AsFortran(); 697 case Character: 698 return characterTypeSpec().AsFortran(); 699 case TypeDerived: 700 return "TYPE(" + derivedTypeSpec().AsFortran() + ')'; 701 case ClassDerived: 702 return "CLASS(" + derivedTypeSpec().AsFortran() + ')'; 703 case TypeStar: 704 return "TYPE(*)"; 705 case ClassStar: 706 return "CLASS(*)"; 707 } 708 } 709 710 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const DeclTypeSpec &x) { 711 return o << x.AsFortran(); 712 } 713 714 void ProcInterface::set_symbol(const Symbol &symbol) { 715 CHECK(!type_); 716 symbol_ = &symbol; 717 } 718 void ProcInterface::set_type(const DeclTypeSpec &type) { 719 CHECK(!symbol_); 720 type_ = &type; 721 } 722 723 } // namespace Fortran::semantics 724