1 //===-- lib/Semantics/runtime-type-info.cpp ---------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "flang/Semantics/runtime-type-info.h" 10 #include "mod-file.h" 11 #include "flang/Evaluate/fold-designator.h" 12 #include "flang/Evaluate/fold.h" 13 #include "flang/Evaluate/tools.h" 14 #include "flang/Evaluate/type.h" 15 #include "flang/Semantics/scope.h" 16 #include "flang/Semantics/tools.h" 17 #include <functional> 18 #include <list> 19 #include <map> 20 #include <string> 21 22 namespace Fortran::semantics { 23 24 static int FindLenParameterIndex( 25 const SymbolVector ¶meters, const Symbol &symbol) { 26 int lenIndex{0}; 27 for (SymbolRef ref : parameters) { 28 if (&*ref == &symbol) { 29 return lenIndex; 30 } 31 if (ref->get<TypeParamDetails>().attr() == common::TypeParamAttr::Len) { 32 ++lenIndex; 33 } 34 } 35 DIE("Length type parameter not found in parameter order"); 36 return -1; 37 } 38 39 class RuntimeTableBuilder { 40 public: 41 RuntimeTableBuilder(SemanticsContext &, RuntimeDerivedTypeTables &); 42 void DescribeTypes(Scope &scope, bool inSchemata); 43 44 private: 45 const Symbol *DescribeType(Scope &); 46 const Symbol &GetSchemaSymbol(const char *) const; 47 const DeclTypeSpec &GetSchema(const char *) const; 48 SomeExpr GetEnumValue(const char *) const; 49 Symbol &CreateObject(const std::string &, const DeclTypeSpec &, Scope &); 50 // The names of created symbols are saved in and owned by the 51 // RuntimeDerivedTypeTables instance returned by 52 // BuildRuntimeDerivedTypeTables() so that references to those names remain 53 // valid for lowering. 54 SourceName SaveObjectName(const std::string &); 55 SomeExpr SaveNameAsPointerTarget(Scope &, const std::string &); 56 const SymbolVector *GetTypeParameters(const Symbol &); 57 evaluate::StructureConstructor DescribeComponent(const Symbol &, 58 const ObjectEntityDetails &, Scope &, Scope &, 59 const std::string &distinctName, const SymbolVector *parameters); 60 evaluate::StructureConstructor DescribeComponent( 61 const Symbol &, const ProcEntityDetails &, Scope &); 62 bool InitializeDataPointer(evaluate::StructureConstructorValues &, 63 const Symbol &symbol, const ObjectEntityDetails &object, Scope &scope, 64 Scope &dtScope, const std::string &distinctName); 65 evaluate::StructureConstructor PackageIntValue( 66 const SomeExpr &genre, std::int64_t = 0) const; 67 SomeExpr PackageIntValueExpr(const SomeExpr &genre, std::int64_t = 0) const; 68 std::vector<const Symbol *> CollectBindings(const Scope &dtScope) const; 69 std::vector<evaluate::StructureConstructor> DescribeBindings( 70 const Scope &dtScope, Scope &); 71 void DescribeGeneric( 72 const GenericDetails &, std::map<int, evaluate::StructureConstructor> &); 73 void DescribeSpecialProc(std::map<int, evaluate::StructureConstructor> &, 74 const Symbol &specificOrBinding, bool isAssignment, bool isFinal, 75 std::optional<GenericKind::DefinedIo>); 76 void IncorporateDefinedIoGenericInterfaces( 77 std::map<int, evaluate::StructureConstructor> &, SourceName, 78 GenericKind::DefinedIo, const Scope *); 79 80 // Instantiated for ParamValue and Bound 81 template <typename A> 82 evaluate::StructureConstructor GetValue( 83 const A &x, const SymbolVector *parameters) { 84 if (x.isExplicit()) { 85 return GetValue(x.GetExplicit(), parameters); 86 } else { 87 return PackageIntValue(deferredEnum_); 88 } 89 } 90 91 // Specialization for optional<Expr<SomeInteger and SubscriptInteger>> 92 template <typename T> 93 evaluate::StructureConstructor GetValue( 94 const std::optional<evaluate::Expr<T>> &expr, 95 const SymbolVector *parameters) { 96 if (auto constValue{evaluate::ToInt64(expr)}) { 97 return PackageIntValue(explicitEnum_, *constValue); 98 } 99 if (expr) { 100 if (parameters) { 101 if (const Symbol * lenParam{evaluate::ExtractBareLenParameter(*expr)}) { 102 return PackageIntValue( 103 lenParameterEnum_, FindLenParameterIndex(*parameters, *lenParam)); 104 } 105 } 106 context_.Say(location_, 107 "Specification expression '%s' is neither constant nor a length " 108 "type parameter"_err_en_US, 109 expr->AsFortran()); 110 } 111 return PackageIntValue(deferredEnum_); 112 } 113 114 SemanticsContext &context_; 115 RuntimeDerivedTypeTables &tables_; 116 std::map<const Symbol *, SymbolVector> orderedTypeParameters_; 117 int anonymousTypes_{0}; 118 119 const DeclTypeSpec &derivedTypeSchema_; // TYPE(DerivedType) 120 const DeclTypeSpec &componentSchema_; // TYPE(Component) 121 const DeclTypeSpec &procPtrSchema_; // TYPE(ProcPtrComponent) 122 const DeclTypeSpec &valueSchema_; // TYPE(Value) 123 const DeclTypeSpec &bindingSchema_; // TYPE(Binding) 124 const DeclTypeSpec &specialSchema_; // TYPE(SpecialBinding) 125 SomeExpr deferredEnum_; // Value::Genre::Deferred 126 SomeExpr explicitEnum_; // Value::Genre::Explicit 127 SomeExpr lenParameterEnum_; // Value::Genre::LenParameter 128 SomeExpr scalarAssignmentEnum_; // SpecialBinding::Which::ScalarAssignment 129 SomeExpr 130 elementalAssignmentEnum_; // SpecialBinding::Which::ElementalAssignment 131 SomeExpr readFormattedEnum_; // SpecialBinding::Which::ReadFormatted 132 SomeExpr readUnformattedEnum_; // SpecialBinding::Which::ReadUnformatted 133 SomeExpr writeFormattedEnum_; // SpecialBinding::Which::WriteFormatted 134 SomeExpr writeUnformattedEnum_; // SpecialBinding::Which::WriteUnformatted 135 SomeExpr elementalFinalEnum_; // SpecialBinding::Which::ElementalFinal 136 SomeExpr assumedRankFinalEnum_; // SpecialBinding::Which::AssumedRankFinal 137 SomeExpr scalarFinalEnum_; // SpecialBinding::Which::ScalarFinal 138 parser::CharBlock location_; 139 std::set<const Scope *> ignoreScopes_; 140 }; 141 142 RuntimeTableBuilder::RuntimeTableBuilder( 143 SemanticsContext &c, RuntimeDerivedTypeTables &t) 144 : context_{c}, tables_{t}, derivedTypeSchema_{GetSchema("derivedtype")}, 145 componentSchema_{GetSchema("component")}, procPtrSchema_{GetSchema( 146 "procptrcomponent")}, 147 valueSchema_{GetSchema("value")}, bindingSchema_{GetSchema("binding")}, 148 specialSchema_{GetSchema("specialbinding")}, deferredEnum_{GetEnumValue( 149 "deferred")}, 150 explicitEnum_{GetEnumValue("explicit")}, lenParameterEnum_{GetEnumValue( 151 "lenparameter")}, 152 scalarAssignmentEnum_{GetEnumValue("scalarassignment")}, 153 elementalAssignmentEnum_{GetEnumValue("elementalassignment")}, 154 readFormattedEnum_{GetEnumValue("readformatted")}, 155 readUnformattedEnum_{GetEnumValue("readunformatted")}, 156 writeFormattedEnum_{GetEnumValue("writeformatted")}, 157 writeUnformattedEnum_{GetEnumValue("writeunformatted")}, 158 elementalFinalEnum_{GetEnumValue("elementalfinal")}, 159 assumedRankFinalEnum_{GetEnumValue("assumedrankfinal")}, 160 scalarFinalEnum_{GetEnumValue("scalarfinal")} { 161 ignoreScopes_.insert(tables_.schemata); 162 } 163 164 void RuntimeTableBuilder::DescribeTypes(Scope &scope, bool inSchemata) { 165 inSchemata |= ignoreScopes_.find(&scope) != ignoreScopes_.end(); 166 if (scope.IsDerivedType()) { 167 if (!inSchemata) { // don't loop trying to describe a schema 168 DescribeType(scope); 169 } 170 } else { 171 scope.InstantiateDerivedTypes(); 172 } 173 for (Scope &child : scope.children()) { 174 DescribeTypes(child, inSchemata); 175 } 176 } 177 178 // Returns derived type instantiation's parameters in declaration order 179 const SymbolVector *RuntimeTableBuilder::GetTypeParameters( 180 const Symbol &symbol) { 181 auto iter{orderedTypeParameters_.find(&symbol)}; 182 if (iter != orderedTypeParameters_.end()) { 183 return &iter->second; 184 } else { 185 return &orderedTypeParameters_ 186 .emplace(&symbol, OrderParameterDeclarations(symbol)) 187 .first->second; 188 } 189 } 190 191 static Scope &GetContainingNonDerivedScope(Scope &scope) { 192 Scope *p{&scope}; 193 while (p->IsDerivedType()) { 194 p = &p->parent(); 195 } 196 return *p; 197 } 198 199 static const Symbol &GetSchemaField( 200 const DerivedTypeSpec &derived, const std::string &name) { 201 const Scope &scope{ 202 DEREF(derived.scope() ? derived.scope() : derived.typeSymbol().scope())}; 203 auto iter{scope.find(SourceName(name))}; 204 CHECK(iter != scope.end()); 205 return *iter->second; 206 } 207 208 static const Symbol &GetSchemaField( 209 const DeclTypeSpec &derived, const std::string &name) { 210 return GetSchemaField(DEREF(derived.AsDerived()), name); 211 } 212 213 static evaluate::StructureConstructorValues &AddValue( 214 evaluate::StructureConstructorValues &values, const DeclTypeSpec &spec, 215 const std::string &name, SomeExpr &&x) { 216 values.emplace(GetSchemaField(spec, name), std::move(x)); 217 return values; 218 } 219 220 static evaluate::StructureConstructorValues &AddValue( 221 evaluate::StructureConstructorValues &values, const DeclTypeSpec &spec, 222 const std::string &name, const SomeExpr &x) { 223 values.emplace(GetSchemaField(spec, name), x); 224 return values; 225 } 226 227 static SomeExpr IntToExpr(std::int64_t n) { 228 return evaluate::AsGenericExpr(evaluate::ExtentExpr{n}); 229 } 230 231 static evaluate::StructureConstructor Structure( 232 const DeclTypeSpec &spec, evaluate::StructureConstructorValues &&values) { 233 return {DEREF(spec.AsDerived()), std::move(values)}; 234 } 235 236 static SomeExpr StructureExpr(evaluate::StructureConstructor &&x) { 237 return SomeExpr{evaluate::Expr<evaluate::SomeDerived>{std::move(x)}}; 238 } 239 240 static int GetIntegerKind(const Symbol &symbol) { 241 auto dyType{evaluate::DynamicType::From(symbol)}; 242 CHECK(dyType && dyType->category() == TypeCategory::Integer); 243 return dyType->kind(); 244 } 245 246 // Save a rank-1 array constant of some numeric type as an 247 // initialized data object in a scope. 248 template <typename T> 249 static SomeExpr SaveNumericPointerTarget( 250 Scope &scope, SourceName name, std::vector<typename T::Scalar> &&x) { 251 if (x.empty()) { 252 return SomeExpr{evaluate::NullPointer{}}; 253 } else { 254 ObjectEntityDetails object; 255 if (const auto *spec{scope.FindType( 256 DeclTypeSpec{NumericTypeSpec{T::category, KindExpr{T::kind}}})}) { 257 object.set_type(*spec); 258 } else { 259 object.set_type(scope.MakeNumericType(T::category, KindExpr{T::kind})); 260 } 261 auto elements{static_cast<evaluate::ConstantSubscript>(x.size())}; 262 ArraySpec arraySpec; 263 arraySpec.push_back(ShapeSpec::MakeExplicit(Bound{0}, Bound{elements - 1})); 264 object.set_shape(arraySpec); 265 object.set_init(evaluate::AsGenericExpr(evaluate::Constant<T>{ 266 std::move(x), evaluate::ConstantSubscripts{elements}})); 267 Symbol &symbol{*scope 268 .try_emplace(name, Attrs{Attr::TARGET, Attr::SAVE}, 269 std::move(object)) 270 .first->second}; 271 symbol.set(Symbol::Flag::CompilerCreated); 272 return evaluate::AsGenericExpr( 273 evaluate::Expr<T>{evaluate::Designator<T>{symbol}}); 274 } 275 } 276 277 // Save an arbitrarily shaped array constant of some derived type 278 // as an initialized data object in a scope. 279 static SomeExpr SaveDerivedPointerTarget(Scope &scope, SourceName name, 280 std::vector<evaluate::StructureConstructor> &&x, 281 evaluate::ConstantSubscripts &&shape) { 282 if (x.empty()) { 283 return SomeExpr{evaluate::NullPointer{}}; 284 } else { 285 const auto &derivedType{x.front().GetType().GetDerivedTypeSpec()}; 286 ObjectEntityDetails object; 287 DeclTypeSpec typeSpec{DeclTypeSpec::TypeDerived, derivedType}; 288 if (const DeclTypeSpec * spec{scope.FindType(typeSpec)}) { 289 object.set_type(*spec); 290 } else { 291 object.set_type(scope.MakeDerivedType( 292 DeclTypeSpec::TypeDerived, common::Clone(derivedType))); 293 } 294 if (!shape.empty()) { 295 ArraySpec arraySpec; 296 for (auto n : shape) { 297 arraySpec.push_back(ShapeSpec::MakeExplicit(Bound{0}, Bound{n - 1})); 298 } 299 object.set_shape(arraySpec); 300 } 301 object.set_init( 302 evaluate::AsGenericExpr(evaluate::Constant<evaluate::SomeDerived>{ 303 derivedType, std::move(x), std::move(shape)})); 304 Symbol &symbol{*scope 305 .try_emplace(name, Attrs{Attr::TARGET, Attr::SAVE}, 306 std::move(object)) 307 .first->second}; 308 symbol.set(Symbol::Flag::CompilerCreated); 309 return evaluate::AsGenericExpr( 310 evaluate::Designator<evaluate::SomeDerived>{symbol}); 311 } 312 } 313 314 static SomeExpr SaveObjectInit( 315 Scope &scope, SourceName name, const ObjectEntityDetails &object) { 316 Symbol &symbol{*scope 317 .try_emplace(name, Attrs{Attr::TARGET, Attr::SAVE}, 318 ObjectEntityDetails{object}) 319 .first->second}; 320 CHECK(symbol.get<ObjectEntityDetails>().init().has_value()); 321 symbol.set(Symbol::Flag::CompilerCreated); 322 return evaluate::AsGenericExpr( 323 evaluate::Designator<evaluate::SomeDerived>{symbol}); 324 } 325 326 template <int KIND> static SomeExpr IntExpr(std::int64_t n) { 327 return evaluate::AsGenericExpr( 328 evaluate::Constant<evaluate::Type<TypeCategory::Integer, KIND>>{n}); 329 } 330 331 const Symbol *RuntimeTableBuilder::DescribeType(Scope &dtScope) { 332 if (const Symbol * info{dtScope.runtimeDerivedTypeDescription()}) { 333 return info; 334 } 335 const DerivedTypeSpec *derivedTypeSpec{dtScope.derivedTypeSpec()}; 336 if (!derivedTypeSpec && !dtScope.IsParameterizedDerivedType() && 337 dtScope.symbol()) { 338 // This derived type was declared (obviously, there's a Scope) but never 339 // used in this compilation (no instantiated DerivedTypeSpec points here). 340 // Create a DerivedTypeSpec now for it so that ComponentIterator 341 // will work. This covers the case of a derived type that's declared in 342 // a module but used only by clients and submodules, enabling the 343 // run-time "no initialization needed here" flag to work. 344 DerivedTypeSpec derived{dtScope.symbol()->name(), *dtScope.symbol()}; 345 DeclTypeSpec &decl{ 346 dtScope.MakeDerivedType(DeclTypeSpec::TypeDerived, std::move(derived))}; 347 derivedTypeSpec = &decl.derivedTypeSpec(); 348 } 349 const Symbol *dtSymbol{ 350 derivedTypeSpec ? &derivedTypeSpec->typeSymbol() : dtScope.symbol()}; 351 if (!dtSymbol) { 352 return nullptr; 353 } 354 auto locationRestorer{common::ScopedSet(location_, dtSymbol->name())}; 355 // Check for an existing description that can be imported from a USE'd module 356 std::string typeName{dtSymbol->name().ToString()}; 357 if (typeName.empty() || typeName[0] == '.') { 358 return nullptr; 359 } 360 std::string distinctName{typeName}; 361 if (&dtScope != dtSymbol->scope()) { 362 distinctName += "."s + std::to_string(anonymousTypes_++); 363 } 364 std::string dtDescName{".dt."s + distinctName}; 365 Scope &scope{GetContainingNonDerivedScope(dtScope)}; 366 if (distinctName == typeName && scope.IsModule()) { 367 if (const Symbol * description{scope.FindSymbol(SourceName{dtDescName})}) { 368 dtScope.set_runtimeDerivedTypeDescription(*description); 369 return description; 370 } 371 } 372 // Create a new description object before populating it so that mutual 373 // references will work as pointer targets. 374 Symbol &dtObject{CreateObject(dtDescName, derivedTypeSchema_, scope)}; 375 dtScope.set_runtimeDerivedTypeDescription(dtObject); 376 evaluate::StructureConstructorValues dtValues; 377 AddValue(dtValues, derivedTypeSchema_, "name"s, 378 SaveNameAsPointerTarget(scope, typeName)); 379 bool isPDTdefinition{ 380 !derivedTypeSpec && dtScope.IsParameterizedDerivedType()}; 381 if (!isPDTdefinition) { 382 auto sizeInBytes{static_cast<common::ConstantSubscript>(dtScope.size())}; 383 if (auto alignment{dtScope.alignment().value_or(0)}) { 384 sizeInBytes += alignment - 1; 385 sizeInBytes /= alignment; 386 sizeInBytes *= alignment; 387 } 388 AddValue( 389 dtValues, derivedTypeSchema_, "sizeinbytes"s, IntToExpr(sizeInBytes)); 390 } 391 bool isPDTinstantiation{derivedTypeSpec && &dtScope != dtSymbol->scope()}; 392 if (isPDTinstantiation) { 393 // is PDT instantiation 394 const Symbol *uninstDescObject{ 395 DescribeType(DEREF(const_cast<Scope *>(dtSymbol->scope())))}; 396 AddValue(dtValues, derivedTypeSchema_, "uninstantiated"s, 397 evaluate::AsGenericExpr(evaluate::Expr<evaluate::SomeDerived>{ 398 evaluate::Designator<evaluate::SomeDerived>{ 399 DEREF(uninstDescObject)}})); 400 } else { 401 AddValue(dtValues, derivedTypeSchema_, "uninstantiated"s, 402 SomeExpr{evaluate::NullPointer{}}); 403 } 404 using Int8 = evaluate::Type<TypeCategory::Integer, 8>; 405 using Int1 = evaluate::Type<TypeCategory::Integer, 1>; 406 std::vector<Int8::Scalar> kinds; 407 std::vector<Int1::Scalar> lenKinds; 408 const SymbolVector *parameters{GetTypeParameters(*dtSymbol)}; 409 if (parameters) { 410 // Package the derived type's parameters in declaration order for 411 // each category of parameter. KIND= type parameters are described 412 // by their instantiated (or default) values, while LEN= type 413 // parameters are described by their INTEGER kinds. 414 for (SymbolRef ref : *parameters) { 415 const auto &tpd{ref->get<TypeParamDetails>()}; 416 if (tpd.attr() == common::TypeParamAttr::Kind) { 417 auto value{evaluate::ToInt64(tpd.init()).value_or(0)}; 418 if (derivedTypeSpec) { 419 if (const auto *pv{derivedTypeSpec->FindParameter(ref->name())}) { 420 if (pv->GetExplicit()) { 421 if (auto instantiatedValue{ 422 evaluate::ToInt64(*pv->GetExplicit())}) { 423 value = *instantiatedValue; 424 } 425 } 426 } 427 } 428 kinds.emplace_back(value); 429 } else { // LEN= parameter 430 lenKinds.emplace_back(GetIntegerKind(*ref)); 431 } 432 } 433 } 434 AddValue(dtValues, derivedTypeSchema_, "kindparameter"s, 435 SaveNumericPointerTarget<Int8>( 436 scope, SaveObjectName(".kp."s + distinctName), std::move(kinds))); 437 AddValue(dtValues, derivedTypeSchema_, "lenparameterkind"s, 438 SaveNumericPointerTarget<Int1>( 439 scope, SaveObjectName(".lpk."s + distinctName), std::move(lenKinds))); 440 // Traverse the components of the derived type 441 if (!isPDTdefinition) { 442 std::vector<const Symbol *> dataComponentSymbols; 443 std::vector<evaluate::StructureConstructor> procPtrComponents; 444 std::map<int, evaluate::StructureConstructor> specials; 445 for (const auto &pair : dtScope) { 446 const Symbol &symbol{*pair.second}; 447 auto locationRestorer{common::ScopedSet(location_, symbol.name())}; 448 std::visit( 449 common::visitors{ 450 [&](const TypeParamDetails &) { 451 // already handled above in declaration order 452 }, 453 [&](const ObjectEntityDetails &) { 454 dataComponentSymbols.push_back(&symbol); 455 }, 456 [&](const ProcEntityDetails &proc) { 457 if (IsProcedurePointer(symbol)) { 458 procPtrComponents.emplace_back( 459 DescribeComponent(symbol, proc, scope)); 460 } 461 }, 462 [&](const ProcBindingDetails &) { // handled in a later pass 463 }, 464 [&](const GenericDetails &generic) { 465 DescribeGeneric(generic, specials); 466 }, 467 [&](const auto &) { 468 common::die( 469 "unexpected details on symbol '%s' in derived type scope", 470 symbol.name().ToString().c_str()); 471 }, 472 }, 473 symbol.details()); 474 } 475 // Sort the data component symbols by offset before emitting them 476 std::sort(dataComponentSymbols.begin(), dataComponentSymbols.end(), 477 [](const Symbol *x, const Symbol *y) { 478 return x->offset() < y->offset(); 479 }); 480 std::vector<evaluate::StructureConstructor> dataComponents; 481 for (const Symbol *symbol : dataComponentSymbols) { 482 auto locationRestorer{common::ScopedSet(location_, symbol->name())}; 483 dataComponents.emplace_back( 484 DescribeComponent(*symbol, symbol->get<ObjectEntityDetails>(), scope, 485 dtScope, distinctName, parameters)); 486 } 487 AddValue(dtValues, derivedTypeSchema_, "component"s, 488 SaveDerivedPointerTarget(scope, SaveObjectName(".c."s + distinctName), 489 std::move(dataComponents), 490 evaluate::ConstantSubscripts{ 491 static_cast<evaluate::ConstantSubscript>( 492 dataComponents.size())})); 493 AddValue(dtValues, derivedTypeSchema_, "procptr"s, 494 SaveDerivedPointerTarget(scope, SaveObjectName(".p."s + distinctName), 495 std::move(procPtrComponents), 496 evaluate::ConstantSubscripts{ 497 static_cast<evaluate::ConstantSubscript>( 498 procPtrComponents.size())})); 499 // Compile the "vtable" of type-bound procedure bindings 500 std::vector<evaluate::StructureConstructor> bindings{ 501 DescribeBindings(dtScope, scope)}; 502 AddValue(dtValues, derivedTypeSchema_, "binding"s, 503 SaveDerivedPointerTarget(scope, SaveObjectName(".v."s + distinctName), 504 std::move(bindings), 505 evaluate::ConstantSubscripts{ 506 static_cast<evaluate::ConstantSubscript>(bindings.size())})); 507 // Describe "special" bindings to defined assignments, FINAL subroutines, 508 // and user-defined derived type I/O subroutines. 509 const DerivedTypeDetails &dtDetails{dtSymbol->get<DerivedTypeDetails>()}; 510 for (const auto &pair : dtDetails.finals()) { 511 DescribeSpecialProc( 512 specials, *pair.second, false /*!isAssignment*/, true, std::nullopt); 513 } 514 IncorporateDefinedIoGenericInterfaces(specials, 515 SourceName{"read(formatted)", 15}, 516 GenericKind::DefinedIo::ReadFormatted, &scope); 517 IncorporateDefinedIoGenericInterfaces(specials, 518 SourceName{"read(unformatted)", 17}, 519 GenericKind::DefinedIo::ReadUnformatted, &scope); 520 IncorporateDefinedIoGenericInterfaces(specials, 521 SourceName{"write(formatted)", 16}, 522 GenericKind::DefinedIo::WriteFormatted, &scope); 523 IncorporateDefinedIoGenericInterfaces(specials, 524 SourceName{"write(unformatted)", 18}, 525 GenericKind::DefinedIo::WriteUnformatted, &scope); 526 // Pack the special procedure bindings in ascending order of their "which" 527 // code values, and compile a little-endian bit-set of those codes for 528 // use in O(1) look-up at run time. 529 std::vector<evaluate::StructureConstructor> sortedSpecials; 530 std::uint32_t specialBitSet{0}; 531 for (auto &pair : specials) { 532 auto bit{std::uint32_t{1} << pair.first}; 533 CHECK(!(specialBitSet & bit)); 534 specialBitSet |= bit; 535 sortedSpecials.emplace_back(std::move(pair.second)); 536 } 537 AddValue(dtValues, derivedTypeSchema_, "special"s, 538 SaveDerivedPointerTarget(scope, SaveObjectName(".s."s + distinctName), 539 std::move(sortedSpecials), 540 evaluate::ConstantSubscripts{ 541 static_cast<evaluate::ConstantSubscript>(specials.size())})); 542 AddValue(dtValues, derivedTypeSchema_, "specialbitset"s, 543 IntExpr<4>(specialBitSet)); 544 // Note the presence/absence of a parent component 545 AddValue(dtValues, derivedTypeSchema_, "hasparent"s, 546 IntExpr<1>(dtScope.GetDerivedTypeParent() != nullptr)); 547 // To avoid wasting run time attempting to initialize derived type 548 // instances without any initialized components, analyze the type 549 // and set a flag if there's nothing to do for it at run time. 550 AddValue(dtValues, derivedTypeSchema_, "noinitializationneeded"s, 551 IntExpr<1>( 552 derivedTypeSpec && !derivedTypeSpec->HasDefaultInitialization())); 553 // Similarly, a flag to short-circuit destruction when not needed. 554 AddValue(dtValues, derivedTypeSchema_, "nodestructionneeded"s, 555 IntExpr<1>(derivedTypeSpec && !derivedTypeSpec->HasDestruction())); 556 // Similarly, a flag to short-circuit finalization when not needed. 557 AddValue(dtValues, derivedTypeSchema_, "nofinalizationneeded"s, 558 IntExpr<1>(derivedTypeSpec && !IsFinalizable(*derivedTypeSpec))); 559 } 560 dtObject.get<ObjectEntityDetails>().set_init(MaybeExpr{ 561 StructureExpr(Structure(derivedTypeSchema_, std::move(dtValues)))}); 562 return &dtObject; 563 } 564 565 static const Symbol &GetSymbol(const Scope &schemata, SourceName name) { 566 auto iter{schemata.find(name)}; 567 CHECK(iter != schemata.end()); 568 const Symbol &symbol{*iter->second}; 569 return symbol; 570 } 571 572 const Symbol &RuntimeTableBuilder::GetSchemaSymbol(const char *name) const { 573 return GetSymbol( 574 DEREF(tables_.schemata), SourceName{name, std::strlen(name)}); 575 } 576 577 const DeclTypeSpec &RuntimeTableBuilder::GetSchema( 578 const char *schemaName) const { 579 Scope &schemata{DEREF(tables_.schemata)}; 580 SourceName name{schemaName, std::strlen(schemaName)}; 581 const Symbol &symbol{GetSymbol(schemata, name)}; 582 CHECK(symbol.has<DerivedTypeDetails>()); 583 CHECK(symbol.scope()); 584 CHECK(symbol.scope()->IsDerivedType()); 585 const DeclTypeSpec *spec{nullptr}; 586 if (symbol.scope()->derivedTypeSpec()) { 587 DeclTypeSpec typeSpec{ 588 DeclTypeSpec::TypeDerived, *symbol.scope()->derivedTypeSpec()}; 589 spec = schemata.FindType(typeSpec); 590 } 591 if (!spec) { 592 DeclTypeSpec typeSpec{ 593 DeclTypeSpec::TypeDerived, DerivedTypeSpec{name, symbol}}; 594 spec = schemata.FindType(typeSpec); 595 } 596 if (!spec) { 597 spec = &schemata.MakeDerivedType( 598 DeclTypeSpec::TypeDerived, DerivedTypeSpec{name, symbol}); 599 } 600 CHECK(spec->AsDerived()); 601 return *spec; 602 } 603 604 SomeExpr RuntimeTableBuilder::GetEnumValue(const char *name) const { 605 const Symbol &symbol{GetSchemaSymbol(name)}; 606 auto value{evaluate::ToInt64(symbol.get<ObjectEntityDetails>().init())}; 607 CHECK(value.has_value()); 608 return IntExpr<1>(*value); 609 } 610 611 Symbol &RuntimeTableBuilder::CreateObject( 612 const std::string &name, const DeclTypeSpec &type, Scope &scope) { 613 ObjectEntityDetails object; 614 object.set_type(type); 615 auto pair{scope.try_emplace(SaveObjectName(name), 616 Attrs{Attr::TARGET, Attr::SAVE}, std::move(object))}; 617 CHECK(pair.second); 618 Symbol &result{*pair.first->second}; 619 result.set(Symbol::Flag::CompilerCreated); 620 return result; 621 } 622 623 SourceName RuntimeTableBuilder::SaveObjectName(const std::string &name) { 624 return *tables_.names.insert(name).first; 625 } 626 627 SomeExpr RuntimeTableBuilder::SaveNameAsPointerTarget( 628 Scope &scope, const std::string &name) { 629 CHECK(!name.empty()); 630 CHECK(name.front() != '.'); 631 ObjectEntityDetails object; 632 auto len{static_cast<common::ConstantSubscript>(name.size())}; 633 if (const auto *spec{scope.FindType(DeclTypeSpec{CharacterTypeSpec{ 634 ParamValue{len, common::TypeParamAttr::Len}, KindExpr{1}}})}) { 635 object.set_type(*spec); 636 } else { 637 object.set_type(scope.MakeCharacterType( 638 ParamValue{len, common::TypeParamAttr::Len}, KindExpr{1})); 639 } 640 using evaluate::Ascii; 641 using AsciiExpr = evaluate::Expr<Ascii>; 642 object.set_init(evaluate::AsGenericExpr(AsciiExpr{name})); 643 Symbol &symbol{*scope 644 .try_emplace(SaveObjectName(".n."s + name), 645 Attrs{Attr::TARGET, Attr::SAVE}, std::move(object)) 646 .first->second}; 647 symbol.set(Symbol::Flag::CompilerCreated); 648 return evaluate::AsGenericExpr( 649 AsciiExpr{evaluate::Designator<Ascii>{symbol}}); 650 } 651 652 evaluate::StructureConstructor RuntimeTableBuilder::DescribeComponent( 653 const Symbol &symbol, const ObjectEntityDetails &object, Scope &scope, 654 Scope &dtScope, const std::string &distinctName, 655 const SymbolVector *parameters) { 656 evaluate::StructureConstructorValues values; 657 auto &foldingContext{context_.foldingContext()}; 658 auto typeAndShape{evaluate::characteristics::TypeAndShape::Characterize( 659 symbol, foldingContext)}; 660 CHECK(typeAndShape.has_value()); 661 auto dyType{typeAndShape->type()}; 662 const auto &shape{typeAndShape->shape()}; 663 AddValue(values, componentSchema_, "name"s, 664 SaveNameAsPointerTarget(scope, symbol.name().ToString())); 665 AddValue(values, componentSchema_, "category"s, 666 IntExpr<1>(static_cast<int>(dyType.category()))); 667 if (dyType.IsUnlimitedPolymorphic() || 668 dyType.category() == TypeCategory::Derived) { 669 AddValue(values, componentSchema_, "kind"s, IntExpr<1>(0)); 670 } else { 671 AddValue(values, componentSchema_, "kind"s, IntExpr<1>(dyType.kind())); 672 } 673 AddValue(values, componentSchema_, "offset"s, IntExpr<8>(symbol.offset())); 674 // CHARACTER length 675 auto len{typeAndShape->LEN()}; 676 if (const semantics::DerivedTypeSpec * 677 pdtInstance{dtScope.derivedTypeSpec()}) { 678 auto restorer{foldingContext.WithPDTInstance(*pdtInstance)}; 679 len = Fold(foldingContext, std::move(len)); 680 } 681 if (dyType.category() == TypeCategory::Character && len) { 682 AddValue(values, componentSchema_, "characterlen"s, 683 evaluate::AsGenericExpr(GetValue(len, parameters))); 684 } else { 685 AddValue(values, componentSchema_, "characterlen"s, 686 PackageIntValueExpr(deferredEnum_)); 687 } 688 // Describe component's derived type 689 std::vector<evaluate::StructureConstructor> lenParams; 690 if (dyType.category() == TypeCategory::Derived && 691 !dyType.IsUnlimitedPolymorphic()) { 692 const DerivedTypeSpec &spec{dyType.GetDerivedTypeSpec()}; 693 Scope *derivedScope{const_cast<Scope *>( 694 spec.scope() ? spec.scope() : spec.typeSymbol().scope())}; 695 const Symbol *derivedDescription{DescribeType(DEREF(derivedScope))}; 696 AddValue(values, componentSchema_, "derived"s, 697 evaluate::AsGenericExpr(evaluate::Expr<evaluate::SomeDerived>{ 698 evaluate::Designator<evaluate::SomeDerived>{ 699 DEREF(derivedDescription)}})); 700 // Package values of LEN parameters, if any 701 if (const SymbolVector * specParams{GetTypeParameters(spec.typeSymbol())}) { 702 for (SymbolRef ref : *specParams) { 703 const auto &tpd{ref->get<TypeParamDetails>()}; 704 if (tpd.attr() == common::TypeParamAttr::Len) { 705 if (const ParamValue * paramValue{spec.FindParameter(ref->name())}) { 706 lenParams.emplace_back(GetValue(*paramValue, parameters)); 707 } else { 708 lenParams.emplace_back(GetValue(tpd.init(), parameters)); 709 } 710 } 711 } 712 } 713 } else { 714 // Subtle: a category of Derived with a null derived type pointer 715 // signifies CLASS(*) 716 AddValue(values, componentSchema_, "derived"s, 717 SomeExpr{evaluate::NullPointer{}}); 718 } 719 // LEN type parameter values for the component's type 720 if (!lenParams.empty()) { 721 AddValue(values, componentSchema_, "lenvalue"s, 722 SaveDerivedPointerTarget(scope, 723 SaveObjectName( 724 ".lv."s + distinctName + "."s + symbol.name().ToString()), 725 std::move(lenParams), 726 evaluate::ConstantSubscripts{ 727 static_cast<evaluate::ConstantSubscript>(lenParams.size())})); 728 } else { 729 AddValue(values, componentSchema_, "lenvalue"s, 730 SomeExpr{evaluate::NullPointer{}}); 731 } 732 // Shape information 733 int rank{evaluate::GetRank(shape)}; 734 AddValue(values, componentSchema_, "rank"s, IntExpr<1>(rank)); 735 if (rank > 0 && !IsAllocatable(symbol) && !IsPointer(symbol)) { 736 std::vector<evaluate::StructureConstructor> bounds; 737 evaluate::NamedEntity entity{symbol}; 738 for (int j{0}; j < rank; ++j) { 739 bounds.emplace_back(GetValue(std::make_optional(evaluate::GetLowerBound( 740 foldingContext, entity, j)), 741 parameters)); 742 bounds.emplace_back(GetValue( 743 evaluate::GetUpperBound(foldingContext, entity, j), parameters)); 744 } 745 AddValue(values, componentSchema_, "bounds"s, 746 SaveDerivedPointerTarget(scope, 747 SaveObjectName( 748 ".b."s + distinctName + "."s + symbol.name().ToString()), 749 std::move(bounds), evaluate::ConstantSubscripts{2, rank})); 750 } else { 751 AddValue( 752 values, componentSchema_, "bounds"s, SomeExpr{evaluate::NullPointer{}}); 753 } 754 // Default component initialization 755 bool hasDataInit{false}; 756 if (IsAllocatable(symbol)) { 757 AddValue(values, componentSchema_, "genre"s, GetEnumValue("allocatable")); 758 } else if (IsPointer(symbol)) { 759 AddValue(values, componentSchema_, "genre"s, GetEnumValue("pointer")); 760 hasDataInit = InitializeDataPointer( 761 values, symbol, object, scope, dtScope, distinctName); 762 } else if (IsAutomaticObject(symbol)) { 763 AddValue(values, componentSchema_, "genre"s, GetEnumValue("automatic")); 764 } else { 765 AddValue(values, componentSchema_, "genre"s, GetEnumValue("data")); 766 hasDataInit = object.init().has_value(); 767 if (hasDataInit) { 768 AddValue(values, componentSchema_, "initialization"s, 769 SaveObjectInit(scope, 770 SaveObjectName( 771 ".di."s + distinctName + "."s + symbol.name().ToString()), 772 object)); 773 } 774 } 775 if (!hasDataInit) { 776 AddValue(values, componentSchema_, "initialization"s, 777 SomeExpr{evaluate::NullPointer{}}); 778 } 779 return {DEREF(componentSchema_.AsDerived()), std::move(values)}; 780 } 781 782 evaluate::StructureConstructor RuntimeTableBuilder::DescribeComponent( 783 const Symbol &symbol, const ProcEntityDetails &proc, Scope &scope) { 784 evaluate::StructureConstructorValues values; 785 AddValue(values, procPtrSchema_, "name"s, 786 SaveNameAsPointerTarget(scope, symbol.name().ToString())); 787 AddValue(values, procPtrSchema_, "offset"s, IntExpr<8>(symbol.offset())); 788 if (auto init{proc.init()}; init && *init) { 789 AddValue(values, procPtrSchema_, "initialization"s, 790 SomeExpr{evaluate::ProcedureDesignator{**init}}); 791 } else { 792 AddValue(values, procPtrSchema_, "initialization"s, 793 SomeExpr{evaluate::NullPointer{}}); 794 } 795 return {DEREF(procPtrSchema_.AsDerived()), std::move(values)}; 796 } 797 798 // Create a static pointer object with the same initialization 799 // from whence the runtime can memcpy() the data pointer 800 // component initialization. 801 // Creates and interconnects the symbols, scopes, and types for 802 // TYPE :: ptrDt 803 // type, POINTER :: name 804 // END TYPE 805 // TYPE(ptrDt), TARGET, SAVE :: ptrInit = ptrDt(designator) 806 // and then initializes the original component by setting 807 // initialization = ptrInit 808 // which takes the address of ptrInit because the type is C_PTR. 809 // This technique of wrapping the data pointer component into 810 // a derived type instance disables any reason for lowering to 811 // attempt to dereference the RHS of an initializer, thereby 812 // allowing the runtime to actually perform the initialization 813 // by means of a simple memcpy() of the wrapped descriptor in 814 // ptrInit to the data pointer component being initialized. 815 bool RuntimeTableBuilder::InitializeDataPointer( 816 evaluate::StructureConstructorValues &values, const Symbol &symbol, 817 const ObjectEntityDetails &object, Scope &scope, Scope &dtScope, 818 const std::string &distinctName) { 819 if (object.init().has_value()) { 820 SourceName ptrDtName{SaveObjectName( 821 ".dp."s + distinctName + "."s + symbol.name().ToString())}; 822 Symbol &ptrDtSym{ 823 *scope.try_emplace(ptrDtName, Attrs{}, UnknownDetails{}).first->second}; 824 ptrDtSym.set(Symbol::Flag::CompilerCreated); 825 Scope &ptrDtScope{scope.MakeScope(Scope::Kind::DerivedType, &ptrDtSym)}; 826 ignoreScopes_.insert(&ptrDtScope); 827 ObjectEntityDetails ptrDtObj; 828 ptrDtObj.set_type(DEREF(object.type())); 829 ptrDtObj.set_shape(object.shape()); 830 Symbol &ptrDtComp{*ptrDtScope 831 .try_emplace(symbol.name(), Attrs{Attr::POINTER}, 832 std::move(ptrDtObj)) 833 .first->second}; 834 DerivedTypeDetails ptrDtDetails; 835 ptrDtDetails.add_component(ptrDtComp); 836 ptrDtSym.set_details(std::move(ptrDtDetails)); 837 ptrDtSym.set_scope(&ptrDtScope); 838 DeclTypeSpec &ptrDtDeclType{ 839 scope.MakeDerivedType(DeclTypeSpec::Category::TypeDerived, 840 DerivedTypeSpec{ptrDtName, ptrDtSym})}; 841 DerivedTypeSpec &ptrDtDerived{DEREF(ptrDtDeclType.AsDerived())}; 842 ptrDtDerived.set_scope(ptrDtScope); 843 ptrDtDerived.CookParameters(context_.foldingContext()); 844 ptrDtDerived.Instantiate(scope); 845 ObjectEntityDetails ptrInitObj; 846 ptrInitObj.set_type(ptrDtDeclType); 847 evaluate::StructureConstructorValues ptrInitValues; 848 AddValue( 849 ptrInitValues, ptrDtDeclType, symbol.name().ToString(), *object.init()); 850 ptrInitObj.set_init(evaluate::AsGenericExpr( 851 Structure(ptrDtDeclType, std::move(ptrInitValues)))); 852 AddValue(values, componentSchema_, "initialization"s, 853 SaveObjectInit(scope, 854 SaveObjectName( 855 ".di."s + distinctName + "."s + symbol.name().ToString()), 856 ptrInitObj)); 857 return true; 858 } else { 859 return false; 860 } 861 } 862 863 evaluate::StructureConstructor RuntimeTableBuilder::PackageIntValue( 864 const SomeExpr &genre, std::int64_t n) const { 865 evaluate::StructureConstructorValues xs; 866 AddValue(xs, valueSchema_, "genre"s, genre); 867 AddValue(xs, valueSchema_, "value"s, IntToExpr(n)); 868 return Structure(valueSchema_, std::move(xs)); 869 } 870 871 SomeExpr RuntimeTableBuilder::PackageIntValueExpr( 872 const SomeExpr &genre, std::int64_t n) const { 873 return StructureExpr(PackageIntValue(genre, n)); 874 } 875 876 std::vector<const Symbol *> RuntimeTableBuilder::CollectBindings( 877 const Scope &dtScope) const { 878 std::vector<const Symbol *> result; 879 std::map<SourceName, const Symbol *> localBindings; 880 // Collect local bindings 881 for (auto pair : dtScope) { 882 const Symbol &symbol{*pair.second}; 883 if (symbol.has<ProcBindingDetails>()) { 884 localBindings.emplace(symbol.name(), &symbol); 885 } 886 } 887 if (const Scope * parentScope{dtScope.GetDerivedTypeParent()}) { 888 result = CollectBindings(*parentScope); 889 // Apply overrides from the local bindings of the extended type 890 for (auto iter{result.begin()}; iter != result.end(); ++iter) { 891 const Symbol &symbol{**iter}; 892 auto overridden{localBindings.find(symbol.name())}; 893 if (overridden != localBindings.end()) { 894 *iter = overridden->second; 895 localBindings.erase(overridden); 896 } 897 } 898 } 899 // Add remaining (non-overriding) local bindings in name order to the result 900 for (auto pair : localBindings) { 901 result.push_back(pair.second); 902 } 903 return result; 904 } 905 906 std::vector<evaluate::StructureConstructor> 907 RuntimeTableBuilder::DescribeBindings(const Scope &dtScope, Scope &scope) { 908 std::vector<evaluate::StructureConstructor> result; 909 for (const Symbol *symbol : CollectBindings(dtScope)) { 910 evaluate::StructureConstructorValues values; 911 AddValue(values, bindingSchema_, "proc"s, 912 SomeExpr{evaluate::ProcedureDesignator{ 913 symbol->get<ProcBindingDetails>().symbol()}}); 914 AddValue(values, bindingSchema_, "name"s, 915 SaveNameAsPointerTarget(scope, symbol->name().ToString())); 916 result.emplace_back(DEREF(bindingSchema_.AsDerived()), std::move(values)); 917 } 918 return result; 919 } 920 921 void RuntimeTableBuilder::DescribeGeneric(const GenericDetails &generic, 922 std::map<int, evaluate::StructureConstructor> &specials) { 923 std::visit(common::visitors{ 924 [&](const GenericKind::OtherKind &k) { 925 if (k == GenericKind::OtherKind::Assignment) { 926 for (auto ref : generic.specificProcs()) { 927 DescribeSpecialProc(specials, *ref, true, 928 false /*!final*/, std::nullopt); 929 } 930 } 931 }, 932 [&](const GenericKind::DefinedIo &io) { 933 switch (io) { 934 case GenericKind::DefinedIo::ReadFormatted: 935 case GenericKind::DefinedIo::ReadUnformatted: 936 case GenericKind::DefinedIo::WriteFormatted: 937 case GenericKind::DefinedIo::WriteUnformatted: 938 for (auto ref : generic.specificProcs()) { 939 DescribeSpecialProc( 940 specials, *ref, false, false /*!final*/, io); 941 } 942 break; 943 } 944 }, 945 [](const auto &) {}, 946 }, 947 generic.kind().u); 948 } 949 950 void RuntimeTableBuilder::DescribeSpecialProc( 951 std::map<int, evaluate::StructureConstructor> &specials, 952 const Symbol &specificOrBinding, bool isAssignment, bool isFinal, 953 std::optional<GenericKind::DefinedIo> io) { 954 const auto *binding{specificOrBinding.detailsIf<ProcBindingDetails>()}; 955 const Symbol &specific{*(binding ? &binding->symbol() : &specificOrBinding)}; 956 if (auto proc{evaluate::characteristics::Procedure::Characterize( 957 specific, context_.foldingContext())}) { 958 std::uint8_t isArgDescriptorSet{0}; 959 int argThatMightBeDescriptor{0}; 960 MaybeExpr which; 961 if (isAssignment) { 962 // Only type-bound asst's with the same type on both dummy arguments 963 // are germane to the runtime, which needs only these to implement 964 // component assignment as part of intrinsic assignment. 965 // Non-type-bound generic INTERFACEs and assignments from distinct 966 // types must not be used for component intrinsic assignment. 967 CHECK(proc->dummyArguments.size() == 2); 968 const auto t1{ 969 DEREF(std::get_if<evaluate::characteristics::DummyDataObject>( 970 &proc->dummyArguments[0].u)) 971 .type.type()}; 972 const auto t2{ 973 DEREF(std::get_if<evaluate::characteristics::DummyDataObject>( 974 &proc->dummyArguments[1].u)) 975 .type.type()}; 976 if (!binding || t1.category() != TypeCategory::Derived || 977 t2.category() != TypeCategory::Derived || 978 t1.IsUnlimitedPolymorphic() || t2.IsUnlimitedPolymorphic() || 979 t1.GetDerivedTypeSpec() != t2.GetDerivedTypeSpec()) { 980 return; 981 } 982 which = proc->IsElemental() ? elementalAssignmentEnum_ 983 : scalarAssignmentEnum_; 984 if (binding && binding->passName() && 985 *binding->passName() == proc->dummyArguments[1].name) { 986 argThatMightBeDescriptor = 1; 987 isArgDescriptorSet |= 2; 988 } else { 989 argThatMightBeDescriptor = 2; // the non-passed-object argument 990 isArgDescriptorSet |= 1; 991 } 992 } else if (isFinal) { 993 CHECK(binding == nullptr); // FINALs are not bindings 994 CHECK(proc->dummyArguments.size() == 1); 995 if (proc->IsElemental()) { 996 which = elementalFinalEnum_; 997 } else { 998 const auto &typeAndShape{ 999 std::get<evaluate::characteristics::DummyDataObject>( 1000 proc->dummyArguments.at(0).u) 1001 .type}; 1002 if (typeAndShape.attrs().test( 1003 evaluate::characteristics::TypeAndShape::Attr::AssumedRank)) { 1004 which = assumedRankFinalEnum_; 1005 isArgDescriptorSet |= 1; 1006 } else { 1007 which = scalarFinalEnum_; 1008 if (int rank{evaluate::GetRank(typeAndShape.shape())}; rank > 0) { 1009 argThatMightBeDescriptor = 1; 1010 which = IntExpr<1>(ToInt64(which).value() + rank); 1011 } 1012 } 1013 } 1014 } else { // user defined derived type I/O 1015 CHECK(proc->dummyArguments.size() >= 4); 1016 if (binding) { 1017 isArgDescriptorSet |= 1; 1018 } 1019 switch (io.value()) { 1020 case GenericKind::DefinedIo::ReadFormatted: 1021 which = readFormattedEnum_; 1022 break; 1023 case GenericKind::DefinedIo::ReadUnformatted: 1024 which = readUnformattedEnum_; 1025 break; 1026 case GenericKind::DefinedIo::WriteFormatted: 1027 which = writeFormattedEnum_; 1028 break; 1029 case GenericKind::DefinedIo::WriteUnformatted: 1030 which = writeUnformattedEnum_; 1031 break; 1032 } 1033 } 1034 if (argThatMightBeDescriptor != 0 && 1035 !proc->dummyArguments.at(argThatMightBeDescriptor - 1) 1036 .CanBePassedViaImplicitInterface()) { 1037 isArgDescriptorSet |= 1 << (argThatMightBeDescriptor - 1); 1038 } 1039 evaluate::StructureConstructorValues values; 1040 auto index{evaluate::ToInt64(which)}; 1041 CHECK(index.has_value()); 1042 AddValue( 1043 values, specialSchema_, "which"s, SomeExpr{std::move(which.value())}); 1044 AddValue(values, specialSchema_, "isargdescriptorset"s, 1045 IntExpr<1>(isArgDescriptorSet)); 1046 AddValue(values, specialSchema_, "proc"s, 1047 SomeExpr{evaluate::ProcedureDesignator{specific}}); 1048 auto pair{specials.try_emplace( 1049 *index, DEREF(specialSchema_.AsDerived()), std::move(values))}; 1050 CHECK(pair.second); // ensure not already present 1051 } 1052 } 1053 1054 void RuntimeTableBuilder::IncorporateDefinedIoGenericInterfaces( 1055 std::map<int, evaluate::StructureConstructor> &specials, SourceName name, 1056 GenericKind::DefinedIo definedIo, const Scope *scope) { 1057 for (; !scope->IsGlobal(); scope = &scope->parent()) { 1058 if (auto asst{scope->find(name)}; asst != scope->end()) { 1059 const Symbol &generic{*asst->second}; 1060 const auto &genericDetails{generic.get<GenericDetails>()}; 1061 CHECK(std::holds_alternative<GenericKind::DefinedIo>( 1062 genericDetails.kind().u)); 1063 CHECK(std::get<GenericKind::DefinedIo>(genericDetails.kind().u) == 1064 definedIo); 1065 for (auto ref : genericDetails.specificProcs()) { 1066 DescribeSpecialProc(specials, *ref, false, false, definedIo); 1067 } 1068 } 1069 } 1070 } 1071 1072 RuntimeDerivedTypeTables BuildRuntimeDerivedTypeTables( 1073 SemanticsContext &context) { 1074 RuntimeDerivedTypeTables result; 1075 result.schemata = context.GetBuiltinModule("__fortran_type_info"); 1076 if (result.schemata) { 1077 RuntimeTableBuilder builder{context, result}; 1078 builder.DescribeTypes(context.globalScope(), false); 1079 } 1080 return result; 1081 } 1082 } // namespace Fortran::semantics 1083