llvm-project
3956 строк · 160.5 Кб
1//===-- lib/Semantics/check-declarations.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// Static declaration checking
10
11#include "check-declarations.h"12#include "definable.h"13#include "pointer-assignment.h"14#include "flang/Evaluate/check-expression.h"15#include "flang/Evaluate/fold.h"16#include "flang/Evaluate/tools.h"17#include "flang/Parser/characters.h"18#include "flang/Semantics/scope.h"19#include "flang/Semantics/semantics.h"20#include "flang/Semantics/symbol.h"21#include "flang/Semantics/tools.h"22#include "flang/Semantics/type.h"23#include <algorithm>24#include <map>25#include <string>26
27namespace Fortran::semantics {28
29namespace characteristics = evaluate::characteristics;30using characteristics::DummyArgument;31using characteristics::DummyDataObject;32using characteristics::DummyProcedure;33using characteristics::FunctionResult;34using characteristics::Procedure;35
36class CheckHelper {37public:38explicit CheckHelper(SemanticsContext &c) : context_{c} {}39
40SemanticsContext &context() { return context_; }41void Check() { Check(context_.globalScope()); }42void Check(const ParamValue &, bool canBeAssumed);43void Check(const Bound &bound) {44CheckSpecExpr(bound.GetExplicit(), /*forElementalFunctionResult=*/false);45}46void Check(const ShapeSpec &spec) {47Check(spec.lbound());48Check(spec.ubound());49}50void Check(const ArraySpec &);51void Check(const DeclTypeSpec &, bool canHaveAssumedTypeParameters);52void Check(const Symbol &);53void CheckCommonBlock(const Symbol &);54void Check(const Scope &);55const Procedure *Characterize(const Symbol &);56
57private:58template <typename A>59void CheckSpecExpr(const A &x, bool forElementalFunctionResult) {60evaluate::CheckSpecificationExpr(61x, DEREF(scope_), foldingContext_, forElementalFunctionResult);62}63void CheckValue(const Symbol &, const DerivedTypeSpec *);64void CheckVolatile(const Symbol &, const DerivedTypeSpec *);65void CheckContiguous(const Symbol &);66void CheckPointer(const Symbol &);67void CheckPassArg(68const Symbol &proc, const Symbol *interface, const WithPassArg &);69void CheckProcBinding(const Symbol &, const ProcBindingDetails &);70void CheckObjectEntity(const Symbol &, const ObjectEntityDetails &);71void CheckPointerInitialization(const Symbol &);72void CheckArraySpec(const Symbol &, const ArraySpec &);73void CheckProcEntity(const Symbol &, const ProcEntityDetails &);74void CheckSubprogram(const Symbol &, const SubprogramDetails &);75void CheckExternal(const Symbol &);76void CheckAssumedTypeEntity(const Symbol &, const ObjectEntityDetails &);77void CheckDerivedType(const Symbol &, const DerivedTypeDetails &);78bool CheckFinal(79const Symbol &subroutine, SourceName, const Symbol &derivedType);80bool CheckDistinguishableFinals(const Symbol &f1, SourceName f1name,81const Symbol &f2, SourceName f2name, const Symbol &derivedType);82void CheckGeneric(const Symbol &, const GenericDetails &);83void CheckHostAssoc(const Symbol &, const HostAssocDetails &);84bool CheckDefinedOperator(85SourceName, GenericKind, const Symbol &, const Procedure &);86std::optional<parser::MessageFixedText> CheckNumberOfArgs(87const GenericKind &, std::size_t);88bool CheckDefinedOperatorArg(89const SourceName &, const Symbol &, const Procedure &, std::size_t);90bool CheckDefinedAssignment(const Symbol &, const Procedure &);91bool CheckDefinedAssignmentArg(const Symbol &, const DummyArgument &, int);92void CheckSpecifics(const Symbol &, const GenericDetails &);93void CheckEquivalenceSet(const EquivalenceSet &);94void CheckEquivalenceObject(const EquivalenceObject &);95void CheckBlockData(const Scope &);96void CheckGenericOps(const Scope &);97bool CheckConflicting(const Symbol &, Attr, Attr);98void WarnMissingFinal(const Symbol &);99void CheckSymbolType(const Symbol &); // C702100bool InPure() const {101return innermostSymbol_ && IsPureProcedure(*innermostSymbol_);102}103bool InElemental() const {104return innermostSymbol_ && IsElementalProcedure(*innermostSymbol_);105}106bool InFunction() const {107return innermostSymbol_ && IsFunction(*innermostSymbol_);108}109bool InInterface() const {110const SubprogramDetails *subp{innermostSymbol_111? innermostSymbol_->detailsIf<SubprogramDetails>()112: nullptr};113return subp && subp->isInterface();114}115template <typename... A>116parser::Message *SayWithDeclaration(const Symbol &symbol, A &&...x) {117parser::Message *msg{messages_.Say(std::forward<A>(x)...)};118if (msg && messages_.at().begin() != symbol.name().begin()) {119evaluate::AttachDeclaration(*msg, symbol);120}121return msg;122}123bool InModuleFile() const {124return FindModuleFileContaining(context_.FindScope(messages_.at())) !=125nullptr;126}127template <typename... A> parser::Message *WarnIfNotInModuleFile(A &&...x) {128if (InModuleFile()) {129return nullptr;130} else {131return messages_.Say(std::forward<A>(x)...);132}133}134template <typename... A>135parser::Message *WarnIfNotInModuleFile(parser::CharBlock source, A &&...x) {136if (FindModuleFileContaining(context_.FindScope(source))) {137return nullptr;138}139return messages_.Say(source, std::forward<A>(x)...);140}141bool IsResultOkToDiffer(const FunctionResult &);142void CheckGlobalName(const Symbol &);143void CheckProcedureAssemblyName(const Symbol &symbol);144void CheckExplicitSave(const Symbol &);145parser::Messages WhyNotInteroperableDerivedType(const Symbol &);146parser::Messages WhyNotInteroperableObject(const Symbol &);147parser::Messages WhyNotInteroperableFunctionResult(const Symbol &);148parser::Messages WhyNotInteroperableProcedure(const Symbol &, bool isError);149void CheckBindC(const Symbol &);150// Check functions for defined I/O procedures151void CheckDefinedIoProc(152const Symbol &, const GenericDetails &, common::DefinedIo);153bool CheckDioDummyIsData(const Symbol &, const Symbol *, std::size_t);154void CheckDioDummyIsDerived(155const Symbol &, const Symbol &, common::DefinedIo ioKind, const Symbol &);156void CheckDioDummyIsDefaultInteger(const Symbol &, const Symbol &);157void CheckDioDummyIsScalar(const Symbol &, const Symbol &);158void CheckDioDummyAttrs(const Symbol &, const Symbol &, Attr);159void CheckDioDtvArg(160const Symbol &, const Symbol *, common::DefinedIo, const Symbol &);161void CheckGenericVsIntrinsic(const Symbol &, const GenericDetails &);162void CheckDefaultIntegerArg(const Symbol &, const Symbol *, Attr);163void CheckDioAssumedLenCharacterArg(164const Symbol &, const Symbol *, std::size_t, Attr);165void CheckDioVlistArg(const Symbol &, const Symbol *, std::size_t);166void CheckDioArgCount(const Symbol &, common::DefinedIo ioKind, std::size_t);167struct TypeWithDefinedIo {168const DerivedTypeSpec &type;169common::DefinedIo ioKind;170const Symbol &proc;171const Symbol &generic;172};173void CheckAlreadySeenDefinedIo(const DerivedTypeSpec &, common::DefinedIo,174const Symbol &, const Symbol &generic);175void CheckModuleProcedureDef(const Symbol &);176
177SemanticsContext &context_;178evaluate::FoldingContext &foldingContext_{context_.foldingContext()};179parser::ContextualMessages &messages_{foldingContext_.messages()};180const Scope *scope_{nullptr};181bool scopeIsUninstantiatedPDT_{false};182// This symbol is the one attached to the innermost enclosing scope183// that has a symbol.184const Symbol *innermostSymbol_{nullptr};185// Cache of calls to Procedure::Characterize(Symbol)186std::map<SymbolRef, std::optional<Procedure>, SymbolAddressCompare>187characterizeCache_;188// Collection of module procedure symbols with non-BIND(C)189// global names, qualified by their module.190std::map<std::pair<SourceName, const Symbol *>, SymbolRef> moduleProcs_;191// Collection of symbols with global names, BIND(C) or otherwise192std::map<std::string, SymbolRef> globalNames_;193// Collection of external procedures without global definitions194std::map<std::string, SymbolRef> externalNames_;195// Collection of target dependent assembly names of external and BIND(C)196// procedures.197std::map<std::string, SymbolRef> procedureAssemblyNames_;198// Derived types that have been examined by WhyNotInteroperable_XXX199UnorderedSymbolSet examinedByWhyNotInteroperable_;200};201
202class DistinguishabilityHelper {203public:204DistinguishabilityHelper(SemanticsContext &context) : context_{context} {}205void Add(const Symbol &, GenericKind, const Symbol &, const Procedure &);206void Check(const Scope &);207
208private:209void SayNotDistinguishable(const Scope &, const SourceName &, GenericKind,210const Symbol &, const Symbol &, bool isHardConflict);211void AttachDeclaration(parser::Message &, const Scope &, const Symbol &);212
213SemanticsContext &context_;214struct ProcedureInfo {215GenericKind kind;216const Procedure &procedure;217};218std::map<SourceName, std::map<const Symbol *, ProcedureInfo>>219nameToSpecifics_;220};221
222void CheckHelper::Check(const ParamValue &value, bool canBeAssumed) {223if (value.isAssumed()) {224if (!canBeAssumed) { // C795, C721, C726225messages_.Say(226"An assumed (*) type parameter may be used only for a (non-statement function) dummy argument, associate name, character named constant, or external function result"_err_en_US);227}228} else {229CheckSpecExpr(value.GetExplicit(), /*forElementalFunctionResult=*/false);230}231}
232
233void CheckHelper::Check(const ArraySpec &shape) {234for (const auto &spec : shape) {235Check(spec);236}237}
238
239void CheckHelper::Check(240const DeclTypeSpec &type, bool canHaveAssumedTypeParameters) {241if (type.category() == DeclTypeSpec::Character) {242Check(type.characterTypeSpec().length(), canHaveAssumedTypeParameters);243} else if (const DerivedTypeSpec *derived{type.AsDerived()}) {244for (auto &parm : derived->parameters()) {245Check(parm.second, canHaveAssumedTypeParameters);246}247}248}
249
250void CheckHelper::Check(const Symbol &symbol) {251if (symbol.name().size() > common::maxNameLen &&252&symbol == &symbol.GetUltimate()) {253if (context_.ShouldWarn(common::LanguageFeature::LongNames)) {254WarnIfNotInModuleFile(symbol.name(),255"%s has length %d, which is greater than the maximum name length %d"_port_en_US,256symbol.name(), symbol.name().size(), common::maxNameLen);257}258}259if (context_.HasError(symbol)) {260return;261}262auto restorer{messages_.SetLocation(symbol.name())};263context_.set_location(symbol.name());264const DeclTypeSpec *type{symbol.GetType()};265const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};266bool isDone{false};267common::visit(268common::visitors{269[&](const UseDetails &x) { isDone = true; },270[&](const HostAssocDetails &x) {271CheckHostAssoc(symbol, x);272isDone = true;273},274[&](const ProcBindingDetails &x) {275CheckProcBinding(symbol, x);276isDone = true;277},278[&](const ObjectEntityDetails &x) { CheckObjectEntity(symbol, x); },279[&](const ProcEntityDetails &x) { CheckProcEntity(symbol, x); },280[&](const SubprogramDetails &x) { CheckSubprogram(symbol, x); },281[&](const DerivedTypeDetails &x) { CheckDerivedType(symbol, x); },282[&](const GenericDetails &x) { CheckGeneric(symbol, x); },283[](const auto &) {},284},285symbol.details());286if (symbol.attrs().test(Attr::VOLATILE)) {287CheckVolatile(symbol, derived);288}289if (symbol.attrs().test(Attr::BIND_C)) {290CheckBindC(symbol);291}292if (symbol.attrs().test(Attr::SAVE) &&293!symbol.implicitAttrs().test(Attr::SAVE)) {294CheckExplicitSave(symbol);295}296if (symbol.attrs().test(Attr::CONTIGUOUS)) {297CheckContiguous(symbol);298}299CheckGlobalName(symbol);300CheckProcedureAssemblyName(symbol);301if (symbol.attrs().test(Attr::ASYNCHRONOUS) &&302!evaluate::IsVariable(symbol)) {303messages_.Say(304"An entity may not have the ASYNCHRONOUS attribute unless it is a variable"_err_en_US);305}306if (symbol.attrs().HasAny({Attr::INTENT_IN, Attr::INTENT_INOUT,307Attr::INTENT_OUT, Attr::OPTIONAL, Attr::VALUE}) &&308!IsDummy(symbol)) {309messages_.Say(310"Only a dummy argument may have an INTENT, VALUE, or OPTIONAL attribute"_err_en_US);311} else if (symbol.attrs().test(Attr::VALUE)) {312CheckValue(symbol, derived);313}314
315if (isDone) {316return; // following checks do not apply317}318
319if (symbol.attrs().test(Attr::PROTECTED)) {320if (symbol.owner().kind() != Scope::Kind::Module) { // C854321messages_.Say(322"A PROTECTED entity must be in the specification part of a module"_err_en_US);323}324if (!evaluate::IsVariable(symbol) && !IsProcedurePointer(symbol)) { // C855325messages_.Say(326"A PROTECTED entity must be a variable or pointer"_err_en_US);327}328if (FindCommonBlockContaining(symbol)) { // C856329messages_.Say(330"A PROTECTED entity may not be in a common block"_err_en_US);331}332}333if (IsPointer(symbol)) {334CheckPointer(symbol);335}336if (InPure()) {337if (InInterface()) {338// Declarations in interface definitions "have no effect" if they339// are not pertinent to the characteristics of the procedure.340// Restrictions on entities in pure procedure interfaces don't need341// enforcement.342} else if (!FindCommonBlockContaining(symbol) && IsSaved(symbol)) {343if (IsInitialized(symbol)) {344messages_.Say(345"A pure subprogram may not initialize a variable"_err_en_US);346} else {347messages_.Say(348"A pure subprogram may not have a variable with the SAVE attribute"_err_en_US);349}350}351if (symbol.attrs().test(Attr::VOLATILE) &&352(IsDummy(symbol) || !InInterface())) {353messages_.Say(354"A pure subprogram may not have a variable with the VOLATILE attribute"_err_en_US);355}356if (innermostSymbol_ && innermostSymbol_->name() == "__builtin_c_funloc") {357// The intrinsic procedure C_FUNLOC() gets a pass on this check.358} else if (IsProcedure(symbol) && !IsPureProcedure(symbol) &&359IsDummy(symbol)) {360messages_.Say(361"A dummy procedure of a pure subprogram must be pure"_err_en_US);362}363}364const auto *object{symbol.detailsIf<ObjectEntityDetails>()};365if (type) { // Section 7.2, paragraph 7; C795366bool isChar{type->category() == DeclTypeSpec::Character};367bool canHaveAssumedParameter{(isChar && IsNamedConstant(symbol)) ||368(IsAssumedLengthCharacter(symbol) && // C722369(IsExternal(symbol) ||370ClassifyProcedure(symbol) ==371ProcedureDefinitionClass::Dummy)) ||372symbol.test(Symbol::Flag::ParentComp)};373if (!IsStmtFunctionDummy(symbol)) { // C726374if (object) {375canHaveAssumedParameter |= object->isDummy() ||376(isChar && object->isFuncResult()) ||377IsStmtFunctionResult(symbol); // Avoids multiple messages378} else {379canHaveAssumedParameter |= symbol.has<AssocEntityDetails>();380}381}382if (IsProcedurePointer(symbol) && symbol.HasExplicitInterface()) {383// Don't check function result types here384} else {385Check(*type, canHaveAssumedParameter);386}387if (InFunction() && IsFunctionResult(symbol)) {388if (InPure()) {389if (type->IsPolymorphic() && IsAllocatable(symbol)) { // C1585390messages_.Say(391"Result of pure function may not be both polymorphic and ALLOCATABLE"_err_en_US);392}393if (derived) {394// These cases would be caught be the general validation of local395// variables in a pure context, but these messages are more specific.396if (HasImpureFinal(symbol)) { // C1584397messages_.Say(398"Result of pure function may not have an impure FINAL subroutine"_err_en_US);399}400if (auto bad{FindPolymorphicAllocatableUltimateComponent(*derived)}) {401SayWithDeclaration(*bad,402"Result of pure function may not have polymorphic ALLOCATABLE ultimate component '%s'"_err_en_US,403bad.BuildResultDesignatorName());404}405}406}407if (InElemental() && isChar) { // F'2023 C15121408CheckSpecExpr(type->characterTypeSpec().length().GetExplicit(),409/*forElementalFunctionResult=*/true);410// TODO: check PDT LEN parameters411}412}413}414if (IsAssumedLengthCharacter(symbol) && IsFunction(symbol)) { // C723415if (symbol.attrs().test(Attr::RECURSIVE)) {416messages_.Say(417"An assumed-length CHARACTER(*) function cannot be RECURSIVE"_err_en_US);418}419if (symbol.Rank() > 0) {420messages_.Say(421"An assumed-length CHARACTER(*) function cannot return an array"_err_en_US);422}423if (!IsStmtFunction(symbol)) {424if (IsElementalProcedure(symbol)) {425messages_.Say(426"An assumed-length CHARACTER(*) function cannot be ELEMENTAL"_err_en_US);427} else if (IsPureProcedure(symbol)) {428messages_.Say(429"An assumed-length CHARACTER(*) function cannot be PURE"_err_en_US);430}431}432if (const Symbol *result{FindFunctionResult(symbol)}) {433if (IsPointer(*result)) {434messages_.Say(435"An assumed-length CHARACTER(*) function cannot return a POINTER"_err_en_US);436}437}438if (IsProcedurePointer(symbol) && IsDummy(symbol)) {439if (context_.ShouldWarn(common::UsageWarning::Portability)) {440messages_.Say(441"A dummy procedure pointer should not have assumed-length CHARACTER(*) result type"_port_en_US);442}443// The non-dummy case is a hard error that's caught elsewhere.444}445}446if (IsDummy(symbol)) {447if (IsNamedConstant(symbol)) {448messages_.Say(449"A dummy argument may not also be a named constant"_err_en_US);450}451} else if (IsFunctionResult(symbol)) {452if (IsNamedConstant(symbol)) {453messages_.Say(454"A function result may not also be a named constant"_err_en_US);455}456}457if (IsAutomatic(symbol)) {458if (const Symbol * common{FindCommonBlockContaining(symbol)}) {459messages_.Say(460"Automatic data object '%s' may not appear in COMMON block /%s/"_err_en_US,461symbol.name(), common->name());462} else if (symbol.owner().IsModule()) {463messages_.Say(464"Automatic data object '%s' may not appear in a module"_err_en_US,465symbol.name());466}467}468if (IsProcedure(symbol)) {469if (IsAllocatable(symbol)) {470messages_.Say(471"Procedure '%s' may not be ALLOCATABLE"_err_en_US, symbol.name());472}473if (!symbol.HasExplicitInterface() && symbol.Rank() > 0) {474messages_.Say(475"Procedure '%s' may not be an array without an explicit interface"_err_en_US,476symbol.name());477}478}479}
480
481void CheckHelper::CheckCommonBlock(const Symbol &symbol) {482CheckGlobalName(symbol);483if (symbol.attrs().test(Attr::BIND_C)) {484CheckBindC(symbol);485}486for (MutableSymbolRef ref : symbol.get<CommonBlockDetails>().objects()) {487if (ref->test(Symbol::Flag::CrayPointee)) {488messages_.Say(ref->name(),489"Cray pointee '%s' may not be a member of a COMMON block"_err_en_US,490ref->name());491}492}493}
494
495// C859, C860
496void CheckHelper::CheckExplicitSave(const Symbol &symbol) {497const Symbol &ultimate{symbol.GetUltimate()};498if (ultimate.test(Symbol::Flag::InDataStmt)) {499// checked elsewhere500} else if (symbol.has<UseDetails>()) {501messages_.Say(502"The USE-associated name '%s' may not have an explicit SAVE attribute"_err_en_US,503symbol.name());504} else if (IsDummy(ultimate)) {505messages_.Say(506"The dummy argument '%s' may not have an explicit SAVE attribute"_err_en_US,507symbol.name());508} else if (IsFunctionResult(ultimate)) {509messages_.Say(510"The function result variable '%s' may not have an explicit SAVE attribute"_err_en_US,511symbol.name());512} else if (const Symbol * common{FindCommonBlockContaining(ultimate)}) {513messages_.Say(514"The entity '%s' in COMMON block /%s/ may not have an explicit SAVE attribute"_err_en_US,515symbol.name(), common->name());516} else if (IsAutomatic(ultimate)) {517messages_.Say(518"The automatic object '%s' may not have an explicit SAVE attribute"_err_en_US,519symbol.name());520} else if (!evaluate::IsVariable(ultimate) && !IsProcedurePointer(ultimate)) {521messages_.Say(522"The entity '%s' with an explicit SAVE attribute must be a variable, procedure pointer, or COMMON block"_err_en_US,523symbol.name());524}525}
526
527void CheckHelper::CheckValue(528const Symbol &symbol, const DerivedTypeSpec *derived) { // C863 - C865529if (IsProcedure(symbol)) {530messages_.Say(531"VALUE attribute may apply only to a dummy data object"_err_en_US);532return; // don't pile on533}534if (IsAssumedSizeArray(symbol)) {535messages_.Say(536"VALUE attribute may not apply to an assumed-size array"_err_en_US);537}538if (evaluate::IsCoarray(symbol)) {539messages_.Say("VALUE attribute may not apply to a coarray"_err_en_US);540}541if (IsAllocatable(symbol)) {542messages_.Say("VALUE attribute may not apply to an ALLOCATABLE"_err_en_US);543} else if (IsPointer(symbol)) {544messages_.Say("VALUE attribute may not apply to a POINTER"_err_en_US);545}546if (IsIntentInOut(symbol)) {547messages_.Say(548"VALUE attribute may not apply to an INTENT(IN OUT) argument"_err_en_US);549} else if (IsIntentOut(symbol)) {550messages_.Say(551"VALUE attribute may not apply to an INTENT(OUT) argument"_err_en_US);552}553if (symbol.attrs().test(Attr::VOLATILE)) {554messages_.Say("VALUE attribute may not apply to a VOLATILE"_err_en_US);555}556if (innermostSymbol_ && IsBindCProcedure(*innermostSymbol_)) {557if (IsOptional(symbol)) {558messages_.Say(559"VALUE attribute may not apply to an OPTIONAL in a BIND(C) procedure"_err_en_US);560}561if (symbol.Rank() > 0) {562messages_.Say(563"VALUE attribute may not apply to an array in a BIND(C) procedure"_err_en_US);564}565}566if (derived) {567if (FindCoarrayUltimateComponent(*derived)) {568messages_.Say(569"VALUE attribute may not apply to a type with a coarray ultimate component"_err_en_US);570}571}572if (evaluate::IsAssumedRank(symbol)) {573messages_.Say(574"VALUE attribute may not apply to an assumed-rank array"_err_en_US);575}576if (context_.ShouldWarn(common::UsageWarning::Portability) &&577IsAssumedLengthCharacter(symbol)) {578// F'2008 feature not widely implemented579messages_.Say(580"VALUE attribute on assumed-length CHARACTER may not be portable"_port_en_US);581}582}
583
584void CheckHelper::CheckAssumedTypeEntity( // C709585const Symbol &symbol, const ObjectEntityDetails &details) {586if (const DeclTypeSpec *type{symbol.GetType()};587type && type->category() == DeclTypeSpec::TypeStar) {588if (!IsDummy(symbol)) {589messages_.Say(590"Assumed-type entity '%s' must be a dummy argument"_err_en_US,591symbol.name());592} else {593if (symbol.attrs().test(Attr::ALLOCATABLE)) {594messages_.Say("Assumed-type argument '%s' cannot have the ALLOCATABLE"595" attribute"_err_en_US,596symbol.name());597}598if (symbol.attrs().test(Attr::POINTER)) {599messages_.Say("Assumed-type argument '%s' cannot have the POINTER"600" attribute"_err_en_US,601symbol.name());602}603if (symbol.attrs().test(Attr::VALUE)) {604messages_.Say("Assumed-type argument '%s' cannot have the VALUE"605" attribute"_err_en_US,606symbol.name());607}608if (symbol.attrs().test(Attr::INTENT_OUT)) {609messages_.Say(610"Assumed-type argument '%s' cannot be INTENT(OUT)"_err_en_US,611symbol.name());612}613if (evaluate::IsCoarray(symbol)) {614messages_.Say(615"Assumed-type argument '%s' cannot be a coarray"_err_en_US,616symbol.name());617}618if (details.IsArray() && details.shape().IsExplicitShape()) {619messages_.Say("Assumed-type array argument '%s' must be assumed shape,"620" assumed size, or assumed rank"_err_en_US,621symbol.name());622}623}624}625}
626
627void CheckHelper::CheckObjectEntity(628const Symbol &symbol, const ObjectEntityDetails &details) {629CheckSymbolType(symbol);630CheckArraySpec(symbol, details.shape());631CheckConflicting(symbol, Attr::ALLOCATABLE, Attr::PARAMETER);632CheckConflicting(symbol, Attr::ASYNCHRONOUS, Attr::PARAMETER);633CheckConflicting(symbol, Attr::SAVE, Attr::PARAMETER);634CheckConflicting(symbol, Attr::TARGET, Attr::PARAMETER);635CheckConflicting(symbol, Attr::VOLATILE, Attr::PARAMETER);636Check(details.shape());637Check(details.coshape());638if (details.shape().Rank() > common::maxRank) {639messages_.Say(640"'%s' has rank %d, which is greater than the maximum supported rank %d"_err_en_US,641symbol.name(), details.shape().Rank(), common::maxRank);642} else if (details.shape().Rank() + details.coshape().Rank() >643common::maxRank) {644messages_.Say(645"'%s' has rank %d and corank %d, whose sum is greater than the maximum supported rank %d"_err_en_US,646symbol.name(), details.shape().Rank(), details.coshape().Rank(),647common::maxRank);648}649CheckAssumedTypeEntity(symbol, details);650WarnMissingFinal(symbol);651const DeclTypeSpec *type{details.type()};652const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};653bool isComponent{symbol.owner().IsDerivedType()};654if (!details.coshape().empty()) {655bool isDeferredCoshape{details.coshape().CanBeDeferredShape()};656if (IsAllocatable(symbol)) {657if (!isDeferredCoshape) { // C827658messages_.Say("'%s' is an ALLOCATABLE coarray and must have a deferred"659" coshape"_err_en_US,660symbol.name());661}662} else if (isComponent) { // C746663std::string deferredMsg{664isDeferredCoshape ? "" : " and have a deferred coshape"};665messages_.Say("Component '%s' is a coarray and must have the ALLOCATABLE"666" attribute%s"_err_en_US,667symbol.name(), deferredMsg);668} else {669if (!details.coshape().CanBeAssumedSize()) { // C828670messages_.Say(671"'%s' is a non-ALLOCATABLE coarray and must have an explicit coshape"_err_en_US,672symbol.name());673}674}675if (IsBadCoarrayType(derived)) { // C747 & C824676messages_.Say(677"Coarray '%s' may not have type TEAM_TYPE, C_PTR, or C_FUNPTR"_err_en_US,678symbol.name());679}680if (evaluate::IsAssumedRank(symbol)) {681messages_.Say("Coarray '%s' may not be an assumed-rank array"_err_en_US,682symbol.name());683}684}685if (details.isDummy()) {686if (IsIntentOut(symbol)) {687// Some of these errors would also be caught by the general check688// for definability of automatically deallocated local variables,689// but these messages are more specific.690if (FindUltimateComponent(symbol, [](const Symbol &x) {691return evaluate::IsCoarray(x) && IsAllocatable(x);692})) { // C846693messages_.Say(694"An INTENT(OUT) dummy argument may not be, or contain, an ALLOCATABLE coarray"_err_en_US);695}696if (IsOrContainsEventOrLockComponent(symbol)) { // C847697messages_.Say(698"An INTENT(OUT) dummy argument may not be, or contain, EVENT_TYPE or LOCK_TYPE"_err_en_US);699}700if (IsAssumedSizeArray(symbol)) { // C834701if (type && type->IsPolymorphic()) {702messages_.Say(703"An INTENT(OUT) assumed-size dummy argument array may not be polymorphic"_err_en_US);704}705if (derived) {706if (derived->HasDefaultInitialization()) {707messages_.Say(708"An INTENT(OUT) assumed-size dummy argument array may not have a derived type with any default component initialization"_err_en_US);709}710if (IsFinalizable(*derived)) {711messages_.Say(712"An INTENT(OUT) assumed-size dummy argument array may not be finalizable"_err_en_US);713}714}715}716}717if (InPure() && !IsStmtFunction(DEREF(innermostSymbol_)) &&718!IsPointer(symbol) && !IsIntentIn(symbol) &&719!symbol.attrs().test(Attr::VALUE)) {720const char *what{InFunction() ? "function" : "subroutine"};721bool ok{true};722if (IsIntentOut(symbol)) {723if (type && type->IsPolymorphic()) { // C1588724messages_.Say(725"An INTENT(OUT) dummy argument of a pure %s may not be polymorphic"_err_en_US,726what);727ok = false;728} else if (derived) {729if (FindUltimateComponent(*derived, [](const Symbol &x) {730const DeclTypeSpec *type{x.GetType()};731return type && type->IsPolymorphic();732})) { // C1588733messages_.Say(734"An INTENT(OUT) dummy argument of a pure %s may not have a polymorphic ultimate component"_err_en_US,735what);736ok = false;737}738if (HasImpureFinal(symbol)) { // C1587739messages_.Say(740"An INTENT(OUT) dummy argument of a pure %s may not have an impure FINAL subroutine"_err_en_US,741what);742ok = false;743}744}745} else if (!IsIntentInOut(symbol)) { // C1586746messages_.Say(747"non-POINTER dummy argument of pure %s must have INTENT() or VALUE attribute"_err_en_US,748what);749ok = false;750}751if (ok && InFunction() && !InModuleFile() && !InElemental()) {752if (context_.IsEnabled(common::LanguageFeature::RelaxedPureDummy)) {753if (context_.ShouldWarn(common::LanguageFeature::RelaxedPureDummy)) {754messages_.Say(755"non-POINTER dummy argument of pure function should be INTENT(IN) or VALUE"_warn_en_US);756}757} else {758messages_.Say(759"non-POINTER dummy argument of pure function must be INTENT(IN) or VALUE"_err_en_US);760}761}762}763if (auto ignoreTKR{GetIgnoreTKR(symbol)}; !ignoreTKR.empty()) {764const Symbol *ownerSymbol{symbol.owner().symbol()};765const auto *ownerSubp{ownerSymbol->detailsIf<SubprogramDetails>()};766bool inInterface{ownerSubp && ownerSubp->isInterface()};767bool inExplicitInterface{768inInterface && !IsSeparateModuleProcedureInterface(ownerSymbol)};769bool inModuleProc{770!inInterface && ownerSymbol && IsModuleProcedure(*ownerSymbol)};771if (!inExplicitInterface && !inModuleProc) {772messages_.Say(773"!DIR$ IGNORE_TKR may apply only in an interface or a module procedure"_err_en_US);774}775if (ownerSymbol && ownerSymbol->attrs().test(Attr::ELEMENTAL) &&776details.ignoreTKR().test(common::IgnoreTKR::Rank)) {777messages_.Say(778"!DIR$ IGNORE_TKR(R) may not apply in an ELEMENTAL procedure"_err_en_US);779}780if (IsPassedViaDescriptor(symbol)) {781if (IsAllocatableOrObjectPointer(&symbol)) {782if (inExplicitInterface) {783if (context_.ShouldWarn(common::UsageWarning::IgnoreTKRUsage)) {784WarnIfNotInModuleFile(785"!DIR$ IGNORE_TKR should not apply to an allocatable or pointer"_warn_en_US);786}787} else {788messages_.Say(789"!DIR$ IGNORE_TKR may not apply to an allocatable or pointer"_err_en_US);790}791} else if (ignoreTKR.test(common::IgnoreTKR::Rank)) {792if (ignoreTKR.count() == 1 && evaluate::IsAssumedRank(symbol)) {793if (context_.ShouldWarn(common::UsageWarning::IgnoreTKRUsage)) {794WarnIfNotInModuleFile(795"!DIR$ IGNORE_TKR(R) is not meaningful for an assumed-rank array"_warn_en_US);796}797} else if (inExplicitInterface) {798if (context_.ShouldWarn(common::UsageWarning::IgnoreTKRUsage)) {799WarnIfNotInModuleFile(800"!DIR$ IGNORE_TKR(R) should not apply to a dummy argument passed via descriptor"_warn_en_US);801}802} else {803messages_.Say(804"!DIR$ IGNORE_TKR(R) may not apply to a dummy argument passed via descriptor"_err_en_US);805}806}807}808}809} else if (!details.ignoreTKR().empty()) {810messages_.Say(811"!DIR$ IGNORE_TKR directive may apply only to a dummy data argument"_err_en_US);812}813if (InElemental()) {814if (details.isDummy()) { // C15100815if (details.shape().Rank() > 0) {816messages_.Say(817"A dummy argument of an ELEMENTAL procedure must be scalar"_err_en_US);818}819if (IsAllocatable(symbol)) {820messages_.Say(821"A dummy argument of an ELEMENTAL procedure may not be ALLOCATABLE"_err_en_US);822}823if (evaluate::IsCoarray(symbol)) {824messages_.Say(825"A dummy argument of an ELEMENTAL procedure may not be a coarray"_err_en_US);826}827if (IsPointer(symbol)) {828messages_.Say(829"A dummy argument of an ELEMENTAL procedure may not be a POINTER"_err_en_US);830}831if (!symbol.attrs().HasAny(Attrs{Attr::VALUE, Attr::INTENT_IN,832Attr::INTENT_INOUT, Attr::INTENT_OUT})) { // F'2023 C15120833messages_.Say(834"A dummy argument of an ELEMENTAL procedure must have an INTENT() or VALUE attribute"_err_en_US);835}836} else if (IsFunctionResult(symbol)) { // C15101837if (details.shape().Rank() > 0) {838messages_.Say(839"The result of an ELEMENTAL function must be scalar"_err_en_US);840}841if (IsAllocatable(symbol)) {842messages_.Say(843"The result of an ELEMENTAL function may not be ALLOCATABLE"_err_en_US);844}845if (IsPointer(symbol)) {846messages_.Say(847"The result of an ELEMENTAL function may not be a POINTER"_err_en_US);848}849}850}851if (HasDeclarationInitializer(symbol)) { // C808; ignore DATA initialization852CheckPointerInitialization(symbol);853if (IsAutomatic(symbol)) {854messages_.Say(855"An automatic variable or component must not be initialized"_err_en_US);856} else if (IsDummy(symbol)) {857messages_.Say("A dummy argument must not be initialized"_err_en_US);858} else if (IsFunctionResult(symbol)) {859messages_.Say("A function result must not be initialized"_err_en_US);860} else if (IsInBlankCommon(symbol)) {861if (context_.ShouldWarn(common::LanguageFeature::InitBlankCommon)) {862WarnIfNotInModuleFile(863"A variable in blank COMMON should not be initialized"_port_en_US);864}865}866}867if (symbol.owner().kind() == Scope::Kind::BlockData) {868if (IsAllocatable(symbol)) {869messages_.Say(870"An ALLOCATABLE variable may not appear in a BLOCK DATA subprogram"_err_en_US);871} else if (IsInitialized(symbol) && !FindCommonBlockContaining(symbol)) {872messages_.Say(873"An initialized variable in BLOCK DATA must be in a COMMON block"_err_en_US);874}875}876if (derived && InPure() && !InInterface() &&877IsAutomaticallyDestroyed(symbol) &&878!IsIntentOut(symbol) /*has better messages*/ &&879!IsFunctionResult(symbol) /*ditto*/) {880// Check automatically deallocated local variables for possible881// problems with finalization in PURE.882if (auto whyNot{883WhyNotDefinable(symbol.name(), symbol.owner(), {}, symbol)}) {884if (auto *msg{messages_.Say(885"'%s' may not be a local variable in a pure subprogram"_err_en_US,886symbol.name())}) {887msg->Attach(std::move(*whyNot));888}889}890}891if (symbol.attrs().test(Attr::EXTERNAL)) {892SayWithDeclaration(symbol,893"'%s' is a data object and may not be EXTERNAL"_err_en_US,894symbol.name());895}896
897// Check CUDA attributes and special circumstances of being in device898// subprograms899const Scope &progUnit{GetProgramUnitContaining(symbol)};900const auto *subpDetails{!isComponent && progUnit.symbol()901? progUnit.symbol()->detailsIf<SubprogramDetails>()902: nullptr};903bool inDeviceSubprogram{IsCUDADeviceContext(&symbol.owner())};904if (inDeviceSubprogram) {905if (IsSaved(symbol)) {906if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {907WarnIfNotInModuleFile(908"'%s' should not have the SAVE attribute or initialization in a device subprogram"_warn_en_US,909symbol.name());910}911}912if (IsPointer(symbol)) {913if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {914WarnIfNotInModuleFile(915"Pointer '%s' may not be associated in a device subprogram"_warn_en_US,916symbol.name());917}918}919if (details.isDummy() &&920details.cudaDataAttr().value_or(common::CUDADataAttr::Device) !=921common::CUDADataAttr::Device &&922details.cudaDataAttr().value_or(common::CUDADataAttr::Device) !=923common::CUDADataAttr::Managed) {924if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {925WarnIfNotInModuleFile(926"Dummy argument '%s' may not have ATTRIBUTES(%s) in a device subprogram"_warn_en_US,927symbol.name(),928parser::ToUpperCaseLetters(929common::EnumToString(*details.cudaDataAttr())));930}931}932}933if (details.cudaDataAttr()) {934if (auto dyType{evaluate::DynamicType::From(symbol)}) {935if (dyType->category() != TypeCategory::Derived) {936if (!IsCUDAIntrinsicType(*dyType)) {937messages_.Say(938"'%s' has intrinsic type '%s' that is not available on the device"_err_en_US,939symbol.name(), dyType->AsFortran());940}941}942}943auto attr{*details.cudaDataAttr()};944switch (attr) {945case common::CUDADataAttr::Constant:946if (subpDetails && !inDeviceSubprogram) {947messages_.Say(948"Object '%s' with ATTRIBUTES(CONSTANT) may not be declared in a host subprogram"_err_en_US,949symbol.name());950} else if (IsAllocatableOrPointer(symbol) ||951symbol.attrs().test(Attr::TARGET)) {952messages_.Say(953"Object '%s' with ATTRIBUTES(CONSTANT) may not be allocatable, pointer, or target"_err_en_US,954symbol.name());955} else if (auto shape{evaluate::GetShape(foldingContext_, symbol)};956!shape ||957!evaluate::AsConstantExtents(foldingContext_, *shape)) {958messages_.Say(959"Object '%s' with ATTRIBUTES(CONSTANT) must have constant array bounds"_err_en_US,960symbol.name());961}962break;963case common::CUDADataAttr::Device:964if (isComponent && !IsAllocatable(symbol)) {965messages_.Say(966"Component '%s' with ATTRIBUTES(DEVICE) must also be allocatable"_err_en_US,967symbol.name());968}969break;970case common::CUDADataAttr::Managed:971if (!IsAutomatic(symbol) && !IsAllocatable(symbol) &&972!details.isDummy() && !evaluate::IsExplicitShape(symbol)) {973messages_.Say(974"Object '%s' with ATTRIBUTES(MANAGED) must also be allocatable, automatic, explicit shape, or a dummy argument"_err_en_US,975symbol.name());976}977break;978case common::CUDADataAttr::Pinned:979if (inDeviceSubprogram) {980if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {981WarnIfNotInModuleFile(982"Object '%s' with ATTRIBUTES(PINNED) may not be declared in a device subprogram"_warn_en_US,983symbol.name());984}985} else if (IsPointer(symbol)) {986if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {987WarnIfNotInModuleFile(988"Object '%s' with ATTRIBUTES(PINNED) may not be a pointer"_warn_en_US,989symbol.name());990}991} else if (!IsAllocatable(symbol)) {992if (context_.ShouldWarn(common::UsageWarning::CUDAUsage)) {993WarnIfNotInModuleFile(994"Object '%s' with ATTRIBUTES(PINNED) should also be allocatable"_warn_en_US,995symbol.name());996}997}998break;999case common::CUDADataAttr::Shared:1000if (IsAllocatableOrPointer(symbol) || symbol.attrs().test(Attr::TARGET)) {1001messages_.Say(1002"Object '%s' with ATTRIBUTES(SHARED) may not be allocatable, pointer, or target"_err_en_US,1003symbol.name());1004} else if (!inDeviceSubprogram) {1005messages_.Say(1006"Object '%s' with ATTRIBUTES(SHARED) must be declared in a device subprogram"_err_en_US,1007symbol.name());1008}1009break;1010case common::CUDADataAttr::Unified:1011if (((!subpDetails &&1012symbol.owner().kind() != Scope::Kind::MainProgram) ||1013inDeviceSubprogram) &&1014!isComponent) {1015messages_.Say(1016"Object '%s' with ATTRIBUTES(UNIFIED) must be declared in a host subprogram"_err_en_US,1017symbol.name());1018}1019break;1020case common::CUDADataAttr::Texture:1021messages_.Say(1022"ATTRIBUTES(TEXTURE) is obsolete and no longer supported"_err_en_US);1023break;1024}1025if (attr != common::CUDADataAttr::Pinned) {1026if (details.commonBlock()) {1027messages_.Say(1028"Object '%s' with ATTRIBUTES(%s) may not be in COMMON"_err_en_US,1029symbol.name(),1030parser::ToUpperCaseLetters(common::EnumToString(attr)));1031} else if (FindEquivalenceSet(symbol)) {1032messages_.Say(1033"Object '%s' with ATTRIBUTES(%s) may not be in an equivalence group"_err_en_US,1034symbol.name(),1035parser::ToUpperCaseLetters(common::EnumToString(attr)));1036}1037}1038if (subpDetails /* not a module variable */ && IsSaved(symbol) &&1039!inDeviceSubprogram && !IsAllocatable(symbol) &&1040attr == common::CUDADataAttr::Device) {1041messages_.Say(1042"Saved object '%s' in host code may not have ATTRIBUTES(DEVICE) unless allocatable"_err_en_US,1043symbol.name(),1044parser::ToUpperCaseLetters(common::EnumToString(attr)));1045}1046if (isComponent) {1047if (attr == common::CUDADataAttr::Device) {1048const DeclTypeSpec *type{symbol.GetType()};1049if (const DerivedTypeSpec *1050derived{type ? type->AsDerived() : nullptr}) {1051DirectComponentIterator directs{*derived};1052if (auto iter{std::find_if(directs.begin(), directs.end(),1053[](const Symbol &) { return false; })}) {1054messages_.Say(1055"Derived type component '%s' may not have ATTRIBUTES(DEVICE) as it has a direct device component '%s'"_err_en_US,1056symbol.name(), iter.BuildResultDesignatorName());1057}1058}1059} else if (attr == common::CUDADataAttr::Constant ||1060attr == common::CUDADataAttr::Shared) {1061messages_.Say(1062"Derived type component '%s' may not have ATTRIBUTES(%s)"_err_en_US,1063symbol.name(),1064parser::ToUpperCaseLetters(common::EnumToString(attr)));1065}1066} else if (!subpDetails && symbol.owner().kind() != Scope::Kind::Module &&1067symbol.owner().kind() != Scope::Kind::MainProgram &&1068symbol.owner().kind() != Scope::Kind::BlockConstruct) {1069messages_.Say(1070"ATTRIBUTES(%s) may apply only to module, host subprogram, block, or device subprogram data"_err_en_US,1071parser::ToUpperCaseLetters(common::EnumToString(attr)));1072}1073}1074
1075if (derived && derived->IsVectorType()) {1076CHECK(type);1077std::string typeName{type->AsFortran()};1078if (IsAssumedShape(symbol)) {1079SayWithDeclaration(symbol,1080"Assumed-shape entity of %s type is not supported"_err_en_US,1081typeName);1082} else if (IsDeferredShape(symbol)) {1083SayWithDeclaration(symbol,1084"Deferred-shape entity of %s type is not supported"_err_en_US,1085typeName);1086} else if (evaluate::IsAssumedRank(symbol)) {1087SayWithDeclaration(symbol,1088"Assumed Rank entity of %s type is not supported"_err_en_US,1089typeName);1090}1091}1092}
1093
1094void CheckHelper::CheckPointerInitialization(const Symbol &symbol) {1095if (IsPointer(symbol) && !context_.HasError(symbol) &&1096!scopeIsUninstantiatedPDT_) {1097if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {1098if (object->init()) { // C764, C765; C8081099if (auto designator{evaluate::AsGenericExpr(symbol)}) {1100auto restorer{messages_.SetLocation(symbol.name())};1101context_.set_location(symbol.name());1102CheckInitialDataPointerTarget(1103context_, *designator, *object->init(), DEREF(scope_));1104}1105}1106} else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {1107if (proc->init() && *proc->init()) {1108// C1519 - must be nonelemental external or module procedure,1109// or an unrestricted specific intrinsic function.1110const Symbol &ultimate{(*proc->init())->GetUltimate()};1111bool checkTarget{true};1112if (ultimate.attrs().test(Attr::INTRINSIC)) {1113if (auto intrinsic{context_.intrinsics().IsSpecificIntrinsicFunction(1114ultimate.name().ToString())};1115!intrinsic || intrinsic->isRestrictedSpecific) { // C10301116context_.Say(1117"Intrinsic procedure '%s' is not an unrestricted specific "1118"intrinsic permitted for use as the initializer for procedure "1119"pointer '%s'"_err_en_US,1120ultimate.name(), symbol.name());1121checkTarget = false;1122}1123} else if ((!ultimate.attrs().test(Attr::EXTERNAL) &&1124ultimate.owner().kind() != Scope::Kind::Module) ||1125IsDummy(ultimate) || IsPointer(ultimate)) {1126context_.Say("Procedure pointer '%s' initializer '%s' is neither "1127"an external nor a module procedure"_err_en_US,1128symbol.name(), ultimate.name());1129checkTarget = false;1130} else if (IsElementalProcedure(ultimate)) {1131context_.Say("Procedure pointer '%s' cannot be initialized with the "1132"elemental procedure '%s'"_err_en_US,1133symbol.name(), ultimate.name());1134checkTarget = false;1135}1136if (checkTarget) {1137SomeExpr lhs{evaluate::ProcedureDesignator{symbol}};1138SomeExpr rhs{evaluate::ProcedureDesignator{**proc->init()}};1139CheckPointerAssignment(context_, lhs, rhs,1140GetProgramUnitOrBlockConstructContaining(symbol),1141/*isBoundsRemapping=*/false, /*isAssumedRank=*/false);1142}1143}1144}1145}1146}
1147
1148// The six different kinds of array-specs:
1149// array-spec -> explicit-shape-list | deferred-shape-list
1150// | assumed-shape-list | implied-shape-list
1151// | assumed-size | assumed-rank
1152// explicit-shape -> [ lb : ] ub
1153// deferred-shape -> :
1154// assumed-shape -> [ lb ] :
1155// implied-shape -> [ lb : ] *
1156// assumed-size -> [ explicit-shape-list , ] [ lb : ] *
1157// assumed-rank -> ..
1158// Note:
1159// - deferred-shape is also an assumed-shape
1160// - A single "*" or "lb:*" might be assumed-size or implied-shape-list
1161void CheckHelper::CheckArraySpec(1162const Symbol &symbol, const ArraySpec &arraySpec) {1163if (arraySpec.Rank() == 0) {1164return;1165}1166bool isExplicit{arraySpec.IsExplicitShape()};1167bool canBeDeferred{arraySpec.CanBeDeferredShape()};1168bool canBeImplied{arraySpec.CanBeImpliedShape()};1169bool canBeAssumedShape{arraySpec.CanBeAssumedShape()};1170bool canBeAssumedSize{arraySpec.CanBeAssumedSize()};1171bool isAssumedRank{arraySpec.IsAssumedRank()};1172bool isCUDAShared{1173GetCUDADataAttr(&symbol).value_or(common::CUDADataAttr::Device) ==1174common::CUDADataAttr::Shared};1175bool isCrayPointee{symbol.test(Symbol::Flag::CrayPointee)};1176std::optional<parser::MessageFixedText> msg;1177if (isCrayPointee && !isExplicit && !canBeAssumedSize) {1178msg =1179"Cray pointee '%s' must have explicit shape or assumed size"_err_en_US;1180} else if (IsAllocatableOrPointer(symbol) && !canBeDeferred &&1181!isAssumedRank) {1182if (symbol.owner().IsDerivedType()) { // C7451183if (IsAllocatable(symbol)) {1184msg = "Allocatable array component '%s' must have"1185" deferred shape"_err_en_US;1186} else {1187msg = "Array pointer component '%s' must have deferred shape"_err_en_US;1188}1189} else {1190if (IsAllocatable(symbol)) { // C8321191msg = "Allocatable array '%s' must have deferred shape or"1192" assumed rank"_err_en_US;1193} else {1194msg = "Array pointer '%s' must have deferred shape or"1195" assumed rank"_err_en_US;1196}1197}1198} else if (IsDummy(symbol)) {1199if (canBeImplied && !canBeAssumedSize) { // C8361200msg = "Dummy array argument '%s' may not have implied shape"_err_en_US;1201}1202} else if (canBeAssumedShape && !canBeDeferred) {1203msg = "Assumed-shape array '%s' must be a dummy argument"_err_en_US;1204} else if (isAssumedRank) { // C8371205msg = "Assumed-rank array '%s' must be a dummy argument"_err_en_US;1206} else if (canBeAssumedSize && !canBeImplied && !isCUDAShared &&1207!isCrayPointee) { // C8331208msg = "Assumed-size array '%s' must be a dummy argument"_err_en_US;1209} else if (canBeImplied) {1210if (!IsNamedConstant(symbol) && !isCUDAShared &&1211!isCrayPointee) { // C835, C8361212msg = "Implied-shape array '%s' must be a named constant or a "1213"dummy argument"_err_en_US;1214}1215} else if (IsNamedConstant(symbol)) {1216if (!isExplicit && !canBeImplied) {1217msg = "Named constant '%s' array must have constant or"1218" implied shape"_err_en_US;1219}1220} else if (!isExplicit &&1221!(IsAllocatableOrPointer(symbol) || isCrayPointee)) {1222if (symbol.owner().IsDerivedType()) { // C7491223msg = "Component array '%s' without ALLOCATABLE or POINTER attribute must"1224" have explicit shape"_err_en_US;1225} else { // C8161226msg = "Array '%s' without ALLOCATABLE or POINTER attribute must have"1227" explicit shape"_err_en_US;1228}1229}1230if (msg) {1231context_.Say(std::move(*msg), symbol.name());1232}1233}
1234
1235void CheckHelper::CheckProcEntity(1236const Symbol &symbol, const ProcEntityDetails &details) {1237CheckSymbolType(symbol);1238const Symbol *interface{details.procInterface()};1239if (details.isDummy()) {1240if (!symbol.attrs().test(Attr::POINTER) && // C8431241symbol.attrs().HasAny(1242{Attr::INTENT_IN, Attr::INTENT_OUT, Attr::INTENT_INOUT})) {1243messages_.Say("A dummy procedure without the POINTER attribute"1244" may not have an INTENT attribute"_err_en_US);1245}1246if (InElemental()) { // C151001247messages_.Say(1248"An ELEMENTAL subprogram may not have a dummy procedure"_err_en_US);1249}1250if (interface && IsElementalProcedure(*interface)) {1251// There's no explicit constraint or "shall" that we can find in the1252// standard for this check, but it seems to be implied in multiple1253// sites, and ELEMENTAL non-intrinsic actual arguments *are*1254// explicitly forbidden. But we allow "PROCEDURE(SIN)::dummy"1255// because it is explicitly legal to *pass* the specific intrinsic1256// function SIN as an actual argument.1257if (interface->attrs().test(Attr::INTRINSIC)) {1258if (context_.ShouldWarn(common::UsageWarning::Portability)) {1259messages_.Say(1260"A dummy procedure should not have an ELEMENTAL intrinsic as its interface"_port_en_US);1261}1262} else {1263messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US);1264}1265}1266} else if (IsPointer(symbol)) {1267CheckPointerInitialization(symbol);1268if (interface) {1269if (interface->attrs().test(Attr::INTRINSIC)) {1270auto intrinsic{context_.intrinsics().IsSpecificIntrinsicFunction(1271interface->name().ToString())};1272if (!intrinsic || intrinsic->isRestrictedSpecific) { // C15151273messages_.Say(1274"Intrinsic procedure '%s' is not an unrestricted specific "1275"intrinsic permitted for use as the definition of the interface "1276"to procedure pointer '%s'"_err_en_US,1277interface->name(), symbol.name());1278} else if (IsElementalProcedure(*interface)) {1279if (context_.ShouldWarn(common::UsageWarning::Portability)) {1280messages_.Say(1281"Procedure pointer '%s' should not have an ELEMENTAL intrinsic as its interface"_port_en_US,1282symbol.name()); // C15171283}1284}1285} else if (IsElementalProcedure(*interface)) {1286messages_.Say("Procedure pointer '%s' may not be ELEMENTAL"_err_en_US,1287symbol.name()); // C15171288}1289}1290if (symbol.owner().IsDerivedType()) {1291CheckPassArg(symbol, interface, details);1292}1293} else if (symbol.owner().IsDerivedType()) {1294const auto &name{symbol.name()};1295messages_.Say(name,1296"Procedure component '%s' must have POINTER attribute"_err_en_US, name);1297}1298CheckExternal(symbol);1299}
1300
1301// When a module subprogram has the MODULE prefix the following must match
1302// with the corresponding separate module procedure interface body:
1303// - C1549: characteristics and dummy argument names
1304// - C1550: binding label
1305// - C1551: NON_RECURSIVE prefix
1306class SubprogramMatchHelper {1307public:1308explicit SubprogramMatchHelper(CheckHelper &checkHelper)1309: checkHelper{checkHelper} {}1310
1311void Check(const Symbol &, const Symbol &);1312
1313private:1314SemanticsContext &context() { return checkHelper.context(); }1315void CheckDummyArg(const Symbol &, const Symbol &, const DummyArgument &,1316const DummyArgument &);1317void CheckDummyDataObject(const Symbol &, const Symbol &,1318const DummyDataObject &, const DummyDataObject &);1319void CheckDummyProcedure(const Symbol &, const Symbol &,1320const DummyProcedure &, const DummyProcedure &);1321bool CheckSameIntent(1322const Symbol &, const Symbol &, common::Intent, common::Intent);1323template <typename... A>1324void Say(1325const Symbol &, const Symbol &, parser::MessageFixedText &&, A &&...);1326template <typename ATTRS>1327bool CheckSameAttrs(const Symbol &, const Symbol &, ATTRS, ATTRS);1328bool ShapesAreCompatible(const DummyDataObject &, const DummyDataObject &);1329evaluate::Shape FoldShape(const evaluate::Shape &);1330std::optional<evaluate::Shape> FoldShape(1331const std::optional<evaluate::Shape> &shape) {1332if (shape) {1333return FoldShape(*shape);1334}1335return std::nullopt;1336}1337std::string AsFortran(DummyDataObject::Attr attr) {1338return parser::ToUpperCaseLetters(DummyDataObject::EnumToString(attr));1339}1340std::string AsFortran(DummyProcedure::Attr attr) {1341return parser::ToUpperCaseLetters(DummyProcedure::EnumToString(attr));1342}1343
1344CheckHelper &checkHelper;1345};1346
1347// 15.6.2.6 para 3 - can the result of an ENTRY differ from its function?
1348bool CheckHelper::IsResultOkToDiffer(const FunctionResult &result) {1349if (result.attrs.test(FunctionResult::Attr::Allocatable) ||1350result.attrs.test(FunctionResult::Attr::Pointer)) {1351return false;1352}1353const auto *typeAndShape{result.GetTypeAndShape()};1354if (!typeAndShape || typeAndShape->Rank() != 0) {1355return false;1356}1357auto category{typeAndShape->type().category()};1358if (category == TypeCategory::Character ||1359category == TypeCategory::Derived) {1360return false;1361}1362int kind{typeAndShape->type().kind()};1363return kind == context_.GetDefaultKind(category) ||1364(category == TypeCategory::Real &&1365kind == context_.doublePrecisionKind());1366}
1367
1368void CheckHelper::CheckSubprogram(1369const Symbol &symbol, const SubprogramDetails &details) {1370// Evaluate a procedure definition's characteristics to flush out1371// any errors that analysis might expose, in case this subprogram hasn't1372// had any calls in this compilation unit that would have validated them.1373if (!context_.HasError(symbol) && !details.isDummy() &&1374!details.isInterface() && !details.stmtFunction()) {1375if (!Procedure::Characterize(symbol, foldingContext_)) {1376context_.SetError(symbol);1377}1378}1379if (const Symbol *iface{FindSeparateModuleSubprogramInterface(&symbol)}) {1380SubprogramMatchHelper{*this}.Check(symbol, *iface);1381}1382if (const Scope *entryScope{details.entryScope()}) {1383// ENTRY F'2023 15.6.2.61384std::optional<parser::MessageFixedText> error;1385const Symbol *subprogram{entryScope->symbol()};1386const SubprogramDetails *subprogramDetails{nullptr};1387if (subprogram) {1388subprogramDetails = subprogram->detailsIf<SubprogramDetails>();1389}1390if (!(entryScope->parent().IsGlobal() || entryScope->parent().IsModule() ||1391entryScope->parent().IsSubmodule())) {1392error = "ENTRY may not appear in an internal subprogram"_err_en_US;1393} else if (subprogramDetails && details.isFunction() &&1394subprogramDetails->isFunction() &&1395!context_.HasError(details.result()) &&1396!context_.HasError(subprogramDetails->result())) {1397auto result{FunctionResult::Characterize(1398details.result(), context_.foldingContext())};1399auto subpResult{FunctionResult::Characterize(1400subprogramDetails->result(), context_.foldingContext())};1401if (result && subpResult && *result != *subpResult &&1402(!IsResultOkToDiffer(*result) || !IsResultOkToDiffer(*subpResult))) {1403error =1404"Result of ENTRY is not compatible with result of containing function"_err_en_US;1405}1406}1407if (error) {1408if (auto *msg{messages_.Say(symbol.name(), *error)}) {1409if (subprogram) {1410msg->Attach(subprogram->name(), "Containing subprogram"_en_US);1411}1412}1413}1414}1415if (details.isFunction() &&1416details.result().name() != symbol.name()) { // F'2023 C1569 & C15831417if (auto iter{symbol.owner().find(details.result().name())};1418iter != symbol.owner().end()) {1419const Symbol &resNameSym{*iter->second};1420if (const auto *resNameSubp{resNameSym.detailsIf<SubprogramDetails>()}) {1421if (const Scope * resNameEntryScope{resNameSubp->entryScope()}) {1422const Scope *myScope{1423details.entryScope() ? details.entryScope() : symbol.scope()};1424if (resNameEntryScope == myScope) {1425if (auto *msg{messages_.Say(symbol.name(),1426"Explicit RESULT('%s') of function '%s' cannot have the same name as a distinct ENTRY into the same scope"_err_en_US,1427details.result().name(), symbol.name())}) {1428msg->Attach(1429resNameSym.name(), "ENTRY with conflicting name"_en_US);1430}1431}1432}1433}1434}1435}1436if (const MaybeExpr & stmtFunction{details.stmtFunction()}) {1437if (auto msg{evaluate::CheckStatementFunction(1438symbol, *stmtFunction, context_.foldingContext())}) {1439SayWithDeclaration(symbol, std::move(*msg));1440} else if (IsPointer(symbol)) {1441SayWithDeclaration(symbol,1442"A statement function must not have the POINTER attribute"_err_en_US);1443} else if (details.result().flags().test(Symbol::Flag::Implicit)) {1444// 15.6.4 p2 weird requirement1445if (const Symbol *1446host{symbol.owner().parent().FindSymbol(symbol.name())}) {1447if (context_.ShouldWarn(1448common::LanguageFeature::StatementFunctionExtensions)) {1449evaluate::AttachDeclaration(1450messages_.Say(symbol.name(),1451"An implicitly typed statement function should not appear when the same symbol is available in its host scope"_port_en_US),1452*host);1453}1454}1455}1456if (GetProgramUnitOrBlockConstructContaining(symbol).kind() ==1457Scope::Kind::BlockConstruct) { // C11071458messages_.Say(symbol.name(),1459"A statement function definition may not appear in a BLOCK construct"_err_en_US);1460}1461}1462if (IsElementalProcedure(symbol)) {1463// See comment on the similar check in CheckProcEntity()1464if (details.isDummy()) {1465messages_.Say("A dummy procedure may not be ELEMENTAL"_err_en_US);1466} else {1467for (const Symbol *dummy : details.dummyArgs()) {1468if (!dummy) { // C151001469messages_.Say(1470"An ELEMENTAL subroutine may not have an alternate return dummy argument"_err_en_US);1471}1472}1473}1474}1475if (details.isInterface()) {1476if (!details.isDummy() && details.isFunction() &&1477IsAssumedLengthCharacter(details.result())) { // C7211478messages_.Say(details.result().name(),1479"A function interface may not declare an assumed-length CHARACTER(*) result"_err_en_US);1480}1481}1482CheckExternal(symbol);1483CheckModuleProcedureDef(symbol);1484auto cudaAttrs{details.cudaSubprogramAttrs()};1485if (cudaAttrs &&1486(*cudaAttrs == common::CUDASubprogramAttrs::Global ||1487*cudaAttrs == common::CUDASubprogramAttrs::Grid_Global) &&1488details.isFunction()) {1489messages_.Say(symbol.name(),1490"A function may not have ATTRIBUTES(GLOBAL) or ATTRIBUTES(GRID_GLOBAL)"_err_en_US);1491}1492if (cudaAttrs &&1493(*cudaAttrs == common::CUDASubprogramAttrs::Global ||1494*cudaAttrs == common::CUDASubprogramAttrs::Grid_Global) &&1495symbol.attrs().HasAny({Attr::RECURSIVE, Attr::PURE, Attr::ELEMENTAL})) {1496messages_.Say(symbol.name(),1497"A kernel subprogram may not be RECURSIVE, PURE, or ELEMENTAL"_err_en_US);1498}1499if (cudaAttrs && *cudaAttrs != common::CUDASubprogramAttrs::Host) {1500// CUDA device subprogram checks1501if (ClassifyProcedure(symbol) == ProcedureDefinitionClass::Internal) {1502messages_.Say(symbol.name(),1503"A device subprogram may not be an internal subprogram"_err_en_US);1504}1505}1506if ((!details.cudaLaunchBounds().empty() ||1507!details.cudaClusterDims().empty()) &&1508!(cudaAttrs &&1509(*cudaAttrs == common::CUDASubprogramAttrs::Global ||1510*cudaAttrs == common::CUDASubprogramAttrs::Grid_Global))) {1511messages_.Say(symbol.name(),1512"A subroutine may not have LAUNCH_BOUNDS() or CLUSTER_DIMS() unless it has ATTRIBUTES(GLOBAL) or ATTRIBUTES(GRID_GLOBAL)"_err_en_US);1513}1514if (!IsStmtFunction(symbol)) {1515if (const Scope * outerDevice{FindCUDADeviceContext(&symbol.owner())};1516outerDevice && outerDevice->symbol()) {1517if (auto *msg{messages_.Say(symbol.name(),1518"'%s' may not be an internal procedure of CUDA device subprogram '%s'"_err_en_US,1519symbol.name(), outerDevice->symbol()->name())}) {1520msg->Attach(outerDevice->symbol()->name(),1521"Containing CUDA device subprogram"_en_US);1522}1523}1524}1525}
1526
1527void CheckHelper::CheckExternal(const Symbol &symbol) {1528if (IsExternal(symbol)) {1529std::string interfaceName{symbol.name().ToString()};1530if (const auto *bind{symbol.GetBindName()}) {1531interfaceName = *bind;1532}1533if (const Symbol * global{FindGlobal(symbol)};1534global && global != &symbol) {1535std::string definitionName{global->name().ToString()};1536if (const auto *bind{global->GetBindName()}) {1537definitionName = *bind;1538}1539if (interfaceName == definitionName) {1540parser::Message *msg{nullptr};1541if (!IsProcedure(*global)) {1542if ((symbol.flags().test(Symbol::Flag::Function) ||1543symbol.flags().test(Symbol::Flag::Subroutine)) &&1544context_.ShouldWarn(common::UsageWarning::ExternalNameConflict)) {1545msg = WarnIfNotInModuleFile(1546"The global entity '%s' corresponding to the local procedure '%s' is not a callable subprogram"_warn_en_US,1547global->name(), symbol.name());1548}1549} else if (auto chars{Characterize(symbol)}) {1550if (auto globalChars{Characterize(*global)}) {1551if (chars->HasExplicitInterface()) {1552std::string whyNot;1553if (!chars->IsCompatibleWith(*globalChars,1554/*ignoreImplicitVsExplicit=*/false, &whyNot) &&1555context_.ShouldWarn(1556common::UsageWarning::ExternalInterfaceMismatch)) {1557msg = WarnIfNotInModuleFile(1558"The global subprogram '%s' is not compatible with its local procedure declaration (%s)"_warn_en_US,1559global->name(), whyNot);1560}1561} else if (!globalChars->CanBeCalledViaImplicitInterface() &&1562context_.ShouldWarn(1563common::UsageWarning::ExternalInterfaceMismatch)) {1564msg = messages_.Say(1565"The global subprogram '%s' may not be referenced via the implicit interface '%s'"_err_en_US,1566global->name(), symbol.name());1567}1568}1569}1570if (msg) {1571if (msg->IsFatal()) {1572context_.SetError(symbol);1573}1574evaluate::AttachDeclaration(msg, *global);1575evaluate::AttachDeclaration(msg, symbol);1576}1577}1578} else if (auto iter{externalNames_.find(interfaceName)};1579iter != externalNames_.end()) {1580const Symbol &previous{*iter->second};1581if (auto chars{Characterize(symbol)}) {1582if (auto previousChars{Characterize(previous)}) {1583std::string whyNot;1584if (!chars->IsCompatibleWith(*previousChars,1585/*ignoreImplicitVsExplicit=*/false, &whyNot) &&1586context_.ShouldWarn(1587common::UsageWarning::ExternalInterfaceMismatch)) {1588if (auto *msg{WarnIfNotInModuleFile(1589"The external interface '%s' is not compatible with an earlier definition (%s)"_warn_en_US,1590symbol.name(), whyNot)}) {1591evaluate::AttachDeclaration(msg, previous);1592evaluate::AttachDeclaration(msg, symbol);1593}1594}1595}1596}1597} else {1598externalNames_.emplace(interfaceName, symbol);1599}1600}1601}
1602
1603void CheckHelper::CheckDerivedType(1604const Symbol &derivedType, const DerivedTypeDetails &details) {1605if (details.isForwardReferenced() && !context_.HasError(derivedType)) {1606messages_.Say("The derived type '%s' has not been defined"_err_en_US,1607derivedType.name());1608}1609const Scope *scope{derivedType.scope()};1610if (!scope) {1611CHECK(details.isForwardReferenced());1612return;1613}1614CHECK(scope->symbol() == &derivedType);1615CHECK(scope->IsDerivedType());1616if (derivedType.attrs().test(Attr::ABSTRACT) && // C7341617(derivedType.attrs().test(Attr::BIND_C) || details.sequence())) {1618messages_.Say("An ABSTRACT derived type must be extensible"_err_en_US);1619}1620if (const DeclTypeSpec *parent{FindParentTypeSpec(derivedType)}) {1621const DerivedTypeSpec *parentDerived{parent->AsDerived()};1622if (!IsExtensibleType(parentDerived)) { // C7051623messages_.Say("The parent type is not extensible"_err_en_US);1624}1625if (!derivedType.attrs().test(Attr::ABSTRACT) && parentDerived &&1626parentDerived->typeSymbol().attrs().test(Attr::ABSTRACT)) {1627ScopeComponentIterator components{*parentDerived};1628for (const Symbol &component : components) {1629if (component.attrs().test(Attr::DEFERRED)) {1630if (scope->FindComponent(component.name()) == &component) {1631SayWithDeclaration(component,1632"Non-ABSTRACT extension of ABSTRACT derived type '%s' lacks a binding for DEFERRED procedure '%s'"_err_en_US,1633parentDerived->typeSymbol().name(), component.name());1634}1635}1636}1637}1638DerivedTypeSpec derived{derivedType.name(), derivedType};1639derived.set_scope(*scope);1640if (FindCoarrayUltimateComponent(derived) && // C7361641!(parentDerived && FindCoarrayUltimateComponent(*parentDerived))) {1642messages_.Say(1643"Type '%s' has a coarray ultimate component so the type at the base "1644"of its type extension chain ('%s') must be a type that has a "1645"coarray ultimate component"_err_en_US,1646derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());1647}1648if (FindEventOrLockPotentialComponent(derived) && // C7371649!(FindEventOrLockPotentialComponent(*parentDerived) ||1650IsEventTypeOrLockType(parentDerived))) {1651messages_.Say(1652"Type '%s' has an EVENT_TYPE or LOCK_TYPE component, so the type "1653"at the base of its type extension chain ('%s') must either have an "1654"EVENT_TYPE or LOCK_TYPE component, or be EVENT_TYPE or "1655"LOCK_TYPE"_err_en_US,1656derivedType.name(), scope->GetDerivedTypeBase().GetSymbol()->name());1657}1658}1659if (HasIntrinsicTypeName(derivedType)) { // C7291660messages_.Say("A derived type name cannot be the name of an intrinsic"1661" type"_err_en_US);1662}1663std::map<SourceName, SymbolRef> previous;1664for (const auto &pair : details.finals()) {1665SourceName source{pair.first};1666const Symbol &ref{*pair.second};1667if (CheckFinal(ref, source, derivedType) &&1668std::all_of(previous.begin(), previous.end(),1669[&](std::pair<SourceName, SymbolRef> prev) {1670return CheckDistinguishableFinals(1671ref, source, *prev.second, prev.first, derivedType);1672})) {1673previous.emplace(source, ref);1674}1675}1676}
1677
1678// C786
1679bool CheckHelper::CheckFinal(1680const Symbol &subroutine, SourceName finalName, const Symbol &derivedType) {1681if (!IsModuleProcedure(subroutine)) {1682SayWithDeclaration(subroutine, finalName,1683"FINAL subroutine '%s' of derived type '%s' must be a module procedure"_err_en_US,1684subroutine.name(), derivedType.name());1685return false;1686}1687const Procedure *proc{Characterize(subroutine)};1688if (!proc) {1689return false; // error recovery1690}1691if (!proc->IsSubroutine()) {1692SayWithDeclaration(subroutine, finalName,1693"FINAL subroutine '%s' of derived type '%s' must be a subroutine"_err_en_US,1694subroutine.name(), derivedType.name());1695return false;1696}1697if (proc->dummyArguments.size() != 1) {1698SayWithDeclaration(subroutine, finalName,1699"FINAL subroutine '%s' of derived type '%s' must have a single dummy argument"_err_en_US,1700subroutine.name(), derivedType.name());1701return false;1702}1703const auto &arg{proc->dummyArguments[0]};1704const Symbol *errSym{&subroutine};1705if (const auto *details{subroutine.detailsIf<SubprogramDetails>()}) {1706if (!details->dummyArgs().empty()) {1707if (const Symbol *argSym{details->dummyArgs()[0]}) {1708errSym = argSym;1709}1710}1711}1712const auto *ddo{std::get_if<DummyDataObject>(&arg.u)};1713if (!ddo) {1714SayWithDeclaration(subroutine, finalName,1715"FINAL subroutine '%s' of derived type '%s' must have a single dummy argument that is a data object"_err_en_US,1716subroutine.name(), derivedType.name());1717return false;1718}1719bool ok{true};1720if (arg.IsOptional()) {1721SayWithDeclaration(*errSym, finalName,1722"FINAL subroutine '%s' of derived type '%s' must not have an OPTIONAL dummy argument"_err_en_US,1723subroutine.name(), derivedType.name());1724ok = false;1725}1726if (ddo->attrs.test(DummyDataObject::Attr::Allocatable)) {1727SayWithDeclaration(*errSym, finalName,1728"FINAL subroutine '%s' of derived type '%s' must not have an ALLOCATABLE dummy argument"_err_en_US,1729subroutine.name(), derivedType.name());1730ok = false;1731}1732if (ddo->attrs.test(DummyDataObject::Attr::Pointer)) {1733SayWithDeclaration(*errSym, finalName,1734"FINAL subroutine '%s' of derived type '%s' must not have a POINTER dummy argument"_err_en_US,1735subroutine.name(), derivedType.name());1736ok = false;1737}1738if (ddo->intent == common::Intent::Out) {1739SayWithDeclaration(*errSym, finalName,1740"FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with INTENT(OUT)"_err_en_US,1741subroutine.name(), derivedType.name());1742ok = false;1743}1744if (ddo->attrs.test(DummyDataObject::Attr::Value)) {1745SayWithDeclaration(*errSym, finalName,1746"FINAL subroutine '%s' of derived type '%s' must not have a dummy argument with the VALUE attribute"_err_en_US,1747subroutine.name(), derivedType.name());1748ok = false;1749}1750if (ddo->type.corank() > 0) {1751SayWithDeclaration(*errSym, finalName,1752"FINAL subroutine '%s' of derived type '%s' must not have a coarray dummy argument"_err_en_US,1753subroutine.name(), derivedType.name());1754ok = false;1755}1756if (ddo->type.type().IsPolymorphic()) {1757SayWithDeclaration(*errSym, finalName,1758"FINAL subroutine '%s' of derived type '%s' must not have a polymorphic dummy argument"_err_en_US,1759subroutine.name(), derivedType.name());1760ok = false;1761} else if (ddo->type.type().category() != TypeCategory::Derived ||1762&ddo->type.type().GetDerivedTypeSpec().typeSymbol() != &derivedType) {1763SayWithDeclaration(*errSym, finalName,1764"FINAL subroutine '%s' of derived type '%s' must have a TYPE(%s) dummy argument"_err_en_US,1765subroutine.name(), derivedType.name(), derivedType.name());1766ok = false;1767} else { // check that all LEN type parameters are assumed1768for (auto ref : OrderParameterDeclarations(derivedType)) {1769if (IsLenTypeParameter(*ref)) {1770const auto *value{1771ddo->type.type().GetDerivedTypeSpec().FindParameter(ref->name())};1772if (!value || !value->isAssumed()) {1773SayWithDeclaration(*errSym, finalName,1774"FINAL subroutine '%s' of derived type '%s' must have a dummy argument with an assumed LEN type parameter '%s=*'"_err_en_US,1775subroutine.name(), derivedType.name(), ref->name());1776ok = false;1777}1778}1779}1780}1781return ok;1782}
1783
1784bool CheckHelper::CheckDistinguishableFinals(const Symbol &f1,1785SourceName f1Name, const Symbol &f2, SourceName f2Name,1786const Symbol &derivedType) {1787const Procedure *p1{Characterize(f1)};1788const Procedure *p2{Characterize(f2)};1789if (p1 && p2) {1790std::optional<bool> areDistinct{characteristics::Distinguishable(1791context_.languageFeatures(), *p1, *p2)};1792if (areDistinct.value_or(false)) {1793return true;1794}1795if (auto *msg{messages_.Say(f1Name,1796"FINAL subroutines '%s' and '%s' of derived type '%s' cannot be distinguished by rank or KIND type parameter value"_err_en_US,1797f1Name, f2Name, derivedType.name())}) {1798msg->Attach(f2Name, "FINAL declaration of '%s'"_en_US, f2.name())1799.Attach(f1.name(), "Definition of '%s'"_en_US, f1Name)1800.Attach(f2.name(), "Definition of '%s'"_en_US, f2Name);1801}1802}1803return false;1804}
1805
1806void CheckHelper::CheckHostAssoc(1807const Symbol &symbol, const HostAssocDetails &details) {1808const Symbol &hostSymbol{details.symbol()};1809if (hostSymbol.test(Symbol::Flag::ImplicitOrError)) {1810if (details.implicitOrSpecExprError) {1811messages_.Say("Implicitly typed local entity '%s' not allowed in"1812" specification expression"_err_en_US,1813symbol.name());1814} else if (details.implicitOrExplicitTypeError) {1815messages_.Say(1816"No explicit type declared for '%s'"_err_en_US, symbol.name());1817}1818}1819}
1820
1821void CheckHelper::CheckGeneric(1822const Symbol &symbol, const GenericDetails &details) {1823CheckSpecifics(symbol, details);1824common::visit(common::visitors{1825[&](const common::DefinedIo &io) {1826CheckDefinedIoProc(symbol, details, io);1827},1828[&](const GenericKind::OtherKind &other) {1829if (other == GenericKind::OtherKind::Name) {1830CheckGenericVsIntrinsic(symbol, details);1831}1832},1833[](const auto &) {},1834},1835details.kind().u);1836// Ensure that shadowed symbols are checked1837if (details.specific()) {1838Check(*details.specific());1839}1840if (details.derivedType()) {1841Check(*details.derivedType());1842}1843}
1844
1845// Check that the specifics of this generic are distinguishable from each other
1846void CheckHelper::CheckSpecifics(1847const Symbol &generic, const GenericDetails &details) {1848GenericKind kind{details.kind()};1849DistinguishabilityHelper helper{context_};1850for (const Symbol &specific : details.specificProcs()) {1851if (specific.attrs().test(Attr::ABSTRACT)) {1852if (auto *msg{messages_.Say(generic.name(),1853"Generic interface '%s' must not use abstract interface '%s' as a specific procedure"_err_en_US,1854generic.name(), specific.name())}) {1855msg->Attach(1856specific.name(), "Definition of '%s'"_en_US, specific.name());1857}1858continue;1859}1860if (specific.attrs().test(Attr::INTRINSIC)) {1861// GNU Fortran allows INTRINSIC procedures in generics.1862auto intrinsic{context_.intrinsics().IsSpecificIntrinsicFunction(1863specific.name().ToString())};1864if (intrinsic && !intrinsic->isRestrictedSpecific) {1865if (context_.ShouldWarn(common::LanguageFeature::IntrinsicAsSpecific)) {1866if (auto *msg{messages_.Say(specific.name(),1867"Specific procedure '%s' of generic interface '%s' should not be INTRINSIC"_port_en_US,1868specific.name(), generic.name())}) {1869msg->Attach(1870generic.name(), "Definition of '%s'"_en_US, generic.name());1871}1872}1873} else {1874if (context_.ShouldWarn(common::LanguageFeature::IntrinsicAsSpecific)) {1875if (auto *msg{messages_.Say(specific.name(),1876"Procedure '%s' of generic interface '%s' is INTRINSIC but not an unrestricted specific intrinsic function"_port_en_US,1877specific.name(), generic.name())}) {1878msg->Attach(1879generic.name(), "Definition of '%s'"_en_US, generic.name());1880}1881}1882continue;1883}1884}1885if (IsStmtFunction(specific)) {1886if (auto *msg{messages_.Say(specific.name(),1887"Specific procedure '%s' of generic interface '%s' may not be a statement function"_err_en_US,1888specific.name(), generic.name())}) {1889msg->Attach(generic.name(), "Definition of '%s'"_en_US, generic.name());1890}1891continue;1892}1893if (const Procedure *procedure{Characterize(specific)}) {1894if (procedure->HasExplicitInterface()) {1895helper.Add(generic, kind, specific, *procedure);1896} else {1897if (auto *msg{messages_.Say(specific.name(),1898"Specific procedure '%s' of generic interface '%s' must have an explicit interface"_err_en_US,1899specific.name(), generic.name())}) {1900msg->Attach(1901generic.name(), "Definition of '%s'"_en_US, generic.name());1902}1903}1904}1905}1906helper.Check(generic.owner());1907}
1908
1909static bool CUDAHostDeviceDiffer(1910const Procedure &proc, const DummyDataObject &arg) {1911auto procCUDA{1912proc.cudaSubprogramAttrs.value_or(common::CUDASubprogramAttrs::Host)};1913bool procIsHostOnly{procCUDA == common::CUDASubprogramAttrs::Host};1914bool procIsDeviceOnly{1915!procIsHostOnly && procCUDA != common::CUDASubprogramAttrs::HostDevice};1916const auto &argCUDA{arg.cudaDataAttr};1917bool argIsHostOnly{!argCUDA || *argCUDA == common::CUDADataAttr::Pinned};1918bool argIsDeviceOnly{(!argCUDA && procIsDeviceOnly) ||1919(argCUDA &&1920(*argCUDA != common::CUDADataAttr::Managed &&1921*argCUDA != common::CUDADataAttr::Pinned &&1922*argCUDA != common::CUDADataAttr::Unified))};1923return (procIsHostOnly && argIsDeviceOnly) ||1924(procIsDeviceOnly && argIsHostOnly);1925}
1926
1927static bool ConflictsWithIntrinsicAssignment(const Procedure &proc) {1928const auto &lhsData{std::get<DummyDataObject>(proc.dummyArguments[0].u)};1929const auto &lhsTnS{lhsData.type};1930const auto &rhsData{std::get<DummyDataObject>(proc.dummyArguments[1].u)};1931const auto &rhsTnS{rhsData.type};1932return !CUDAHostDeviceDiffer(proc, lhsData) &&1933!CUDAHostDeviceDiffer(proc, rhsData) &&1934Tristate::No ==1935IsDefinedAssignment(1936lhsTnS.type(), lhsTnS.Rank(), rhsTnS.type(), rhsTnS.Rank());1937}
1938
1939static bool ConflictsWithIntrinsicOperator(1940const GenericKind &kind, const Procedure &proc) {1941if (!kind.IsIntrinsicOperator()) {1942return false;1943}1944const auto &arg0Data{std::get<DummyDataObject>(proc.dummyArguments[0].u)};1945if (CUDAHostDeviceDiffer(proc, arg0Data)) {1946return false;1947}1948const auto &arg0TnS{arg0Data.type};1949auto type0{arg0TnS.type()};1950if (proc.dummyArguments.size() == 1) { // unary1951return common::visit(1952common::visitors{1953[&](common::NumericOperator) { return IsIntrinsicNumeric(type0); },1954[&](common::LogicalOperator) { return IsIntrinsicLogical(type0); },1955[](const auto &) -> bool { DIE("bad generic kind"); },1956},1957kind.u);1958} else { // binary1959int rank0{arg0TnS.Rank()};1960const auto &arg1Data{std::get<DummyDataObject>(proc.dummyArguments[1].u)};1961if (CUDAHostDeviceDiffer(proc, arg1Data)) {1962return false;1963}1964const auto &arg1TnS{arg1Data.type};1965auto type1{arg1TnS.type()};1966int rank1{arg1TnS.Rank()};1967return common::visit(1968common::visitors{1969[&](common::NumericOperator) {1970return IsIntrinsicNumeric(type0, rank0, type1, rank1);1971},1972[&](common::LogicalOperator) {1973return IsIntrinsicLogical(type0, rank0, type1, rank1);1974},1975[&](common::RelationalOperator opr) {1976return IsIntrinsicRelational(opr, type0, rank0, type1, rank1);1977},1978[&](GenericKind::OtherKind x) {1979CHECK(x == GenericKind::OtherKind::Concat);1980return IsIntrinsicConcat(type0, rank0, type1, rank1);1981},1982[](const auto &) -> bool { DIE("bad generic kind"); },1983},1984kind.u);1985}1986}
1987
1988// Check if this procedure can be used for defined operators (see 15.4.3.4.2).
1989bool CheckHelper::CheckDefinedOperator(SourceName opName, GenericKind kind,1990const Symbol &specific, const Procedure &proc) {1991if (context_.HasError(specific)) {1992return false;1993}1994std::optional<parser::MessageFixedText> msg;1995auto checkDefinedOperatorArgs{1996[&](SourceName opName, const Symbol &specific, const Procedure &proc) {1997bool arg0Defined{CheckDefinedOperatorArg(opName, specific, proc, 0)};1998bool arg1Defined{CheckDefinedOperatorArg(opName, specific, proc, 1)};1999return arg0Defined && arg1Defined;2000}};2001if (specific.attrs().test(Attr::NOPASS)) { // C7742002msg = "%s procedure '%s' may not have NOPASS attribute"_err_en_US;2003} else if (!proc.functionResult.has_value()) {2004msg = "%s procedure '%s' must be a function"_err_en_US;2005} else if (proc.functionResult->IsAssumedLengthCharacter()) {2006const auto *subpDetails{specific.detailsIf<SubprogramDetails>()};2007if (subpDetails && !subpDetails->isDummy() && subpDetails->isInterface()) {2008// Error is caught by more general test for interfaces with2009// assumed-length character function results2010return true;2011}2012msg = "%s function '%s' may not have assumed-length CHARACTER(*)"2013" result"_err_en_US;2014} else if (auto m{CheckNumberOfArgs(kind, proc.dummyArguments.size())}) {2015msg = std::move(m);2016} else if (!checkDefinedOperatorArgs(opName, specific, proc)) {2017return false; // error was reported2018} else if (ConflictsWithIntrinsicOperator(kind, proc)) {2019msg = "%s function '%s' conflicts with intrinsic operator"_err_en_US;2020} else {2021return true; // OK2022}2023bool isFatal{msg->IsFatal()};2024if (isFatal || !FindModuleFileContaining(specific.owner())) {2025SayWithDeclaration(2026specific, std::move(*msg), MakeOpName(opName), specific.name());2027}2028if (isFatal) {2029context_.SetError(specific);2030}2031return !isFatal;2032}
2033
2034// If the number of arguments is wrong for this intrinsic operator, return
2035// false and return the error message in msg.
2036std::optional<parser::MessageFixedText> CheckHelper::CheckNumberOfArgs(2037const GenericKind &kind, std::size_t nargs) {2038if (!kind.IsIntrinsicOperator()) {2039if (nargs < 1 || nargs > 2) {2040if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {2041return "%s function '%s' should have 1 or 2 dummy arguments"_warn_en_US;2042}2043}2044return std::nullopt;2045}2046std::size_t min{2}, max{2}; // allowed number of args; default is binary2047common::visit(common::visitors{2048[&](const common::NumericOperator &x) {2049if (x == common::NumericOperator::Add ||2050x == common::NumericOperator::Subtract) {2051min = 1; // + and - are unary or binary2052}2053},2054[&](const common::LogicalOperator &x) {2055if (x == common::LogicalOperator::Not) {2056min = 1; // .NOT. is unary2057max = 1;2058}2059},2060[](const common::RelationalOperator &) {2061// all are binary2062},2063[](const GenericKind::OtherKind &x) {2064CHECK(x == GenericKind::OtherKind::Concat);2065},2066[](const auto &) { DIE("expected intrinsic operator"); },2067},2068kind.u);2069if (nargs >= min && nargs <= max) {2070return std::nullopt;2071} else if (max == 1) {2072return "%s function '%s' must have one dummy argument"_err_en_US;2073} else if (min == 2) {2074return "%s function '%s' must have two dummy arguments"_err_en_US;2075} else {2076return "%s function '%s' must have one or two dummy arguments"_err_en_US;2077}2078}
2079
2080bool CheckHelper::CheckDefinedOperatorArg(const SourceName &opName,2081const Symbol &symbol, const Procedure &proc, std::size_t pos) {2082if (pos >= proc.dummyArguments.size()) {2083return true;2084}2085auto &arg{proc.dummyArguments.at(pos)};2086std::optional<parser::MessageFixedText> msg;2087if (arg.IsOptional()) {2088msg = "In %s function '%s', dummy argument '%s' may not be"2089" OPTIONAL"_err_en_US;2090} else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)};2091dataObject == nullptr) {2092msg = "In %s function '%s', dummy argument '%s' must be a"2093" data object"_err_en_US;2094} else if (dataObject->intent == common::Intent::Out) {2095msg =2096"In %s function '%s', dummy argument '%s' may not be INTENT(OUT)"_err_en_US;2097} else if (dataObject->intent != common::Intent::In &&2098!dataObject->attrs.test(DummyDataObject::Attr::Value)) {2099if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {2100msg =2101"In %s function '%s', dummy argument '%s' should have INTENT(IN) or VALUE attribute"_warn_en_US;2102}2103}2104if (msg) {2105bool isFatal{msg->IsFatal()};2106if (isFatal || !FindModuleFileContaining(symbol.owner())) {2107SayWithDeclaration(symbol, std::move(*msg),2108parser::ToUpperCaseLetters(opName.ToString()), symbol.name(),2109arg.name);2110}2111if (isFatal) {2112return false;2113}2114}2115return true;2116}
2117
2118// Check if this procedure can be used for defined assignment (see 15.4.3.4.3).
2119bool CheckHelper::CheckDefinedAssignment(2120const Symbol &specific, const Procedure &proc) {2121if (context_.HasError(specific)) {2122return false;2123}2124std::optional<parser::MessageFixedText> msg;2125if (specific.attrs().test(Attr::NOPASS)) { // C7742126msg = "Defined assignment procedure '%s' may not have"2127" NOPASS attribute"_err_en_US;2128} else if (!proc.IsSubroutine()) {2129msg = "Defined assignment procedure '%s' must be a subroutine"_err_en_US;2130} else if (proc.dummyArguments.size() != 2) {2131msg = "Defined assignment subroutine '%s' must have"2132" two dummy arguments"_err_en_US;2133} else {2134// Check both arguments even if the first has an error.2135bool ok0{CheckDefinedAssignmentArg(specific, proc.dummyArguments[0], 0)};2136bool ok1{CheckDefinedAssignmentArg(specific, proc.dummyArguments[1], 1)};2137if (!(ok0 && ok1)) {2138return false; // error was reported2139} else if (ConflictsWithIntrinsicAssignment(proc)) {2140msg =2141"Defined assignment subroutine '%s' conflicts with intrinsic assignment"_err_en_US;2142} else {2143return true; // OK2144}2145}2146SayWithDeclaration(specific, std::move(msg.value()), specific.name());2147context_.SetError(specific);2148return false;2149}
2150
2151bool CheckHelper::CheckDefinedAssignmentArg(2152const Symbol &symbol, const DummyArgument &arg, int pos) {2153std::optional<parser::MessageFixedText> msg;2154if (arg.IsOptional()) {2155msg = "In defined assignment subroutine '%s', dummy argument '%s'"2156" may not be OPTIONAL"_err_en_US;2157} else if (const auto *dataObject{std::get_if<DummyDataObject>(&arg.u)}) {2158if (pos == 0) {2159if (dataObject->intent == common::Intent::In) {2160msg = "In defined assignment subroutine '%s', first dummy argument '%s'"2161" may not have INTENT(IN)"_err_en_US;2162} else if (dataObject->intent != common::Intent::Out &&2163dataObject->intent != common::Intent::InOut) {2164if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {2165msg =2166"In defined assignment subroutine '%s', first dummy argument '%s' should have INTENT(OUT) or INTENT(INOUT)"_warn_en_US;2167}2168}2169} else if (pos == 1) {2170if (dataObject->intent == common::Intent::Out) {2171msg = "In defined assignment subroutine '%s', second dummy"2172" argument '%s' may not have INTENT(OUT)"_err_en_US;2173} else if (dataObject->intent != common::Intent::In &&2174!dataObject->attrs.test(DummyDataObject::Attr::Value)) {2175if (context_.ShouldWarn(common::UsageWarning::DefinedOperatorArgs)) {2176msg =2177"In defined assignment subroutine '%s', second dummy argument '%s' should have INTENT(IN) or VALUE attribute"_warn_en_US;2178}2179} else if (dataObject->attrs.test(DummyDataObject::Attr::Pointer)) {2180msg =2181"In defined assignment subroutine '%s', second dummy argument '%s' must not be a pointer"_err_en_US;2182} else if (dataObject->attrs.test(DummyDataObject::Attr::Allocatable)) {2183msg =2184"In defined assignment subroutine '%s', second dummy argument '%s' must not be an allocatable"_err_en_US;2185}2186} else {2187DIE("pos must be 0 or 1");2188}2189} else {2190msg = "In defined assignment subroutine '%s', dummy argument '%s'"2191" must be a data object"_err_en_US;2192}2193if (msg) {2194bool isFatal{msg->IsFatal()};2195if (isFatal || !FindModuleFileContaining(symbol.owner())) {2196SayWithDeclaration(symbol, std::move(*msg), symbol.name(), arg.name);2197}2198if (isFatal) {2199context_.SetError(symbol);2200return false;2201}2202}2203return true;2204}
2205
2206// Report a conflicting attribute error if symbol has both of these attributes
2207bool CheckHelper::CheckConflicting(const Symbol &symbol, Attr a1, Attr a2) {2208if (symbol.attrs().test(a1) && symbol.attrs().test(a2)) {2209messages_.Say("'%s' may not have both the %s and %s attributes"_err_en_US,2210symbol.name(), AttrToString(a1), AttrToString(a2));2211return true;2212} else {2213return false;2214}2215}
2216
2217void CheckHelper::WarnMissingFinal(const Symbol &symbol) {2218const auto *object{symbol.detailsIf<ObjectEntityDetails>()};2219if (!object || object->IsAssumedRank() ||2220(!IsAutomaticallyDestroyed(symbol) &&2221symbol.owner().kind() != Scope::Kind::DerivedType)) {2222return;2223}2224const DeclTypeSpec *type{object->type()};2225const DerivedTypeSpec *derived{type ? type->AsDerived() : nullptr};2226const Symbol *derivedSym{derived ? &derived->typeSymbol() : nullptr};2227int rank{object->shape().Rank()};2228const Symbol *initialDerivedSym{derivedSym};2229while (const auto *derivedDetails{2230derivedSym ? derivedSym->detailsIf<DerivedTypeDetails>() : nullptr}) {2231if (!derivedDetails->finals().empty() &&2232!derivedDetails->GetFinalForRank(rank) &&2233context_.ShouldWarn(common::UsageWarning::Final)) {2234if (auto *msg{derivedSym == initialDerivedSym2235? WarnIfNotInModuleFile(symbol.name(),2236"'%s' of derived type '%s' does not have a FINAL subroutine for its rank (%d)"_warn_en_US,2237symbol.name(), derivedSym->name(), rank)2238: WarnIfNotInModuleFile(symbol.name(),2239"'%s' of derived type '%s' extended from '%s' does not have a FINAL subroutine for its rank (%d)"_warn_en_US,2240symbol.name(), initialDerivedSym->name(),2241derivedSym->name(), rank)}) {2242msg->Attach(derivedSym->name(),2243"Declaration of derived type '%s'"_en_US, derivedSym->name());2244}2245return;2246}2247derived = derivedSym->GetParentTypeSpec();2248derivedSym = derived ? &derived->typeSymbol() : nullptr;2249}2250}
2251
2252const Procedure *CheckHelper::Characterize(const Symbol &symbol) {2253auto it{characterizeCache_.find(symbol)};2254if (it == characterizeCache_.end()) {2255auto pair{characterizeCache_.emplace(SymbolRef{symbol},2256Procedure::Characterize(symbol, context_.foldingContext()))};2257it = pair.first;2258}2259return common::GetPtrFromOptional(it->second);2260}
2261
2262void CheckHelper::CheckVolatile(const Symbol &symbol,2263const DerivedTypeSpec *derived) { // C866 - C8682264if (IsIntentIn(symbol)) {2265messages_.Say(2266"VOLATILE attribute may not apply to an INTENT(IN) argument"_err_en_US);2267}2268if (IsProcedure(symbol)) {2269messages_.Say("VOLATILE attribute may apply only to a variable"_err_en_US);2270}2271if (symbol.has<UseDetails>() || symbol.has<HostAssocDetails>()) {2272const Symbol &ultimate{symbol.GetUltimate()};2273if (evaluate::IsCoarray(ultimate)) {2274messages_.Say(2275"VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US);2276}2277if (derived) {2278if (FindCoarrayUltimateComponent(*derived)) {2279messages_.Say(2280"VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US);2281}2282}2283}2284}
2285
2286void CheckHelper::CheckContiguous(const Symbol &symbol) {2287if (evaluate::IsVariable(symbol) &&2288((IsPointer(symbol) && symbol.Rank() > 0) || IsAssumedShape(symbol) ||2289evaluate::IsAssumedRank(symbol))) {2290} else if (!context_.IsEnabled(2291common::LanguageFeature::RedundantContiguous) ||2292context_.ShouldWarn(common::LanguageFeature::RedundantContiguous)) {2293parser::MessageFixedText msg{symbol.owner().IsDerivedType()2294? "CONTIGUOUS component '%s' should be an array with the POINTER attribute"_port_en_US2295: "CONTIGUOUS entity '%s' should be an array pointer, assumed-shape, or assumed-rank"_port_en_US};2296if (!context_.IsEnabled(common::LanguageFeature::RedundantContiguous)) {2297msg.set_severity(parser::Severity::Error);2298}2299messages_.Say(std::move(msg), symbol.name());2300}2301}
2302
2303void CheckHelper::CheckPointer(const Symbol &symbol) { // C8522304CheckConflicting(symbol, Attr::POINTER, Attr::TARGET);2305CheckConflicting(symbol, Attr::POINTER, Attr::ALLOCATABLE); // C7512306CheckConflicting(symbol, Attr::POINTER, Attr::INTRINSIC);2307// Prohibit constant pointers. The standard does not explicitly prohibit2308// them, but the PARAMETER attribute requires a entity-decl to have an2309// initialization that is a constant-expr, and the only form of2310// initialization that allows a constant-expr is the one that's not a "=>"2311// pointer initialization. See C811, C807, and section 8.5.13.2312CheckConflicting(symbol, Attr::POINTER, Attr::PARAMETER);2313if (symbol.Corank() > 0) {2314messages_.Say(2315"'%s' may not have the POINTER attribute because it is a coarray"_err_en_US,2316symbol.name());2317}2318}
2319
2320// C760 constraints on the passed-object dummy argument
2321// C757 constraints on procedure pointer components
2322void CheckHelper::CheckPassArg(2323const Symbol &proc, const Symbol *interface0, const WithPassArg &details) {2324if (proc.attrs().test(Attr::NOPASS)) {2325return;2326}2327const auto &name{proc.name()};2328const Symbol *interface {2329interface0 ? FindInterface(*interface0) : nullptr2330};2331if (!interface) {2332messages_.Say(name,2333"Procedure component '%s' must have NOPASS attribute or explicit interface"_err_en_US,2334name);2335return;2336}2337const auto *subprogram{interface->detailsIf<SubprogramDetails>()};2338if (!subprogram) {2339messages_.Say(name,2340"Procedure component '%s' has invalid interface '%s'"_err_en_US, name,2341interface->name());2342return;2343}2344std::optional<SourceName> passName{details.passName()};2345const auto &dummyArgs{subprogram->dummyArgs()};2346if (!passName) {2347if (dummyArgs.empty()) {2348messages_.Say(name,2349proc.has<ProcEntityDetails>()2350? "Procedure component '%s' with no dummy arguments"2351" must have NOPASS attribute"_err_en_US2352: "Procedure binding '%s' with no dummy arguments"2353" must have NOPASS attribute"_err_en_US,2354name);2355context_.SetError(*interface);2356return;2357}2358Symbol *argSym{dummyArgs[0]};2359if (!argSym) {2360messages_.Say(interface->name(),2361"Cannot use an alternate return as the passed-object dummy "2362"argument"_err_en_US);2363return;2364}2365passName = dummyArgs[0]->name();2366}2367std::optional<int> passArgIndex{};2368for (std::size_t i{0}; i < dummyArgs.size(); ++i) {2369if (dummyArgs[i] && dummyArgs[i]->name() == *passName) {2370passArgIndex = i;2371break;2372}2373}2374if (!passArgIndex) { // C7582375messages_.Say(*passName,2376"'%s' is not a dummy argument of procedure interface '%s'"_err_en_US,2377*passName, interface->name());2378return;2379}2380const Symbol &passArg{*dummyArgs[*passArgIndex]};2381std::optional<parser::MessageFixedText> msg;2382if (!passArg.has<ObjectEntityDetails>()) {2383msg = "Passed-object dummy argument '%s' of procedure '%s'"2384" must be a data object"_err_en_US;2385} else if (passArg.attrs().test(Attr::POINTER)) {2386msg = "Passed-object dummy argument '%s' of procedure '%s'"2387" may not have the POINTER attribute"_err_en_US;2388} else if (passArg.attrs().test(Attr::ALLOCATABLE)) {2389msg = "Passed-object dummy argument '%s' of procedure '%s'"2390" may not have the ALLOCATABLE attribute"_err_en_US;2391} else if (passArg.attrs().test(Attr::VALUE)) {2392msg = "Passed-object dummy argument '%s' of procedure '%s'"2393" may not have the VALUE attribute"_err_en_US;2394} else if (passArg.Rank() > 0) {2395msg = "Passed-object dummy argument '%s' of procedure '%s'"2396" must be scalar"_err_en_US;2397}2398if (msg) {2399messages_.Say(name, std::move(*msg), passName.value(), name);2400return;2401}2402const DeclTypeSpec *type{passArg.GetType()};2403if (!type) {2404return; // an error already occurred2405}2406const Symbol &typeSymbol{*proc.owner().GetSymbol()};2407const DerivedTypeSpec *derived{type->AsDerived()};2408if (!derived || derived->typeSymbol() != typeSymbol) {2409messages_.Say(name,2410"Passed-object dummy argument '%s' of procedure '%s'"2411" must be of type '%s' but is '%s'"_err_en_US,2412passName.value(), name, typeSymbol.name(), type->AsFortran());2413return;2414}2415if (IsExtensibleType(derived) != type->IsPolymorphic()) {2416messages_.Say(name,2417type->IsPolymorphic()2418? "Passed-object dummy argument '%s' of procedure '%s'"2419" may not be polymorphic because '%s' is not extensible"_err_en_US2420: "Passed-object dummy argument '%s' of procedure '%s'"2421" must be polymorphic because '%s' is extensible"_err_en_US,2422passName.value(), name, typeSymbol.name());2423return;2424}2425for (const auto &[paramName, paramValue] : derived->parameters()) {2426if (paramValue.isLen() && !paramValue.isAssumed()) {2427messages_.Say(name,2428"Passed-object dummy argument '%s' of procedure '%s'"2429" has non-assumed length parameter '%s'"_err_en_US,2430passName.value(), name, paramName);2431}2432}2433}
2434
2435void CheckHelper::CheckProcBinding(2436const Symbol &symbol, const ProcBindingDetails &binding) {2437const Scope &dtScope{symbol.owner()};2438CHECK(dtScope.kind() == Scope::Kind::DerivedType);2439if (symbol.attrs().test(Attr::DEFERRED)) {2440if (const Symbol *dtSymbol{dtScope.symbol()}) {2441if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { // C7332442SayWithDeclaration(*dtSymbol,2443"Procedure bound to non-ABSTRACT derived type '%s' may not be DEFERRED"_err_en_US,2444dtSymbol->name());2445}2446}2447if (symbol.attrs().test(Attr::NON_OVERRIDABLE)) {2448messages_.Say(2449"Type-bound procedure '%s' may not be both DEFERRED and NON_OVERRIDABLE"_err_en_US,2450symbol.name());2451}2452}2453if (binding.symbol().attrs().test(Attr::INTRINSIC) &&2454!context_.intrinsics().IsSpecificIntrinsicFunction(2455binding.symbol().name().ToString())) {2456messages_.Say(2457"Intrinsic procedure '%s' is not a specific intrinsic permitted for use in the definition of binding '%s'"_err_en_US,2458binding.symbol().name(), symbol.name());2459}2460bool isInaccessibleDeferred{false};2461if (const Symbol *2462overridden{FindOverriddenBinding(symbol, isInaccessibleDeferred)}) {2463if (isInaccessibleDeferred) {2464SayWithDeclaration(*overridden,2465"Override of PRIVATE DEFERRED '%s' must appear in its module"_err_en_US,2466symbol.name());2467}2468if (overridden->attrs().test(Attr::NON_OVERRIDABLE)) {2469SayWithDeclaration(*overridden,2470"Override of NON_OVERRIDABLE '%s' is not permitted"_err_en_US,2471symbol.name());2472}2473if (const auto *overriddenBinding{2474overridden->detailsIf<ProcBindingDetails>()}) {2475if (!IsPureProcedure(symbol) && IsPureProcedure(*overridden)) {2476SayWithDeclaration(*overridden,2477"An overridden pure type-bound procedure binding must also be pure"_err_en_US);2478return;2479}2480if (!IsElementalProcedure(binding.symbol()) &&2481IsElementalProcedure(*overridden)) {2482SayWithDeclaration(*overridden,2483"A type-bound procedure and its override must both, or neither, be ELEMENTAL"_err_en_US);2484return;2485}2486bool isNopass{symbol.attrs().test(Attr::NOPASS)};2487if (isNopass != overridden->attrs().test(Attr::NOPASS)) {2488SayWithDeclaration(*overridden,2489isNopass
2490? "A NOPASS type-bound procedure may not override a passed-argument procedure"_err_en_US2491: "A passed-argument type-bound procedure may not override a NOPASS procedure"_err_en_US);2492} else {2493const auto *bindingChars{Characterize(binding.symbol())};2494const auto *overriddenChars{Characterize(*overridden)};2495if (bindingChars && overriddenChars) {2496if (isNopass) {2497if (!bindingChars->CanOverride(*overriddenChars, std::nullopt)) {2498SayWithDeclaration(*overridden,2499"A NOPASS type-bound procedure and its override must have identical interfaces"_err_en_US);2500}2501} else if (!context_.HasError(binding.symbol())) {2502auto passIndex{bindingChars->FindPassIndex(binding.passName())};2503auto overriddenPassIndex{2504overriddenChars->FindPassIndex(overriddenBinding->passName())};2505if (passIndex && overriddenPassIndex) {2506if (*passIndex != *overriddenPassIndex) {2507SayWithDeclaration(*overridden,2508"A type-bound procedure and its override must use the same PASS argument"_err_en_US);2509} else if (!bindingChars->CanOverride(2510*overriddenChars, passIndex)) {2511SayWithDeclaration(*overridden,2512"A type-bound procedure and its override must have compatible interfaces"_err_en_US);2513}2514}2515}2516}2517}2518if (symbol.attrs().test(Attr::PRIVATE)) {2519if (FindModuleContaining(dtScope) ==2520FindModuleContaining(overridden->owner())) {2521// types declared in same madule2522if (!overridden->attrs().test(Attr::PRIVATE)) {2523SayWithDeclaration(*overridden,2524"A PRIVATE procedure may not override a PUBLIC procedure"_err_en_US);2525}2526} else { // types declared in distinct madules2527if (!CheckAccessibleSymbol(dtScope.parent(), *overridden)) {2528SayWithDeclaration(*overridden,2529"A PRIVATE procedure may not override an accessible procedure"_err_en_US);2530}2531}2532}2533} else {2534SayWithDeclaration(*overridden,2535"A type-bound procedure binding may not have the same name as a parent component"_err_en_US);2536}2537}2538CheckPassArg(symbol, &binding.symbol(), binding);2539}
2540
2541void CheckHelper::Check(const Scope &scope) {2542scope_ = &scope;2543common::Restorer<const Symbol *> restorer{innermostSymbol_, innermostSymbol_};2544if (const Symbol *symbol{scope.symbol()}) {2545innermostSymbol_ = symbol;2546}2547if (scope.IsParameterizedDerivedTypeInstantiation()) {2548auto restorer{common::ScopedSet(scopeIsUninstantiatedPDT_, false)};2549auto restorer2{context_.foldingContext().messages().SetContext(2550scope.instantiationContext().get())};2551for (const auto &pair : scope) {2552CheckPointerInitialization(*pair.second);2553}2554} else {2555auto restorer{common::ScopedSet(2556scopeIsUninstantiatedPDT_, scope.IsParameterizedDerivedType())};2557for (const auto &set : scope.equivalenceSets()) {2558CheckEquivalenceSet(set);2559}2560for (const auto &pair : scope) {2561Check(*pair.second);2562}2563if (scope.IsSubmodule() && scope.symbol()) {2564// Submodule names are not in their parent's scopes2565Check(*scope.symbol());2566}2567for (const auto &pair : scope.commonBlocks()) {2568CheckCommonBlock(*pair.second);2569}2570int mainProgCnt{0};2571for (const Scope &child : scope.children()) {2572Check(child);2573// A program shall consist of exactly one main program (5.2.2).2574if (child.kind() == Scope::Kind::MainProgram) {2575++mainProgCnt;2576if (mainProgCnt > 1) {2577messages_.Say(child.sourceRange(),2578"A source file cannot contain more than one main program"_err_en_US);2579}2580}2581}2582if (scope.kind() == Scope::Kind::BlockData) {2583CheckBlockData(scope);2584}2585if (auto name{scope.GetName()}) {2586auto iter{scope.find(*name)};2587if (iter != scope.end()) {2588const char *kind{nullptr};2589if (context_.ShouldWarn(common::LanguageFeature::BenignNameClash)) {2590switch (scope.kind()) {2591case Scope::Kind::Module:2592kind = scope.symbol()->get<ModuleDetails>().isSubmodule()2593? "submodule"2594: "module";2595break;2596case Scope::Kind::MainProgram:2597kind = "main program";2598break;2599case Scope::Kind::BlockData:2600kind = "BLOCK DATA subprogram";2601break;2602default:;2603}2604if (kind) {2605messages_.Say(iter->second->name(),2606"Name '%s' declared in a %s should not have the same name as the %s"_port_en_US,2607*name, kind, kind);2608}2609}2610}2611}2612CheckGenericOps(scope);2613}2614}
2615
2616void CheckHelper::CheckEquivalenceSet(const EquivalenceSet &set) {2617auto iter{2618std::find_if(set.begin(), set.end(), [](const EquivalenceObject &object) {2619return FindCommonBlockContaining(object.symbol) != nullptr;2620})};2621if (iter != set.end()) {2622const Symbol &commonBlock{DEREF(FindCommonBlockContaining(iter->symbol))};2623for (auto &object : set) {2624if (&object != &*iter) {2625if (auto *details{object.symbol.detailsIf<ObjectEntityDetails>()}) {2626if (details->commonBlock()) {2627if (details->commonBlock() != &commonBlock) { // 8.10.3 paragraph 12628if (auto *msg{messages_.Say(object.symbol.name(),2629"Two objects in the same EQUIVALENCE set may not be members of distinct COMMON blocks"_err_en_US)}) {2630msg->Attach(iter->symbol.name(),2631"Other object in EQUIVALENCE set"_en_US)2632.Attach(details->commonBlock()->name(),2633"COMMON block containing '%s'"_en_US,2634object.symbol.name())2635.Attach(commonBlock.name(),2636"COMMON block containing '%s'"_en_US,2637iter->symbol.name());2638}2639}2640} else {2641// Mark all symbols in the equivalence set with the same COMMON2642// block to prevent spurious error messages about initialization2643// in BLOCK DATA outside COMMON2644details->set_commonBlock(commonBlock);2645}2646}2647}2648}2649}2650for (const EquivalenceObject &object : set) {2651CheckEquivalenceObject(object);2652}2653}
2654
2655static bool InCommonWithBind(const Symbol &symbol) {2656if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {2657const Symbol *commonBlock{details->commonBlock()};2658return commonBlock && commonBlock->attrs().test(Attr::BIND_C);2659} else {2660return false;2661}2662}
2663
2664void CheckHelper::CheckEquivalenceObject(const EquivalenceObject &object) {2665parser::MessageFixedText msg;2666const Symbol &symbol{object.symbol};2667if (symbol.owner().IsDerivedType()) {2668msg =2669"Derived type component '%s' is not allowed in an equivalence set"_err_en_US;2670} else if (IsDummy(symbol)) {2671msg = "Dummy argument '%s' is not allowed in an equivalence set"_err_en_US;2672} else if (symbol.IsFuncResult()) {2673msg = "Function result '%s' is not allow in an equivalence set"_err_en_US;2674} else if (IsPointer(symbol)) {2675msg = "Pointer '%s' is not allowed in an equivalence set"_err_en_US;2676} else if (IsAllocatable(symbol)) {2677msg =2678"Allocatable variable '%s' is not allowed in an equivalence set"_err_en_US;2679} else if (symbol.Corank() > 0) {2680msg = "Coarray '%s' is not allowed in an equivalence set"_err_en_US;2681} else if (symbol.has<UseDetails>()) {2682msg =2683"Use-associated variable '%s' is not allowed in an equivalence set"_err_en_US;2684} else if (symbol.attrs().test(Attr::BIND_C)) {2685msg =2686"Variable '%s' with BIND attribute is not allowed in an equivalence set"_err_en_US;2687} else if (symbol.attrs().test(Attr::TARGET)) {2688msg =2689"Variable '%s' with TARGET attribute is not allowed in an equivalence set"_err_en_US;2690} else if (IsNamedConstant(symbol)) {2691msg = "Named constant '%s' is not allowed in an equivalence set"_err_en_US;2692} else if (InCommonWithBind(symbol)) {2693msg =2694"Variable '%s' in common block with BIND attribute is not allowed in an equivalence set"_err_en_US;2695} else if (!symbol.has<ObjectEntityDetails>()) {2696msg = "'%s' in equivalence set is not a data object"_err_en_US;2697} else if (const auto *type{symbol.GetType()}) {2698const auto *derived{type->AsDerived()};2699if (derived && !derived->IsVectorType()) {2700if (const auto *comp{2701FindUltimateComponent(*derived, IsAllocatableOrPointer)}) {2702msg = IsPointer(*comp)2703? "Derived type object '%s' with pointer ultimate component is not allowed in an equivalence set"_err_en_US2704: "Derived type object '%s' with allocatable ultimate component is not allowed in an equivalence set"_err_en_US;2705} else if (!derived->typeSymbol().get<DerivedTypeDetails>().sequence()) {2706msg =2707"Nonsequence derived type object '%s' is not allowed in an equivalence set"_err_en_US;2708}2709} else if (IsAutomatic(symbol)) {2710msg =2711"Automatic object '%s' is not allowed in an equivalence set"_err_en_US;2712} else if (symbol.test(Symbol::Flag::CrayPointee)) {2713messages_.Say(object.symbol.name(),2714"Cray pointee '%s' may not be a member of an EQUIVALENCE group"_err_en_US,2715object.symbol.name());2716}2717}2718if (!msg.text().empty()) {2719context_.Say(object.source, std::move(msg), symbol.name());2720}2721}
2722
2723void CheckHelper::CheckBlockData(const Scope &scope) {2724// BLOCK DATA subprograms should contain only named common blocks.2725// C1415 presents a list of statements that shouldn't appear in2726// BLOCK DATA, but so long as the subprogram contains no executable2727// code and allocates no storage outside named COMMON, we're happy2728// (e.g., an ENUM is strictly not allowed).2729for (const auto &pair : scope) {2730const Symbol &symbol{*pair.second};2731if (!(symbol.has<CommonBlockDetails>() || symbol.has<UseDetails>() ||2732symbol.has<UseErrorDetails>() || symbol.has<DerivedTypeDetails>() ||2733symbol.has<SubprogramDetails>() ||2734symbol.has<ObjectEntityDetails>() ||2735(symbol.has<ProcEntityDetails>() &&2736!symbol.attrs().test(Attr::POINTER)))) {2737messages_.Say(symbol.name(),2738"'%s' may not appear in a BLOCK DATA subprogram"_err_en_US,2739symbol.name());2740}2741}2742}
2743
2744// Check distinguishability of generic assignment and operators.
2745// For these, generics and generic bindings must be considered together.
2746void CheckHelper::CheckGenericOps(const Scope &scope) {2747DistinguishabilityHelper helper{context_};2748auto addSpecifics{[&](const Symbol &generic) {2749const auto *details{generic.GetUltimate().detailsIf<GenericDetails>()};2750if (!details) {2751// Not a generic; ensure characteristics are defined if a function.2752auto restorer{messages_.SetLocation(generic.name())};2753if (IsFunction(generic) && !context_.HasError(generic)) {2754if (const Symbol *result{FindFunctionResult(generic)};2755result && !context_.HasError(*result)) {2756Characterize(generic);2757}2758}2759return;2760}2761GenericKind kind{details->kind()};2762if (!kind.IsAssignment() && !kind.IsOperator()) {2763return;2764}2765const SymbolVector &specifics{details->specificProcs()};2766const std::vector<SourceName> &bindingNames{details->bindingNames()};2767for (std::size_t i{0}; i < specifics.size(); ++i) {2768const Symbol &specific{*specifics[i]};2769auto restorer{messages_.SetLocation(bindingNames[i])};2770if (const Procedure *proc{Characterize(specific)}) {2771if (kind.IsAssignment()) {2772if (!CheckDefinedAssignment(specific, *proc)) {2773continue;2774}2775} else {2776if (!CheckDefinedOperator(generic.name(), kind, specific, *proc)) {2777continue;2778}2779}2780helper.Add(generic, kind, specific, *proc);2781}2782}2783}};2784for (const auto &pair : scope) {2785const Symbol &symbol{*pair.second};2786addSpecifics(symbol);2787const Symbol &ultimate{symbol.GetUltimate()};2788if (ultimate.has<DerivedTypeDetails>()) {2789if (const Scope *typeScope{ultimate.scope()}) {2790for (const auto &pair2 : *typeScope) {2791addSpecifics(*pair2.second);2792}2793}2794}2795}2796helper.Check(scope);2797}
2798
2799static bool IsSubprogramDefinition(const Symbol &symbol) {2800const auto *subp{symbol.detailsIf<SubprogramDetails>()};2801return subp && !subp->isInterface() && symbol.scope() &&2802symbol.scope()->kind() == Scope::Kind::Subprogram;2803}
2804
2805static bool IsBlockData(const Symbol &symbol) {2806return symbol.scope() && symbol.scope()->kind() == Scope::Kind::BlockData;2807}
2808
2809static bool IsExternalProcedureDefinition(const Symbol &symbol) {2810return IsBlockData(symbol) ||2811(IsSubprogramDefinition(symbol) &&2812(IsExternal(symbol) || symbol.GetBindName()));2813}
2814
2815static std::optional<std::string> DefinesGlobalName(const Symbol &symbol) {2816if (const auto *module{symbol.detailsIf<ModuleDetails>()}) {2817if (!module->isSubmodule() && !symbol.owner().IsIntrinsicModules()) {2818return symbol.name().ToString();2819}2820} else if (IsBlockData(symbol)) {2821return symbol.name().ToString();2822} else {2823const std::string *bindC{symbol.GetBindName()};2824if (symbol.has<CommonBlockDetails>() ||2825IsExternalProcedureDefinition(symbol) ||2826(symbol.owner().IsGlobal() && IsExternal(symbol))) {2827return bindC ? *bindC : symbol.name().ToString();2828} else if (bindC &&2829(symbol.has<ObjectEntityDetails>() || IsModuleProcedure(symbol))) {2830return *bindC;2831}2832}2833return std::nullopt;2834}
2835
2836// 19.2 p2
2837void CheckHelper::CheckGlobalName(const Symbol &symbol) {2838if (auto global{DefinesGlobalName(symbol)}) {2839auto pair{globalNames_.emplace(std::move(*global), symbol)};2840if (!pair.second) {2841const Symbol &other{*pair.first->second};2842if (context_.HasError(symbol) || context_.HasError(other)) {2843// don't pile on2844} else if (symbol.has<CommonBlockDetails>() &&2845other.has<CommonBlockDetails>() && symbol.name() == other.name()) {2846// Two common blocks can have the same global name so long as2847// they're not in the same scope.2848} else if ((IsProcedure(symbol) || IsBlockData(symbol)) &&2849(IsProcedure(other) || IsBlockData(other)) &&2850(!IsExternalProcedureDefinition(symbol) ||2851!IsExternalProcedureDefinition(other))) {2852// both are procedures/BLOCK DATA, not both definitions2853} else if (symbol.has<ModuleDetails>()) {2854if (context_.ShouldWarn(common::LanguageFeature::BenignNameClash)) {2855messages_.Say(symbol.name(),2856"Module '%s' conflicts with a global name"_port_en_US,2857pair.first->first);2858}2859} else if (other.has<ModuleDetails>()) {2860if (context_.ShouldWarn(common::LanguageFeature::BenignNameClash)) {2861messages_.Say(symbol.name(),2862"Global name '%s' conflicts with a module"_port_en_US,2863pair.first->first);2864}2865} else if (auto *msg{messages_.Say(symbol.name(),2866"Two entities have the same global name '%s'"_err_en_US,2867pair.first->first)}) {2868msg->Attach(other.name(), "Conflicting declaration"_en_US);2869context_.SetError(symbol);2870context_.SetError(other);2871}2872}2873}2874}
2875
2876void CheckHelper::CheckProcedureAssemblyName(const Symbol &symbol) {2877if (!IsProcedure(symbol) || symbol != symbol.GetUltimate())2878return;2879const std::string *bindName{symbol.GetBindName()};2880const bool hasExplicitBindingLabel{2881symbol.GetIsExplicitBindName() && bindName};2882if (hasExplicitBindingLabel || IsExternal(symbol)) {2883const std::string assemblyName{hasExplicitBindingLabel2884? *bindName2885: common::GetExternalAssemblyName(2886symbol.name().ToString(), context_.underscoring())};2887auto pair{procedureAssemblyNames_.emplace(std::move(assemblyName), symbol)};2888if (!pair.second) {2889const Symbol &other{*pair.first->second};2890const bool otherHasExplicitBindingLabel{2891other.GetIsExplicitBindName() && other.GetBindName()};2892if (otherHasExplicitBindingLabel != hasExplicitBindingLabel) {2893// The BIND(C,NAME="...") binding label is the same as the name that2894// will be used in LLVM IR for an external procedure declared without2895// BIND(C) in the same file. While this is not forbidden by the2896// standard, this name collision would lead to a crash when producing2897// the IR.2898if (auto *msg{messages_.Say(symbol.name(),2899"%s procedure assembly name conflicts with %s procedure assembly name"_err_en_US,2900hasExplicitBindingLabel ? "BIND(C)" : "Non BIND(C)",2901hasExplicitBindingLabel ? "non BIND(C)" : "BIND(C)")}) {2902msg->Attach(other.name(), "Conflicting declaration"_en_US);2903}2904context_.SetError(symbol);2905context_.SetError(other);2906}2907// Otherwise, the global names also match and the conflict is analyzed2908// by CheckGlobalName.2909}2910}2911}
2912
2913parser::Messages CheckHelper::WhyNotInteroperableDerivedType(2914const Symbol &symbol) {2915parser::Messages msgs;2916if (examinedByWhyNotInteroperable_.find(symbol) !=2917examinedByWhyNotInteroperable_.end()) {2918return msgs;2919}2920examinedByWhyNotInteroperable_.insert(symbol);2921if (const auto *derived{symbol.detailsIf<DerivedTypeDetails>()}) {2922if (derived->sequence()) { // C18012923msgs.Say(symbol.name(),2924"An interoperable derived type cannot have the SEQUENCE attribute"_err_en_US);2925} else if (!derived->paramDecls().empty()) { // C18022926msgs.Say(symbol.name(),2927"An interoperable derived type cannot have a type parameter"_err_en_US);2928} else if (const auto *parent{2929symbol.scope()->GetDerivedTypeParent()}) { // C18032930if (symbol.attrs().test(Attr::BIND_C)) {2931msgs.Say(symbol.name(),2932"A derived type with the BIND attribute cannot be an extended derived type"_err_en_US);2933} else {2934bool interoperableParent{true};2935if (parent->symbol()) {2936auto bad{WhyNotInteroperableDerivedType(*parent->symbol())};2937if (bad.AnyFatalError()) {2938auto &msg{msgs.Say(symbol.name(),2939"The parent of an interoperable type is not interoperable"_err_en_US)};2940bad.AttachTo(msg, parser::Severity::None);2941interoperableParent = false;2942}2943}2944if (interoperableParent) {2945msgs.Say(symbol.name(),2946"An interoperable type should not be an extended derived type"_warn_en_US);2947}2948}2949}2950const Symbol *parentComponent{symbol.scope()2951? derived->GetParentComponent(*symbol.scope())2952: nullptr};2953for (const auto &pair : *symbol.scope()) {2954const Symbol &component{*pair.second};2955if (&component == parentComponent) {2956continue; // was checked above2957}2958if (IsProcedure(component)) { // C18042959msgs.Say(component.name(),2960"An interoperable derived type cannot have a type bound procedure"_err_en_US);2961} else if (IsAllocatableOrPointer(component)) { // C18062962msgs.Say(component.name(),2963"An interoperable derived type cannot have a pointer or allocatable component"_err_en_US);2964} else if (const auto *type{component.GetType()}) {2965if (const auto *derived{type->AsDerived()}) {2966auto bad{WhyNotInteroperableDerivedType(derived->typeSymbol())};2967if (bad.AnyFatalError()) {2968auto &msg{msgs.Say(component.name(),2969"Component '%s' of an interoperable derived type must have an interoperable type but does not"_err_en_US,2970component.name())};2971bad.AttachTo(msg, parser::Severity::None);2972} else if (!derived->typeSymbol().GetUltimate().attrs().test(2973Attr::BIND_C)) {2974auto &msg{2975msgs.Say(component.name(),2976"Derived type of component '%s' of an interoperable derived type should have the BIND attribute"_warn_en_US,2977component.name())2978.Attach(derived->typeSymbol().name(),2979"Non-BIND(C) component type"_en_US)};2980bad.AttachTo(msg, parser::Severity::None);2981} else {2982msgs.Annex(std::move(bad));2983}2984} else if (!IsInteroperableIntrinsicType(2985*type, context_.languageFeatures())) {2986auto maybeDyType{evaluate::DynamicType::From(*type)};2987if (type->category() == DeclTypeSpec::Logical) {2988if (context_.ShouldWarn(common::UsageWarning::LogicalVsCBool)) {2989msgs.Say(component.name(),2990"A LOGICAL component of an interoperable type should have the interoperable KIND=C_BOOL"_port_en_US);2991}2992} else if (type->category() == DeclTypeSpec::Character &&2993maybeDyType && maybeDyType->kind() == 1) {2994if (context_.ShouldWarn(common::UsageWarning::BindCCharLength)) {2995msgs.Say(component.name(),2996"A CHARACTER component of an interoperable type should have length 1"_port_en_US);2997}2998} else {2999msgs.Say(component.name(),3000"Each component of an interoperable derived type must have an interoperable type"_err_en_US);3001}3002}3003}3004if (auto extents{3005evaluate::GetConstantExtents(foldingContext_, &component)};3006extents && evaluate::GetSize(*extents) == 0) {3007msgs.Say(component.name(),3008"An array component of an interoperable type must have at least one element"_err_en_US);3009}3010}3011if (derived->componentNames().empty()) { // F'2023 C18053012if (context_.ShouldWarn(common::LanguageFeature::EmptyBindCDerivedType)) {3013msgs.Say(symbol.name(),3014"A derived type with the BIND attribute should not be empty"_warn_en_US);3015}3016}3017}3018if (msgs.AnyFatalError()) {3019examinedByWhyNotInteroperable_.erase(symbol);3020}3021return msgs;3022}
3023
3024parser::Messages CheckHelper::WhyNotInteroperableObject(const Symbol &symbol) {3025parser::Messages msgs;3026if (examinedByWhyNotInteroperable_.find(symbol) !=3027examinedByWhyNotInteroperable_.end()) {3028return msgs;3029}3030bool isExplicitBindC{symbol.attrs().test(Attr::BIND_C)};3031examinedByWhyNotInteroperable_.insert(symbol);3032CHECK(symbol.has<ObjectEntityDetails>());3033if (isExplicitBindC && !symbol.owner().IsModule()) {3034msgs.Say(symbol.name(),3035"A variable with BIND(C) attribute may only appear in the specification part of a module"_err_en_US);3036}3037auto shape{evaluate::GetShape(foldingContext_, symbol)};3038if (shape) {3039if (evaluate::GetRank(*shape) == 0) { // 18.3.43040if (IsAllocatableOrPointer(symbol) && !IsDummy(symbol)) {3041msgs.Say(symbol.name(),3042"A scalar interoperable variable may not be ALLOCATABLE or POINTER"_err_en_US);3043}3044} else if (auto extents{3045evaluate::AsConstantExtents(foldingContext_, *shape)}) {3046if (evaluate::GetSize(*extents) == 0) {3047msgs.Say(symbol.name(),3048"Interoperable array must have at least one element"_err_en_US);3049}3050} else if (!evaluate::IsExplicitShape(symbol) &&3051!IsAssumedSizeArray(symbol) &&3052!(IsDummy(symbol) && !symbol.attrs().test(Attr::VALUE))) {3053msgs.Say(symbol.name(),3054"BIND(C) array must have explicit shape or be assumed-size unless a dummy argument without the VALUE attribute"_err_en_US);3055}3056}3057if (const auto *type{symbol.GetType()}) {3058const auto *derived{type->AsDerived()};3059if (derived && !derived->typeSymbol().attrs().test(Attr::BIND_C)) {3060if (!context_.IsEnabled(3061common::LanguageFeature::NonBindCInteroperability)) {3062msgs.Say(symbol.name(),3063"The derived type of an interoperable object must be BIND(C)"_err_en_US)3064.Attach(derived->typeSymbol().name(), "Non-BIND(C) type"_en_US);3065} else if (auto bad{3066WhyNotInteroperableDerivedType(derived->typeSymbol())};3067bad.AnyFatalError()) {3068bad.AttachTo(3069msgs.Say(symbol.name(),3070"The derived type of an interoperable object must be interoperable, but is not"_err_en_US)3071.Attach(derived->typeSymbol().name(),3072"Non-interoperable type"_en_US),3073parser::Severity::None);3074} else {3075msgs.Say(symbol.name(),3076"The derived type of an interoperable object should be BIND(C)"_warn_en_US)3077.Attach(derived->typeSymbol().name(), "Non-BIND(C) type"_en_US);3078}3079}3080if (type->IsAssumedType()) { // ok3081} else if (IsAssumedLengthCharacter(symbol)) {3082} else if (IsAllocatableOrPointer(symbol) &&3083type->category() == DeclTypeSpec::Character &&3084type->characterTypeSpec().length().isDeferred()) {3085// ok; F'2023 18.3.7 p2(6)3086} else if (derived ||3087IsInteroperableIntrinsicType(*type, context_.languageFeatures())) {3088// F'2023 18.3.7 p2(4,5)3089} else if (type->category() == DeclTypeSpec::Logical) {3090if (context_.ShouldWarn(common::UsageWarning::LogicalVsCBool) &&3091!InModuleFile()) {3092if (IsDummy(symbol)) {3093msgs.Say(symbol.name(),3094"A BIND(C) LOGICAL dummy argument should have the interoperable KIND=C_BOOL"_port_en_US);3095} else {3096msgs.Say(symbol.name(),3097"A BIND(C) LOGICAL object should have the interoperable KIND=C_BOOL"_port_en_US);3098}3099}3100} else if (symbol.attrs().test(Attr::VALUE)) {3101msgs.Say(symbol.name(),3102"A BIND(C) VALUE dummy argument must have an interoperable type"_err_en_US);3103} else {3104msgs.Say(symbol.name(),3105"A BIND(C) object must have an interoperable type"_err_en_US);3106}3107}3108if (IsOptional(symbol) && !symbol.attrs().test(Attr::VALUE)) {3109msgs.Say(symbol.name(),3110"An interoperable procedure with an OPTIONAL dummy argument might not be portable"_port_en_US);3111}3112if (IsDescriptor(symbol) && IsPointer(symbol) &&3113symbol.attrs().test(Attr::CONTIGUOUS)) {3114msgs.Say(symbol.name(),3115"An interoperable pointer must not be CONTIGUOUS"_err_en_US);3116}3117if (msgs.AnyFatalError()) {3118examinedByWhyNotInteroperable_.erase(symbol);3119}3120return msgs;3121}
3122
3123parser::Messages CheckHelper::WhyNotInteroperableFunctionResult(3124const Symbol &symbol) {3125parser::Messages msgs;3126if (IsPointer(symbol) || IsAllocatable(symbol)) {3127msgs.Say(symbol.name(),3128"Interoperable function result may not have ALLOCATABLE or POINTER attribute"_err_en_US);3129}3130if (const DeclTypeSpec * type{symbol.GetType()};3131type && type->category() == DeclTypeSpec::Character) {3132bool isConstOne{false}; // 18.3.1(1)3133if (const auto &len{type->characterTypeSpec().length().GetExplicit()}) {3134if (auto constLen{evaluate::ToInt64(*len)}) {3135isConstOne = constLen == 1;3136}3137}3138if (!isConstOne) {3139msgs.Say(symbol.name(),3140"Interoperable character function result must have length one"_err_en_US);3141}3142}3143if (symbol.Rank() > 0) {3144msgs.Say(symbol.name(),3145"Interoperable function result must be scalar"_err_en_US);3146}3147if (symbol.Corank()) {3148msgs.Say(symbol.name(),3149"Interoperable function result may not be a coarray"_err_en_US);3150}3151return msgs;3152}
3153
3154parser::Messages CheckHelper::WhyNotInteroperableProcedure(3155const Symbol &symbol, bool isError) {3156parser::Messages msgs;3157if (examinedByWhyNotInteroperable_.find(symbol) !=3158examinedByWhyNotInteroperable_.end()) {3159return msgs;3160}3161isError |= symbol.attrs().test(Attr::BIND_C);3162examinedByWhyNotInteroperable_.insert(symbol);3163if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) {3164if (isError) {3165if (!proc->procInterface() ||3166!proc->procInterface()->attrs().test(Attr::BIND_C)) {3167msgs.Say(symbol.name(),3168"An interface name with the BIND attribute must appear if the BIND attribute appears in a procedure declaration"_err_en_US);3169}3170} else if (!proc->procInterface()) {3171msgs.Say(symbol.name(),3172"An interoperable procedure should have an interface"_port_en_US);3173} else if (!proc->procInterface()->attrs().test(Attr::BIND_C)) {3174auto bad{WhyNotInteroperableProcedure(3175*proc->procInterface(), /*isError=*/false)};3176if (bad.AnyFatalError()) {3177bad.AttachTo(msgs.Say(symbol.name(),3178"An interoperable procedure must have an interoperable interface"_err_en_US));3179} else {3180msgs.Say(symbol.name(),3181"An interoperable procedure should have an interface with the BIND attribute"_warn_en_US);3182}3183}3184} else if (const auto *subp{symbol.detailsIf<SubprogramDetails>()}) {3185for (const Symbol *dummy : subp->dummyArgs()) {3186if (dummy) {3187parser::Messages dummyMsgs;3188if (dummy->has<ProcEntityDetails>() ||3189dummy->has<SubprogramDetails>()) {3190dummyMsgs = WhyNotInteroperableProcedure(*dummy, /*isError=*/false);3191if (dummyMsgs.empty() && !dummy->attrs().test(Attr::BIND_C)) {3192dummyMsgs.Say(dummy->name(),3193"A dummy procedure of an interoperable procedure should be BIND(C)"_warn_en_US);3194}3195} else if (dummy->has<ObjectEntityDetails>()) {3196dummyMsgs = WhyNotInteroperableObject(*dummy);3197} else {3198CheckBindC(*dummy);3199}3200msgs.Annex(std::move(dummyMsgs));3201} else {3202msgs.Say(symbol.name(),3203"A subprogram interface with the BIND attribute may not have an alternate return argument"_err_en_US);3204}3205}3206if (subp->isFunction()) {3207if (subp->result().has<ObjectEntityDetails>()) {3208msgs.Annex(WhyNotInteroperableFunctionResult(subp->result()));3209} else {3210msgs.Say(subp->result().name(),3211"The result of an interoperable function must be a data object"_err_en_US);3212}3213}3214}3215if (msgs.AnyFatalError()) {3216examinedByWhyNotInteroperable_.erase(symbol);3217}3218return msgs;3219}
3220
3221void CheckHelper::CheckBindC(const Symbol &symbol) {3222bool isExplicitBindC{symbol.attrs().test(Attr::BIND_C)};3223if (isExplicitBindC) {3224CheckConflicting(symbol, Attr::BIND_C, Attr::ELEMENTAL);3225CheckConflicting(symbol, Attr::BIND_C, Attr::INTRINSIC);3226CheckConflicting(symbol, Attr::BIND_C, Attr::PARAMETER);3227} else {3228// symbol must be interoperable (e.g., dummy argument of interoperable3229// procedure interface) but is not itself BIND(C).3230}3231parser::Messages whyNot;3232if (const std::string * bindName{symbol.GetBindName()};3233bindName) { // has a binding name3234if (!bindName->empty()) {3235bool ok{bindName->front() == '_' || parser::IsLetter(bindName->front())};3236for (char ch : *bindName) {3237ok &= ch == '_' || parser::IsLetter(ch) || parser::IsDecimalDigit(ch);3238}3239if (!ok) {3240messages_.Say(symbol.name(),3241"Symbol has a BIND(C) name that is not a valid C language identifier"_err_en_US);3242context_.SetError(symbol);3243}3244}3245}3246if (symbol.GetIsExplicitBindName()) { // BIND(C,NAME=...); C1552, C15293247auto defClass{ClassifyProcedure(symbol)};3248if (IsProcedurePointer(symbol)) {3249messages_.Say(symbol.name(),3250"A procedure pointer may not have a BIND attribute with a name"_err_en_US);3251context_.SetError(symbol);3252} else if (defClass == ProcedureDefinitionClass::None ||3253IsExternal(symbol)) {3254} else if (symbol.attrs().test(Attr::ABSTRACT)) {3255messages_.Say(symbol.name(),3256"An ABSTRACT interface may not have a BIND attribute with a name"_err_en_US);3257context_.SetError(symbol);3258} else if (defClass == ProcedureDefinitionClass::Internal ||3259defClass == ProcedureDefinitionClass::Dummy) {3260messages_.Say(symbol.name(),3261"An internal or dummy procedure may not have a BIND(C,NAME=) binding label"_err_en_US);3262context_.SetError(symbol);3263}3264}3265if (symbol.has<ObjectEntityDetails>()) {3266whyNot = WhyNotInteroperableObject(symbol);3267} else if (symbol.has<ProcEntityDetails>() ||3268symbol.has<SubprogramDetails>()) {3269whyNot = WhyNotInteroperableProcedure(symbol, /*isError=*/isExplicitBindC);3270} else if (symbol.has<DerivedTypeDetails>()) {3271whyNot = WhyNotInteroperableDerivedType(symbol);3272}3273if (!whyNot.empty()) {3274bool anyFatal{whyNot.AnyFatalError()};3275if (anyFatal ||3276(!InModuleFile() &&3277context_.ShouldWarn(3278common::LanguageFeature::NonBindCInteroperability))) {3279context_.messages().Annex(std::move(whyNot));3280}3281if (anyFatal) {3282context_.SetError(symbol);3283}3284}3285}
3286
3287bool CheckHelper::CheckDioDummyIsData(3288const Symbol &subp, const Symbol *arg, std::size_t position) {3289if (arg && arg->detailsIf<ObjectEntityDetails>()) {3290return true;3291} else {3292if (arg) {3293messages_.Say(arg->name(),3294"Dummy argument '%s' must be a data object"_err_en_US, arg->name());3295} else {3296messages_.Say(subp.name(),3297"Dummy argument %d of '%s' must be a data object"_err_en_US, position,3298subp.name());3299}3300return false;3301}3302}
3303
3304void CheckHelper::CheckAlreadySeenDefinedIo(const DerivedTypeSpec &derivedType,3305common::DefinedIo ioKind, const Symbol &proc, const Symbol &generic) {3306// Check for conflict between non-type-bound defined I/O and type-bound3307// generics. It's okay to have two or more distinct defined I/O procedures for3308// the same type if they're coming from distinct non-type-bound interfaces.3309// (The non-type-bound interfaces would have been merged into a single generic3310// -- with errors where indistinguishable -- when both were visible from the3311// same scope.)3312if (generic.owner().IsDerivedType()) {3313return;3314}3315if (const Scope * dtScope{derivedType.scope()}) {3316if (auto iter{dtScope->find(generic.name())}; iter != dtScope->end()) {3317for (auto specRef : iter->second->get<GenericDetails>().specificProcs()) {3318const Symbol &specific{specRef->get<ProcBindingDetails>().symbol()};3319if (specific == proc) { // unambiguous, accept3320continue;3321}3322if (const auto *specDT{GetDtvArgDerivedType(specific)};3323specDT && evaluate::AreSameDerivedType(derivedType, *specDT)) {3324SayWithDeclaration(*specRef, proc.name(),3325"Derived type '%s' has conflicting type-bound input/output procedure '%s'"_err_en_US,3326derivedType.name(), GenericKind::AsFortran(ioKind));3327return;3328}3329}3330}3331}3332}
3333
3334void CheckHelper::CheckDioDummyIsDerived(const Symbol &subp, const Symbol &arg,3335common::DefinedIo ioKind, const Symbol &generic) {3336if (const DeclTypeSpec *type{arg.GetType()}) {3337if (const DerivedTypeSpec *derivedType{type->AsDerived()}) {3338CheckAlreadySeenDefinedIo(*derivedType, ioKind, subp, generic);3339bool isPolymorphic{type->IsPolymorphic()};3340if (isPolymorphic != IsExtensibleType(derivedType)) {3341messages_.Say(arg.name(),3342"Dummy argument '%s' of a defined input/output procedure must be %s when the derived type is %s"_err_en_US,3343arg.name(), isPolymorphic ? "TYPE()" : "CLASS()",3344isPolymorphic ? "not extensible" : "extensible");3345}3346} else {3347messages_.Say(arg.name(),3348"Dummy argument '%s' of a defined input/output procedure must have a"3349" derived type"_err_en_US,3350arg.name());3351}3352}3353}
3354
3355void CheckHelper::CheckDioDummyIsDefaultInteger(3356const Symbol &subp, const Symbol &arg) {3357if (const DeclTypeSpec *type{arg.GetType()};3358type && type->IsNumeric(TypeCategory::Integer)) {3359if (const auto kind{evaluate::ToInt64(type->numericTypeSpec().kind())};3360kind && *kind == context_.GetDefaultKind(TypeCategory::Integer)) {3361return;3362}3363}3364messages_.Say(arg.name(),3365"Dummy argument '%s' of a defined input/output procedure"3366" must be an INTEGER of default KIND"_err_en_US,3367arg.name());3368}
3369
3370void CheckHelper::CheckDioDummyIsScalar(const Symbol &subp, const Symbol &arg) {3371if (arg.Rank() > 0 || arg.Corank() > 0) {3372messages_.Say(arg.name(),3373"Dummy argument '%s' of a defined input/output procedure"3374" must be a scalar"_err_en_US,3375arg.name());3376}3377}
3378
3379void CheckHelper::CheckDioDtvArg(const Symbol &subp, const Symbol *arg,3380common::DefinedIo ioKind, const Symbol &generic) {3381// Dtv argument looks like: dtv-type-spec, INTENT(INOUT) :: dtv3382if (CheckDioDummyIsData(subp, arg, 0)) {3383CheckDioDummyIsDerived(subp, *arg, ioKind, generic);3384CheckDioDummyAttrs(subp, *arg,3385ioKind == common::DefinedIo::ReadFormatted ||3386ioKind == common::DefinedIo::ReadUnformatted3387? Attr::INTENT_INOUT3388: Attr::INTENT_IN);3389}3390}
3391
3392// If an explicit INTRINSIC name is a function, so must all the specifics be,
3393// and similarly for subroutines
3394void CheckHelper::CheckGenericVsIntrinsic(3395const Symbol &symbol, const GenericDetails &generic) {3396if (symbol.attrs().test(Attr::INTRINSIC)) {3397const evaluate::IntrinsicProcTable &table{3398context_.foldingContext().intrinsics()};3399bool isSubroutine{table.IsIntrinsicSubroutine(symbol.name().ToString())};3400if (isSubroutine || table.IsIntrinsicFunction(symbol.name().ToString())) {3401for (const SymbolRef &ref : generic.specificProcs()) {3402const Symbol &ultimate{ref->GetUltimate()};3403bool specificFunc{ultimate.test(Symbol::Flag::Function)};3404bool specificSubr{ultimate.test(Symbol::Flag::Subroutine)};3405if (!specificFunc && !specificSubr) {3406if (const auto *proc{ultimate.detailsIf<SubprogramDetails>()}) {3407if (proc->isFunction()) {3408specificFunc = true;3409} else {3410specificSubr = true;3411}3412}3413}3414if ((specificFunc || specificSubr) &&3415isSubroutine != specificSubr) { // C8483416messages_.Say(symbol.name(),3417"Generic interface '%s' with explicit intrinsic %s of the same name may not have specific procedure '%s' that is a %s"_err_en_US,3418symbol.name(), isSubroutine ? "subroutine" : "function",3419ref->name(), isSubroutine ? "function" : "subroutine");3420}3421}3422}3423}3424}
3425
3426void CheckHelper::CheckDefaultIntegerArg(3427const Symbol &subp, const Symbol *arg, Attr intent) {3428// Argument looks like: INTEGER, INTENT(intent) :: arg3429if (CheckDioDummyIsData(subp, arg, 1)) {3430CheckDioDummyIsDefaultInteger(subp, *arg);3431CheckDioDummyIsScalar(subp, *arg);3432CheckDioDummyAttrs(subp, *arg, intent);3433}3434}
3435
3436void CheckHelper::CheckDioAssumedLenCharacterArg(const Symbol &subp,3437const Symbol *arg, std::size_t argPosition, Attr intent) {3438// Argument looks like: CHARACTER (LEN=*), INTENT(intent) :: (iotype OR iomsg)3439if (CheckDioDummyIsData(subp, arg, argPosition)) {3440CheckDioDummyAttrs(subp, *arg, intent);3441const DeclTypeSpec *type{arg ? arg->GetType() : nullptr};3442const IntrinsicTypeSpec *intrinsic{type ? type->AsIntrinsic() : nullptr};3443const auto kind{3444intrinsic ? evaluate::ToInt64(intrinsic->kind()) : std::nullopt};3445if (!IsAssumedLengthCharacter(*arg) ||3446(!kind ||3447*kind !=3448context_.defaultKinds().GetDefaultKind(3449TypeCategory::Character))) {3450messages_.Say(arg->name(),3451"Dummy argument '%s' of a defined input/output procedure"3452" must be assumed-length CHARACTER of default kind"_err_en_US,3453arg->name());3454}3455}3456}
3457
3458void CheckHelper::CheckDioVlistArg(3459const Symbol &subp, const Symbol *arg, std::size_t argPosition) {3460// Vlist argument looks like: INTEGER, INTENT(IN) :: v_list(:)3461if (CheckDioDummyIsData(subp, arg, argPosition)) {3462CheckDioDummyIsDefaultInteger(subp, *arg);3463CheckDioDummyAttrs(subp, *arg, Attr::INTENT_IN);3464const auto *objectDetails{arg->detailsIf<ObjectEntityDetails>()};3465if (!objectDetails || !objectDetails->shape().CanBeDeferredShape()) {3466messages_.Say(arg->name(),3467"Dummy argument '%s' of a defined input/output procedure must be"3468" deferred shape"_err_en_US,3469arg->name());3470}3471}3472}
3473
3474void CheckHelper::CheckDioArgCount(3475const Symbol &subp, common::DefinedIo ioKind, std::size_t argCount) {3476const std::size_t requiredArgCount{3477(std::size_t)(ioKind == common::DefinedIo::ReadFormatted ||3478ioKind == common::DefinedIo::WriteFormatted3479? 63480: 4)};3481if (argCount != requiredArgCount) {3482SayWithDeclaration(subp,3483"Defined input/output procedure '%s' must have"3484" %d dummy arguments rather than %d"_err_en_US,3485subp.name(), requiredArgCount, argCount);3486context_.SetError(subp);3487}3488}
3489
3490void CheckHelper::CheckDioDummyAttrs(3491const Symbol &subp, const Symbol &arg, Attr goodIntent) {3492// Defined I/O procedures can't have attributes other than INTENT3493Attrs attrs{arg.attrs()};3494if (!attrs.test(goodIntent)) {3495messages_.Say(arg.name(),3496"Dummy argument '%s' of a defined input/output procedure"3497" must have intent '%s'"_err_en_US,3498arg.name(), AttrToString(goodIntent));3499}3500attrs = attrs - Attr::INTENT_IN - Attr::INTENT_OUT - Attr::INTENT_INOUT;3501if (!attrs.empty()) {3502messages_.Say(arg.name(),3503"Dummy argument '%s' of a defined input/output procedure may not have"3504" any attributes"_err_en_US,3505arg.name());3506}3507}
3508
3509// Enforce semantics for defined input/output procedures (12.6.4.8.2) and C777
3510void CheckHelper::CheckDefinedIoProc(const Symbol &symbol,3511const GenericDetails &details, common::DefinedIo ioKind) {3512for (auto ref : details.specificProcs()) {3513const Symbol &ultimate{ref->GetUltimate()};3514const auto *binding{ultimate.detailsIf<ProcBindingDetails>()};3515const Symbol &specific{*(binding ? &binding->symbol() : &ultimate)};3516if (ultimate.attrs().test(Attr::NOPASS)) { // C7743517messages_.Say("Defined input/output procedure '%s' may not have NOPASS "3518"attribute"_err_en_US,3519ultimate.name());3520context_.SetError(ultimate);3521}3522if (const auto *subpDetails{specific.detailsIf<SubprogramDetails>()}) {3523const std::vector<Symbol *> &dummyArgs{subpDetails->dummyArgs()};3524CheckDioArgCount(specific, ioKind, dummyArgs.size());3525int argCount{0};3526for (auto *arg : dummyArgs) {3527switch (argCount++) {3528case 0:3529// dtv-type-spec, INTENT(INOUT) :: dtv3530CheckDioDtvArg(specific, arg, ioKind, symbol);3531break;3532case 1:3533// INTEGER, INTENT(IN) :: unit3534CheckDefaultIntegerArg(specific, arg, Attr::INTENT_IN);3535break;3536case 2:3537if (ioKind == common::DefinedIo::ReadFormatted ||3538ioKind == common::DefinedIo::WriteFormatted) {3539// CHARACTER (LEN=*), INTENT(IN) :: iotype3540CheckDioAssumedLenCharacterArg(3541specific, arg, argCount, Attr::INTENT_IN);3542} else {3543// INTEGER, INTENT(OUT) :: iostat3544CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT);3545}3546break;3547case 3:3548if (ioKind == common::DefinedIo::ReadFormatted ||3549ioKind == common::DefinedIo::WriteFormatted) {3550// INTEGER, INTENT(IN) :: v_list(:)3551CheckDioVlistArg(specific, arg, argCount);3552} else {3553// CHARACTER (LEN=*), INTENT(INOUT) :: iomsg3554CheckDioAssumedLenCharacterArg(3555specific, arg, argCount, Attr::INTENT_INOUT);3556}3557break;3558case 4:3559// INTEGER, INTENT(OUT) :: iostat3560CheckDefaultIntegerArg(specific, arg, Attr::INTENT_OUT);3561break;3562case 5:3563// CHARACTER (LEN=*), INTENT(INOUT) :: iomsg3564CheckDioAssumedLenCharacterArg(3565specific, arg, argCount, Attr::INTENT_INOUT);3566break;3567default:;3568}3569}3570}3571}3572}
3573
3574void CheckHelper::CheckSymbolType(const Symbol &symbol) {3575const Symbol *result{FindFunctionResult(symbol)};3576const Symbol &relevant{result ? *result : symbol};3577if (IsAllocatable(relevant)) { // always ok3578} else if (IsProcedurePointer(symbol) && result && IsPointer(*result)) {3579// procedure pointer returning allocatable or pointer: ok3580} else if (IsPointer(relevant) && !IsProcedure(relevant)) {3581// object pointers are always ok3582} else if (auto dyType{evaluate::DynamicType::From(relevant)}) {3583if (dyType->IsPolymorphic() && !dyType->IsAssumedType() &&3584!(IsDummy(symbol) && !IsProcedure(relevant))) { // C7083585messages_.Say(3586"CLASS entity '%s' must be a dummy argument, allocatable, or object pointer"_err_en_US,3587symbol.name());3588}3589if (dyType->HasDeferredTypeParameter()) { // C7023590messages_.Say(3591"'%s' has a type %s with a deferred type parameter but is neither an allocatable nor an object pointer"_err_en_US,3592symbol.name(), dyType->AsFortran());3593}3594}3595}
3596
3597void CheckHelper::CheckModuleProcedureDef(const Symbol &symbol) {3598auto procClass{ClassifyProcedure(symbol)};3599if (const auto *subprogram{symbol.detailsIf<SubprogramDetails>()};3600subprogram &&3601(procClass == ProcedureDefinitionClass::Module &&3602symbol.attrs().test(Attr::MODULE)) &&3603!subprogram->bindName() && !subprogram->isInterface()) {3604const Symbol &interface {3605subprogram->moduleInterface() ? *subprogram->moduleInterface() : symbol3606};3607if (const Symbol *3608module{interface.owner().kind() == Scope::Kind::Module3609? interface.owner().symbol()3610: nullptr};3611module && module->has<ModuleDetails>()) {3612std::pair<SourceName, const Symbol *> key{symbol.name(), module};3613auto iter{moduleProcs_.find(key)};3614if (iter == moduleProcs_.end()) {3615moduleProcs_.emplace(std::move(key), symbol);3616} else if (3617auto *msg{messages_.Say(symbol.name(),3618"Module procedure '%s' in '%s' has multiple definitions"_err_en_US,3619symbol.name(), GetModuleOrSubmoduleName(*module))}) {3620msg->Attach(iter->second->name(), "Previous definition of '%s'"_en_US,3621symbol.name());3622}3623}3624}3625}
3626
3627void SubprogramMatchHelper::Check(3628const Symbol &symbol1, const Symbol &symbol2) {3629const auto details1{symbol1.get<SubprogramDetails>()};3630const auto details2{symbol2.get<SubprogramDetails>()};3631if (details1.isFunction() != details2.isFunction()) {3632Say(symbol1, symbol2,3633details1.isFunction()3634? "Module function '%s' was declared as a subroutine in the"3635" corresponding interface body"_err_en_US3636: "Module subroutine '%s' was declared as a function in the"3637" corresponding interface body"_err_en_US);3638return;3639}3640const auto &args1{details1.dummyArgs()};3641const auto &args2{details2.dummyArgs()};3642int nargs1{static_cast<int>(args1.size())};3643int nargs2{static_cast<int>(args2.size())};3644if (nargs1 != nargs2) {3645Say(symbol1, symbol2,3646"Module subprogram '%s' has %d args but the corresponding interface"3647" body has %d"_err_en_US,3648nargs1, nargs2);3649return;3650}3651bool nonRecursive1{symbol1.attrs().test(Attr::NON_RECURSIVE)};3652if (nonRecursive1 != symbol2.attrs().test(Attr::NON_RECURSIVE)) { // C15513653Say(symbol1, symbol2,3654nonRecursive1
3655? "Module subprogram '%s' has NON_RECURSIVE prefix but"3656" the corresponding interface body does not"_err_en_US3657: "Module subprogram '%s' does not have NON_RECURSIVE prefix but "3658"the corresponding interface body does"_err_en_US);3659}3660const std::string *bindName1{details1.bindName()};3661const std::string *bindName2{details2.bindName()};3662if (!bindName1 && !bindName2) {3663// OK - neither has a binding label3664} else if (!bindName1) {3665Say(symbol1, symbol2,3666"Module subprogram '%s' does not have a binding label but the"3667" corresponding interface body does"_err_en_US);3668} else if (!bindName2) {3669Say(symbol1, symbol2,3670"Module subprogram '%s' has a binding label but the"3671" corresponding interface body does not"_err_en_US);3672} else if (*bindName1 != *bindName2) {3673Say(symbol1, symbol2,3674"Module subprogram '%s' has binding label '%s' but the corresponding"3675" interface body has '%s'"_err_en_US,3676*details1.bindName(), *details2.bindName());3677}3678const Procedure *proc1{checkHelper.Characterize(symbol1)};3679const Procedure *proc2{checkHelper.Characterize(symbol2)};3680if (!proc1 || !proc2) {3681return;3682}3683if (proc1->attrs.test(Procedure::Attr::Pure) !=3684proc2->attrs.test(Procedure::Attr::Pure)) {3685Say(symbol1, symbol2,3686"Module subprogram '%s' and its corresponding interface body are not both PURE"_err_en_US);3687}3688if (proc1->attrs.test(Procedure::Attr::Elemental) !=3689proc2->attrs.test(Procedure::Attr::Elemental)) {3690Say(symbol1, symbol2,3691"Module subprogram '%s' and its corresponding interface body are not both ELEMENTAL"_err_en_US);3692}3693if (proc1->attrs.test(Procedure::Attr::BindC) !=3694proc2->attrs.test(Procedure::Attr::BindC)) {3695Say(symbol1, symbol2,3696"Module subprogram '%s' and its corresponding interface body are not both BIND(C)"_err_en_US);3697}3698if (proc1->functionResult && proc2->functionResult) {3699std::string whyNot;3700if (!proc1->functionResult->IsCompatibleWith(3701*proc2->functionResult, &whyNot)) {3702Say(symbol1, symbol2,3703"Result of function '%s' is not compatible with the result of the corresponding interface body: %s"_err_en_US,3704whyNot);3705}3706}3707for (int i{0}; i < nargs1; ++i) {3708const Symbol *arg1{args1[i]};3709const Symbol *arg2{args2[i]};3710if (arg1 && !arg2) {3711Say(symbol1, symbol2,3712"Dummy argument %2$d of '%1$s' is not an alternate return indicator"3713" but the corresponding argument in the interface body is"_err_en_US,3714i + 1);3715} else if (!arg1 && arg2) {3716Say(symbol1, symbol2,3717"Dummy argument %2$d of '%1$s' is an alternate return indicator but"3718" the corresponding argument in the interface body is not"_err_en_US,3719i + 1);3720} else if (arg1 && arg2) {3721SourceName name1{arg1->name()};3722SourceName name2{arg2->name()};3723if (name1 != name2) {3724Say(*arg1, *arg2,3725"Dummy argument name '%s' does not match corresponding name '%s'"3726" in interface body"_err_en_US,3727name2);3728} else {3729CheckDummyArg(3730*arg1, *arg2, proc1->dummyArguments[i], proc2->dummyArguments[i]);3731}3732}3733}3734}
3735
3736void SubprogramMatchHelper::CheckDummyArg(const Symbol &symbol1,3737const Symbol &symbol2, const DummyArgument &arg1,3738const DummyArgument &arg2) {3739common::visit(3740common::visitors{3741[&](const DummyDataObject &obj1, const DummyDataObject &obj2) {3742CheckDummyDataObject(symbol1, symbol2, obj1, obj2);3743},3744[&](const DummyProcedure &proc1, const DummyProcedure &proc2) {3745CheckDummyProcedure(symbol1, symbol2, proc1, proc2);3746},3747[&](const DummyDataObject &, const auto &) {3748Say(symbol1, symbol2,3749"Dummy argument '%s' is a data object; the corresponding"3750" argument in the interface body is not"_err_en_US);3751},3752[&](const DummyProcedure &, const auto &) {3753Say(symbol1, symbol2,3754"Dummy argument '%s' is a procedure; the corresponding"3755" argument in the interface body is not"_err_en_US);3756},3757[&](const auto &, const auto &) {3758llvm_unreachable("Dummy arguments are not data objects or"3759"procedures");3760},3761},3762arg1.u, arg2.u);3763}
3764
3765void SubprogramMatchHelper::CheckDummyDataObject(const Symbol &symbol1,3766const Symbol &symbol2, const DummyDataObject &obj1,3767const DummyDataObject &obj2) {3768if (!CheckSameIntent(symbol1, symbol2, obj1.intent, obj2.intent)) {3769} else if (!CheckSameAttrs(symbol1, symbol2, obj1.attrs, obj2.attrs)) {3770} else if (!obj1.type.type().IsEquivalentTo(obj2.type.type())) {3771Say(symbol1, symbol2,3772"Dummy argument '%s' has type %s; the corresponding argument in the interface body has distinct type %s"_err_en_US,3773obj1.type.type().AsFortran(), obj2.type.type().AsFortran());3774} else if (!ShapesAreCompatible(obj1, obj2)) {3775Say(symbol1, symbol2,3776"The shape of dummy argument '%s' does not match the shape of the"3777" corresponding argument in the interface body"_err_en_US);3778}3779// TODO: coshape3780}
3781
3782void SubprogramMatchHelper::CheckDummyProcedure(const Symbol &symbol1,3783const Symbol &symbol2, const DummyProcedure &proc1,3784const DummyProcedure &proc2) {3785if (!CheckSameIntent(symbol1, symbol2, proc1.intent, proc2.intent)) {3786} else if (!CheckSameAttrs(symbol1, symbol2, proc1.attrs, proc2.attrs)) {3787} else if (proc1 != proc2) {3788Say(symbol1, symbol2,3789"Dummy procedure '%s' does not match the corresponding argument in"3790" the interface body"_err_en_US);3791}3792}
3793
3794bool SubprogramMatchHelper::CheckSameIntent(const Symbol &symbol1,3795const Symbol &symbol2, common::Intent intent1, common::Intent intent2) {3796if (intent1 == intent2) {3797return true;3798} else {3799Say(symbol1, symbol2,3800"The intent of dummy argument '%s' does not match the intent"3801" of the corresponding argument in the interface body"_err_en_US);3802return false;3803}3804}
3805
3806// Report an error referring to first symbol with declaration of second symbol
3807template <typename... A>3808void SubprogramMatchHelper::Say(const Symbol &symbol1, const Symbol &symbol2,3809parser::MessageFixedText &&text, A &&...args) {3810auto &message{context().Say(symbol1.name(), std::move(text), symbol1.name(),3811std::forward<A>(args)...)};3812evaluate::AttachDeclaration(message, symbol2);3813}
3814
3815template <typename ATTRS>3816bool SubprogramMatchHelper::CheckSameAttrs(3817const Symbol &symbol1, const Symbol &symbol2, ATTRS attrs1, ATTRS attrs2) {3818if (attrs1 == attrs2) {3819return true;3820}3821attrs1.IterateOverMembers([&](auto attr) {3822if (!attrs2.test(attr)) {3823Say(symbol1, symbol2,3824"Dummy argument '%s' has the %s attribute; the corresponding"3825" argument in the interface body does not"_err_en_US,3826AsFortran(attr));3827}3828});3829attrs2.IterateOverMembers([&](auto attr) {3830if (!attrs1.test(attr)) {3831Say(symbol1, symbol2,3832"Dummy argument '%s' does not have the %s attribute; the"3833" corresponding argument in the interface body does"_err_en_US,3834AsFortran(attr));3835}3836});3837return false;3838}
3839
3840bool SubprogramMatchHelper::ShapesAreCompatible(3841const DummyDataObject &obj1, const DummyDataObject &obj2) {3842return characteristics::ShapesAreCompatible(3843FoldShape(obj1.type.shape()), FoldShape(obj2.type.shape()));3844}
3845
3846evaluate::Shape SubprogramMatchHelper::FoldShape(const evaluate::Shape &shape) {3847evaluate::Shape result;3848for (const auto &extent : shape) {3849result.emplace_back(3850evaluate::Fold(context().foldingContext(), common::Clone(extent)));3851}3852return result;3853}
3854
3855void DistinguishabilityHelper::Add(const Symbol &generic, GenericKind kind,3856const Symbol &ultimateSpecific, const Procedure &procedure) {3857if (!context_.HasError(ultimateSpecific)) {3858nameToSpecifics_[generic.name()].emplace(3859&ultimateSpecific, ProcedureInfo{kind, procedure});3860}3861}
3862
3863void DistinguishabilityHelper::Check(const Scope &scope) {3864if (FindModuleFileContaining(scope)) {3865// Distinguishability was checked when the module was created;3866// don't let optional warnings then become errors now.3867return;3868}3869for (const auto &[name, info] : nameToSpecifics_) {3870for (auto iter1{info.begin()}; iter1 != info.end(); ++iter1) {3871const auto &[ultimate, procInfo]{*iter1};3872const auto &[kind, proc]{procInfo};3873for (auto iter2{iter1}; ++iter2 != info.end();) {3874auto distinguishable{kind.IsName()3875? evaluate::characteristics::Distinguishable3876: evaluate::characteristics::DistinguishableOpOrAssign};3877std::optional<bool> distinct{distinguishable(3878context_.languageFeatures(), proc, iter2->second.procedure)};3879if (!distinct.value_or(false)) {3880SayNotDistinguishable(GetTopLevelUnitContaining(scope), name, kind,3881*ultimate, *iter2->first, distinct.has_value());3882}3883}3884}3885}3886}
3887
3888void DistinguishabilityHelper::SayNotDistinguishable(const Scope &scope,3889const SourceName &name, GenericKind kind, const Symbol &proc1,3890const Symbol &proc2, bool isHardConflict) {3891bool isUseAssociated{!scope.sourceRange().Contains(name)};3892// The rules for distinguishing specific procedures (F'2023 15.4.3.4.5)3893// are inadequate for some real-world cases like pFUnit.3894// When there are optional dummy arguments or unlimited polymorphic3895// dummy data object arguments, the best that we can do is emit an optional3896// portability warning. Also, named generics created by USE association3897// merging shouldn't receive hard errors for ambiguity.3898// (Non-named generics might be defined I/O procedures or defined3899// assignments that need to be used by the runtime.)3900bool isWarning{!isHardConflict || (isUseAssociated && kind.IsName())};3901if (isWarning &&3902(!context_.ShouldWarn(3903common::LanguageFeature::IndistinguishableSpecifics) ||3904FindModuleFileContaining(scope))) {3905return;3906}3907std::string name1{proc1.name().ToString()};3908std::string name2{proc2.name().ToString()};3909if (kind.IsOperator() || kind.IsAssignment()) {3910// proc1 and proc2 may come from different scopes so qualify their names3911if (proc1.owner().IsDerivedType()) {3912name1 = proc1.owner().GetName()->ToString() + '%' + name1;3913}3914if (proc2.owner().IsDerivedType()) {3915name2 = proc2.owner().GetName()->ToString() + '%' + name2;3916}3917}3918parser::Message *msg;3919if (!isUseAssociated) {3920CHECK(isWarning == !isHardConflict);3921msg = &context_.Say(name,3922isHardConflict
3923? "Generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US3924: "Generic '%s' should not have specific procedures '%s' and '%s' as their interfaces are not distinguishable by the rules in the standard"_port_en_US,3925MakeOpName(name), name1, name2);3926} else {3927msg = &context_.Say(*GetTopLevelUnitContaining(proc1).GetName(),3928isHardConflict
3929? (isWarning3930? "USE-associated generic '%s' should not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_warn_en_US3931: "USE-associated generic '%s' may not have specific procedures '%s' and '%s' as their interfaces are not distinguishable"_err_en_US)3932: "USE-associated generic '%s' should not have specific procedures '%s' and '%s' as their interfaces are not distinguishable by the rules in the standard"_port_en_US,3933MakeOpName(name), name1, name2);3934}3935AttachDeclaration(*msg, scope, proc1);3936AttachDeclaration(*msg, scope, proc2);3937}
3938
3939// `evaluate::AttachDeclaration` doesn't handle the generic case where `proc`
3940// comes from a different module but is not necessarily use-associated.
3941void DistinguishabilityHelper::AttachDeclaration(3942parser::Message &msg, const Scope &scope, const Symbol &proc) {3943const Scope &unit{GetTopLevelUnitContaining(proc)};3944if (unit == scope) {3945evaluate::AttachDeclaration(msg, proc);3946} else {3947msg.Attach(unit.GetName().value(),3948"'%s' is USE-associated from module '%s'"_en_US, proc.name(),3949unit.GetName().value());3950}3951}
3952
3953void CheckDeclarations(SemanticsContext &context) {3954CheckHelper{context}.Check();3955}
3956} // namespace Fortran::semantics3957