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