1 //===-- lib/Semantics/check-call.cpp --------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "check-call.h"
10 #include "pointer-assignment.h"
11 #include "flang/Evaluate/characteristics.h"
12 #include "flang/Evaluate/check-expression.h"
13 #include "flang/Evaluate/shape.h"
14 #include "flang/Evaluate/tools.h"
15 #include "flang/Parser/characters.h"
16 #include "flang/Parser/message.h"
17 #include "flang/Semantics/scope.h"
18 #include "flang/Semantics/tools.h"
19 #include <map>
20 #include <string>
21 
22 using namespace Fortran::parser::literals;
23 namespace characteristics = Fortran::evaluate::characteristics;
24 
25 namespace Fortran::semantics {
26 
27 static void CheckImplicitInterfaceArg(
28     evaluate::ActualArgument &arg, parser::ContextualMessages &messages) {
29   auto restorer{
30       messages.SetLocation(arg.sourceLocation().value_or(messages.at()))};
31   if (auto kw{arg.keyword()}) {
32     messages.Say(*kw,
33         "Keyword '%s=' may not appear in a reference to a procedure with an implicit interface"_err_en_US,
34         *kw);
35   }
36   if (auto type{arg.GetType()}) {
37     if (type->IsAssumedType()) {
38       messages.Say(
39           "Assumed type argument requires an explicit interface"_err_en_US);
40     } else if (type->IsPolymorphic()) {
41       messages.Say(
42           "Polymorphic argument requires an explicit interface"_err_en_US);
43     } else if (const DerivedTypeSpec * derived{GetDerivedTypeSpec(type)}) {
44       if (!derived->parameters().empty()) {
45         messages.Say(
46             "Parameterized derived type argument requires an explicit interface"_err_en_US);
47       }
48     }
49   }
50   if (const auto *expr{arg.UnwrapExpr()}) {
51     if (IsBOZLiteral(*expr)) {
52       messages.Say("BOZ argument requires an explicit interface"_err_en_US);
53     } else if (evaluate::IsNullPointer(*expr)) {
54       messages.Say(
55           "Null pointer argument requires an explicit interface"_err_en_US);
56     } else if (auto named{evaluate::ExtractNamedEntity(*expr)}) {
57       const Symbol &symbol{named->GetLastSymbol()};
58       if (symbol.Corank() > 0) {
59         messages.Say(
60             "Coarray argument requires an explicit interface"_err_en_US);
61       }
62       if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
63         if (details->IsAssumedRank()) {
64           messages.Say(
65               "Assumed rank argument requires an explicit interface"_err_en_US);
66         }
67       }
68       if (symbol.attrs().test(Attr::ASYNCHRONOUS)) {
69         messages.Say(
70             "ASYNCHRONOUS argument requires an explicit interface"_err_en_US);
71       }
72       if (symbol.attrs().test(Attr::VOLATILE)) {
73         messages.Say(
74             "VOLATILE argument requires an explicit interface"_err_en_US);
75       }
76     }
77   }
78 }
79 
80 // When scalar CHARACTER actual arguments are known to be short,
81 // we extend them on the right with spaces and a warning.
82 static void PadShortCharacterActual(evaluate::Expr<evaluate::SomeType> &actual,
83     const characteristics::TypeAndShape &dummyType,
84     characteristics::TypeAndShape &actualType,
85     evaluate::FoldingContext &context, parser::ContextualMessages &messages) {
86   if (dummyType.type().category() == TypeCategory::Character &&
87       actualType.type().category() == TypeCategory::Character &&
88       dummyType.type().kind() == actualType.type().kind() &&
89       GetRank(actualType.shape()) == 0) {
90     if (dummyType.LEN() && actualType.LEN()) {
91       auto dummyLength{ToInt64(Fold(context, common::Clone(*dummyType.LEN())))};
92       auto actualLength{
93           ToInt64(Fold(context, common::Clone(*actualType.LEN())))};
94       if (dummyLength && actualLength && *actualLength < *dummyLength) {
95         messages.Say(
96             "Actual length '%jd' is less than expected length '%jd'"_warn_en_US,
97             *actualLength, *dummyLength);
98         auto converted{ConvertToType(dummyType.type(), std::move(actual))};
99         CHECK(converted);
100         actual = std::move(*converted);
101         actualType.set_LEN(SubscriptIntExpr{*dummyLength});
102       }
103     }
104   }
105 }
106 
107 // Automatic conversion of different-kind INTEGER scalar actual
108 // argument expressions (not variables) to INTEGER scalar dummies.
109 // We return nonstandard INTEGER(8) results from intrinsic functions
110 // like SIZE() by default in order to facilitate the use of large
111 // arrays.  Emit a warning when downconverting.
112 static void ConvertIntegerActual(evaluate::Expr<evaluate::SomeType> &actual,
113     const characteristics::TypeAndShape &dummyType,
114     characteristics::TypeAndShape &actualType,
115     parser::ContextualMessages &messages) {
116   if (dummyType.type().category() == TypeCategory::Integer &&
117       actualType.type().category() == TypeCategory::Integer &&
118       dummyType.type().kind() != actualType.type().kind() &&
119       GetRank(dummyType.shape()) == 0 && GetRank(actualType.shape()) == 0 &&
120       !evaluate::IsVariable(actual)) {
121     auto converted{
122         evaluate::ConvertToType(dummyType.type(), std::move(actual))};
123     CHECK(converted);
124     actual = std::move(*converted);
125     if (dummyType.type().kind() < actualType.type().kind()) {
126       messages.Say(
127           "Actual argument scalar expression of type INTEGER(%d) was converted to smaller dummy argument type INTEGER(%d)"_port_en_US,
128           actualType.type().kind(), dummyType.type().kind());
129     }
130     actualType = dummyType;
131   }
132 }
133 
134 static bool DefersSameTypeParameters(
135     const DerivedTypeSpec &actual, const DerivedTypeSpec &dummy) {
136   for (const auto &pair : actual.parameters()) {
137     const ParamValue &actualValue{pair.second};
138     const ParamValue *dummyValue{dummy.FindParameter(pair.first)};
139     if (!dummyValue || (actualValue.isDeferred() != dummyValue->isDeferred())) {
140       return false;
141     }
142   }
143   return true;
144 }
145 
146 static void CheckExplicitDataArg(const characteristics::DummyDataObject &dummy,
147     const std::string &dummyName, evaluate::Expr<evaluate::SomeType> &actual,
148     characteristics::TypeAndShape &actualType, bool isElemental,
149     evaluate::FoldingContext &context, const Scope *scope,
150     const evaluate::SpecificIntrinsic *intrinsic,
151     bool allowIntegerConversions) {
152 
153   // Basic type & rank checking
154   parser::ContextualMessages &messages{context.messages()};
155   PadShortCharacterActual(actual, dummy.type, actualType, context, messages);
156   if (allowIntegerConversions) {
157     ConvertIntegerActual(actual, dummy.type, actualType, messages);
158   }
159   bool typesCompatible{dummy.type.type().IsTkCompatibleWith(actualType.type())};
160   if (typesCompatible) {
161     if (isElemental) {
162     } else if (dummy.type.attrs().test(
163                    characteristics::TypeAndShape::Attr::AssumedRank)) {
164     } else if (!dummy.type.attrs().test(
165                    characteristics::TypeAndShape::Attr::AssumedShape) &&
166         !dummy.type.attrs().test(
167             characteristics::TypeAndShape::Attr::DeferredShape) &&
168         (actualType.Rank() > 0 || IsArrayElement(actual))) {
169       // Sequence association (15.5.2.11) applies -- rank need not match
170       // if the actual argument is an array or array element designator,
171       // and the dummy is not assumed-shape or an INTENT(IN) pointer
172       // that's standing in for an assumed-shape dummy.
173     } else {
174       // Let CheckConformance accept scalars; storage association
175       // cases are checked here below.
176       CheckConformance(messages, dummy.type.shape(), actualType.shape(),
177           evaluate::CheckConformanceFlags::EitherScalarExpandable,
178           "dummy argument", "actual argument");
179     }
180   } else {
181     const auto &len{actualType.LEN()};
182     messages.Say(
183         "Actual argument type '%s' is not compatible with dummy argument type '%s'"_err_en_US,
184         actualType.type().AsFortran(len ? len->AsFortran() : ""),
185         dummy.type.type().AsFortran());
186   }
187 
188   bool actualIsPolymorphic{actualType.type().IsPolymorphic()};
189   bool dummyIsPolymorphic{dummy.type.type().IsPolymorphic()};
190   bool actualIsCoindexed{ExtractCoarrayRef(actual).has_value()};
191   bool actualIsAssumedSize{actualType.attrs().test(
192       characteristics::TypeAndShape::Attr::AssumedSize)};
193   bool dummyIsAssumedSize{dummy.type.attrs().test(
194       characteristics::TypeAndShape::Attr::AssumedSize)};
195   bool dummyIsAsynchronous{
196       dummy.attrs.test(characteristics::DummyDataObject::Attr::Asynchronous)};
197   bool dummyIsVolatile{
198       dummy.attrs.test(characteristics::DummyDataObject::Attr::Volatile)};
199   bool dummyIsValue{
200       dummy.attrs.test(characteristics::DummyDataObject::Attr::Value)};
201 
202   if (actualIsPolymorphic && dummyIsPolymorphic &&
203       actualIsCoindexed) { // 15.5.2.4(2)
204     messages.Say(
205         "Coindexed polymorphic object may not be associated with a polymorphic %s"_err_en_US,
206         dummyName);
207   }
208   if (actualIsPolymorphic && !dummyIsPolymorphic &&
209       actualIsAssumedSize) { // 15.5.2.4(2)
210     messages.Say(
211         "Assumed-size polymorphic array may not be associated with a monomorphic %s"_err_en_US,
212         dummyName);
213   }
214 
215   // Derived type actual argument checks
216   const Symbol *actualFirstSymbol{evaluate::GetFirstSymbol(actual)};
217   bool actualIsAsynchronous{
218       actualFirstSymbol && actualFirstSymbol->attrs().test(Attr::ASYNCHRONOUS)};
219   bool actualIsVolatile{
220       actualFirstSymbol && actualFirstSymbol->attrs().test(Attr::VOLATILE)};
221   if (const auto *derived{evaluate::GetDerivedTypeSpec(actualType.type())}) {
222     if (dummy.type.type().IsAssumedType()) {
223       if (!derived->parameters().empty()) { // 15.5.2.4(2)
224         messages.Say(
225             "Actual argument associated with TYPE(*) %s may not have a parameterized derived type"_err_en_US,
226             dummyName);
227       }
228       if (const Symbol *
229           tbp{FindImmediateComponent(*derived, [](const Symbol &symbol) {
230             return symbol.has<ProcBindingDetails>();
231           })}) { // 15.5.2.4(2)
232         evaluate::SayWithDeclaration(messages, *tbp,
233             "Actual argument associated with TYPE(*) %s may not have type-bound procedure '%s'"_err_en_US,
234             dummyName, tbp->name());
235       }
236       const auto &finals{
237           derived->typeSymbol().get<DerivedTypeDetails>().finals()};
238       if (!finals.empty()) { // 15.5.2.4(2)
239         if (auto *msg{messages.Say(
240                 "Actual argument associated with TYPE(*) %s may not have derived type '%s' with FINAL subroutine '%s'"_err_en_US,
241                 dummyName, derived->typeSymbol().name(),
242                 finals.begin()->first)}) {
243           msg->Attach(finals.begin()->first,
244               "FINAL subroutine '%s' in derived type '%s'"_en_US,
245               finals.begin()->first, derived->typeSymbol().name());
246         }
247       }
248     }
249     if (actualIsCoindexed) {
250       if (dummy.intent != common::Intent::In && !dummyIsValue) {
251         if (auto bad{
252                 FindAllocatableUltimateComponent(*derived)}) { // 15.5.2.4(6)
253           evaluate::SayWithDeclaration(messages, *bad,
254               "Coindexed actual argument with ALLOCATABLE ultimate component '%s' must be associated with a %s with VALUE or INTENT(IN) attributes"_err_en_US,
255               bad.BuildResultDesignatorName(), dummyName);
256         }
257       }
258       if (auto coarrayRef{evaluate::ExtractCoarrayRef(actual)}) { // C1537
259         const Symbol &coarray{coarrayRef->GetLastSymbol()};
260         if (const DeclTypeSpec * type{coarray.GetType()}) {
261           if (const DerivedTypeSpec * derived{type->AsDerived()}) {
262             if (auto bad{semantics::FindPointerUltimateComponent(*derived)}) {
263               evaluate::SayWithDeclaration(messages, coarray,
264                   "Coindexed object '%s' with POINTER ultimate component '%s' cannot be associated with %s"_err_en_US,
265                   coarray.name(), bad.BuildResultDesignatorName(), dummyName);
266             }
267           }
268         }
269       }
270     }
271     if (actualIsVolatile != dummyIsVolatile) { // 15.5.2.4(22)
272       if (auto bad{semantics::FindCoarrayUltimateComponent(*derived)}) {
273         evaluate::SayWithDeclaration(messages, *bad,
274             "VOLATILE attribute must match for %s when actual argument has a coarray ultimate component '%s'"_err_en_US,
275             dummyName, bad.BuildResultDesignatorName());
276       }
277     }
278   }
279 
280   // Rank and shape checks
281   const auto *actualLastSymbol{evaluate::GetLastSymbol(actual)};
282   if (actualLastSymbol) {
283     actualLastSymbol = &ResolveAssociations(*actualLastSymbol);
284   }
285   const ObjectEntityDetails *actualLastObject{actualLastSymbol
286           ? actualLastSymbol->detailsIf<ObjectEntityDetails>()
287           : nullptr};
288   int actualRank{evaluate::GetRank(actualType.shape())};
289   bool actualIsPointer{evaluate::IsObjectPointer(actual, context)};
290   bool dummyIsAssumedRank{dummy.type.attrs().test(
291       characteristics::TypeAndShape::Attr::AssumedRank)};
292   if (dummy.type.attrs().test(
293           characteristics::TypeAndShape::Attr::AssumedShape)) {
294     // 15.5.2.4(16)
295     if (actualRank == 0) {
296       messages.Say(
297           "Scalar actual argument may not be associated with assumed-shape %s"_err_en_US,
298           dummyName);
299     }
300     if (actualIsAssumedSize && actualLastSymbol) {
301       evaluate::SayWithDeclaration(messages, *actualLastSymbol,
302           "Assumed-size array may not be associated with assumed-shape %s"_err_en_US,
303           dummyName);
304     }
305   } else if (actualRank == 0 && dummy.type.Rank() > 0) {
306     // Actual is scalar, dummy is an array.  15.5.2.4(14), 15.5.2.11
307     if (actualIsCoindexed) {
308       messages.Say(
309           "Coindexed scalar actual argument must be associated with a scalar %s"_err_en_US,
310           dummyName);
311     }
312     bool actualIsArrayElement{IsArrayElement(actual)};
313     bool actualIsCKindCharacter{
314         actualType.type().category() == TypeCategory::Character &&
315         actualType.type().kind() == 1};
316     if (!actualIsCKindCharacter) {
317       if (!actualIsArrayElement &&
318           !(dummy.type.type().IsAssumedType() && dummyIsAssumedSize) &&
319           !dummyIsAssumedRank) {
320         messages.Say(
321             "Whole scalar actual argument may not be associated with a %s array"_err_en_US,
322             dummyName);
323       }
324       if (actualIsPolymorphic) {
325         messages.Say(
326             "Polymorphic scalar may not be associated with a %s array"_err_en_US,
327             dummyName);
328       }
329       if (actualIsArrayElement && actualLastSymbol &&
330           IsPointer(*actualLastSymbol)) {
331         messages.Say(
332             "Element of pointer array may not be associated with a %s array"_err_en_US,
333             dummyName);
334       }
335       if (actualLastSymbol && IsAssumedShape(*actualLastSymbol)) {
336         messages.Say(
337             "Element of assumed-shape array may not be associated with a %s array"_err_en_US,
338             dummyName);
339       }
340     }
341   }
342   if (actualLastObject && actualLastObject->IsCoarray() &&
343       IsAllocatable(*actualLastSymbol) && dummy.intent == common::Intent::Out &&
344       !(intrinsic &&
345           evaluate::AcceptsIntentOutAllocatableCoarray(
346               intrinsic->name))) { // C846
347     messages.Say(
348         "ALLOCATABLE coarray '%s' may not be associated with INTENT(OUT) %s"_err_en_US,
349         actualLastSymbol->name(), dummyName);
350   }
351 
352   // Definability
353   const char *reason{nullptr};
354   if (dummy.intent == common::Intent::Out) {
355     reason = "INTENT(OUT)";
356   } else if (dummy.intent == common::Intent::InOut) {
357     reason = "INTENT(IN OUT)";
358   } else if (dummyIsAsynchronous) {
359     reason = "ASYNCHRONOUS";
360   } else if (dummyIsVolatile) {
361     reason = "VOLATILE";
362   }
363   if (reason && scope) {
364     bool vectorSubscriptIsOk{isElemental || dummyIsValue}; // 15.5.2.4(21)
365     if (auto why{WhyNotModifiable(
366             messages.at(), actual, *scope, vectorSubscriptIsOk)}) {
367       if (auto *msg{messages.Say(
368               "Actual argument associated with %s %s must be definable"_err_en_US, // C1158
369               reason, dummyName)}) {
370         msg->Attach(*why);
371       }
372     }
373   }
374 
375   // Cases when temporaries might be needed but must not be permitted.
376   bool actualIsContiguous{IsSimplyContiguous(actual, context)};
377   bool dummyIsAssumedShape{dummy.type.attrs().test(
378       characteristics::TypeAndShape::Attr::AssumedShape)};
379   bool dummyIsPointer{
380       dummy.attrs.test(characteristics::DummyDataObject::Attr::Pointer)};
381   bool dummyIsContiguous{
382       dummy.attrs.test(characteristics::DummyDataObject::Attr::Contiguous)};
383   if ((actualIsAsynchronous || actualIsVolatile) &&
384       (dummyIsAsynchronous || dummyIsVolatile) && !dummyIsValue) {
385     if (actualIsCoindexed) { // C1538
386       messages.Say(
387           "Coindexed ASYNCHRONOUS or VOLATILE actual argument may not be associated with %s with ASYNCHRONOUS or VOLATILE attributes unless VALUE"_err_en_US,
388           dummyName);
389     }
390     if (actualRank > 0 && !actualIsContiguous) {
391       if (dummyIsContiguous ||
392           !(dummyIsAssumedShape || dummyIsAssumedRank ||
393               (actualIsPointer && dummyIsPointer))) { // C1539 & C1540
394         messages.Say(
395             "ASYNCHRONOUS or VOLATILE actual argument that is not simply contiguous may not be associated with a contiguous %s"_err_en_US,
396             dummyName);
397       }
398     }
399   }
400 
401   // 15.5.2.6 -- dummy is ALLOCATABLE
402   bool dummyIsAllocatable{
403       dummy.attrs.test(characteristics::DummyDataObject::Attr::Allocatable)};
404   bool actualIsAllocatable{evaluate::IsAllocatableDesignator(actual)};
405   if (dummyIsAllocatable) {
406     if (!actualIsAllocatable) {
407       messages.Say(
408           "ALLOCATABLE %s must be associated with an ALLOCATABLE actual argument"_err_en_US,
409           dummyName);
410     }
411     if (actualIsAllocatable && actualIsCoindexed &&
412         dummy.intent != common::Intent::In) {
413       messages.Say(
414           "ALLOCATABLE %s must have INTENT(IN) to be associated with a coindexed actual argument"_err_en_US,
415           dummyName);
416     }
417     if (!actualIsCoindexed && actualLastSymbol &&
418         actualLastSymbol->Corank() != dummy.type.corank()) {
419       messages.Say(
420           "ALLOCATABLE %s has corank %d but actual argument has corank %d"_err_en_US,
421           dummyName, dummy.type.corank(), actualLastSymbol->Corank());
422     }
423   }
424 
425   // 15.5.2.7 -- dummy is POINTER
426   if (dummyIsPointer) {
427     if (dummyIsContiguous && !actualIsContiguous) {
428       messages.Say(
429           "Actual argument associated with CONTIGUOUS POINTER %s must be simply contiguous"_err_en_US,
430           dummyName);
431     }
432     if (!actualIsPointer) {
433       if (dummy.intent == common::Intent::In) {
434         semantics::CheckPointerAssignment(
435             context, parser::CharBlock{}, dummyName, dummy, actual);
436       } else {
437         messages.Say(
438             "Actual argument associated with POINTER %s must also be POINTER unless INTENT(IN)"_err_en_US,
439             dummyName);
440       }
441     }
442   }
443 
444   // 15.5.2.5 -- actual & dummy are both POINTER or both ALLOCATABLE
445   if ((actualIsPointer && dummyIsPointer) ||
446       (actualIsAllocatable && dummyIsAllocatable)) {
447     bool actualIsUnlimited{actualType.type().IsUnlimitedPolymorphic()};
448     bool dummyIsUnlimited{dummy.type.type().IsUnlimitedPolymorphic()};
449     if (actualIsUnlimited != dummyIsUnlimited) {
450       if (typesCompatible) {
451         messages.Say(
452             "If a POINTER or ALLOCATABLE dummy or actual argument is unlimited polymorphic, both must be so"_err_en_US);
453       }
454     } else if (dummyIsPolymorphic != actualIsPolymorphic) {
455       if (dummy.intent == common::Intent::In && typesCompatible) {
456         // extension: allow with warning, rule is only relevant for definables
457         messages.Say(
458             "If a POINTER or ALLOCATABLE dummy or actual argument is polymorphic, both should be so"_port_en_US);
459       } else {
460         messages.Say(
461             "If a POINTER or ALLOCATABLE dummy or actual argument is polymorphic, both must be so"_err_en_US);
462       }
463     } else if (!actualIsUnlimited && typesCompatible) {
464       if (!actualType.type().IsTkCompatibleWith(dummy.type.type())) {
465         if (dummy.intent == common::Intent::In) {
466           // extension: allow with warning, rule is only relevant for definables
467           messages.Say(
468               "POINTER or ALLOCATABLE dummy and actual arguments should have the same declared type and kind"_port_en_US);
469         } else {
470           messages.Say(
471               "POINTER or ALLOCATABLE dummy and actual arguments must have the same declared type and kind"_err_en_US);
472         }
473       }
474       if (const auto *derived{
475               evaluate::GetDerivedTypeSpec(actualType.type())}) {
476         if (!DefersSameTypeParameters(
477                 *derived, *evaluate::GetDerivedTypeSpec(dummy.type.type()))) {
478           messages.Say(
479               "Dummy and actual arguments must defer the same type parameters when POINTER or ALLOCATABLE"_err_en_US);
480         }
481       }
482     }
483   }
484 
485   // 15.5.2.8 -- coarray dummy arguments
486   if (dummy.type.corank() > 0) {
487     if (actualType.corank() == 0) {
488       messages.Say(
489           "Actual argument associated with coarray %s must be a coarray"_err_en_US,
490           dummyName);
491     }
492     if (dummyIsVolatile) {
493       if (!actualIsVolatile) {
494         messages.Say(
495             "non-VOLATILE coarray may not be associated with VOLATILE coarray %s"_err_en_US,
496             dummyName);
497       }
498     } else {
499       if (actualIsVolatile) {
500         messages.Say(
501             "VOLATILE coarray may not be associated with non-VOLATILE coarray %s"_err_en_US,
502             dummyName);
503       }
504     }
505     if (actualRank == dummy.type.Rank() && !actualIsContiguous) {
506       if (dummyIsContiguous) {
507         messages.Say(
508             "Actual argument associated with a CONTIGUOUS coarray %s must be simply contiguous"_err_en_US,
509             dummyName);
510       } else if (!dummyIsAssumedShape && !dummyIsAssumedRank) {
511         messages.Say(
512             "Actual argument associated with coarray %s (not assumed shape or rank) must be simply contiguous"_err_en_US,
513             dummyName);
514       }
515     }
516   }
517 
518   // NULL(MOLD=) checking for non-intrinsic procedures
519   bool dummyIsOptional{
520       dummy.attrs.test(characteristics::DummyDataObject::Attr::Optional)};
521   bool actualIsNull{evaluate::IsNullPointer(actual)};
522   if (!intrinsic && !dummyIsPointer && !dummyIsOptional && actualIsNull) {
523     messages.Say(
524         "Actual argument associated with %s may not be null pointer %s"_err_en_US,
525         dummyName, actual.AsFortran());
526   }
527 }
528 
529 static void CheckProcedureArg(evaluate::ActualArgument &arg,
530     const characteristics::Procedure &proc,
531     const characteristics::DummyProcedure &dummy, const std::string &dummyName,
532     evaluate::FoldingContext &context) {
533   parser::ContextualMessages &messages{context.messages()};
534   auto restorer{
535       messages.SetLocation(arg.sourceLocation().value_or(messages.at()))};
536   const characteristics::Procedure &interface { dummy.procedure.value() };
537   if (const auto *expr{arg.UnwrapExpr()}) {
538     bool dummyIsPointer{
539         dummy.attrs.test(characteristics::DummyProcedure::Attr::Pointer)};
540     const auto *argProcDesignator{
541         std::get_if<evaluate::ProcedureDesignator>(&expr->u)};
542     const auto *argProcSymbol{
543         argProcDesignator ? argProcDesignator->GetSymbol() : nullptr};
544     if (auto argChars{characteristics::DummyArgument::FromActual(
545             "actual argument", *expr, context)}) {
546       if (!argChars->IsTypelessIntrinsicDummy()) {
547         if (auto *argProc{
548                 std::get_if<characteristics::DummyProcedure>(&argChars->u)}) {
549           characteristics::Procedure &argInterface{argProc->procedure.value()};
550           argInterface.attrs.reset(
551               characteristics::Procedure::Attr::NullPointer);
552           if (!argProcSymbol || argProcSymbol->attrs().test(Attr::INTRINSIC)) {
553             // It's ok to pass ELEMENTAL unrestricted intrinsic functions.
554             argInterface.attrs.reset(
555                 characteristics::Procedure::Attr::Elemental);
556           } else if (argInterface.attrs.test(
557                          characteristics::Procedure::Attr::Elemental)) {
558             if (argProcSymbol) { // C1533
559               evaluate::SayWithDeclaration(messages, *argProcSymbol,
560                   "Non-intrinsic ELEMENTAL procedure '%s' may not be passed as an actual argument"_err_en_US,
561                   argProcSymbol->name());
562               return; // avoid piling on with checks below
563             } else {
564               argInterface.attrs.reset(
565                   characteristics::Procedure::Attr::NullPointer);
566             }
567           }
568           if (interface.HasExplicitInterface()) {
569             if (!interface.IsCompatibleWith(argInterface)) {
570               // 15.5.2.9(1): Explicit interfaces must match
571               if (argInterface.HasExplicitInterface()) {
572                 messages.Say(
573                     "Actual procedure argument has interface incompatible with %s"_err_en_US,
574                     dummyName);
575                 return;
576               } else if (proc.IsPure()) {
577                 messages.Say(
578                     "Actual procedure argument for %s of a PURE procedure must have an explicit interface"_err_en_US,
579                     dummyName);
580               } else {
581                 messages.Say(
582                     "Actual procedure argument has an implicit interface "
583                     "which is not known to be compatible with %s which has an "
584                     "explicit interface"_warn_en_US,
585                     dummyName);
586               }
587             }
588           } else { // 15.5.2.9(2,3)
589             if (interface.IsSubroutine() && argInterface.IsFunction()) {
590               messages.Say(
591                   "Actual argument associated with procedure %s is a function but must be a subroutine"_err_en_US,
592                   dummyName);
593             } else if (interface.IsFunction()) {
594               if (argInterface.IsFunction()) {
595                 if (!interface.functionResult->IsCompatibleWith(
596                         *argInterface.functionResult)) {
597                   messages.Say(
598                       "Actual argument function associated with procedure %s has incompatible result type"_err_en_US,
599                       dummyName);
600                 }
601               } else if (argInterface.IsSubroutine()) {
602                 messages.Say(
603                     "Actual argument associated with procedure %s is a subroutine but must be a function"_err_en_US,
604                     dummyName);
605               }
606             }
607           }
608         } else {
609           messages.Say(
610               "Actual argument associated with procedure %s is not a procedure"_err_en_US,
611               dummyName);
612         }
613       } else if (IsNullPointer(*expr)) {
614         if (!dummyIsPointer) {
615           messages.Say(
616               "Actual argument associated with procedure %s is a null pointer"_err_en_US,
617               dummyName);
618         }
619       } else {
620         messages.Say(
621             "Actual argument associated with procedure %s is typeless"_err_en_US,
622             dummyName);
623       }
624     }
625     if (interface.HasExplicitInterface() && dummyIsPointer &&
626         dummy.intent != common::Intent::In) {
627       const Symbol *last{GetLastSymbol(*expr)};
628       if (!(last && IsProcedurePointer(*last))) {
629         // 15.5.2.9(5) -- dummy procedure POINTER
630         // Interface compatibility has already been checked above
631         messages.Say(
632             "Actual argument associated with procedure pointer %s must be a POINTER unless INTENT(IN)"_err_en_US,
633             dummyName);
634       }
635     }
636   } else {
637     messages.Say(
638         "Assumed-type argument may not be forwarded as procedure %s"_err_en_US,
639         dummyName);
640   }
641 }
642 
643 // Allow BOZ literal actual arguments when they can be converted to a known
644 // dummy argument type
645 static void ConvertBOZLiteralArg(
646     evaluate::ActualArgument &arg, const evaluate::DynamicType &type) {
647   if (auto *expr{arg.UnwrapExpr()}) {
648     if (IsBOZLiteral(*expr)) {
649       if (auto converted{evaluate::ConvertToType(type, SomeExpr{*expr})}) {
650         arg = std::move(*converted);
651       }
652     }
653   }
654 }
655 
656 static void CheckExplicitInterfaceArg(evaluate::ActualArgument &arg,
657     const characteristics::DummyArgument &dummy,
658     const characteristics::Procedure &proc, evaluate::FoldingContext &context,
659     const Scope *scope, const evaluate::SpecificIntrinsic *intrinsic,
660     bool allowIntegerConversions) {
661   auto &messages{context.messages()};
662   std::string dummyName{"dummy argument"};
663   if (!dummy.name.empty()) {
664     dummyName += " '"s + parser::ToLowerCaseLetters(dummy.name) + "='";
665   }
666   auto restorer{
667       messages.SetLocation(arg.sourceLocation().value_or(messages.at()))};
668   std::visit(
669       common::visitors{
670           [&](const characteristics::DummyDataObject &object) {
671             ConvertBOZLiteralArg(arg, object.type.type());
672             if (auto *expr{arg.UnwrapExpr()}) {
673               if (auto type{characteristics::TypeAndShape::Characterize(
674                       *expr, context)}) {
675                 arg.set_dummyIntent(object.intent);
676                 bool isElemental{object.type.Rank() == 0 && proc.IsElemental()};
677                 CheckExplicitDataArg(object, dummyName, *expr, *type,
678                     isElemental, context, scope, intrinsic,
679                     allowIntegerConversions);
680               } else if (object.type.type().IsTypelessIntrinsicArgument() &&
681                   IsBOZLiteral(*expr)) {
682                 // ok
683               } else if (object.type.type().IsTypelessIntrinsicArgument() &&
684                   evaluate::IsNullPointer(*expr)) {
685                 // ok, ASSOCIATED(NULL())
686               } else if ((object.attrs.test(characteristics::DummyDataObject::
687                                   Attr::Pointer) ||
688                              object.attrs.test(characteristics::
689                                      DummyDataObject::Attr::Optional)) &&
690                   evaluate::IsNullPointer(*expr)) {
691                 // ok, FOO(NULL())
692               } else {
693                 messages.Say(
694                     "Actual argument '%s' associated with %s is not a variable or typed expression"_err_en_US,
695                     expr->AsFortran(), dummyName);
696               }
697             } else {
698               const Symbol &assumed{DEREF(arg.GetAssumedTypeDummy())};
699               if (!object.type.type().IsAssumedType()) {
700                 messages.Say(
701                     "Assumed-type '%s' may be associated only with an assumed-type %s"_err_en_US,
702                     assumed.name(), dummyName);
703               } else if (object.type.attrs().test(evaluate::characteristics::
704                                  TypeAndShape::Attr::AssumedRank) &&
705                   !IsAssumedShape(assumed) &&
706                   !evaluate::IsAssumedRank(assumed)) {
707                 messages.Say( // C711
708                     "Assumed-type '%s' must be either assumed shape or assumed rank to be associated with assumed rank %s"_err_en_US,
709                     assumed.name(), dummyName);
710               }
711             }
712           },
713           [&](const characteristics::DummyProcedure &dummy) {
714             CheckProcedureArg(arg, proc, dummy, dummyName, context);
715           },
716           [&](const characteristics::AlternateReturn &) {
717             // All semantic checking is done elsewhere
718           },
719       },
720       dummy.u);
721 }
722 
723 static void RearrangeArguments(const characteristics::Procedure &proc,
724     evaluate::ActualArguments &actuals, parser::ContextualMessages &messages) {
725   CHECK(proc.HasExplicitInterface());
726   if (actuals.size() < proc.dummyArguments.size()) {
727     actuals.resize(proc.dummyArguments.size());
728   } else if (actuals.size() > proc.dummyArguments.size()) {
729     messages.Say(
730         "Too many actual arguments (%zd) passed to procedure that expects only %zd"_err_en_US,
731         actuals.size(), proc.dummyArguments.size());
732   }
733   std::map<std::string, evaluate::ActualArgument> kwArgs;
734   for (auto &x : actuals) {
735     if (x && x->keyword()) {
736       auto emplaced{
737           kwArgs.try_emplace(x->keyword()->ToString(), std::move(*x))};
738       if (!emplaced.second) {
739         messages.Say(*x->keyword(),
740             "Argument keyword '%s=' appears on more than one effective argument in this procedure reference"_err_en_US,
741             *x->keyword());
742       }
743       x.reset();
744     }
745   }
746   if (!kwArgs.empty()) {
747     int index{0};
748     for (const auto &dummy : proc.dummyArguments) {
749       if (!dummy.name.empty()) {
750         auto iter{kwArgs.find(dummy.name)};
751         if (iter != kwArgs.end()) {
752           evaluate::ActualArgument &x{iter->second};
753           if (actuals[index]) {
754             messages.Say(*x.keyword(),
755                 "Keyword argument '%s=' has already been specified positionally (#%d) in this procedure reference"_err_en_US,
756                 *x.keyword(), index + 1);
757           } else {
758             actuals[index] = std::move(x);
759           }
760           kwArgs.erase(iter);
761         }
762       }
763       ++index;
764     }
765     for (auto &bad : kwArgs) {
766       evaluate::ActualArgument &x{bad.second};
767       messages.Say(*x.keyword(),
768           "Argument keyword '%s=' is not recognized for this procedure reference"_err_en_US,
769           *x.keyword());
770     }
771   }
772 }
773 
774 // The actual argument arrays to an ELEMENTAL procedure must conform.
775 static bool CheckElementalConformance(parser::ContextualMessages &messages,
776     const characteristics::Procedure &proc, evaluate::ActualArguments &actuals,
777     evaluate::FoldingContext &context) {
778   std::optional<evaluate::Shape> shape;
779   std::string shapeName;
780   int index{0};
781   for (const auto &arg : actuals) {
782     const auto &dummy{proc.dummyArguments.at(index++)};
783     if (arg) {
784       if (const auto *expr{arg->UnwrapExpr()}) {
785         if (auto argShape{evaluate::GetShape(context, *expr)}) {
786           if (GetRank(*argShape) > 0) {
787             std::string argName{"actual argument ("s + expr->AsFortran() +
788                 ") corresponding to dummy argument #" + std::to_string(index) +
789                 " ('" + dummy.name + "')"};
790             if (shape) {
791               auto tristate{evaluate::CheckConformance(messages, *shape,
792                   *argShape, evaluate::CheckConformanceFlags::None,
793                   shapeName.c_str(), argName.c_str())};
794               if (tristate && !*tristate) {
795                 return false;
796               }
797             } else {
798               shape = std::move(argShape);
799               shapeName = argName;
800             }
801           }
802         }
803       }
804     }
805   }
806   return true;
807 }
808 
809 static parser::Messages CheckExplicitInterface(
810     const characteristics::Procedure &proc, evaluate::ActualArguments &actuals,
811     const evaluate::FoldingContext &context, const Scope *scope,
812     const evaluate::SpecificIntrinsic *intrinsic,
813     bool allowIntegerConversions) {
814   parser::Messages buffer;
815   parser::ContextualMessages messages{context.messages().at(), &buffer};
816   RearrangeArguments(proc, actuals, messages);
817   if (buffer.empty()) {
818     int index{0};
819     evaluate::FoldingContext localContext{context, messages};
820     for (auto &actual : actuals) {
821       const auto &dummy{proc.dummyArguments.at(index++)};
822       if (actual) {
823         CheckExplicitInterfaceArg(*actual, dummy, proc, localContext, scope,
824             intrinsic, allowIntegerConversions);
825       } else if (!dummy.IsOptional()) {
826         if (dummy.name.empty()) {
827           messages.Say(
828               "Dummy argument #%d is not OPTIONAL and is not associated with "
829               "an actual argument in this procedure reference"_err_en_US,
830               index);
831         } else {
832           messages.Say("Dummy argument '%s=' (#%d) is not OPTIONAL and is not "
833                        "associated with an actual argument in this procedure "
834                        "reference"_err_en_US,
835               dummy.name, index);
836         }
837       }
838     }
839     if (proc.IsElemental() && !buffer.AnyFatalError()) {
840       CheckElementalConformance(messages, proc, actuals, localContext);
841     }
842   }
843   return buffer;
844 }
845 
846 parser::Messages CheckExplicitInterface(const characteristics::Procedure &proc,
847     evaluate::ActualArguments &actuals, const evaluate::FoldingContext &context,
848     const Scope &scope, const evaluate::SpecificIntrinsic *intrinsic) {
849   return CheckExplicitInterface(
850       proc, actuals, context, &scope, intrinsic, true);
851 }
852 
853 bool CheckInterfaceForGeneric(const characteristics::Procedure &proc,
854     evaluate::ActualArguments &actuals, const evaluate::FoldingContext &context,
855     bool allowIntegerConversions) {
856   return !CheckExplicitInterface(
857       proc, actuals, context, nullptr, nullptr, allowIntegerConversions)
858               .AnyFatalError();
859 }
860 
861 void CheckArguments(const characteristics::Procedure &proc,
862     evaluate::ActualArguments &actuals, evaluate::FoldingContext &context,
863     const Scope &scope, bool treatingExternalAsImplicit,
864     const evaluate::SpecificIntrinsic *intrinsic) {
865   bool explicitInterface{proc.HasExplicitInterface()};
866   parser::ContextualMessages &messages{context.messages()};
867   if (!explicitInterface || treatingExternalAsImplicit) {
868     parser::Messages buffer;
869     {
870       auto restorer{messages.SetMessages(buffer)};
871       for (auto &actual : actuals) {
872         if (actual) {
873           CheckImplicitInterfaceArg(*actual, messages);
874         }
875       }
876     }
877     if (!buffer.empty()) {
878       if (auto *msgs{messages.messages()}) {
879         msgs->Annex(std::move(buffer));
880       }
881       return; // don't pile on
882     }
883   }
884   if (explicitInterface) {
885     auto buffer{
886         CheckExplicitInterface(proc, actuals, context, scope, intrinsic)};
887     if (treatingExternalAsImplicit && !buffer.empty()) {
888       if (auto *msg{messages.Say(
889               "If the procedure's interface were explicit, this reference would be in error:"_warn_en_US)}) {
890         buffer.AttachTo(*msg);
891       }
892     }
893     if (auto *msgs{messages.messages()}) {
894       msgs->Annex(std::move(buffer));
895     }
896   }
897 }
898 } // namespace Fortran::semantics
899