Debian Codegraph @

flang/lib/Semantics/check-call.cpp

raw
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 "definable.h"
11 #include "pointer-assignment.h"
12 #include "flang/Evaluate/characteristics.h"
13 #include "flang/Evaluate/check-expression.h"
14 #include "flang/Evaluate/fold-designator.h"
15 #include "flang/Evaluate/shape.h"
16 #include "flang/Evaluate/tools.h"
17 #include "flang/Parser/characters.h"
18 #include "flang/Parser/message.h"
19 #include "flang/Semantics/scope.h"
20 #include "flang/Semantics/tools.h"
21 #include <map>
22 #include <string>
23
24 using namespace Fortran::parser::literals;
25 namespace characteristics = Fortran::evaluate::characteristics;
26
27 namespace Fortran::semantics {
28
29 static void CheckImplicitInterfaceArg(evaluate::ActualArgument &arg,
30 parser::ContextualMessages &messages, evaluate::FoldingContext &context) {
31 auto restorer{
32 messages.SetLocation(arg.sourceLocation().value_or(messages.at()))};
33 if (auto kw{arg.keyword()}) {
34 messages.Say(*kw,
35 "Keyword '%s=' may not appear in a reference to a procedure with an implicit interface"_err_en_US,
36 *kw);
37 }
38 auto type{arg.GetType()};
39 if (type) {
40 if (type->IsAssumedType()) {
41 messages.Say(
42 "Assumed type actual argument requires an explicit interface"_err_en_US);
43 } else if (type->IsUnlimitedPolymorphic()) {
44 messages.Say(
45 "Unlimited polymorphic actual argument requires an explicit interface"_err_en_US);
46 } else if (const DerivedTypeSpec * derived{GetDerivedTypeSpec(type)}) {
47 if (!derived->parameters().empty()) {
48 messages.Say(
49 "Parameterized derived type actual argument requires an explicit interface"_err_en_US);
50 }
51 }
52 }
53 if (arg.isPercentVal() &&
54 (!type || !type->IsLengthlessIntrinsicType() || arg.Rank() != 0)) {
55 messages.Say(
56 "%VAL argument must be a scalar numeric or logical expression"_err_en_US);
57 }
58 if (const auto *expr{arg.UnwrapExpr()}) {
59 if (IsBOZLiteral(*expr)) {
60 messages.Say("BOZ argument requires an explicit interface"_err_en_US);
61 } else if (evaluate::IsNullPointer(*expr)) {
62 messages.Say(
63 "Null pointer argument requires an explicit interface"_err_en_US);
64 } else if (auto named{evaluate::ExtractNamedEntity(*expr)}) {
65 const Symbol &symbol{named->GetLastSymbol()};
66 if (symbol.Corank() > 0) {
67 messages.Say(
68 "Coarray argument requires an explicit interface"_err_en_US);
69 }
70 if (evaluate::IsAssumedRank(symbol)) {
71 messages.Say(
72 "Assumed rank argument requires an explicit interface"_err_en_US);
73 }
74 if (symbol.attrs().test(Attr::ASYNCHRONOUS)) {
75 messages.Say(
76 "ASYNCHRONOUS argument requires an explicit interface"_err_en_US);
77 }
78 if (symbol.attrs().test(Attr::VOLATILE)) {
79 messages.Say(
80 "VOLATILE argument requires an explicit interface"_err_en_US);
81 }
82 } else if (auto argChars{characteristics::DummyArgument::FromActual(
83 "actual argument", *expr, context,
84 /*forImplicitInterface=*/true)}) {
85 const auto *argProcDesignator{
86 std::get_if<evaluate::ProcedureDesignator>(&expr->u)};
87 if (const auto *argProcSymbol{
88 argProcDesignator ? argProcDesignator->GetSymbol() : nullptr}) {
89 if (!argChars->IsTypelessIntrinsicDummy() && argProcDesignator &&
90 argProcDesignator->IsElemental()) { // C1533
91 evaluate::SayWithDeclaration(messages, *argProcSymbol,
92 "Non-intrinsic ELEMENTAL procedure '%s' may not be passed as an actual argument"_err_en_US,
93 argProcSymbol->name());
94 } else if (const auto *subp{argProcSymbol->GetUltimate()
95 .detailsIf<SubprogramDetails>()}) {
96 if (subp->stmtFunction()) {
97 evaluate::SayWithDeclaration(messages, *argProcSymbol,
98 "Statement function '%s' may not be passed as an actual argument"_err_en_US,
99 argProcSymbol->name());
100 }
101 }
102 }
103 }
104 }
105 }
106
107 // F'2023 15.5.2.12p1: "Sequence association only applies when the dummy
108 // argument is an explicit-shape or assumed-size array."
109 static bool CanAssociateWithStorageSequence(
110 const characteristics::DummyDataObject &dummy) {
111 return !dummy.type.attrs().test(
112 characteristics::TypeAndShape::Attr::AssumedRank) &&
113 !dummy.type.attrs().test(
114 characteristics::TypeAndShape::Attr::AssumedShape) &&
115 !dummy.type.attrs().test(characteristics::TypeAndShape::Attr::Coarray) &&
116 !dummy.attrs.test(characteristics::DummyDataObject::Attr::Allocatable) &&
117 !dummy.attrs.test(characteristics::DummyDataObject::Attr::Pointer);
118 }
119
120 // When a CHARACTER actual argument is known to be short,
121 // we extend it on the right with spaces and a warning if
122 // possible. When it is long, and not required to be equal,
123 // the usage conforms to the standard and no warning is needed.
124 static void CheckCharacterActual(evaluate::Expr<evaluate::SomeType> &actual,
125 const characteristics::DummyDataObject &dummy,
126 characteristics::TypeAndShape &actualType, SemanticsContext &context,
127 parser::ContextualMessages &messages, bool extentErrors,
128 const std::string &dummyName) {
129 if (dummy.type.type().category() == TypeCategory::Character &&
130 actualType.type().category() == TypeCategory::Character &&
131 dummy.type.type().kind() == actualType.type().kind() &&
132 !dummy.attrs.test(
133 characteristics::DummyDataObject::Attr::DeducedFromActual)) {
134 if (dummy.type.LEN() && actualType.LEN()) {
135 evaluate::FoldingContext &foldingContext{context.foldingContext()};
136 auto dummyLength{
137 ToInt64(Fold(foldingContext, common::Clone(*dummy.type.LEN())))};
138 auto actualLength{
139 ToInt64(Fold(foldingContext, common::Clone(*actualType.LEN())))};
140 if (dummyLength && actualLength) {
141 bool canAssociate{CanAssociateWithStorageSequence(dummy)};
142 if (dummy.type.Rank() > 0 && canAssociate) {
143 // Character storage sequence association (F'2023 15.5.2.12p4)
144 if (auto dummySize{evaluate::ToInt64(evaluate::Fold(
145 foldingContext, evaluate::GetSize(dummy.type.shape())))}) {
146 auto dummyChars{*dummySize * *dummyLength};
147 if (actualType.Rank() == 0) {
148 evaluate::DesignatorFolder folder{
149 context.foldingContext(), /*getLastComponent=*/true};
150 if (auto actualOffset{folder.FoldDesignator(actual)}) {
151 std::int64_t actualChars{*actualLength};
152 if (static_cast<std::size_t>(actualOffset->offset()) >=
153 actualOffset->symbol().size() ||
154 !evaluate::IsContiguous(
155 actualOffset->symbol(), foldingContext)) {
156 // If substring, take rest of substring
157 if (*actualLength > 0) {
158 actualChars -=
159 (actualOffset->offset() / actualType.type().kind()) %
160 *actualLength;
161 }
162 } else {
163 actualChars = (static_cast<std::int64_t>(
164 actualOffset->symbol().size()) -
165 actualOffset->offset()) /
166 actualType.type().kind();
167 }
168 if (actualChars < dummyChars &&
169 (extentErrors ||
170 context.ShouldWarn(
171 common::UsageWarning::ShortCharacterActual))) {
172 auto msg{
173 "Actual argument has fewer characters remaining in storage sequence (%jd) than %s (%jd)"_warn_en_US};
174 if (extentErrors) {
175 msg.set_severity(parser::Severity::Error);
176 }
177 messages.Say(std::move(msg),
178 static_cast<std::intmax_t>(actualChars), dummyName,
179 static_cast<std::intmax_t>(dummyChars));
180 }
181 }
182 } else { // actual.type.Rank() > 0
183 if (auto actualSize{evaluate::ToInt64(evaluate::Fold(
184 foldingContext, evaluate::GetSize(actualType.shape())))};
185 actualSize &&
186 *actualSize * *actualLength < *dummySize * *dummyLength &&
187 (extentErrors ||
188 context.ShouldWarn(
189 common::UsageWarning::ShortCharacterActual))) {
190 auto msg{
191 "Actual argument array has fewer characters (%jd) than %s array (%jd)"_warn_en_US};
192 if (extentErrors) {
193 msg.set_severity(parser::Severity::Error);
194 }
195 messages.Say(std::move(msg),
196 static_cast<std::intmax_t>(*actualSize * *actualLength),
197 dummyName,
198 static_cast<std::intmax_t>(*dummySize * *dummyLength));
199 }
200 }
201 }
202 } else if (*actualLength != *dummyLength) {
203 // Not using storage sequence association, and the lengths don't
204 // match.
205 if (!canAssociate) {
206 // F'2023 15.5.2.5 paragraph 4
207 messages.Say(
208 "Actual argument variable length '%jd' does not match the expected length '%jd'"_err_en_US,
209 *actualLength, *dummyLength);
210 } else if (*actualLength < *dummyLength) {
211 CHECK(dummy.type.Rank() == 0);
212 bool isVariable{evaluate::IsVariable(actual)};
213 if (context.ShouldWarn(
214 common::UsageWarning::ShortCharacterActual)) {
215 if (isVariable) {
216 messages.Say(
217 "Actual argument variable length '%jd' is less than expected length '%jd'"_warn_en_US,
218 *actualLength, *dummyLength);
219 } else {
220 messages.Say(
221 "Actual argument expression length '%jd' is less than expected length '%jd'"_warn_en_US,
222 *actualLength, *dummyLength);
223 }
224 }
225 if (!isVariable) {
226 auto converted{
227 ConvertToType(dummy.type.type(), std::move(actual))};
228 CHECK(converted);
229 actual = std::move(*converted);
230 actualType.set_LEN(SubscriptIntExpr{*dummyLength});
231 }
232 }
233 }
234 }
235 }
236 }
237 }
238
239 // Automatic conversion of different-kind INTEGER scalar actual
240 // argument expressions (not variables) to INTEGER scalar dummies.
241 // We return nonstandard INTEGER(8) results from intrinsic functions
242 // like SIZE() by default in order to facilitate the use of large
243 // arrays. Emit a warning when downconverting.
244 static void ConvertIntegerActual(evaluate::Expr<evaluate::SomeType> &actual,
245 const characteristics::TypeAndShape &dummyType,
246 characteristics::TypeAndShape &actualType,
247 parser::ContextualMessages &messages, SemanticsContext &semanticsContext) {
248 if (dummyType.type().category() == TypeCategory::Integer &&
249 actualType.type().category() == TypeCategory::Integer &&
250 dummyType.type().kind() != actualType.type().kind() &&
251 dummyType.Rank() == 0 && actualType.Rank() == 0 &&
252 !evaluate::IsVariable(actual)) {
253 auto converted{
254 evaluate::ConvertToType(dummyType.type(), std::move(actual))};
255 CHECK(converted);
256 actual = std::move(*converted);
257 if (dummyType.type().kind() < actualType.type().kind()) {
258 if (!semanticsContext.IsEnabled(
259 common::LanguageFeature::ActualIntegerConvertedToSmallerKind) ||
260 semanticsContext.ShouldWarn(
261 common::LanguageFeature::ActualIntegerConvertedToSmallerKind)) {
262 std::optional<parser::MessageFixedText> msg;
263 if (!semanticsContext.IsEnabled(
264 common::LanguageFeature::ActualIntegerConvertedToSmallerKind)) {
265 msg =
266 "Actual argument scalar expression of type INTEGER(%d) cannot beimplicitly converted to smaller dummy argument type INTEGER(%d)"_err_en_US;
267 } else if (semanticsContext.ShouldWarn(
268 common::LanguageFeature::ConvertedArgument)) {
269 msg =
270 "Actual argument scalar expression of type INTEGER(%d) was converted to smaller dummy argument type INTEGER(%d)"_port_en_US;
271 }
272 if (msg) {
273 messages.Say(std::move(msg.value()), actualType.type().kind(),
274 dummyType.type().kind());
275 }
276 }
277 }
278 actualType = dummyType;
279 }
280 }
281
282 // Automatic conversion of different-kind LOGICAL scalar actual argument
283 // expressions (not variables) to LOGICAL scalar dummies when the dummy is of
284 // default logical kind. This allows expressions in dummy arguments to work when
285 // the default logical kind is not the one used in LogicalResult. This will
286 // always be safe even when downconverting so no warning is needed.
287 static void ConvertLogicalActual(evaluate::Expr<evaluate::SomeType> &actual,
288 const characteristics::TypeAndShape &dummyType,
289 characteristics::TypeAndShape &actualType) {
290 if (dummyType.type().category() == TypeCategory::Logical &&
291 actualType.type().category() == TypeCategory::Logical &&
292 dummyType.type().kind() != actualType.type().kind() &&
293 !evaluate::IsVariable(actual)) {
294 auto converted{
295 evaluate::ConvertToType(dummyType.type(), std::move(actual))};
296 CHECK(converted);
297 actual = std::move(*converted);
298 actualType = dummyType;
299 }
300 }
301
302 static bool DefersSameTypeParameters(
303 const DerivedTypeSpec &actual, const DerivedTypeSpec &dummy) {
304 for (const auto &pair : actual.parameters()) {
305 const ParamValue &actualValue{pair.second};
306 const ParamValue *dummyValue{dummy.FindParameter(pair.first)};
307 if (!dummyValue || (actualValue.isDeferred() != dummyValue->isDeferred())) {
308 return false;
309 }
310 }
311 return true;
312 }
313
314 static void CheckExplicitDataArg(const characteristics::DummyDataObject &dummy,
315 const std::string &dummyName, evaluate::Expr<evaluate::SomeType> &actual,
316 characteristics::TypeAndShape &actualType, bool isElemental,
317 SemanticsContext &context, evaluate::FoldingContext &foldingContext,
318 const Scope *scope, const evaluate::SpecificIntrinsic *intrinsic,
319 bool allowActualArgumentConversions, bool extentErrors,
320 const characteristics::Procedure &procedure,
321 const evaluate::ActualArgument &arg) {
322
323 // Basic type & rank checking
324 parser::ContextualMessages &messages{foldingContext.messages()};
325 CheckCharacterActual(
326 actual, dummy, actualType, context, messages, extentErrors, dummyName);
327 bool dummyIsAllocatable{
328 dummy.attrs.test(characteristics::DummyDataObject::Attr::Allocatable)};
329 bool dummyIsPointer{
330 dummy.attrs.test(characteristics::DummyDataObject::Attr::Pointer)};
331 bool dummyIsAllocatableOrPointer{dummyIsAllocatable || dummyIsPointer};
332 allowActualArgumentConversions &= !dummyIsAllocatableOrPointer;
333 bool typesCompatibleWithIgnoreTKR{
334 (dummy.ignoreTKR.test(common::IgnoreTKR::Type) &&
335 (dummy.type.type().category() == TypeCategory::Derived ||
336 actualType.type().category() == TypeCategory::Derived ||
337 dummy.type.type().category() != actualType.type().category())) ||
338 (dummy.ignoreTKR.test(common::IgnoreTKR::Kind) &&
339 dummy.type.type().category() == actualType.type().category())};
340 allowActualArgumentConversions &= !typesCompatibleWithIgnoreTKR;
341 if (allowActualArgumentConversions) {
342 ConvertIntegerActual(actual, dummy.type, actualType, messages, context);
343 ConvertLogicalActual(actual, dummy.type, actualType);
344 }
345 bool typesCompatible{typesCompatibleWithIgnoreTKR ||
346 dummy.type.type().IsTkCompatibleWith(actualType.type())};
347 int dummyRank{dummy.type.Rank()};
348 if (typesCompatible) {
349 if (const auto *constantChar{
350 evaluate::UnwrapConstantValue<evaluate::Ascii>(actual)};
351 constantChar && constantChar->wasHollerith() &&
352 dummy.type.type().IsUnlimitedPolymorphic() &&
353 context.ShouldWarn(common::LanguageFeature::HollerithPolymorphic)) {
354 messages.Say(
355 "passing Hollerith to unlimited polymorphic as if it were CHARACTER"_port_en_US);
356 }
357 } else if (dummyRank == 0 && allowActualArgumentConversions) {
358 // Extension: pass Hollerith literal to scalar as if it had been BOZ
359 if (auto converted{evaluate::HollerithToBOZ(
360 foldingContext, actual, dummy.type.type())}) {
361 if (context.ShouldWarn(
362 common::LanguageFeature::HollerithOrCharacterAsBOZ)) {
363 messages.Say(
364 "passing Hollerith or character literal as if it were BOZ"_port_en_US);
365 }
366 actual = *converted;
367 actualType.type() = dummy.type.type();
368 typesCompatible = true;
369 }
370 }
371 bool dummyIsAssumedRank{dummy.type.attrs().test(
372 characteristics::TypeAndShape::Attr::AssumedRank)};
373 if (typesCompatible) {
374 if (isElemental) {
375 } else if (dummyIsAssumedRank) {
376 } else if (dummy.ignoreTKR.test(common::IgnoreTKR::Rank)) {
377 } else if (dummyRank > 0 && !dummyIsAllocatableOrPointer &&
378 !dummy.type.attrs().test(
379 characteristics::TypeAndShape::Attr::AssumedShape) &&
380 !dummy.type.attrs().test(
381 characteristics::TypeAndShape::Attr::DeferredShape) &&
382 (actualType.Rank() > 0 || IsArrayElement(actual))) {
383 // Sequence association (15.5.2.11) applies -- rank need not match
384 // if the actual argument is an array or array element designator,
385 // and the dummy is an array, but not assumed-shape or an INTENT(IN)
386 // pointer that's standing in for an assumed-shape dummy.
387 } else if (dummy.type.shape() && actualType.shape()) {
388 // Let CheckConformance accept actual scalars; storage association
389 // cases are checked here below.
390 CheckConformance(messages, *dummy.type.shape(), *actualType.shape(),
391 dummyIsAllocatableOrPointer
392 ? evaluate::CheckConformanceFlags::None
393 : evaluate::CheckConformanceFlags::RightScalarExpandable,
394 "dummy argument", "actual argument");
395 }
396 } else {
397 const auto &len{actualType.LEN()};
398 messages.Say(
399 "Actual argument type '%s' is not compatible with dummy argument type '%s'"_err_en_US,
400 actualType.type().AsFortran(len ? len->AsFortran() : ""),
401 dummy.type.type().AsFortran());
402 }
403
404 bool actualIsPolymorphic{actualType.type().IsPolymorphic()};
405 bool dummyIsPolymorphic{dummy.type.type().IsPolymorphic()};
406 bool actualIsCoindexed{ExtractCoarrayRef(actual).has_value()};
407 bool actualIsAssumedSize{actualType.attrs().test(
408 characteristics::TypeAndShape::Attr::AssumedSize)};
409 bool dummyIsAssumedSize{dummy.type.attrs().test(
410 characteristics::TypeAndShape::Attr::AssumedSize)};
411 bool dummyIsAsynchronous{
412 dummy.attrs.test(characteristics::DummyDataObject::Attr::Asynchronous)};
413 bool dummyIsVolatile{
414 dummy.attrs.test(characteristics::DummyDataObject::Attr::Volatile)};
415 bool dummyIsValue{
416 dummy.attrs.test(characteristics::DummyDataObject::Attr::Value)};
417
418 if (actualIsPolymorphic && dummyIsPolymorphic &&
419 actualIsCoindexed) { // 15.5.2.4(2)
420 messages.Say(
421 "Coindexed polymorphic object may not be associated with a polymorphic %s"_err_en_US,
422 dummyName);
423 }
424 if (actualIsPolymorphic && !dummyIsPolymorphic &&
425 actualIsAssumedSize) { // 15.5.2.4(2)
426 messages.Say(
427 "Assumed-size polymorphic array may not be associated with a monomorphic %s"_err_en_US,
428 dummyName);
429 }
430
431 // Derived type actual argument checks
432 const Symbol *actualFirstSymbol{evaluate::GetFirstSymbol(actual)};
433 bool actualIsAsynchronous{
434 actualFirstSymbol && actualFirstSymbol->attrs().test(Attr::ASYNCHRONOUS)};
435 bool actualIsVolatile{
436 actualFirstSymbol && actualFirstSymbol->attrs().test(Attr::VOLATILE)};
437 const auto *derived{evaluate::GetDerivedTypeSpec(actualType.type())};
438 if (derived && !derived->IsVectorType()) {
439 if (dummy.type.type().IsAssumedType()) {
440 if (!derived->parameters().empty()) { // 15.5.2.4(2)
441 messages.Say(
442 "Actual argument associated with TYPE(*) %s may not have a parameterized derived type"_err_en_US,
443 dummyName);
444 }
445 if (const Symbol *
446 tbp{FindImmediateComponent(*derived, [](const Symbol &symbol) {
447 return symbol.has<ProcBindingDetails>();
448 })}) { // 15.5.2.4(2)
449 evaluate::SayWithDeclaration(messages, *tbp,
450 "Actual argument associated with TYPE(*) %s may not have type-bound procedure '%s'"_err_en_US,
451 dummyName, tbp->name());
452 }
453 auto finals{FinalsForDerivedTypeInstantiation(*derived)};
454 if (!finals.empty()) { // 15.5.2.4(2)
455 SourceName name{finals.front()->name()};
456 if (auto *msg{messages.Say(
457 "Actual argument associated with TYPE(*) %s may not have derived type '%s' with FINAL subroutine '%s'"_err_en_US,
458 dummyName, derived->typeSymbol().name(), name)}) {
459 msg->Attach(name, "FINAL subroutine '%s' in derived type '%s'"_en_US,
460 name, derived->typeSymbol().name());
461 }
462 }
463 }
464 if (actualIsCoindexed) {
465 if (dummy.intent != common::Intent::In && !dummyIsValue) {
466 if (auto bad{
467 FindAllocatableUltimateComponent(*derived)}) { // 15.5.2.4(6)
468 evaluate::SayWithDeclaration(messages, *bad,
469 "Coindexed actual argument with ALLOCATABLE ultimate component '%s' must be associated with a %s with VALUE or INTENT(IN) attributes"_err_en_US,
470 bad.BuildResultDesignatorName(), dummyName);
471 }
472 }
473 if (auto coarrayRef{evaluate::ExtractCoarrayRef(actual)}) { // C1537
474 const Symbol &coarray{coarrayRef->GetLastSymbol()};
475 if (const DeclTypeSpec * type{coarray.GetType()}) {
476 if (const DerivedTypeSpec * derived{type->AsDerived()}) {
477 if (auto bad{semantics::FindPointerUltimateComponent(*derived)}) {
478 evaluate::SayWithDeclaration(messages, coarray,
479 "Coindexed object '%s' with POINTER ultimate component '%s' cannot be associated with %s"_err_en_US,
480 coarray.name(), bad.BuildResultDesignatorName(), dummyName);
481 }
482 }
483 }
484 }
485 }
486 if (actualIsVolatile != dummyIsVolatile) { // 15.5.2.4(22)
487 if (auto bad{semantics::FindCoarrayUltimateComponent(*derived)}) {
488 evaluate::SayWithDeclaration(messages, *bad,
489 "VOLATILE attribute must match for %s when actual argument has a coarray ultimate component '%s'"_err_en_US,
490 dummyName, bad.BuildResultDesignatorName());
491 }
492 }
493 }
494
495 // Rank and shape checks
496 const auto *actualLastSymbol{evaluate::GetLastSymbol(actual)};
497 if (actualLastSymbol) {
498 actualLastSymbol = &ResolveAssociations(*actualLastSymbol);
499 }
500 const ObjectEntityDetails *actualLastObject{actualLastSymbol
501 ? actualLastSymbol->detailsIf<ObjectEntityDetails>()
502 : nullptr};
503 int actualRank{actualType.Rank()};
504 bool actualIsPointer{evaluate::IsObjectPointer(actual)};
505 bool actualIsAssumedRank{evaluate::IsAssumedRank(actual)};
506 if (dummy.type.attrs().test(
507 characteristics::TypeAndShape::Attr::AssumedShape)) {
508 // 15.5.2.4(16)
509 if (actualIsAssumedRank) {
510 messages.Say(
511 "Assumed-rank actual argument may not be associated with assumed-shape %s"_err_en_US,
512 dummyName);
513 } else if (actualRank == 0) {
514 messages.Say(
515 "Scalar actual argument may not be associated with assumed-shape %s"_err_en_US,
516 dummyName);
517 } else if (actualIsAssumedSize && actualLastSymbol) {
518 evaluate::SayWithDeclaration(messages, *actualLastSymbol,
519 "Assumed-size array may not be associated with assumed-shape %s"_err_en_US,
520 dummyName);
521 }
522 } else if (dummyRank > 0) {
523 bool basicError{false};
524 if (actualRank == 0 && !actualIsAssumedRank &&
525 !dummyIsAllocatableOrPointer) {
526 // Actual is scalar, dummy is an array. F'2023 15.5.2.5p14
527 if (actualIsCoindexed) {
528 basicError = true;
529 messages.Say(
530 "Coindexed scalar actual argument must be associated with a scalar %s"_err_en_US,
531 dummyName);
532 }
533 bool actualIsArrayElement{IsArrayElement(actual)};
534 bool actualIsCKindCharacter{
535 actualType.type().category() == TypeCategory::Character &&
536 actualType.type().kind() == 1};
537 if (!actualIsCKindCharacter) {
538 if (!actualIsArrayElement &&
539 !(dummy.type.type().IsAssumedType() && dummyIsAssumedSize) &&
540 !dummyIsAssumedRank &&
541 !dummy.ignoreTKR.test(common::IgnoreTKR::Rank)) {
542 basicError = true;
543 messages.Say(
544 "Whole scalar actual argument may not be associated with a %s array"_err_en_US,
545 dummyName);
546 }
547 if (actualIsPolymorphic) {
548 basicError = true;
549 messages.Say(
550 "Polymorphic scalar may not be associated with a %s array"_err_en_US,
551 dummyName);
552 }
553 if (actualIsArrayElement && actualLastSymbol &&
554 !evaluate::IsContiguous(*actualLastSymbol, foldingContext) &&
555 !dummy.ignoreTKR.test(common::IgnoreTKR::Contiguous)) {
556 if (IsPointer(*actualLastSymbol)) {
557 basicError = true;
558 messages.Say(
559 "Element of pointer array may not be associated with a %s array"_err_en_US,
560 dummyName);
561 } else if (IsAssumedShape(*actualLastSymbol) &&
562 !dummy.ignoreTKR.test(common::IgnoreTKR::Contiguous)) {
563 basicError = true;
564 messages.Say(
565 "Element of assumed-shape array may not be associated with a %s array"_err_en_US,
566 dummyName);
567 }
568 }
569 }
570 }
571 // Storage sequence association (F'2023 15.5.2.12p3) checks.
572 // Character storage sequence association is checked in
573 // CheckCharacterActual().
574 if (!basicError &&
575 actualType.type().category() != TypeCategory::Character &&
576 CanAssociateWithStorageSequence(dummy) &&
577 !dummy.attrs.test(
578 characteristics::DummyDataObject::Attr::DeducedFromActual)) {
579 if (auto dummySize{evaluate::ToInt64(evaluate::Fold(
580 foldingContext, evaluate::GetSize(dummy.type.shape())))}) {
581 if (actualRank == 0 && !actualIsAssumedRank) {
582 if (evaluate::IsArrayElement(actual)) {
583 // Actual argument is a scalar array element
584 evaluate::DesignatorFolder folder{
585 context.foldingContext(), /*getLastComponent=*/true};
586 if (auto actualOffset{folder.FoldDesignator(actual)}) {
587 std::optional<std::int64_t> actualElements;
588 if (static_cast<std::size_t>(actualOffset->offset()) >=
589 actualOffset->symbol().size() ||
590 !evaluate::IsContiguous(
591 actualOffset->symbol(), foldingContext)) {
592 actualElements = 1;
593 } else if (auto actualSymType{evaluate::DynamicType::From(
594 actualOffset->symbol())}) {
595 if (auto actualSymTypeBytes{
596 evaluate::ToInt64(evaluate::Fold(foldingContext,
597 actualSymType->MeasureSizeInBytes(
598 foldingContext, false)))};
599 actualSymTypeBytes && *actualSymTypeBytes > 0) {
600 actualElements = (static_cast<std::int64_t>(
601 actualOffset->symbol().size()) -
602 actualOffset->offset()) /
603 *actualSymTypeBytes;
604 }
605 }
606 if (actualElements && *actualElements < *dummySize &&
607 (extentErrors ||
608 context.ShouldWarn(
609 common::UsageWarning::ShortArrayActual))) {
610 auto msg{
611 "Actual argument has fewer elements remaining in storage sequence (%jd) than %s array (%jd)"_warn_en_US};
612 if (extentErrors) {
613 msg.set_severity(parser::Severity::Error);
614 }
615 messages.Say(std::move(msg),
616 static_cast<std::intmax_t>(*actualElements), dummyName,
617 static_cast<std::intmax_t>(*dummySize));
618 }
619 }
620 }
621 } else { // actualRank > 0 || actualIsAssumedRank
622 if (auto actualSize{evaluate::ToInt64(evaluate::Fold(
623 foldingContext, evaluate::GetSize(actualType.shape())))};
624 actualSize && *actualSize < *dummySize &&
625 (extentErrors ||
626 context.ShouldWarn(common::UsageWarning::ShortArrayActual))) {
627 auto msg{
628 "Actual argument array has fewer elements (%jd) than %s array (%jd)"_warn_en_US};
629 if (extentErrors) {
630 msg.set_severity(parser::Severity::Error);
631 }
632 messages.Say(std::move(msg),
633 static_cast<std::intmax_t>(*actualSize), dummyName,
634 static_cast<std::intmax_t>(*dummySize));
635 }
636 }
637 }
638 }
639 }
640 if (actualLastObject && actualLastObject->IsCoarray() &&
641 IsAllocatable(*actualLastSymbol) && dummy.intent == common::Intent::Out &&
642 !(intrinsic &&
643 evaluate::AcceptsIntentOutAllocatableCoarray(
644 intrinsic->name))) { // C846
645 messages.Say(
646 "ALLOCATABLE coarray '%s' may not be associated with INTENT(OUT) %s"_err_en_US,
647 actualLastSymbol->name(), dummyName);
648 }
649
650 // Definability
651 bool actualIsVariable{evaluate::IsVariable(actual)};
652 if (scope) {
653 std::optional<parser::MessageFixedText> undefinableMessage;
654 if (dummy.intent == common::Intent::Out) {
655 undefinableMessage =
656 "Actual argument associated with INTENT(OUT) %s is not definable"_err_en_US;
657 } else if (dummy.intent == common::Intent::InOut) {
658 undefinableMessage =
659 "Actual argument associated with INTENT(IN OUT) %s is not definable"_err_en_US;
660 } else if (context.ShouldWarn(common::LanguageFeature::
661 UndefinableAsynchronousOrVolatileActual)) {
662 if (dummy.attrs.test(
663 characteristics::DummyDataObject::Attr::Asynchronous)) {
664 undefinableMessage =
665 "Actual argument associated with ASYNCHRONOUS %s is not definable"_warn_en_US;
666 } else if (dummy.attrs.test(
667 characteristics::DummyDataObject::Attr::Volatile)) {
668 undefinableMessage =
669 "Actual argument associated with VOLATILE %s is not definable"_warn_en_US;
670 }
671 }
672 if (undefinableMessage) {
673 // Problems with polymorphism are caught in the callee's definition.
674 DefinabilityFlags flags{DefinabilityFlag::PolymorphicOkInPure};
675 if (isElemental) { // 15.5.2.4(21)
676 flags.set(DefinabilityFlag::VectorSubscriptIsOk);
677 }
678 if (actualIsPointer && dummyIsPointer) { // 19.6.8
679 flags.set(DefinabilityFlag::PointerDefinition);
680 }
681 if (auto whyNot{WhyNotDefinable(messages.at(), *scope, flags, actual)}) {
682 if (whyNot->IsFatal()) {
683 if (auto *msg{
684 messages.Say(std::move(*undefinableMessage), dummyName)}) {
685 msg->Attach(
686 std::move(whyNot->set_severity(parser::Severity::Because)));
687 }
688 } else {
689 messages.Say(std::move(*whyNot));
690 }
691 }
692 }
693 }
694
695 // Cases when temporaries might be needed but must not be permitted.
696 bool actualIsContiguous{IsSimplyContiguous(actual, foldingContext)};
697 bool dummyIsAssumedShape{dummy.type.attrs().test(
698 characteristics::TypeAndShape::Attr::AssumedShape)};
699 bool dummyIsContiguous{
700 dummy.attrs.test(characteristics::DummyDataObject::Attr::Contiguous)};
701 if ((actualIsAsynchronous || actualIsVolatile) &&
702 (dummyIsAsynchronous || dummyIsVolatile) && !dummyIsValue) {
703 if (actualIsCoindexed) { // C1538
704 messages.Say(
705 "Coindexed ASYNCHRONOUS or VOLATILE actual argument may not be associated with %s with ASYNCHRONOUS or VOLATILE attributes unless VALUE"_err_en_US,
706 dummyName);
707 }
708 if ((actualRank > 0 || actualIsAssumedRank) && !actualIsContiguous) {
709 if (dummyIsContiguous ||
710 !(dummyIsAssumedShape || dummyIsAssumedRank ||
711 (actualIsPointer && dummyIsPointer))) { // C1539 & C1540
712 messages.Say(
713 "ASYNCHRONOUS or VOLATILE actual argument that is not simply contiguous may not be associated with a contiguous ASYNCHRONOUS or VOLATILE %s"_err_en_US,
714 dummyName);
715 }
716 }
717 }
718
719 // 15.5.2.6 -- dummy is ALLOCATABLE
720 bool actualIsAllocatable{evaluate::IsAllocatableDesignator(actual)};
721 bool dummyIsOptional{
722 dummy.attrs.test(characteristics::DummyDataObject::Attr::Optional)};
723 bool actualIsNull{evaluate::IsNullPointer(actual)};
724 if (dummyIsAllocatable) {
725 if (actualIsAllocatable) {
726 if (actualIsCoindexed && dummy.intent != common::Intent::In) {
727 messages.Say(
728 "ALLOCATABLE %s must have INTENT(IN) to be associated with a coindexed actual argument"_err_en_US,
729 dummyName);
730 }
731 } else if (actualIsNull) {
732 if (dummyIsOptional) {
733 } else if (dummy.intent == common::Intent::In) {
734 // Extension (Intel, NAG, XLF): a NULL() pointer is an acceptable
735 // actual argument for an INTENT(IN) allocatable dummy, and it
736 // is treated as an unassociated allocatable.
737 if (context.ShouldWarn(
738 common::LanguageFeature::NullActualForAllocatable)) {
739 messages.Say(
740 "Allocatable %s is associated with a null pointer"_port_en_US,
741 dummyName);
742 }
743 } else {
744 messages.Say(
745 "A null pointer may not be associated with allocatable %s without INTENT(IN)"_err_en_US,
746 dummyName);
747 }
748 } else {
749 messages.Say(
750 "ALLOCATABLE %s must be associated with an ALLOCATABLE actual argument"_err_en_US,
751 dummyName);
752 }
753 if (!actualIsCoindexed && actualLastSymbol &&
754 actualLastSymbol->Corank() != dummy.type.corank()) {
755 messages.Say(
756 "ALLOCATABLE %s has corank %d but actual argument has corank %d"_err_en_US,
757 dummyName, dummy.type.corank(), actualLastSymbol->Corank());
758 }
759 }
760
761 // 15.5.2.7 -- dummy is POINTER
762 if (dummyIsPointer) {
763 if (actualIsPointer || dummy.intent == common::Intent::In) {
764 if (scope) {
765 semantics::CheckPointerAssignment(context, messages.at(), dummyName,
766 dummy, actual, *scope,
767 /*isAssumedRank=*/dummyIsAssumedRank);
768 }
769 } else if (!actualIsPointer) {
770 messages.Say(
771 "Actual argument associated with POINTER %s must also be POINTER unless INTENT(IN)"_err_en_US,
772 dummyName);
773 }
774 }
775
776 // 15.5.2.5 -- actual & dummy are both POINTER or both ALLOCATABLE
777 // For INTENT(IN), and for a polymorphic actual being associated with a
778 // monomorphic dummy, we relax two checks that are in Fortran to
779 // prevent the callee from changing the type or to avoid having
780 // to use a descriptor.
781 if (!typesCompatible) {
782 // Don't pile on the errors emitted above
783 } else if ((actualIsPointer && dummyIsPointer) ||
784 (actualIsAllocatable && dummyIsAllocatable)) {
785 bool actualIsUnlimited{actualType.type().IsUnlimitedPolymorphic()};
786 bool dummyIsUnlimited{dummy.type.type().IsUnlimitedPolymorphic()};
787 bool checkTypeCompatibility{true};
788 if (actualIsUnlimited != dummyIsUnlimited) {
789 checkTypeCompatibility = false;
790 if (dummyIsUnlimited && dummy.intent == common::Intent::In &&
791 context.IsEnabled(common::LanguageFeature::RelaxedIntentInChecking)) {
792 if (context.ShouldWarn(
793 common::LanguageFeature::RelaxedIntentInChecking)) {
794 messages.Say(
795 "If a POINTER or ALLOCATABLE dummy or actual argument is unlimited polymorphic, both should be so"_port_en_US);
796 }
797 } else {
798 messages.Say(
799 "If a POINTER or ALLOCATABLE dummy or actual argument is unlimited polymorphic, both must be so"_err_en_US);
800 }
801 } else if (dummyIsPolymorphic != actualIsPolymorphic) {
802 if (dummyIsPolymorphic && dummy.intent == common::Intent::In &&
803 context.IsEnabled(common::LanguageFeature::RelaxedIntentInChecking)) {
804 if (context.ShouldWarn(
805 common::LanguageFeature::RelaxedIntentInChecking)) {
806 messages.Say(
807 "If a POINTER or ALLOCATABLE dummy or actual argument is polymorphic, both should be so"_port_en_US);
808 }
809 } else if (actualIsPolymorphic &&
810 context.IsEnabled(common::LanguageFeature::
811 PolymorphicActualAllocatableOrPointerToMonomorphicDummy)) {
812 if (context.ShouldWarn(common::LanguageFeature::
813 PolymorphicActualAllocatableOrPointerToMonomorphicDummy)) {
814 messages.Say(
815 "If a POINTER or ALLOCATABLE actual argument is polymorphic, the corresponding dummy argument should also be so"_port_en_US);
816 }
817 } else {
818 checkTypeCompatibility = false;
819 messages.Say(
820 "If a POINTER or ALLOCATABLE dummy or actual argument is polymorphic, both must be so"_err_en_US);
821 }
822 }
823 if (checkTypeCompatibility && !actualIsUnlimited) {
824 if (!actualType.type().IsTkCompatibleWith(dummy.type.type())) {
825 if (dummy.intent == common::Intent::In &&
826 context.IsEnabled(
827 common::LanguageFeature::RelaxedIntentInChecking)) {
828 if (context.ShouldWarn(
829 common::LanguageFeature::RelaxedIntentInChecking)) {
830 messages.Say(
831 "POINTER or ALLOCATABLE dummy and actual arguments should have the same declared type and kind"_port_en_US);
832 }
833 } else {
834 messages.Say(
835 "POINTER or ALLOCATABLE dummy and actual arguments must have the same declared type and kind"_err_en_US);
836 }
837 }
838 // 15.5.2.5(4)
839 const auto *derived{evaluate::GetDerivedTypeSpec(actualType.type())};
840 if ((derived &&
841 !DefersSameTypeParameters(*derived,
842 *evaluate::GetDerivedTypeSpec(dummy.type.type()))) ||
843 dummy.type.type().HasDeferredTypeParameter() !=
844 actualType.type().HasDeferredTypeParameter()) {
845 messages.Say(
846 "Dummy and actual arguments must defer the same type parameters when POINTER or ALLOCATABLE"_err_en_US);
847 }
848 }
849 }
850
851 // 15.5.2.8 -- coarray dummy arguments
852 if (dummy.type.corank() > 0) {
853 if (actualType.corank() == 0) {
854 messages.Say(
855 "Actual argument associated with coarray %s must be a coarray"_err_en_US,
856 dummyName);
857 }
858 if (dummyIsVolatile) {
859 if (!actualIsVolatile) {
860 messages.Say(
861 "non-VOLATILE coarray may not be associated with VOLATILE coarray %s"_err_en_US,
862 dummyName);
863 }
864 } else {
865 if (actualIsVolatile) {
866 messages.Say(
867 "VOLATILE coarray may not be associated with non-VOLATILE coarray %s"_err_en_US,
868 dummyName);
869 }
870 }
871 if (actualRank == dummyRank && !actualIsContiguous) {
872 if (dummyIsContiguous) {
873 messages.Say(
874 "Actual argument associated with a CONTIGUOUS coarray %s must be simply contiguous"_err_en_US,
875 dummyName);
876 } else if (!dummyIsAssumedShape && !dummyIsAssumedRank) {
877 messages.Say(
878 "Actual argument associated with coarray %s (not assumed shape or rank) must be simply contiguous"_err_en_US,
879 dummyName);
880 }
881 }
882 }
883
884 // NULL(MOLD=) checking for non-intrinsic procedures
885 if (!intrinsic && !dummyIsAllocatableOrPointer && !dummyIsOptional &&
886 actualIsNull) {
887 messages.Say(
888 "Actual argument associated with %s may not be null pointer %s"_err_en_US,
889 dummyName, actual.AsFortran());
890 }
891
892 // Warn about dubious actual argument association with a TARGET dummy
893 // argument
894 if (dummy.attrs.test(characteristics::DummyDataObject::Attr::Target) &&
895 context.ShouldWarn(common::UsageWarning::NonTargetPassedToTarget)) {
896 bool actualIsTemp{!actualIsVariable || HasVectorSubscript(actual) ||
897 evaluate::ExtractCoarrayRef(actual)};
898 if (actualIsTemp) {
899 messages.Say(
900 "Any pointer associated with TARGET %s during this call will not be associated with the value of '%s' afterwards"_warn_en_US,
901 dummyName, actual.AsFortran());
902 } else {
903 auto actualSymbolVector{GetSymbolVector(actual)};
904 if (!evaluate::GetLastTarget(actualSymbolVector)) {
905 messages.Say(
906 "Any pointer associated with TARGET %s during this call must not be used afterwards, as '%s' is not a target"_warn_en_US,
907 dummyName, actual.AsFortran());
908 }
909 }
910 }
911
912 // CUDA specific checks
913 // TODO: These are disabled in OpenACC constructs, which may not be
914 // correct when the target is not a GPU.
915 if (!intrinsic &&
916 !dummy.attrs.test(characteristics::DummyDataObject::Attr::Value) &&
917 !FindOpenACCConstructContaining(scope)) {
918 std::optional<common::CUDADataAttr> actualDataAttr, dummyDataAttr;
919 if (const auto *actualObject{actualLastSymbol
920 ? actualLastSymbol->detailsIf<ObjectEntityDetails>()
921 : nullptr}) {
922 actualDataAttr = actualObject->cudaDataAttr();
923 }
924 dummyDataAttr = dummy.cudaDataAttr;
925 // Treat MANAGED like DEVICE for nonallocatable nonpointer arguments to
926 // device subprograms
927 if (procedure.cudaSubprogramAttrs.value_or(
928 common::CUDASubprogramAttrs::Host) !=
929 common::CUDASubprogramAttrs::Host &&
930 !dummy.attrs.test(
931 characteristics::DummyDataObject::Attr::Allocatable) &&
932 !dummy.attrs.test(characteristics::DummyDataObject::Attr::Pointer)) {
933 if (!dummyDataAttr || *dummyDataAttr == common::CUDADataAttr::Managed) {
934 dummyDataAttr = common::CUDADataAttr::Device;
935 }
936 if ((!actualDataAttr && FindCUDADeviceContext(scope)) ||
937 (actualDataAttr &&
938 *actualDataAttr == common::CUDADataAttr::Managed)) {
939 actualDataAttr = common::CUDADataAttr::Device;
940 }
941 }
942 if (!common::AreCompatibleCUDADataAttrs(dummyDataAttr, actualDataAttr,
943 dummy.ignoreTKR,
944 /*allowUnifiedMatchingRule=*/true, &context.languageFeatures())) {
945 auto toStr{[](std::optional<common::CUDADataAttr> x) {
946 return x ? "ATTRIBUTES("s +
947 parser::ToUpperCaseLetters(common::EnumToString(*x)) + ")"s
948 : "no CUDA data attribute"s;
949 }};
950 messages.Say(
951 "%s has %s but its associated actual argument has %s"_err_en_US,
952 dummyName, toStr(dummyDataAttr), toStr(actualDataAttr));
953 }
954 }
955
956 // Warning for breaking F'2023 change with character allocatables
957 if (intrinsic && dummy.intent != common::Intent::In) {
958 WarnOnDeferredLengthCharacterScalar(
959 context, &actual, messages.at(), dummyName.c_str());
960 }
961
962 // %VAL() and %REF() checking for explicit interface
963 if ((arg.isPercentRef() || arg.isPercentVal()) &&
964 dummy.IsPassedByDescriptor(procedure.IsBindC())) {
965 messages.Say(
966 "%%VAL or %%REF are not allowed for %s that must be passed by means of a descriptor"_err_en_US,
967 dummyName);
968 }
969 if (arg.isPercentVal() &&
970 (!actualType.type().IsLengthlessIntrinsicType() ||
971 actualType.Rank() != 0)) {
972 messages.Say(
973 "%VAL argument must be a scalar numeric or logical expression"_err_en_US);
974 }
975 }
976
977 static void CheckProcedureArg(evaluate::ActualArgument &arg,
978 const characteristics::Procedure &proc,
979 const characteristics::DummyProcedure &dummy, const std::string &dummyName,
980 SemanticsContext &context, bool ignoreImplicitVsExplicit) {
981 evaluate::FoldingContext &foldingContext{context.foldingContext()};
982 parser::ContextualMessages &messages{foldingContext.messages()};
983 auto restorer{
984 messages.SetLocation(arg.sourceLocation().value_or(messages.at()))};
985 const characteristics::Procedure &interface { dummy.procedure.value() };
986 if (const auto *expr{arg.UnwrapExpr()}) {
987 bool dummyIsPointer{
988 dummy.attrs.test(characteristics::DummyProcedure::Attr::Pointer)};
989 const auto *argProcDesignator{
990 std::get_if<evaluate::ProcedureDesignator>(&expr->u)};
991 const auto *argProcSymbol{
992 argProcDesignator ? argProcDesignator->GetSymbol() : nullptr};
993 if (argProcSymbol) {
994 if (const auto *subp{
995 argProcSymbol->GetUltimate().detailsIf<SubprogramDetails>()}) {
996 if (subp->stmtFunction()) {
997 evaluate::SayWithDeclaration(messages, *argProcSymbol,
998 "Statement function '%s' may not be passed as an actual argument"_err_en_US,
999 argProcSymbol->name());
1000 return;
1001 }
1002 } else if (argProcSymbol->has<ProcBindingDetails>()) {
1003 if (!context.IsEnabled(common::LanguageFeature::BindingAsProcedure) ||
1004 context.ShouldWarn(common::LanguageFeature::BindingAsProcedure)) {
1005 parser::MessageFixedText msg{
1006 "Procedure binding '%s' passed as an actual argument"_port_en_US};
1007 if (!context.IsEnabled(common::LanguageFeature::BindingAsProcedure)) {
1008 msg.set_severity(parser::Severity::Error);
1009 }
1010 evaluate::SayWithDeclaration(
1011 messages, *argProcSymbol, std::move(msg), argProcSymbol->name());
1012 }
1013 }
1014 }
1015 if (auto argChars{characteristics::DummyArgument::FromActual(
1016 "actual argument", *expr, foldingContext,
1017 /*forImplicitInterface=*/true)}) {
1018 if (!argChars->IsTypelessIntrinsicDummy()) {
1019 if (auto *argProc{
1020 std::get_if<characteristics::DummyProcedure>(&argChars->u)}) {
1021 characteristics::Procedure &argInterface{argProc->procedure.value()};
1022 argInterface.attrs.reset(
1023 characteristics::Procedure::Attr::NullPointer);
1024 if (!argProcSymbol || argProcSymbol->attrs().test(Attr::INTRINSIC)) {
1025 // It's ok to pass ELEMENTAL unrestricted intrinsic functions.
1026 argInterface.attrs.reset(
1027 characteristics::Procedure::Attr::Elemental);
1028 } else if (argInterface.attrs.test(
1029 characteristics::Procedure::Attr::Elemental)) {
1030 if (argProcSymbol) { // C1533
1031 evaluate::SayWithDeclaration(messages, *argProcSymbol,
1032 "Non-intrinsic ELEMENTAL procedure '%s' may not be passed as an actual argument"_err_en_US,
1033 argProcSymbol->name());
1034 return; // avoid piling on with checks below
1035 } else {
1036 argInterface.attrs.reset(
1037 characteristics::Procedure::Attr::NullPointer);
1038 }
1039 }
1040 if (interface.HasExplicitInterface()) {
1041 std::string whyNot;
1042 std::optional<std::string> warning;
1043 if (!interface.IsCompatibleWith(argInterface,
1044 ignoreImplicitVsExplicit, &whyNot,
1045 /*specificIntrinsic=*/nullptr, &warning)) {
1046 // 15.5.2.9(1): Explicit interfaces must match
1047 if (argInterface.HasExplicitInterface()) {
1048 messages.Say(
1049 "Actual procedure argument has interface incompatible with %s: %s"_err_en_US,
1050 dummyName, whyNot);
1051 return;
1052 } else if (proc.IsPure()) {
1053 messages.Say(
1054 "Actual procedure argument for %s of a PURE procedure must have an explicit interface"_err_en_US,
1055 dummyName);
1056 } else if (context.ShouldWarn(
1057 common::UsageWarning::ImplicitInterfaceActual)) {
1058 messages.Say(
1059 "Actual procedure argument has an implicit interface which is not known to be compatible with %s which has an explicit interface"_warn_en_US,
1060 dummyName);
1061 }
1062 } else if (warning &&
1063 context.ShouldWarn(common::UsageWarning::ProcDummyArgShapes)) {
1064 messages.Say(
1065 "Actual procedure argument has possible interface incompatibility with %s: %s"_warn_en_US,
1066 dummyName, std::move(*warning));
1067 }
1068 } else { // 15.5.2.9(2,3)
1069 if (interface.IsSubroutine() && argInterface.IsFunction()) {
1070 messages.Say(
1071 "Actual argument associated with procedure %s is a function but must be a subroutine"_err_en_US,
1072 dummyName);
1073 } else if (interface.IsFunction()) {
1074 if (argInterface.IsFunction()) {
1075 std::string whyNot;
1076 if (!interface.functionResult->IsCompatibleWith(
1077 *argInterface.functionResult, &whyNot)) {
1078 messages.Say(
1079 "Actual argument function associated with procedure %s is not compatible: %s"_err_en_US,
1080 dummyName, whyNot);
1081 }
1082 } else if (argInterface.IsSubroutine()) {
1083 messages.Say(
1084 "Actual argument associated with procedure %s is a subroutine but must be a function"_err_en_US,
1085 dummyName);
1086 }
1087 }
1088 }
1089 } else {
1090 messages.Say(
1091 "Actual argument associated with procedure %s is not a procedure"_err_en_US,
1092 dummyName);
1093 }
1094 } else if (IsNullPointer(*expr)) {
1095 if (!dummyIsPointer &&
1096 !dummy.attrs.test(
1097 characteristics::DummyProcedure::Attr::Optional)) {
1098 messages.Say(
1099 "Actual argument associated with procedure %s is a null pointer"_err_en_US,
1100 dummyName);
1101 }
1102 } else {
1103 messages.Say(
1104 "Actual argument associated with procedure %s is typeless"_err_en_US,
1105 dummyName);
1106 }
1107 }
1108 if (dummyIsPointer && dummy.intent != common::Intent::In) {
1109 const Symbol *last{GetLastSymbol(*expr)};
1110 if (last && IsProcedurePointer(*last)) {
1111 if (dummy.intent != common::Intent::Default &&
1112 IsIntentIn(last->GetUltimate())) { // 19.6.8
1113 messages.Say(
1114 "Actual argument associated with procedure pointer %s may not be INTENT(IN)"_err_en_US,
1115 dummyName);
1116 }
1117 } else if (!(dummy.intent == common::Intent::Default &&
1118 IsNullProcedurePointer(*expr))) {
1119 // 15.5.2.9(5) -- dummy procedure POINTER
1120 // Interface compatibility has already been checked above
1121 messages.Say(
1122 "Actual argument associated with procedure pointer %s must be a pointer unless INTENT(IN)"_err_en_US,
1123 dummyName);
1124 }
1125 }
1126 } else {
1127 messages.Say(
1128 "Assumed-type argument may not be forwarded as procedure %s"_err_en_US,
1129 dummyName);
1130 }
1131 }
1132
1133 // Allow BOZ literal actual arguments when they can be converted to a known
1134 // dummy argument type
1135 static void ConvertBOZLiteralArg(
1136 evaluate::ActualArgument &arg, const evaluate::DynamicType &type) {
1137 if (auto *expr{arg.UnwrapExpr()}) {
1138 if (IsBOZLiteral(*expr)) {
1139 if (auto converted{evaluate::ConvertToType(type, SomeExpr{*expr})}) {
1140 arg = std::move(*converted);
1141 }
1142 }
1143 }
1144 }
1145
1146 static void CheckExplicitInterfaceArg(evaluate::ActualArgument &arg,
1147 const characteristics::DummyArgument &dummy,
1148 const characteristics::Procedure &proc, SemanticsContext &context,
1149 const Scope *scope, const evaluate::SpecificIntrinsic *intrinsic,
1150 bool allowActualArgumentConversions, bool extentErrors,
1151 bool ignoreImplicitVsExplicit) {
1152 evaluate::FoldingContext &foldingContext{context.foldingContext()};
1153 auto &messages{foldingContext.messages()};
1154 std::string dummyName{"dummy argument"};
1155 if (!dummy.name.empty()) {
1156 dummyName += " '"s + parser::ToLowerCaseLetters(dummy.name) + "='";
1157 }
1158 auto restorer{
1159 messages.SetLocation(arg.sourceLocation().value_or(messages.at()))};
1160 auto CheckActualArgForLabel = [&](evaluate::ActualArgument &arg) {
1161 if (arg.isAlternateReturn()) {
1162 messages.Say(
1163 "Alternate return label '%d' cannot be associated with %s"_err_en_US,
1164 arg.GetLabel(), dummyName);
1165 return false;
1166 } else {
1167 return true;
1168 }
1169 };
1170 common::visit(
1171 common::visitors{
1172 [&](const characteristics::DummyDataObject &object) {
1173 if (CheckActualArgForLabel(arg)) {
1174 ConvertBOZLiteralArg(arg, object.type.type());
1175 if (auto *expr{arg.UnwrapExpr()}) {
1176 if (auto type{characteristics::TypeAndShape::Characterize(
1177 *expr, foldingContext)}) {
1178 arg.set_dummyIntent(object.intent);
1179 bool isElemental{
1180 object.type.Rank() == 0 && proc.IsElemental()};
1181 CheckExplicitDataArg(object, dummyName, *expr, *type,
1182 isElemental, context, foldingContext, scope, intrinsic,
1183 allowActualArgumentConversions, extentErrors, proc, arg);
1184 } else if (object.type.type().IsTypelessIntrinsicArgument() &&
1185 IsBOZLiteral(*expr)) {
1186 // ok
1187 } else if (object.type.type().IsTypelessIntrinsicArgument() &&
1188 evaluate::IsNullObjectPointer(*expr)) {
1189 // ok, ASSOCIATED(NULL(without MOLD=))
1190 } else if (object.type.attrs().test(characteristics::
1191 TypeAndShape::Attr::AssumedRank) &&
1192 evaluate::IsNullObjectPointer(*expr) &&
1193 (object.attrs.test(
1194 characteristics::DummyDataObject::Attr::Allocatable) ||
1195 object.attrs.test(
1196 characteristics::DummyDataObject::Attr::Pointer) ||
1197 !object.attrs.test(characteristics::DummyDataObject::
1198 Attr::Optional))) {
1199 messages.Say(
1200 "NULL() without MOLD= must not be associated with an assumed-rank dummy argument that is ALLOCATABLE, POINTER, or non-OPTIONAL"_err_en_US);
1201 } else if ((object.attrs.test(characteristics::DummyDataObject::
1202 Attr::Pointer) ||
1203 object.attrs.test(characteristics::
1204 DummyDataObject::Attr::Optional)) &&
1205 evaluate::IsNullObjectPointer(*expr)) {
1206 // FOO(NULL(without MOLD=))
1207 if (object.type.type().IsAssumedLengthCharacter()) {
1208 messages.Say(
1209 "Actual argument associated with %s is a NULL() pointer without a MOLD= to provide a character length"_err_en_US,
1210 dummyName);
1211 } else if (const DerivedTypeSpec *
1212 derived{GetDerivedTypeSpec(object.type.type())}) {
1213 for (const auto &[pName, pValue] : derived->parameters()) {
1214 if (pValue.isAssumed()) {
1215 messages.Say(
1216 "Actual argument associated with %s is a NULL() pointer without a MOLD= to provide a value for the assumed type parameter '%s'"_err_en_US,
1217 dummyName, pName.ToString());
1218 break;
1219 }
1220 }
1221 }
1222 } else if (object.attrs.test(characteristics::DummyDataObject::
1223 Attr::Allocatable) &&
1224 evaluate::IsNullPointer(*expr)) {
1225 if (object.intent == common::Intent::In) {
1226 // Extension (Intel, NAG, XLF); see CheckExplicitDataArg.
1227 if (context.ShouldWarn(common::LanguageFeature::
1228 NullActualForAllocatable)) {
1229 messages.Say(
1230 "Allocatable %s is associated with NULL()"_port_en_US,
1231 dummyName);
1232 }
1233 } else {
1234 messages.Say(
1235 "NULL() actual argument '%s' may not be associated with allocatable %s without INTENT(IN)"_err_en_US,
1236 expr->AsFortran(), dummyName);
1237 }
1238 } else {
1239 messages.Say(
1240 "Actual argument '%s' associated with %s is not a variable or typed expression"_err_en_US,
1241 expr->AsFortran(), dummyName);
1242 }
1243 } else {
1244 const Symbol &assumed{DEREF(arg.GetAssumedTypeDummy())};
1245 if (!object.type.type().IsAssumedType()) {
1246 messages.Say(
1247 "Assumed-type '%s' may be associated only with an assumed-type %s"_err_en_US,
1248 assumed.name(), dummyName);
1249 } else if (object.type.attrs().test(characteristics::
1250 TypeAndShape::Attr::AssumedRank) &&
1251 !IsAssumedShape(assumed) &&
1252 !evaluate::IsAssumedRank(assumed)) {
1253 messages.Say( // C711
1254 "Assumed-type '%s' must be either assumed shape or assumed rank to be associated with assumed rank %s"_err_en_US,
1255 assumed.name(), dummyName);
1256 }
1257 }
1258 }
1259 },
1260 [&](const characteristics::DummyProcedure &dummy) {
1261 if (CheckActualArgForLabel(arg)) {
1262 CheckProcedureArg(arg, proc, dummy, dummyName, context,
1263 ignoreImplicitVsExplicit);
1264 }
1265 },
1266 [&](const characteristics::AlternateReturn &) {
1267 // All semantic checking is done elsewhere
1268 },
1269 },
1270 dummy.u);
1271 }
1272
1273 static void RearrangeArguments(const characteristics::Procedure &proc,
1274 evaluate::ActualArguments &actuals, parser::ContextualMessages &messages) {
1275 CHECK(proc.HasExplicitInterface());
1276 if (actuals.size() < proc.dummyArguments.size()) {
1277 actuals.resize(proc.dummyArguments.size());
1278 } else if (actuals.size() > proc.dummyArguments.size()) {
1279 messages.Say(
1280 "Too many actual arguments (%zd) passed to procedure that expects only %zd"_err_en_US,
1281 actuals.size(), proc.dummyArguments.size());
1282 }
1283 std::map<std::string, evaluate::ActualArgument> kwArgs;
1284 bool anyKeyword{false};
1285 int which{1};
1286 for (auto &x : actuals) {
1287 if (!x) {
1288 } else if (x->keyword()) {
1289 auto emplaced{
1290 kwArgs.try_emplace(x->keyword()->ToString(), std::move(*x))};
1291 if (!emplaced.second) {
1292 messages.Say(*x->keyword(),
1293 "Argument keyword '%s=' appears on more than one effective argument in this procedure reference"_err_en_US,
1294 *x->keyword());
1295 }
1296 x.reset();
1297 anyKeyword = true;
1298 } else if (anyKeyword) {
1299 messages.Say(x ? x->sourceLocation() : std::nullopt,
1300 "Actual argument #%d without a keyword may not follow any actual argument with a keyword"_err_en_US,
1301 which);
1302 }
1303 ++which;
1304 }
1305 if (!kwArgs.empty()) {
1306 int index{0};
1307 for (const auto &dummy : proc.dummyArguments) {
1308 if (!dummy.name.empty()) {
1309 auto iter{kwArgs.find(dummy.name)};
1310 if (iter != kwArgs.end()) {
1311 evaluate::ActualArgument &x{iter->second};
1312 if (actuals[index]) {
1313 messages.Say(*x.keyword(),
1314 "Keyword argument '%s=' has already been specified positionally (#%d) in this procedure reference"_err_en_US,
1315 *x.keyword(), index + 1);
1316 } else {
1317 actuals[index] = std::move(x);
1318 }
1319 kwArgs.erase(iter);
1320 }
1321 }
1322 ++index;
1323 }
1324 for (auto &bad : kwArgs) {
1325 evaluate::ActualArgument &x{bad.second};
1326 messages.Say(*x.keyword(),
1327 "Argument keyword '%s=' is not recognized for this procedure reference"_err_en_US,
1328 *x.keyword());
1329 }
1330 }
1331 }
1332
1333 // 15.8.1(3) -- In a reference to an elemental procedure, if any argument is an
1334 // array, each actual argument that corresponds to an INTENT(OUT) or
1335 // INTENT(INOUT) dummy argument shall be an array. The actual argument to an
1336 // ELEMENTAL procedure must conform.
1337 static bool CheckElementalConformance(parser::ContextualMessages &messages,
1338 const characteristics::Procedure &proc, evaluate::ActualArguments &actuals,
1339 evaluate::FoldingContext &context) {
1340 std::optional<evaluate::Shape> shape;
1341 std::string shapeName;
1342 int index{0};
1343 bool hasArrayArg{false};
1344 for (const auto &arg : actuals) {
1345 if (arg && !arg->isAlternateReturn() && arg->Rank() > 0) {
1346 hasArrayArg = true;
1347 break;
1348 }
1349 }
1350 for (const auto &arg : actuals) {
1351 const auto &dummy{proc.dummyArguments.at(index++)};
1352 if (arg) {
1353 if (const auto *expr{arg->UnwrapExpr()}) {
1354 if (auto argShape{evaluate::GetShape(context, *expr)}) {
1355 if (GetRank(*argShape) > 0) {
1356 std::string argName{"actual argument ("s + expr->AsFortran() +
1357 ") corresponding to dummy argument #" + std::to_string(index) +
1358 " ('" + dummy.name + "')"};
1359 if (shape) {
1360 auto tristate{evaluate::CheckConformance(messages, *shape,
1361 *argShape, evaluate::CheckConformanceFlags::None,
1362 shapeName.c_str(), argName.c_str())};
1363 if (tristate && !*tristate) {
1364 return false;
1365 }
1366 } else {
1367 shape = std::move(argShape);
1368 shapeName = argName;
1369 }
1370 } else if ((dummy.GetIntent() == common::Intent::Out ||
1371 dummy.GetIntent() == common::Intent::InOut) &&
1372 hasArrayArg) {
1373 messages.Say(
1374 "In an elemental procedure reference with at least one array argument, actual argument %s that corresponds to an INTENT(OUT) or INTENT(INOUT) dummy argument must be an array"_err_en_US,
1375 expr->AsFortran());
1376 }
1377 }
1378 }
1379 }
1380 }
1381 return true;
1382 }
1383
1384 // ASSOCIATED (16.9.16)
1385 static void CheckAssociated(evaluate::ActualArguments &arguments,
1386 SemanticsContext &semanticsContext, const Scope *scope) {
1387 evaluate::FoldingContext &foldingContext{semanticsContext.foldingContext()};
1388 parser::ContextualMessages &messages{foldingContext.messages()};
1389 bool ok{true};
1390 if (arguments.size() < 2) {
1391 return;
1392 }
1393 if (const auto &pointerArg{arguments[0]}) {
1394 if (const auto *pointerExpr{pointerArg->UnwrapExpr()}) {
1395 if (!IsPointer(*pointerExpr)) {
1396 messages.Say(pointerArg->sourceLocation(),
1397 "POINTER= argument of ASSOCIATED() must be a pointer"_err_en_US);
1398 return;
1399 }
1400 if (const auto &targetArg{arguments[1]}) {
1401 // The standard requires that the TARGET= argument, when present,
1402 // be a valid RHS for a pointer assignment that has the POINTER=
1403 // argument as its LHS. Some popular compilers misinterpret this
1404 // requirement more strongly than necessary, and actually validate
1405 // the POINTER= argument as if it were serving as the LHS of a pointer
1406 // assignment. This, perhaps unintentionally, excludes function
1407 // results, including NULL(), from being used there, as well as
1408 // INTENT(IN) dummy pointers. Detect these conditions and emit
1409 // portability warnings.
1410 if (semanticsContext.ShouldWarn(common::UsageWarning::Portability)) {
1411 if (!evaluate::ExtractDataRef(*pointerExpr) &&
1412 !evaluate::IsProcedurePointer(*pointerExpr)) {
1413 messages.Say(pointerArg->sourceLocation(),
1414 "POINTER= argument of ASSOCIATED() is required by some other compilers to be a pointer"_port_en_US);
1415 } else if (scope && !evaluate::UnwrapProcedureRef(*pointerExpr)) {
1416 if (auto whyNot{WhyNotDefinable(
1417 pointerArg->sourceLocation().value_or(messages.at()),
1418 *scope,
1419 DefinabilityFlags{DefinabilityFlag::PointerDefinition},
1420 *pointerExpr)}) {
1421 if (whyNot->IsFatal()) {
1422 if (auto *msg{messages.Say(pointerArg->sourceLocation(),
1423 "POINTER= argument of ASSOCIATED() is required by some other compilers to be a valid left-hand side of a pointer assignment statement"_port_en_US)}) {
1424 msg->Attach(std::move(
1425 whyNot->set_severity(parser::Severity::Because)));
1426 }
1427 } else {
1428 messages.Say(std::move(*whyNot));
1429 }
1430 }
1431 }
1432 }
1433 if (const auto *targetExpr{targetArg->UnwrapExpr()}) {
1434 if (IsProcedurePointer(*pointerExpr) &&
1435 !IsBareNullPointer(pointerExpr)) { // POINTER= is a procedure
1436 if (auto pointerProc{characteristics::Procedure::Characterize(
1437 *pointerExpr, foldingContext)}) {
1438 if (IsBareNullPointer(targetExpr)) {
1439 } else if (IsProcedurePointerTarget(*targetExpr)) {
1440 if (auto targetProc{characteristics::Procedure::Characterize(
1441 *targetExpr, foldingContext)}) {
1442 bool isCall{!!UnwrapProcedureRef(*targetExpr)};
1443 std::string whyNot;
1444 std::optional<std::string> warning;
1445 const auto *targetProcDesignator{
1446 evaluate::UnwrapExpr<evaluate::ProcedureDesignator>(
1447 *targetExpr)};
1448 const evaluate::SpecificIntrinsic *specificIntrinsic{
1449 targetProcDesignator
1450 ? targetProcDesignator->GetSpecificIntrinsic()
1451 : nullptr};
1452 std::optional<parser::MessageFixedText> msg{
1453 CheckProcCompatibility(isCall, pointerProc, &*targetProc,
1454 specificIntrinsic, whyNot, warning,
1455 /*ignoreImplicitVsExplicit=*/false)};
1456 if (!msg && warning &&
1457 semanticsContext.ShouldWarn(
1458 common::UsageWarning::ProcDummyArgShapes)) {
1459 msg =
1460 "Procedures '%s' and '%s' may not be completely compatible: %s"_warn_en_US;
1461 whyNot = std::move(*warning);
1462 } else if (msg &&
1463 msg->severity() != parser::Severity::Error &&
1464 !semanticsContext.ShouldWarn(
1465 common::UsageWarning::ProcPointerCompatibility)) {
1466 msg.reset();
1467 }
1468 if (msg) {
1469 msg->set_severity(parser::Severity::Warning);
1470 messages.Say(std::move(*msg),
1471 "pointer '" + pointerExpr->AsFortran() + "'",
1472 targetExpr->AsFortran(), whyNot);
1473 }
1474 }
1475 } else if (!IsNullProcedurePointer(*targetExpr)) {
1476 messages.Say(
1477 "POINTER= argument '%s' is a procedure pointer but the TARGET= argument '%s' is not a procedure or procedure pointer"_err_en_US,
1478 pointerExpr->AsFortran(), targetExpr->AsFortran());
1479 }
1480 }
1481 } else if (IsVariable(*targetExpr) || IsNullPointer(*targetExpr)) {
1482 // Object pointer and target
1483 if (ExtractDataRef(*targetExpr)) {
1484 if (SymbolVector symbols{GetSymbolVector(*targetExpr)};
1485 !evaluate::GetLastTarget(symbols)) {
1486 parser::Message *msg{messages.Say(targetArg->sourceLocation(),
1487 "TARGET= argument '%s' must have either the POINTER or the TARGET attribute"_err_en_US,
1488 targetExpr->AsFortran())};
1489 for (SymbolRef ref : symbols) {
1490 msg = evaluate::AttachDeclaration(msg, *ref);
1491 }
1492 } else if (HasVectorSubscript(*targetExpr) ||
1493 ExtractCoarrayRef(*targetExpr)) {
1494 messages.Say(targetArg->sourceLocation(),
1495 "TARGET= argument '%s' may not have a vector subscript or coindexing"_err_en_US,
1496 targetExpr->AsFortran());
1497 }
1498 }
1499 if (const auto pointerType{pointerArg->GetType()}) {
1500 if (const auto targetType{targetArg->GetType()}) {
1501 ok = pointerType->IsTkCompatibleWith(*targetType);
1502 }
1503 }
1504 } else {
1505 messages.Say(
1506 "POINTER= argument '%s' is an object pointer but the TARGET= argument '%s' is not a variable"_err_en_US,
1507 pointerExpr->AsFortran(), targetExpr->AsFortran());
1508 }
1509 if (!IsAssumedRank(*pointerExpr)) {
1510 if (IsAssumedRank(*targetExpr)) {
1511 messages.Say(
1512 "TARGET= argument '%s' may not be assumed-rank when POINTER= argument is not"_err_en_US,
1513 pointerExpr->AsFortran());
1514 } else if (pointerExpr->Rank() != targetExpr->Rank()) {
1515 messages.Say(
1516 "POINTER= argument and TARGET= argument have incompatible ranks %d and %d"_err_en_US,
1517 pointerExpr->Rank(), targetExpr->Rank());
1518 }
1519 }
1520 }
1521 }
1522 }
1523 } else {
1524 // No arguments to ASSOCIATED()
1525 ok = false;
1526 }
1527 if (!ok) {
1528 messages.Say(
1529 "Arguments of ASSOCIATED() must be a pointer and an optional valid target"_err_en_US);
1530 }
1531 }
1532
1533 // IMAGE_INDEX (F'2023 16.9.107)
1534 static void CheckImage_Index(evaluate::ActualArguments &arguments,
1535 parser::ContextualMessages &messages) {
1536 if (arguments[1] && arguments[0]) {
1537 if (const auto subArrShape{
1538 evaluate::GetShape(arguments[1]->UnwrapExpr())}) {
1539 if (const auto *coarrayArgSymbol{UnwrapWholeSymbolOrComponentDataRef(
1540 arguments[0]->UnwrapExpr())}) {
1541 const auto coarrayArgCorank = coarrayArgSymbol->Corank();
1542 if (const auto subArrSize = evaluate::ToInt64(*subArrShape->front())) {
1543 if (subArrSize != coarrayArgCorank) {
1544 messages.Say(arguments[1]->sourceLocation(),
1545 "The size of 'SUB=' (%jd) for intrinsic 'image_index' must be equal to the corank of 'COARRAY=' (%d)"_err_en_US,
1546 static_cast<std::int64_t>(*subArrSize), coarrayArgCorank);
1547 }
1548 }
1549 }
1550 }
1551 }
1552 }
1553
1554 // Ensure that any optional argument that might be absent at run time
1555 // does not require data conversion.
1556 static void CheckMaxMin(const characteristics::Procedure &proc,
1557 evaluate::ActualArguments &arguments,
1558 parser::ContextualMessages &messages) {
1559 if (proc.functionResult) {
1560 if (const auto *typeAndShape{proc.functionResult->GetTypeAndShape()}) {
1561 for (std::size_t j{2}; j < arguments.size(); ++j) {
1562 if (arguments[j]) {
1563 if (const auto *expr{arguments[j]->UnwrapExpr()};
1564 expr && evaluate::MayBePassedAsAbsentOptional(*expr)) {
1565 if (auto thisType{expr->GetType()}) {
1566 if (thisType->category() == TypeCategory::Character &&
1567 typeAndShape->type().category() == TypeCategory::Character &&
1568 thisType->kind() == typeAndShape->type().kind()) {
1569 // don't care about lengths
1570 } else if (*thisType != typeAndShape->type()) {
1571 messages.Say(arguments[j]->sourceLocation(),
1572 "An actual argument to MAX/MIN requiring data conversion may not be OPTIONAL, POINTER, or ALLOCATABLE"_err_en_US);
1573 }
1574 }
1575 }
1576 }
1577 }
1578 }
1579 }
1580 }
1581
1582 // MOVE_ALLOC (F'2023 16.9.147)
1583 static void CheckMove_Alloc(evaluate::ActualArguments &arguments,
1584 parser::ContextualMessages &messages) {
1585 if (arguments.size() >= 1) {
1586 evaluate::CheckForCoindexedObject(
1587 messages, arguments[0], "move_alloc", "from");
1588 }
1589 if (arguments.size() >= 2) {
1590 evaluate::CheckForCoindexedObject(
1591 messages, arguments[1], "move_alloc", "to");
1592 }
1593 if (arguments.size() >= 3) {
1594 evaluate::CheckForCoindexedObject(
1595 messages, arguments[2], "move_alloc", "stat");
1596 }
1597 if (arguments.size() >= 4) {
1598 evaluate::CheckForCoindexedObject(
1599 messages, arguments[3], "move_alloc", "errmsg");
1600 }
1601 if (arguments.size() >= 2 && arguments[0] && arguments[1]) {
1602 for (int j{0}; j < 2; ++j) {
1603 if (const Symbol *
1604 whole{UnwrapWholeSymbolOrComponentDataRef(arguments[j])};
1605 !whole || !IsAllocatable(whole->GetUltimate())) {
1606 messages.Say(*arguments[j]->sourceLocation(),
1607 "Argument #%d to MOVE_ALLOC must be allocatable"_err_en_US, j + 1);
1608 }
1609 }
1610 auto type0{arguments[0]->GetType()};
1611 auto type1{arguments[1]->GetType()};
1612 if (type0 && type1 && type0->IsPolymorphic() && !type1->IsPolymorphic()) {
1613 messages.Say(arguments[1]->sourceLocation(),
1614 "When MOVE_ALLOC(FROM=) is polymorphic, TO= must also be polymorphic"_err_en_US);
1615 }
1616 }
1617 }
1618
1619 // PRESENT (F'2023 16.9.163)
1620 static void CheckPresent(evaluate::ActualArguments &arguments,
1621 parser::ContextualMessages &messages) {
1622 if (arguments.size() == 1) {
1623 if (const auto &arg{arguments[0]}; arg) {
1624 const Symbol *symbol{nullptr};
1625 if (const auto *expr{arg->UnwrapExpr()}) {
1626 if (const auto *proc{
1627 std::get_if<evaluate::ProcedureDesignator>(&expr->u)}) {
1628 symbol = proc->GetSymbol();
1629 } else {
1630 symbol = evaluate::UnwrapWholeSymbolDataRef(*expr);
1631 }
1632 } else {
1633 symbol = arg->GetAssumedTypeDummy();
1634 }
1635 if (!symbol || !symbol->attrs().test(semantics::Attr::OPTIONAL)) {
1636 messages.Say(arg ? arg->sourceLocation() : messages.at(),
1637 "Argument of PRESENT() must be the name of a whole OPTIONAL dummy argument"_err_en_US);
1638 }
1639 }
1640 }
1641 }
1642
1643 // REDUCE (F'2023 16.9.173)
1644 static void CheckReduce(
1645 evaluate::ActualArguments &arguments, evaluate::FoldingContext &context) {
1646 std::optional<evaluate::DynamicType> arrayType;
1647 parser::ContextualMessages &messages{context.messages()};
1648 if (const auto &array{arguments[0]}) {
1649 arrayType = array->GetType();
1650 if (!arguments[/*identity=*/4]) {
1651 if (const auto *expr{array->UnwrapExpr()}) {
1652 if (auto shape{
1653 evaluate::GetShape(context, *expr, /*invariantOnly=*/false)}) {
1654 if (const auto &dim{arguments[2]}; dim && array->Rank() > 1) {
1655 // Partial reduction
1656 auto dimVal{evaluate::ToInt64(dim->UnwrapExpr())};
1657 std::int64_t j{0};
1658 int zeroDims{0};
1659 bool isSelectedDimEmpty{false};
1660 for (const auto &extent : *shape) {
1661 ++j;
1662 if (evaluate::ToInt64(extent) == 0) {
1663 ++zeroDims;
1664 isSelectedDimEmpty |= dimVal && j == *dimVal;
1665 }
1666 }
1667 if (isSelectedDimEmpty && zeroDims == 1) {
1668 messages.Say(
1669 "IDENTITY= must be present when DIM=%d and the array has zero extent on that dimension"_err_en_US,
1670 static_cast<int>(dimVal.value()));
1671 }
1672 } else { // no DIM= or DIM=1 on a vector: total reduction
1673 for (const auto &extent : *shape) {
1674 if (evaluate::ToInt64(extent) == 0) {
1675 messages.Say(
1676 "IDENTITY= must be present when the array is empty and the result is scalar"_err_en_US);
1677 break;
1678 }
1679 }
1680 }
1681 }
1682 }
1683 }
1684 }
1685 std::optional<characteristics::Procedure> procChars;
1686 if (const auto &operation{arguments[1]}) {
1687 if (const auto *expr{operation->UnwrapExpr()}) {
1688 if (const auto *designator{
1689 std::get_if<evaluate::ProcedureDesignator>(&expr->u)}) {
1690 procChars = characteristics::Procedure::Characterize(
1691 *designator, context, /*emitError=*/true);
1692 } else if (const auto *ref{
1693 std::get_if<evaluate::ProcedureRef>(&expr->u)}) {
1694 procChars = characteristics::Procedure::Characterize(*ref, context);
1695 }
1696 }
1697 }
1698 const auto *result{
1699 procChars ? procChars->functionResult->GetTypeAndShape() : nullptr};
1700 if (!procChars || !procChars->IsPure() ||
1701 procChars->dummyArguments.size() != 2 || !procChars->functionResult) {
1702 messages.Say(
1703 "OPERATION= argument of REDUCE() must be a pure function of two data arguments"_err_en_US);
1704 } else if (procChars->attrs.test(characteristics::Procedure::Attr::BindC)) {
1705 messages.Say(
1706 "A BIND(C) OPERATION= argument of REDUCE() is not supported"_err_en_US);
1707 } else if (!result || result->Rank() != 0) {
1708 messages.Say(
1709 "OPERATION= argument of REDUCE() must be a scalar function"_err_en_US);
1710 } else if (result->type().IsPolymorphic() ||
1711 (arrayType && !arrayType->IsTkLenCompatibleWith(result->type()))) {
1712 messages.Say(
1713 "OPERATION= argument of REDUCE() must have the same type as ARRAY="_err_en_US);
1714 } else {
1715 const characteristics::DummyDataObject *data[2]{};
1716 for (int j{0}; j < 2; ++j) {
1717 const auto &dummy{procChars->dummyArguments.at(j)};
1718 data[j] = std::get_if<characteristics::DummyDataObject>(&dummy.u);
1719 }
1720 if (!data[0] || !data[1]) {
1721 messages.Say(
1722 "OPERATION= argument of REDUCE() may not have dummy procedure arguments"_err_en_US);
1723 } else {
1724 for (int j{0}; j < 2; ++j) {
1725 if (data[j]->attrs.test(
1726 characteristics::DummyDataObject::Attr::Optional) ||
1727 data[j]->attrs.test(
1728 characteristics::DummyDataObject::Attr::Allocatable) ||
1729 data[j]->attrs.test(
1730 characteristics::DummyDataObject::Attr::Pointer) ||
1731 data[j]->type.Rank() != 0 || data[j]->type.type().IsPolymorphic() ||
1732 (arrayType &&
1733 !data[j]->type.type().IsTkCompatibleWith(*arrayType))) {
1734 messages.Say(
1735 "Arguments of OPERATION= procedure of REDUCE() must be both scalar of the same type as ARRAY=, and neither allocatable, pointer, polymorphic, nor optional"_err_en_US);
1736 }
1737 }
1738 static constexpr characteristics::DummyDataObject::Attr attrs[]{
1739 characteristics::DummyDataObject::Attr::Asynchronous,
1740 characteristics::DummyDataObject::Attr::Target,
1741 characteristics::DummyDataObject::Attr::Value,
1742 };
1743 for (std::size_t j{0}; j < sizeof attrs / sizeof *attrs; ++j) {
1744 if (data[0]->attrs.test(attrs[j]) != data[1]->attrs.test(attrs[j])) {
1745 messages.Say(
1746 "If either argument of the OPERATION= procedure of REDUCE() has the ASYNCHRONOUS, TARGET, or VALUE attribute, both must have that attribute"_err_en_US);
1747 break;
1748 }
1749 }
1750 }
1751 }
1752 // When the MASK= is present and has no .TRUE. element, and there is
1753 // no IDENTITY=, it's an error.
1754 if (const auto &mask{arguments[3]}; mask && !arguments[/*identity*/ 4]) {
1755 if (const auto *expr{mask->UnwrapExpr()}) {
1756 if (const auto *logical{
1757 std::get_if<evaluate::Expr<evaluate::SomeLogical>>(&expr->u)}) {
1758 if (common::visit(
1759 [](const auto &kindExpr) {
1760 using KindExprType = std::decay_t<decltype(kindExpr)>;
1761 using KindLogical = typename KindExprType::Result;
1762 if (const auto *c{evaluate::UnwrapConstantValue<KindLogical>(
1763 kindExpr)}) {
1764 for (const auto &element : c->values()) {
1765 if (element.IsTrue()) {
1766 return false;
1767 }
1768 }
1769 return true;
1770 }
1771 return false;
1772 },
1773 logical->u)) {
1774 messages.Say(
1775 "MASK= has no .TRUE. element, so IDENTITY= must be present"_err_en_US);
1776 }
1777 }
1778 }
1779 }
1780 }
1781
1782 // TRANSFER (16.9.193)
1783 static void CheckTransferOperandType(SemanticsContext &context,
1784 const evaluate::DynamicType &type, const char *which) {
1785 if (type.IsPolymorphic() &&
1786 context.ShouldWarn(common::UsageWarning::PolymorphicTransferArg)) {
1787 context.foldingContext().messages().Say(
1788 "%s of TRANSFER is polymorphic"_warn_en_US, which);
1789 } else if (!type.IsUnlimitedPolymorphic() &&
1790 type.category() == TypeCategory::Derived &&
1791 context.ShouldWarn(common::UsageWarning::PointerComponentTransferArg)) {
1792 DirectComponentIterator directs{type.GetDerivedTypeSpec()};
1793 if (auto bad{std::find_if(directs.begin(), directs.end(), IsDescriptor)};
1794 bad != directs.end()) {
1795 evaluate::SayWithDeclaration(context.foldingContext().messages(), *bad,
1796 "%s of TRANSFER contains allocatable or pointer component %s"_warn_en_US,
1797 which, bad.BuildResultDesignatorName());
1798 }
1799 }
1800 }
1801
1802 static void CheckTransfer(evaluate::ActualArguments &arguments,
1803 SemanticsContext &context, const Scope *scope) {
1804 evaluate::FoldingContext &foldingContext{context.foldingContext()};
1805 parser::ContextualMessages &messages{foldingContext.messages()};
1806 if (arguments.size() >= 2) {
1807 if (auto source{characteristics::TypeAndShape::Characterize(
1808 arguments[0], foldingContext)}) {
1809 CheckTransferOperandType(context, source->type(), "Source");
1810 if (auto mold{characteristics::TypeAndShape::Characterize(
1811 arguments[1], foldingContext)}) {
1812 CheckTransferOperandType(context, mold->type(), "Mold");
1813 if (mold->Rank() > 0 &&
1814 evaluate::ToInt64(
1815 evaluate::Fold(foldingContext,
1816 mold->MeasureElementSizeInBytes(foldingContext, false)))
1817 .value_or(1) == 0) {
1818 if (auto sourceSize{evaluate::ToInt64(evaluate::Fold(foldingContext,
1819 source->MeasureSizeInBytes(foldingContext)))}) {
1820 if (*sourceSize > 0) {
1821 messages.Say(
1822 "Element size of MOLD= array may not be zero when SOURCE= is not empty"_err_en_US);
1823 }
1824 } else if (context.ShouldWarn(common::UsageWarning::VoidMold)) {
1825 messages.Say(
1826 "Element size of MOLD= array may not be zero unless SOURCE= is empty"_warn_en_US);
1827 }
1828 }
1829 }
1830 }
1831 if (arguments.size() > 2) { // SIZE=
1832 if (const Symbol *
1833 whole{UnwrapWholeSymbolOrComponentDataRef(arguments[2])}) {
1834 if (IsOptional(*whole)) {
1835 messages.Say(
1836 "SIZE= argument may not be the optional dummy argument '%s'"_err_en_US,
1837 whole->name());
1838 } else if (context.ShouldWarn(
1839 common::UsageWarning::TransferSizePresence) &&
1840 IsAllocatableOrObjectPointer(whole)) {
1841 messages.Say(
1842 "SIZE= argument that is allocatable or pointer must be present at execution; parenthesize to silence this warning"_warn_en_US);
1843 }
1844 }
1845 }
1846 }
1847 }
1848
1849 static void CheckSpecificIntrinsic(const characteristics::Procedure &proc,
1850 evaluate::ActualArguments &arguments, SemanticsContext &context,
1851 const Scope *scope, const evaluate::SpecificIntrinsic &intrinsic) {
1852 if (intrinsic.name == "associated") {
1853 CheckAssociated(arguments, context, scope);
1854 } else if (intrinsic.name == "image_index") {
1855 CheckImage_Index(arguments, context.foldingContext().messages());
1856 } else if (intrinsic.name == "max" || intrinsic.name == "min") {
1857 CheckMaxMin(proc, arguments, context.foldingContext().messages());
1858 } else if (intrinsic.name == "move_alloc") {
1859 CheckMove_Alloc(arguments, context.foldingContext().messages());
1860 } else if (intrinsic.name == "present") {
1861 CheckPresent(arguments, context.foldingContext().messages());
1862 } else if (intrinsic.name == "reduce") {
1863 CheckReduce(arguments, context.foldingContext());
1864 } else if (intrinsic.name == "transfer") {
1865 CheckTransfer(arguments, context, scope);
1866 }
1867 }
1868
1869 static parser::Messages CheckExplicitInterface(
1870 const characteristics::Procedure &proc, evaluate::ActualArguments &actuals,
1871 SemanticsContext &context, const Scope *scope,
1872 const evaluate::SpecificIntrinsic *intrinsic,
1873 bool allowActualArgumentConversions, bool extentErrors,
1874 bool ignoreImplicitVsExplicit) {
1875 evaluate::FoldingContext &foldingContext{context.foldingContext()};
1876 parser::ContextualMessages &messages{foldingContext.messages()};
1877 parser::Messages buffer;
1878 auto restorer{messages.SetMessages(buffer)};
1879 RearrangeArguments(proc, actuals, messages);
1880 if (!buffer.empty()) {
1881 return buffer;
1882 }
1883 int index{0};
1884 for (auto &actual : actuals) {
1885 const auto &dummy{proc.dummyArguments.at(index++)};
1886 if (actual) {
1887 CheckExplicitInterfaceArg(*actual, dummy, proc, context, scope, intrinsic,
1888 allowActualArgumentConversions, extentErrors,
1889 ignoreImplicitVsExplicit);
1890 } else if (!dummy.IsOptional()) {
1891 if (dummy.name.empty()) {
1892 messages.Say(
1893 "Dummy argument #%d is not OPTIONAL and is not associated with "
1894 "an actual argument in this procedure reference"_err_en_US,
1895 index);
1896 } else {
1897 messages.Say("Dummy argument '%s=' (#%d) is not OPTIONAL and is not "
1898 "associated with an actual argument in this procedure "
1899 "reference"_err_en_US,
1900 dummy.name, index);
1901 }
1902 }
1903 }
1904 if (proc.IsElemental() && !buffer.AnyFatalError()) {
1905 CheckElementalConformance(messages, proc, actuals, foldingContext);
1906 }
1907 if (intrinsic) {
1908 CheckSpecificIntrinsic(proc, actuals, context, scope, *intrinsic);
1909 }
1910 return buffer;
1911 }
1912
1913 bool CheckInterfaceForGeneric(const characteristics::Procedure &proc,
1914 evaluate::ActualArguments &actuals, SemanticsContext &context,
1915 bool allowActualArgumentConversions) {
1916 return proc.HasExplicitInterface() &&
1917 !CheckExplicitInterface(proc, actuals, context, nullptr, nullptr,
1918 allowActualArgumentConversions, /*extentErrors=*/false,
1919 /*ignoreImplicitVsExplicit=*/false)
1920 .AnyFatalError();
1921 }
1922
1923 bool CheckArgumentIsConstantExprInRange(
1924 const evaluate::ActualArguments &actuals, int index, int lowerBound,
1925 int upperBound, parser::ContextualMessages &messages) {
1926 CHECK(index >= 0 && static_cast<unsigned>(index) < actuals.size());
1927
1928 const std::optional<evaluate::ActualArgument> &argOptional{actuals[index]};
1929 if (!argOptional) {
1930 DIE("Actual argument should have value");
1931 return false;
1932 }
1933
1934 const evaluate::ActualArgument &arg{argOptional.value()};
1935 const evaluate::Expr<evaluate::SomeType> *argExpr{arg.UnwrapExpr()};
1936 CHECK(argExpr != nullptr);
1937
1938 if (!IsConstantExpr(*argExpr)) {
1939 messages.Say("Actual argument #%d must be a constant expression"_err_en_US,
1940 index + 1);
1941 return false;
1942 }
1943
1944 // This does not imply that the kind of the argument is 8. The kind
1945 // for the intrinsic's argument should have been check prior. This is just
1946 // a conversion so that we can read the constant value.
1947 auto scalarValue{evaluate::ToInt64(argExpr)};
1948 CHECK(scalarValue.has_value());
1949
1950 if (*scalarValue < lowerBound || *scalarValue > upperBound) {
1951 messages.Say(
1952 "Argument #%d must be a constant expression in range %d to %d"_err_en_US,
1953 index + 1, lowerBound, upperBound);
1954 return false;
1955 }
1956 return true;
1957 }
1958
1959 bool CheckPPCIntrinsic(const Symbol &generic, const Symbol &specific,
1960 const evaluate::ActualArguments &actuals,
1961 evaluate::FoldingContext &context) {
1962 parser::ContextualMessages &messages{context.messages()};
1963
1964 if (specific.name() == "__ppc_mtfsf") {
1965 return CheckArgumentIsConstantExprInRange(actuals, 0, 0, 7, messages);
1966 }
1967 if (specific.name() == "__ppc_mtfsfi") {
1968 return CheckArgumentIsConstantExprInRange(actuals, 0, 0, 7, messages) &&
1969 CheckArgumentIsConstantExprInRange(actuals, 1, 0, 15, messages);
1970 }
1971 if (specific.name().ToString().compare(0, 14, "__ppc_vec_sld_") == 0) {
1972 return CheckArgumentIsConstantExprInRange(actuals, 2, 0, 15, messages);
1973 }
1974 if (specific.name().ToString().compare(0, 15, "__ppc_vec_sldw_") == 0) {
1975 return CheckArgumentIsConstantExprInRange(actuals, 2, 0, 3, messages);
1976 }
1977 if (specific.name().ToString().compare(0, 14, "__ppc_vec_ctf_") == 0) {
1978 return CheckArgumentIsConstantExprInRange(actuals, 1, 0, 31, messages);
1979 }
1980 if (specific.name().ToString().compare(0, 16, "__ppc_vec_permi_") == 0) {
1981 return CheckArgumentIsConstantExprInRange(actuals, 2, 0, 3, messages);
1982 }
1983 if (specific.name().ToString().compare(0, 21, "__ppc_vec_splat_s32__") == 0) {
1984 return CheckArgumentIsConstantExprInRange(actuals, 0, -16, 15, messages);
1985 }
1986 if (specific.name().ToString().compare(0, 16, "__ppc_vec_splat_") == 0) {
1987 // The value of arg2 in vec_splat must be a constant expression that is
1988 // greater than or equal to 0, and less than the number of elements in arg1.
1989 auto *expr{actuals[0].value().UnwrapExpr()};
1990 auto type{characteristics::TypeAndShape::Characterize(*expr, context)};
1991 assert(type && "unknown type");
1992 const auto *derived{evaluate::GetDerivedTypeSpec(type.value().type())};
1993 if (derived && derived->IsVectorType()) {
1994 for (const auto &pair : derived->parameters()) {
1995 if (pair.first == "element_kind") {
1996 auto vecElemKind{Fortran::evaluate::ToInt64(pair.second.GetExplicit())
1997 .value_or(0)};
1998 auto numElem{vecElemKind == 0 ? 0 : (16 / vecElemKind)};
1999 return CheckArgumentIsConstantExprInRange(
2000 actuals, 1, 0, numElem - 1, messages);
2001 }
2002 }
2003 } else
2004 assert(false && "vector type is expected");
2005 }
2006 return false;
2007 }
2008
2009 bool CheckArguments(const characteristics::Procedure &proc,
2010 evaluate::ActualArguments &actuals, SemanticsContext &context,
2011 const Scope &scope, bool treatingExternalAsImplicit,
2012 bool ignoreImplicitVsExplicit,
2013 const evaluate::SpecificIntrinsic *intrinsic) {
2014 bool explicitInterface{proc.HasExplicitInterface()};
2015 evaluate::FoldingContext foldingContext{context.foldingContext()};
2016 parser::ContextualMessages &messages{foldingContext.messages()};
2017 bool allowArgumentConversions{true};
2018 if (!explicitInterface || treatingExternalAsImplicit) {
2019 parser::Messages buffer;
2020 {
2021 auto restorer{messages.SetMessages(buffer)};
2022 for (auto &actual : actuals) {
2023 if (actual) {
2024 CheckImplicitInterfaceArg(*actual, messages, foldingContext);
2025 }
2026 }
2027 }
2028 if (!buffer.empty()) {
2029 if (auto *msgs{messages.messages()}) {
2030 msgs->Annex(std::move(buffer));
2031 }
2032 return false; // don't pile on
2033 }
2034 allowArgumentConversions = false;
2035 }
2036 if (explicitInterface) {
2037 auto buffer{CheckExplicitInterface(proc, actuals, context, &scope,
2038 intrinsic, allowArgumentConversions,
2039 /*extentErrors=*/true, ignoreImplicitVsExplicit)};
2040 if (!buffer.empty()) {
2041 if (treatingExternalAsImplicit) {
2042 if (context.ShouldWarn(
2043 common::UsageWarning::KnownBadImplicitInterface)) {
2044 if (auto *msg{messages.Say(
2045 "If the procedure's interface were explicit, this reference would be in error"_warn_en_US)}) {
2046 buffer.AttachTo(*msg, parser::Severity::Because);
2047 }
2048 } else {
2049 buffer.clear();
2050 }
2051 }
2052 if (auto *msgs{messages.messages()}) {
2053 msgs->Annex(std::move(buffer));
2054 }
2055 return false;
2056 }
2057 }
2058 return true;
2059 }
2060 } // namespace Fortran::semantics