| 1 |
//===-- lib/Semantics/expression.cpp --------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include "flang/Semantics/expression.h" |
| 10 |
#include "check-call.h" |
| 11 |
#include "pointer-assignment.h" |
| 12 |
#include "resolve-names-utils.h" |
| 13 |
#include "resolve-names.h" |
| 14 |
#include "flang/Common/Fortran.h" |
| 15 |
#include "flang/Common/idioms.h" |
| 16 |
#include "flang/Evaluate/common.h" |
| 17 |
#include "flang/Evaluate/fold.h" |
| 18 |
#include "flang/Evaluate/tools.h" |
| 19 |
#include "flang/Parser/characters.h" |
| 20 |
#include "flang/Parser/dump-parse-tree.h" |
| 21 |
#include "flang/Parser/parse-tree-visitor.h" |
| 22 |
#include "flang/Parser/parse-tree.h" |
| 23 |
#include "flang/Semantics/scope.h" |
| 24 |
#include "flang/Semantics/semantics.h" |
| 25 |
#include "flang/Semantics/symbol.h" |
| 26 |
#include "flang/Semantics/tools.h" |
| 27 |
#include "llvm/Support/raw_ostream.h" |
| 28 |
#include <algorithm> |
| 29 |
#include <functional> |
| 30 |
#include <optional> |
| 31 |
#include <set> |
| 32 |
#include <vector> |
| 33 |
|
| 34 |
// Typedef for optional generic expressions (ubiquitous in this file) |
| 35 |
using MaybeExpr = |
| 36 |
std::optional<Fortran::evaluate::Expr<Fortran::evaluate::SomeType>>; |
| 37 |
|
| 38 |
// Much of the code that implements semantic analysis of expressions is |
| 39 |
// tightly coupled with their typed representations in lib/Evaluate, |
| 40 |
// and appears here in namespace Fortran::evaluate for convenience. |
| 41 |
namespace Fortran::evaluate { |
| 42 |
|
| 43 |
using common::LanguageFeature; |
| 44 |
using common::NumericOperator; |
| 45 |
using common::TypeCategory; |
| 46 |
|
| 47 |
static inline std::string ToUpperCase(std::string_view str) { |
| 48 |
return parser::ToUpperCaseLetters(str); |
| 49 |
} |
| 50 |
|
| 51 |
struct DynamicTypeWithLength : public DynamicType { |
| 52 |
explicit DynamicTypeWithLength(const DynamicType &t) : DynamicType{t} {} |
| 53 |
std::optional<Expr<SubscriptInteger>> LEN() const; |
| 54 |
std::optional<Expr<SubscriptInteger>> length; |
| 55 |
}; |
| 56 |
|
| 57 |
std::optional<Expr<SubscriptInteger>> DynamicTypeWithLength::LEN() const { |
| 58 |
if (length) { |
| 59 |
return length; |
| 60 |
} else { |
| 61 |
return GetCharLength(); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
static std::optional<DynamicTypeWithLength> AnalyzeTypeSpec( |
| 66 |
const std::optional<parser::TypeSpec> &spec, FoldingContext &context) { |
| 67 |
if (spec) { |
| 68 |
if (const semantics::DeclTypeSpec *typeSpec{spec->declTypeSpec}) { |
| 69 |
// Name resolution sets TypeSpec::declTypeSpec only when it's valid |
| 70 |
// (viz., an intrinsic type with valid known kind or a non-polymorphic |
| 71 |
// & non-ABSTRACT derived type). |
| 72 |
if (const semantics::IntrinsicTypeSpec *intrinsic{ |
| 73 |
typeSpec->AsIntrinsic()}) { |
| 74 |
TypeCategory category{intrinsic->category()}; |
| 75 |
if (auto optKind{ToInt64(intrinsic->kind())}) { |
| 76 |
int kind{static_cast<int>(*optKind)}; |
| 77 |
if (category == TypeCategory::Character) { |
| 78 |
const semantics::CharacterTypeSpec &cts{ |
| 79 |
typeSpec->characterTypeSpec()}; |
| 80 |
const semantics::ParamValue &len{cts.length()}; |
| 81 |
// N.B. CHARACTER(LEN=*) is allowed in type-specs in ALLOCATE() & |
| 82 |
// type guards, but not in array constructors. |
| 83 |
DynamicTypeWithLength type{DynamicType{kind, len}}; |
| 84 |
if (auto lenExpr{type.LEN()}) { |
| 85 |
type.length = Fold(context, |
| 86 |
AsExpr(Extremum<SubscriptInteger>{Ordering::Greater, |
| 87 |
Expr<SubscriptInteger>{0}, std::move(*lenExpr)})); |
| 88 |
} |
| 89 |
return type; |
| 90 |
} else { |
| 91 |
return DynamicTypeWithLength{DynamicType{category, kind}}; |
| 92 |
} |
| 93 |
} |
| 94 |
} else if (const semantics::DerivedTypeSpec *derived{ |
| 95 |
typeSpec->AsDerived()}) { |
| 96 |
return DynamicTypeWithLength{DynamicType{*derived}}; |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
return std::nullopt; |
| 101 |
} |
| 102 |
|
| 103 |
// Utilities to set a source location, if we have one, on an actual argument, |
| 104 |
// when it is statically present. |
| 105 |
static void SetArgSourceLocation(ActualArgument &x, parser::CharBlock at) { |
| 106 |
x.set_sourceLocation(at); |
| 107 |
} |
| 108 |
static void SetArgSourceLocation( |
| 109 |
std::optional<ActualArgument> &x, parser::CharBlock at) { |
| 110 |
if (x) { |
| 111 |
x->set_sourceLocation(at); |
| 112 |
} |
| 113 |
} |
| 114 |
static void SetArgSourceLocation( |
| 115 |
std::optional<ActualArgument> &x, std::optional<parser::CharBlock> at) { |
| 116 |
if (x && at) { |
| 117 |
x->set_sourceLocation(*at); |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
class ArgumentAnalyzer { |
| 122 |
public: |
| 123 |
explicit ArgumentAnalyzer(ExpressionAnalyzer &context) |
| 124 |
: context_{context}, source_{context.GetContextualMessages().at()}, |
| 125 |
isProcedureCall_{false} {} |
| 126 |
ArgumentAnalyzer(ExpressionAnalyzer &context, parser::CharBlock source, |
| 127 |
bool isProcedureCall = false) |
| 128 |
: context_{context}, source_{source}, isProcedureCall_{isProcedureCall} {} |
| 129 |
bool fatalErrors() const { return fatalErrors_; } |
| 130 |
ActualArguments &&GetActuals() { |
| 131 |
CHECK(!fatalErrors_); |
| 132 |
return std::move(actuals_); |
| 133 |
} |
| 134 |
const Expr<SomeType> &GetExpr(std::size_t i) const { |
| 135 |
return DEREF(actuals_.at(i).value().UnwrapExpr()); |
| 136 |
} |
| 137 |
Expr<SomeType> &&MoveExpr(std::size_t i) { |
| 138 |
return std::move(DEREF(actuals_.at(i).value().UnwrapExpr())); |
| 139 |
} |
| 140 |
void Analyze(const common::Indirection<parser::Expr> &x) { |
| 141 |
Analyze(x.value()); |
| 142 |
} |
| 143 |
void Analyze(const parser::Expr &x) { |
| 144 |
actuals_.emplace_back(AnalyzeExpr(x)); |
| 145 |
SetArgSourceLocation(actuals_.back(), x.source); |
| 146 |
fatalErrors_ |= !actuals_.back(); |
| 147 |
} |
| 148 |
void Analyze(const parser::Variable &); |
| 149 |
void Analyze(const parser::ActualArgSpec &, bool isSubroutine); |
| 150 |
void ConvertBOZ(std::optional<DynamicType> *thisType, std::size_t, |
| 151 |
std::optional<DynamicType> otherType); |
| 152 |
|
| 153 |
bool IsIntrinsicRelational( |
| 154 |
RelationalOperator, const DynamicType &, const DynamicType &) const; |
| 155 |
bool IsIntrinsicLogical() const; |
| 156 |
bool IsIntrinsicNumeric(NumericOperator) const; |
| 157 |
bool IsIntrinsicConcat() const; |
| 158 |
|
| 159 |
bool CheckConformance(); |
| 160 |
bool CheckAssignmentConformance(); |
| 161 |
bool CheckForNullPointer(const char *where = "as an operand here"); |
| 162 |
bool CheckForAssumedRank(const char *where = "as an operand here"); |
| 163 |
|
| 164 |
// Find and return a user-defined operator or report an error. |
| 165 |
// The provided message is used if there is no such operator. |
| 166 |
// If a definedOpSymbolPtr is provided, the caller must check |
| 167 |
// for its accessibility. |
| 168 |
MaybeExpr TryDefinedOp( |
| 169 |
const char *, parser::MessageFixedText, bool isUserOp = false); |
| 170 |
template <typename E> |
| 171 |
MaybeExpr TryDefinedOp(E opr, parser::MessageFixedText msg) { |
| 172 |
return TryDefinedOp( |
| 173 |
context_.context().languageFeatures().GetNames(opr), msg); |
| 174 |
} |
| 175 |
// Find and return a user-defined assignment |
| 176 |
std::optional<ProcedureRef> TryDefinedAssignment(); |
| 177 |
std::optional<ProcedureRef> GetDefinedAssignmentProc(); |
| 178 |
std::optional<DynamicType> GetType(std::size_t) const; |
| 179 |
void Dump(llvm::raw_ostream &); |
| 180 |
|
| 181 |
private: |
| 182 |
MaybeExpr TryDefinedOp( |
| 183 |
const std::vector<const char *> &, parser::MessageFixedText); |
| 184 |
MaybeExpr TryBoundOp(const Symbol &, int passIndex); |
| 185 |
std::optional<ActualArgument> AnalyzeExpr(const parser::Expr &); |
| 186 |
std::optional<ActualArgument> AnalyzeVariable(const parser::Variable &); |
| 187 |
MaybeExpr AnalyzeExprOrWholeAssumedSizeArray(const parser::Expr &); |
| 188 |
bool AreConformable() const; |
| 189 |
const Symbol *FindBoundOp(parser::CharBlock, int passIndex, |
| 190 |
const Symbol *&generic, bool isSubroutine); |
| 191 |
void AddAssignmentConversion( |
| 192 |
const DynamicType &lhsType, const DynamicType &rhsType); |
| 193 |
bool OkLogicalIntegerAssignment(TypeCategory lhs, TypeCategory rhs); |
| 194 |
int GetRank(std::size_t) const; |
| 195 |
bool IsBOZLiteral(std::size_t i) const { |
| 196 |
return evaluate::IsBOZLiteral(GetExpr(i)); |
| 197 |
} |
| 198 |
void SayNoMatch(const std::string &, bool isAssignment = false); |
| 199 |
std::string TypeAsFortran(std::size_t); |
| 200 |
bool AnyUntypedOrMissingOperand(); |
| 201 |
|
| 202 |
ExpressionAnalyzer &context_; |
| 203 |
ActualArguments actuals_; |
| 204 |
parser::CharBlock source_; |
| 205 |
bool fatalErrors_{false}; |
| 206 |
const bool isProcedureCall_; // false for user-defined op or assignment |
| 207 |
}; |
| 208 |
|
| 209 |
// Wraps a data reference in a typed Designator<>, and a procedure |
| 210 |
// or procedure pointer reference in a ProcedureDesignator. |
| 211 |
MaybeExpr ExpressionAnalyzer::Designate(DataRef &&ref) { |
| 212 |
const Symbol &last{ref.GetLastSymbol()}; |
| 213 |
const Symbol &symbol{BypassGeneric(last).GetUltimate()}; |
| 214 |
if (semantics::IsProcedure(symbol)) { |
| 215 |
if (symbol.attrs().test(semantics::Attr::ABSTRACT)) { |
| 216 |
Say("Abstract procedure interface '%s' may not be used as a designator"_err_en_US, |
| 217 |
last.name()); |
| 218 |
} |
| 219 |
if (auto *component{std::get_if<Component>(&ref.u)}) { |
| 220 |
if (!CheckDataRef(ref)) { |
| 221 |
return std::nullopt; |
| 222 |
} |
| 223 |
return Expr<SomeType>{ProcedureDesignator{std::move(*component)}}; |
| 224 |
} else if (!std::holds_alternative<SymbolRef>(ref.u)) { |
| 225 |
DIE("unexpected alternative in DataRef"); |
| 226 |
} else if (!symbol.attrs().test(semantics::Attr::INTRINSIC)) { |
| 227 |
if (symbol.has<semantics::GenericDetails>()) { |
| 228 |
Say("'%s' is not a specific procedure"_err_en_US, last.name()); |
| 229 |
} else { |
| 230 |
return Expr<SomeType>{ProcedureDesignator{symbol}}; |
| 231 |
} |
| 232 |
} else if (auto interface{context_.intrinsics().IsSpecificIntrinsicFunction( |
| 233 |
symbol.name().ToString())}; |
| 234 |
interface && !interface->isRestrictedSpecific) { |
| 235 |
SpecificIntrinsic intrinsic{ |
| 236 |
symbol.name().ToString(), std::move(*interface)}; |
| 237 |
intrinsic.isRestrictedSpecific = interface->isRestrictedSpecific; |
| 238 |
return Expr<SomeType>{ProcedureDesignator{std::move(intrinsic)}}; |
| 239 |
} else { |
| 240 |
Say("'%s' is not an unrestricted specific intrinsic procedure"_err_en_US, |
| 241 |
last.name()); |
| 242 |
} |
| 243 |
return std::nullopt; |
| 244 |
} else if (MaybeExpr result{AsGenericExpr(std::move(ref))}) { |
| 245 |
return result; |
| 246 |
} else if (semantics::HadUseError( |
| 247 |
context_, GetContextualMessages().at(), &symbol)) { |
| 248 |
return std::nullopt; |
| 249 |
} else { |
| 250 |
if (!context_.HasError(last) && !context_.HasError(symbol)) { |
| 251 |
AttachDeclaration( |
| 252 |
Say("'%s' is not an object that can appear in an expression"_err_en_US, |
| 253 |
last.name()), |
| 254 |
symbol); |
| 255 |
context_.SetError(last); |
| 256 |
} |
| 257 |
return std::nullopt; |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
// Some subscript semantic checks must be deferred until all of the |
| 262 |
// subscripts are in hand. |
| 263 |
MaybeExpr ExpressionAnalyzer::CompleteSubscripts(ArrayRef &&ref) { |
| 264 |
const Symbol &symbol{ref.GetLastSymbol().GetUltimate()}; |
| 265 |
int symbolRank{symbol.Rank()}; |
| 266 |
int subscripts{static_cast<int>(ref.size())}; |
| 267 |
if (subscripts == 0) { |
| 268 |
return std::nullopt; // error recovery |
| 269 |
} else if (subscripts != symbolRank) { |
| 270 |
if (symbolRank != 0) { |
| 271 |
Say("Reference to rank-%d object '%s' has %d subscripts"_err_en_US, |
| 272 |
symbolRank, symbol.name(), subscripts); |
| 273 |
} |
| 274 |
return std::nullopt; |
| 275 |
} else if (symbol.has<semantics::ObjectEntityDetails>() || |
| 276 |
symbol.has<semantics::AssocEntityDetails>()) { |
| 277 |
// C928 & C1002 |
| 278 |
if (Triplet *last{std::get_if<Triplet>(&ref.subscript().back().u)}) { |
| 279 |
if (!last->upper() && IsAssumedSizeArray(symbol)) { |
| 280 |
Say("Assumed-size array '%s' must have explicit final " |
| 281 |
"subscript upper bound value"_err_en_US, |
| 282 |
symbol.name()); |
| 283 |
return std::nullopt; |
| 284 |
} |
| 285 |
} |
| 286 |
} else { |
| 287 |
// Shouldn't get here from Analyze(ArrayElement) without a valid base, |
| 288 |
// which, if not an object, must be a construct entity from |
| 289 |
// SELECT TYPE/RANK or ASSOCIATE. |
| 290 |
CHECK(symbol.has<semantics::AssocEntityDetails>()); |
| 291 |
} |
| 292 |
if (!semantics::IsNamedConstant(symbol) && !inDataStmtObject_) { |
| 293 |
// Subscripts of named constants are checked in folding. |
| 294 |
// Subscripts of DATA statement objects are checked in data statement |
| 295 |
// conversion to initializers. |
| 296 |
CheckConstantSubscripts(ref); |
| 297 |
} |
| 298 |
return Designate(DataRef{std::move(ref)}); |
| 299 |
} |
| 300 |
|
| 301 |
// Applies subscripts to a data reference. |
| 302 |
MaybeExpr ExpressionAnalyzer::ApplySubscripts( |
| 303 |
DataRef &&dataRef, std::vector<Subscript> &&subscripts) { |
| 304 |
if (subscripts.empty()) { |
| 305 |
return std::nullopt; // error recovery |
| 306 |
} |
| 307 |
return common::visit( |
| 308 |
common::visitors{ |
| 309 |
[&](SymbolRef &&symbol) { |
| 310 |
return CompleteSubscripts(ArrayRef{symbol, std::move(subscripts)}); |
| 311 |
}, |
| 312 |
[&](Component &&c) { |
| 313 |
return CompleteSubscripts( |
| 314 |
ArrayRef{std::move(c), std::move(subscripts)}); |
| 315 |
}, |
| 316 |
[&](auto &&) -> MaybeExpr { |
| 317 |
DIE("bad base for ArrayRef"); |
| 318 |
return std::nullopt; |
| 319 |
}, |
| 320 |
}, |
| 321 |
std::move(dataRef.u)); |
| 322 |
} |
| 323 |
|
| 324 |
void ExpressionAnalyzer::CheckConstantSubscripts(ArrayRef &ref) { |
| 325 |
// Fold subscript expressions and check for an empty triplet. |
| 326 |
const Symbol &arraySymbol{ref.base().GetLastSymbol()}; |
| 327 |
Shape lb{GetLBOUNDs(foldingContext_, NamedEntity{arraySymbol})}; |
| 328 |
CHECK(lb.size() >= ref.subscript().size()); |
| 329 |
Shape ub{GetUBOUNDs(foldingContext_, NamedEntity{arraySymbol})}; |
| 330 |
CHECK(ub.size() >= ref.subscript().size()); |
| 331 |
bool anyPossiblyEmptyDim{false}; |
| 332 |
int dim{0}; |
| 333 |
for (Subscript &ss : ref.subscript()) { |
| 334 |
if (Triplet * triplet{std::get_if<Triplet>(&ss.u)}) { |
| 335 |
auto expr{Fold(triplet->stride())}; |
| 336 |
auto stride{ToInt64(expr)}; |
| 337 |
triplet->set_stride(std::move(expr)); |
| 338 |
std::optional<ConstantSubscript> lower, upper; |
| 339 |
if (auto expr{triplet->lower()}) { |
| 340 |
*expr = Fold(std::move(*expr)); |
| 341 |
lower = ToInt64(*expr); |
| 342 |
triplet->set_lower(std::move(*expr)); |
| 343 |
} else { |
| 344 |
lower = ToInt64(lb[dim]); |
| 345 |
} |
| 346 |
if (auto expr{triplet->upper()}) { |
| 347 |
*expr = Fold(std::move(*expr)); |
| 348 |
upper = ToInt64(*expr); |
| 349 |
triplet->set_upper(std::move(*expr)); |
| 350 |
} else { |
| 351 |
upper = ToInt64(ub[dim]); |
| 352 |
} |
| 353 |
if (stride) { |
| 354 |
if (*stride == 0) { |
| 355 |
Say("Stride of triplet must not be zero"_err_en_US); |
| 356 |
return; |
| 357 |
} |
| 358 |
if (lower && upper) { |
| 359 |
if (*stride > 0) { |
| 360 |
anyPossiblyEmptyDim |= *lower > *upper; |
| 361 |
} else { |
| 362 |
anyPossiblyEmptyDim |= *lower < *upper; |
| 363 |
} |
| 364 |
} else { |
| 365 |
anyPossiblyEmptyDim = true; |
| 366 |
} |
| 367 |
} else { // non-constant stride |
| 368 |
if (lower && upper && *lower == *upper) { |
| 369 |
// stride is not relevant |
| 370 |
} else { |
| 371 |
anyPossiblyEmptyDim = true; |
| 372 |
} |
| 373 |
} |
| 374 |
} else { // not triplet |
| 375 |
auto &expr{std::get<IndirectSubscriptIntegerExpr>(ss.u).value()}; |
| 376 |
expr = Fold(std::move(expr)); |
| 377 |
anyPossiblyEmptyDim |= expr.Rank() > 0; // vector subscript |
| 378 |
} |
| 379 |
++dim; |
| 380 |
} |
| 381 |
if (anyPossiblyEmptyDim) { |
| 382 |
return; |
| 383 |
} |
| 384 |
dim = 0; |
| 385 |
for (Subscript &ss : ref.subscript()) { |
| 386 |
auto dimLB{ToInt64(lb[dim])}; |
| 387 |
auto dimUB{ToInt64(ub[dim])}; |
| 388 |
std::optional<ConstantSubscript> val[2]; |
| 389 |
int vals{0}; |
| 390 |
if (auto *triplet{std::get_if<Triplet>(&ss.u)}) { |
| 391 |
auto stride{ToInt64(triplet->stride())}; |
| 392 |
std::optional<ConstantSubscript> lower, upper; |
| 393 |
if (const auto *lowerExpr{triplet->GetLower()}) { |
| 394 |
lower = ToInt64(*lowerExpr); |
| 395 |
} else if (lb[dim]) { |
| 396 |
lower = ToInt64(*lb[dim]); |
| 397 |
} |
| 398 |
if (const auto *upperExpr{triplet->GetUpper()}) { |
| 399 |
upper = ToInt64(*upperExpr); |
| 400 |
} else if (ub[dim]) { |
| 401 |
upper = ToInt64(*ub[dim]); |
| 402 |
} |
| 403 |
if (lower) { |
| 404 |
val[vals++] = *lower; |
| 405 |
if (upper && *upper != lower && (stride && *stride != 0)) { |
| 406 |
// Normalize upper bound for non-unit stride |
| 407 |
// 1:10:2 -> 1:9:2, 10:1:-2 -> 10:2:-2 |
| 408 |
val[vals++] = *lower + *stride * ((*upper - *lower) / *stride); |
| 409 |
} |
| 410 |
} |
| 411 |
} else { |
| 412 |
val[vals++] = |
| 413 |
ToInt64(std::get<IndirectSubscriptIntegerExpr>(ss.u).value()); |
| 414 |
} |
| 415 |
for (int j{0}; j < vals; ++j) { |
| 416 |
if (val[j]) { |
| 417 |
std::optional<parser::MessageFixedText> msg; |
| 418 |
std::optional<ConstantSubscript> bound; |
| 419 |
if (dimLB && *val[j] < *dimLB) { |
| 420 |
msg = |
| 421 |
"Subscript %jd is less than lower bound %jd for dimension %d of array"_err_en_US; |
| 422 |
bound = *dimLB; |
| 423 |
} else if (dimUB && *val[j] > *dimUB) { |
| 424 |
msg = |
| 425 |
"Subscript %jd is greater than upper bound %jd for dimension %d of array"_err_en_US; |
| 426 |
bound = *dimUB; |
| 427 |
if (dim + 1 == arraySymbol.Rank() && IsDummy(arraySymbol) && |
| 428 |
*bound == 1) { |
| 429 |
// Old-school overindexing of a dummy array isn't fatal when |
| 430 |
// it's on the last dimension and the extent is 1. |
| 431 |
msg->set_severity(parser::Severity::Warning); |
| 432 |
} |
| 433 |
} |
| 434 |
if (msg) { |
| 435 |
AttachDeclaration( |
| 436 |
Say(std::move(*msg), static_cast<std::intmax_t>(*val[j]), |
| 437 |
static_cast<std::intmax_t>(bound.value()), dim + 1), |
| 438 |
arraySymbol); |
| 439 |
} |
| 440 |
} |
| 441 |
} |
| 442 |
++dim; |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
// C919a - only one part-ref of a data-ref may have rank > 0 |
| 447 |
bool ExpressionAnalyzer::CheckRanks(const DataRef &dataRef) { |
| 448 |
return common::visit( |
| 449 |
common::visitors{ |
| 450 |
[this](const Component &component) { |
| 451 |
const Symbol &symbol{component.GetLastSymbol()}; |
| 452 |
if (int componentRank{symbol.Rank()}; componentRank > 0) { |
| 453 |
if (int baseRank{component.base().Rank()}; baseRank > 0) { |
| 454 |
Say("Reference to whole rank-%d component '%s' of rank-%d array of derived type is not allowed"_err_en_US, |
| 455 |
componentRank, symbol.name(), baseRank); |
| 456 |
return false; |
| 457 |
} |
| 458 |
} else { |
| 459 |
return CheckRanks(component.base()); |
| 460 |
} |
| 461 |
return true; |
| 462 |
}, |
| 463 |
[this](const ArrayRef &arrayRef) { |
| 464 |
if (const auto *component{arrayRef.base().UnwrapComponent()}) { |
| 465 |
int subscriptRank{0}; |
| 466 |
for (const Subscript &subscript : arrayRef.subscript()) { |
| 467 |
subscriptRank += subscript.Rank(); |
| 468 |
} |
| 469 |
if (subscriptRank > 0) { |
| 470 |
if (int componentBaseRank{component->base().Rank()}; |
| 471 |
componentBaseRank > 0) { |
| 472 |
Say("Subscripts of component '%s' of rank-%d derived type array have rank %d but must all be scalar"_err_en_US, |
| 473 |
component->GetLastSymbol().name(), componentBaseRank, |
| 474 |
subscriptRank); |
| 475 |
return false; |
| 476 |
} |
| 477 |
} else { |
| 478 |
return CheckRanks(component->base()); |
| 479 |
} |
| 480 |
} |
| 481 |
return true; |
| 482 |
}, |
| 483 |
[](const SymbolRef &) { return true; }, |
| 484 |
[](const CoarrayRef &) { return true; }, |
| 485 |
}, |
| 486 |
dataRef.u); |
| 487 |
} |
| 488 |
|
| 489 |
// C911 - if the last name in a data-ref has an abstract derived type, |
| 490 |
// it must also be polymorphic. |
| 491 |
bool ExpressionAnalyzer::CheckPolymorphic(const DataRef &dataRef) { |
| 492 |
if (auto type{DynamicType::From(dataRef.GetLastSymbol())}) { |
| 493 |
if (type->category() == TypeCategory::Derived && !type->IsPolymorphic()) { |
| 494 |
const Symbol &typeSymbol{ |
| 495 |
type->GetDerivedTypeSpec().typeSymbol().GetUltimate()}; |
| 496 |
if (typeSymbol.attrs().test(semantics::Attr::ABSTRACT)) { |
| 497 |
AttachDeclaration( |
| 498 |
Say("Reference to object with abstract derived type '%s' must be polymorphic"_err_en_US, |
| 499 |
typeSymbol.name()), |
| 500 |
typeSymbol); |
| 501 |
return false; |
| 502 |
} |
| 503 |
} |
| 504 |
} |
| 505 |
return true; |
| 506 |
} |
| 507 |
|
| 508 |
bool ExpressionAnalyzer::CheckDataRef(const DataRef &dataRef) { |
| 509 |
// Always check both, don't short-circuit |
| 510 |
bool ranksOk{CheckRanks(dataRef)}; |
| 511 |
bool polyOk{CheckPolymorphic(dataRef)}; |
| 512 |
return ranksOk && polyOk; |
| 513 |
} |
| 514 |
|
| 515 |
// Parse tree correction after a substring S(j:k) was misparsed as an |
| 516 |
// array section. Fortran substrings must have a range, not a |
| 517 |
// single index. |
| 518 |
static std::optional<parser::Substring> FixMisparsedSubstringDataRef( |
| 519 |
parser::DataRef &dataRef) { |
| 520 |
if (auto *ae{ |
| 521 |
std::get_if<common::Indirection<parser::ArrayElement>>(&dataRef.u)}) { |
| 522 |
// ...%a(j:k) and "a" is a character scalar |
| 523 |
parser::ArrayElement &arrElement{ae->value()}; |
| 524 |
if (arrElement.subscripts.size() == 1) { |
| 525 |
if (auto *triplet{std::get_if<parser::SubscriptTriplet>( |
| 526 |
&arrElement.subscripts.front().u)}) { |
| 527 |
if (!std::get<2 /*stride*/>(triplet->t).has_value()) { |
| 528 |
if (const Symbol *symbol{ |
| 529 |
parser::GetLastName(arrElement.base).symbol}) { |
| 530 |
const Symbol &ultimate{symbol->GetUltimate()}; |
| 531 |
if (const semantics::DeclTypeSpec *type{ultimate.GetType()}) { |
| 532 |
if (ultimate.Rank() == 0 && |
| 533 |
type->category() == semantics::DeclTypeSpec::Character) { |
| 534 |
// The ambiguous S(j:k) was parsed as an array section |
| 535 |
// reference, but it's now clear that it's a substring. |
| 536 |
// Fix the parse tree in situ. |
| 537 |
return arrElement.ConvertToSubstring(); |
| 538 |
} |
| 539 |
} |
| 540 |
} |
| 541 |
} |
| 542 |
} |
| 543 |
} |
| 544 |
} |
| 545 |
return std::nullopt; |
| 546 |
} |
| 547 |
|
| 548 |
// When a designator is a misparsed type-param-inquiry of a misparsed |
| 549 |
// substring -- it looks like a structure component reference of an array |
| 550 |
// slice -- fix the substring and then convert to an intrinsic function |
| 551 |
// call to KIND() or LEN(). And when the designator is a misparsed |
| 552 |
// substring, convert it into a substring reference in place. |
| 553 |
MaybeExpr ExpressionAnalyzer::FixMisparsedSubstring( |
| 554 |
const parser::Designator &d) { |
| 555 |
auto &mutate{const_cast<parser::Designator &>(d)}; |
| 556 |
if (auto *dataRef{std::get_if<parser::DataRef>(&mutate.u)}) { |
| 557 |
if (auto *sc{std::get_if<common::Indirection<parser::StructureComponent>>( |
| 558 |
&dataRef->u)}) { |
| 559 |
parser::StructureComponent &structComponent{sc->value()}; |
| 560 |
parser::CharBlock which{structComponent.component.source}; |
| 561 |
if (which == "kind" || which == "len") { |
| 562 |
if (auto substring{ |
| 563 |
FixMisparsedSubstringDataRef(structComponent.base)}) { |
| 564 |
// ...%a(j:k)%kind or %len and "a" is a character scalar |
| 565 |
mutate.u = std::move(*substring); |
| 566 |
if (MaybeExpr substringExpr{Analyze(d)}) { |
| 567 |
return MakeFunctionRef(which, |
| 568 |
ActualArguments{ActualArgument{std::move(*substringExpr)}}); |
| 569 |
} |
| 570 |
} |
| 571 |
} |
| 572 |
} else if (auto substring{FixMisparsedSubstringDataRef(*dataRef)}) { |
| 573 |
mutate.u = std::move(*substring); |
| 574 |
} |
| 575 |
} |
| 576 |
return std::nullopt; |
| 577 |
} |
| 578 |
|
| 579 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Designator &d) { |
| 580 |
auto restorer{GetContextualMessages().SetLocation(d.source)}; |
| 581 |
if (auto substringInquiry{FixMisparsedSubstring(d)}) { |
| 582 |
return substringInquiry; |
| 583 |
} |
| 584 |
// These checks have to be deferred to these "top level" data-refs where |
| 585 |
// we can be sure that there are no following subscripts (yet). |
| 586 |
MaybeExpr result{Analyze(d.u)}; |
| 587 |
if (result) { |
| 588 |
std::optional<DataRef> dataRef{ExtractDataRef(std::move(result))}; |
| 589 |
if (!dataRef) { |
| 590 |
dataRef = ExtractDataRef(std::move(result), /*intoSubstring=*/true); |
| 591 |
} |
| 592 |
if (!dataRef) { |
| 593 |
dataRef = ExtractDataRef(std::move(result), |
| 594 |
/*intoSubstring=*/false, /*intoComplexPart=*/true); |
| 595 |
} |
| 596 |
if (dataRef && !CheckDataRef(*dataRef)) { |
| 597 |
result.reset(); |
| 598 |
} |
| 599 |
} |
| 600 |
return result; |
| 601 |
} |
| 602 |
|
| 603 |
// A utility subroutine to repackage optional expressions of various levels |
| 604 |
// of type specificity as fully general MaybeExpr values. |
| 605 |
template <typename A> common::IfNoLvalue<MaybeExpr, A> AsMaybeExpr(A &&x) { |
| 606 |
return AsGenericExpr(std::move(x)); |
| 607 |
} |
| 608 |
template <typename A> MaybeExpr AsMaybeExpr(std::optional<A> &&x) { |
| 609 |
if (x) { |
| 610 |
return AsMaybeExpr(std::move(*x)); |
| 611 |
} |
| 612 |
return std::nullopt; |
| 613 |
} |
| 614 |
|
| 615 |
// Type kind parameter values for literal constants. |
| 616 |
int ExpressionAnalyzer::AnalyzeKindParam( |
| 617 |
const std::optional<parser::KindParam> &kindParam, int defaultKind) { |
| 618 |
if (!kindParam) { |
| 619 |
return defaultKind; |
| 620 |
} |
| 621 |
std::int64_t kind{common::visit( |
| 622 |
common::visitors{ |
| 623 |
[](std::uint64_t k) { return static_cast<std::int64_t>(k); }, |
| 624 |
[&](const parser::Scalar< |
| 625 |
parser::Integer<parser::Constant<parser::Name>>> &n) { |
| 626 |
if (MaybeExpr ie{Analyze(n)}) { |
| 627 |
return ToInt64(*ie).value_or(defaultKind); |
| 628 |
} |
| 629 |
return static_cast<std::int64_t>(defaultKind); |
| 630 |
}, |
| 631 |
}, |
| 632 |
kindParam->u)}; |
| 633 |
if (kind != static_cast<int>(kind)) { |
| 634 |
Say("Unsupported type kind value (%jd)"_err_en_US, |
| 635 |
static_cast<std::intmax_t>(kind)); |
| 636 |
kind = defaultKind; |
| 637 |
} |
| 638 |
return static_cast<int>(kind); |
| 639 |
} |
| 640 |
|
| 641 |
// Common handling of parser::IntLiteralConstant and SignedIntLiteralConstant |
| 642 |
struct IntTypeVisitor { |
| 643 |
using Result = MaybeExpr; |
| 644 |
using Types = IntegerTypes; |
| 645 |
template <typename T> Result Test() { |
| 646 |
if (T::kind >= kind) { |
| 647 |
const char *p{digits.begin()}; |
| 648 |
using Int = typename T::Scalar; |
| 649 |
typename Int::ValueWithOverflow num{0, false}; |
| 650 |
if (isNegated) { |
| 651 |
auto unsignedNum{Int::Read(p, 10, false /*unsigned*/)}; |
| 652 |
num.value = unsignedNum.value.Negate().value; |
| 653 |
num.overflow = unsignedNum.overflow || num.value > Int{0}; |
| 654 |
if (!num.overflow && num.value.Negate().overflow && |
| 655 |
analyzer.context().ShouldWarn(LanguageFeature::BigIntLiterals) && |
| 656 |
!analyzer.context().IsInModuleFile(digits)) { |
| 657 |
analyzer.Say(digits, |
| 658 |
"negated maximum INTEGER(KIND=%d) literal"_port_en_US, T::kind); |
| 659 |
} |
| 660 |
} else { |
| 661 |
num = Int::Read(p, 10, true /*signed*/); |
| 662 |
} |
| 663 |
if (!num.overflow) { |
| 664 |
if (T::kind > kind) { |
| 665 |
if (!isDefaultKind || |
| 666 |
!analyzer.context().IsEnabled(LanguageFeature::BigIntLiterals)) { |
| 667 |
return std::nullopt; |
| 668 |
} else if (analyzer.context().ShouldWarn( |
| 669 |
LanguageFeature::BigIntLiterals)) { |
| 670 |
analyzer.Say(digits, |
| 671 |
"Integer literal is too large for default INTEGER(KIND=%d); " |
| 672 |
"assuming INTEGER(KIND=%d)"_port_en_US, |
| 673 |
kind, T::kind); |
| 674 |
} |
| 675 |
} |
| 676 |
return Expr<SomeType>{ |
| 677 |
Expr<SomeInteger>{Expr<T>{Constant<T>{std::move(num.value)}}}}; |
| 678 |
} |
| 679 |
} |
| 680 |
return std::nullopt; |
| 681 |
} |
| 682 |
ExpressionAnalyzer &analyzer; |
| 683 |
parser::CharBlock digits; |
| 684 |
std::int64_t kind; |
| 685 |
bool isDefaultKind; |
| 686 |
bool isNegated; |
| 687 |
}; |
| 688 |
|
| 689 |
template <typename PARSED> |
| 690 |
MaybeExpr ExpressionAnalyzer::IntLiteralConstant( |
| 691 |
const PARSED &x, bool isNegated) { |
| 692 |
const auto &kindParam{std::get<std::optional<parser::KindParam>>(x.t)}; |
| 693 |
bool isDefaultKind{!kindParam}; |
| 694 |
int kind{AnalyzeKindParam(kindParam, GetDefaultKind(TypeCategory::Integer))}; |
| 695 |
if (CheckIntrinsicKind(TypeCategory::Integer, kind)) { |
| 696 |
auto digits{std::get<parser::CharBlock>(x.t)}; |
| 697 |
if (MaybeExpr result{common::SearchTypes( |
| 698 |
IntTypeVisitor{*this, digits, kind, isDefaultKind, isNegated})}) { |
| 699 |
return result; |
| 700 |
} else if (isDefaultKind) { |
| 701 |
Say(digits, |
| 702 |
"Integer literal is too large for any allowable " |
| 703 |
"kind of INTEGER"_err_en_US); |
| 704 |
} else { |
| 705 |
Say(digits, "Integer literal is too large for INTEGER(KIND=%d)"_err_en_US, |
| 706 |
kind); |
| 707 |
} |
| 708 |
} |
| 709 |
return std::nullopt; |
| 710 |
} |
| 711 |
|
| 712 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 713 |
const parser::IntLiteralConstant &x, bool isNegated) { |
| 714 |
auto restorer{ |
| 715 |
GetContextualMessages().SetLocation(std::get<parser::CharBlock>(x.t))}; |
| 716 |
return IntLiteralConstant(x, isNegated); |
| 717 |
} |
| 718 |
|
| 719 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 720 |
const parser::SignedIntLiteralConstant &x) { |
| 721 |
auto restorer{GetContextualMessages().SetLocation(x.source)}; |
| 722 |
return IntLiteralConstant(x); |
| 723 |
} |
| 724 |
|
| 725 |
template <typename TYPE> |
| 726 |
Constant<TYPE> ReadRealLiteral( |
| 727 |
parser::CharBlock source, FoldingContext &context) { |
| 728 |
const char *p{source.begin()}; |
| 729 |
auto valWithFlags{ |
| 730 |
Scalar<TYPE>::Read(p, context.targetCharacteristics().roundingMode())}; |
| 731 |
CHECK(p == source.end()); |
| 732 |
RealFlagWarnings(context, valWithFlags.flags, "conversion of REAL literal"); |
| 733 |
auto value{valWithFlags.value}; |
| 734 |
if (context.targetCharacteristics().areSubnormalsFlushedToZero()) { |
| 735 |
value = value.FlushSubnormalToZero(); |
| 736 |
} |
| 737 |
return {value}; |
| 738 |
} |
| 739 |
|
| 740 |
struct RealTypeVisitor { |
| 741 |
using Result = std::optional<Expr<SomeReal>>; |
| 742 |
using Types = RealTypes; |
| 743 |
|
| 744 |
RealTypeVisitor(int k, parser::CharBlock lit, FoldingContext &ctx) |
| 745 |
: kind{k}, literal{lit}, context{ctx} {} |
| 746 |
|
| 747 |
template <typename T> Result Test() { |
| 748 |
if (kind == T::kind) { |
| 749 |
return {AsCategoryExpr(ReadRealLiteral<T>(literal, context))}; |
| 750 |
} |
| 751 |
return std::nullopt; |
| 752 |
} |
| 753 |
|
| 754 |
int kind; |
| 755 |
parser::CharBlock literal; |
| 756 |
FoldingContext &context; |
| 757 |
}; |
| 758 |
|
| 759 |
// Reads a real literal constant and encodes it with the right kind. |
| 760 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::RealLiteralConstant &x) { |
| 761 |
// Use a local message context around the real literal for better |
| 762 |
// provenance on any messages. |
| 763 |
auto restorer{GetContextualMessages().SetLocation(x.real.source)}; |
| 764 |
// If a kind parameter appears, it defines the kind of the literal and the |
| 765 |
// letter used in an exponent part must be 'E' (e.g., the 'E' in |
| 766 |
// "6.02214E+23"). In the absence of an explicit kind parameter, any |
| 767 |
// exponent letter determines the kind. Otherwise, defaults apply. |
| 768 |
auto &defaults{context_.defaultKinds()}; |
| 769 |
int defaultKind{defaults.GetDefaultKind(TypeCategory::Real)}; |
| 770 |
const char *end{x.real.source.end()}; |
| 771 |
char expoLetter{' '}; |
| 772 |
std::optional<int> letterKind; |
| 773 |
for (const char *p{x.real.source.begin()}; p < end; ++p) { |
| 774 |
if (parser::IsLetter(*p)) { |
| 775 |
expoLetter = *p; |
| 776 |
switch (expoLetter) { |
| 777 |
case 'e': |
| 778 |
letterKind = defaults.GetDefaultKind(TypeCategory::Real); |
| 779 |
break; |
| 780 |
case 'd': |
| 781 |
letterKind = defaults.doublePrecisionKind(); |
| 782 |
break; |
| 783 |
case 'q': |
| 784 |
letterKind = defaults.quadPrecisionKind(); |
| 785 |
break; |
| 786 |
default: |
| 787 |
Say("Unknown exponent letter '%c'"_err_en_US, expoLetter); |
| 788 |
} |
| 789 |
break; |
| 790 |
} |
| 791 |
} |
| 792 |
if (letterKind) { |
| 793 |
defaultKind = *letterKind; |
| 794 |
} |
| 795 |
// C716 requires 'E' as an exponent. |
| 796 |
// Extension: allow exponent-letter matching the kind-param. |
| 797 |
auto kind{AnalyzeKindParam(x.kind, defaultKind)}; |
| 798 |
if (letterKind && expoLetter != 'e') { |
| 799 |
if (kind != *letterKind) { |
| 800 |
if (context_.ShouldWarn( |
| 801 |
common::LanguageFeature::ExponentMatchingKindParam)) { |
| 802 |
Say("Explicit kind parameter on real constant disagrees with exponent letter '%c'"_warn_en_US, |
| 803 |
expoLetter); |
| 804 |
} |
| 805 |
} else if (x.kind && |
| 806 |
context_.ShouldWarn( |
| 807 |
common::LanguageFeature::ExponentMatchingKindParam)) { |
| 808 |
Say("Explicit kind parameter together with non-'E' exponent letter " |
| 809 |
"is not standard"_port_en_US); |
| 810 |
} |
| 811 |
} |
| 812 |
auto result{common::SearchTypes( |
| 813 |
RealTypeVisitor{kind, x.real.source, GetFoldingContext()})}; |
| 814 |
if (!result) { // C717 |
| 815 |
Say("Unsupported REAL(KIND=%d)"_err_en_US, kind); |
| 816 |
} |
| 817 |
return AsMaybeExpr(std::move(result)); |
| 818 |
} |
| 819 |
|
| 820 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 821 |
const parser::SignedRealLiteralConstant &x) { |
| 822 |
if (auto result{Analyze(std::get<parser::RealLiteralConstant>(x.t))}) { |
| 823 |
auto &realExpr{std::get<Expr<SomeReal>>(result->u)}; |
| 824 |
if (auto sign{std::get<std::optional<parser::Sign>>(x.t)}) { |
| 825 |
if (sign == parser::Sign::Negative) { |
| 826 |
return AsGenericExpr(-std::move(realExpr)); |
| 827 |
} |
| 828 |
} |
| 829 |
return result; |
| 830 |
} |
| 831 |
return std::nullopt; |
| 832 |
} |
| 833 |
|
| 834 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 835 |
const parser::SignedComplexLiteralConstant &x) { |
| 836 |
auto result{Analyze(std::get<parser::ComplexLiteralConstant>(x.t))}; |
| 837 |
if (!result) { |
| 838 |
return std::nullopt; |
| 839 |
} else if (std::get<parser::Sign>(x.t) == parser::Sign::Negative) { |
| 840 |
return AsGenericExpr(-std::move(std::get<Expr<SomeComplex>>(result->u))); |
| 841 |
} else { |
| 842 |
return result; |
| 843 |
} |
| 844 |
} |
| 845 |
|
| 846 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::ComplexPart &x) { |
| 847 |
return Analyze(x.u); |
| 848 |
} |
| 849 |
|
| 850 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::ComplexLiteralConstant &z) { |
| 851 |
return AnalyzeComplex(Analyze(std::get<0>(z.t)), Analyze(std::get<1>(z.t)), |
| 852 |
"complex literal constant"); |
| 853 |
} |
| 854 |
|
| 855 |
// CHARACTER literal processing. |
| 856 |
MaybeExpr ExpressionAnalyzer::AnalyzeString(std::string &&string, int kind) { |
| 857 |
if (!CheckIntrinsicKind(TypeCategory::Character, kind)) { |
| 858 |
return std::nullopt; |
| 859 |
} |
| 860 |
switch (kind) { |
| 861 |
case 1: |
| 862 |
return AsGenericExpr(Constant<Type<TypeCategory::Character, 1>>{ |
| 863 |
parser::DecodeString<std::string, parser::Encoding::LATIN_1>( |
| 864 |
string, true)}); |
| 865 |
case 2: |
| 866 |
return AsGenericExpr(Constant<Type<TypeCategory::Character, 2>>{ |
| 867 |
parser::DecodeString<std::u16string, parser::Encoding::UTF_8>( |
| 868 |
string, true)}); |
| 869 |
case 4: |
| 870 |
return AsGenericExpr(Constant<Type<TypeCategory::Character, 4>>{ |
| 871 |
parser::DecodeString<std::u32string, parser::Encoding::UTF_8>( |
| 872 |
string, true)}); |
| 873 |
default: |
| 874 |
CRASH_NO_CASE; |
| 875 |
} |
| 876 |
} |
| 877 |
|
| 878 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::CharLiteralConstant &x) { |
| 879 |
int kind{ |
| 880 |
AnalyzeKindParam(std::get<std::optional<parser::KindParam>>(x.t), 1)}; |
| 881 |
auto value{std::get<std::string>(x.t)}; |
| 882 |
return AnalyzeString(std::move(value), kind); |
| 883 |
} |
| 884 |
|
| 885 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 886 |
const parser::HollerithLiteralConstant &x) { |
| 887 |
int kind{GetDefaultKind(TypeCategory::Character)}; |
| 888 |
auto result{AnalyzeString(std::string{x.v}, kind)}; |
| 889 |
if (auto *constant{UnwrapConstantValue<Ascii>(result)}) { |
| 890 |
constant->set_wasHollerith(true); |
| 891 |
} |
| 892 |
return result; |
| 893 |
} |
| 894 |
|
| 895 |
// .TRUE. and .FALSE. of various kinds |
| 896 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::LogicalLiteralConstant &x) { |
| 897 |
auto kind{AnalyzeKindParam(std::get<std::optional<parser::KindParam>>(x.t), |
| 898 |
GetDefaultKind(TypeCategory::Logical))}; |
| 899 |
bool value{std::get<bool>(x.t)}; |
| 900 |
auto result{common::SearchTypes( |
| 901 |
TypeKindVisitor<TypeCategory::Logical, Constant, bool>{ |
| 902 |
kind, std::move(value)})}; |
| 903 |
if (!result) { |
| 904 |
Say("unsupported LOGICAL(KIND=%d)"_err_en_US, kind); // C728 |
| 905 |
} |
| 906 |
return result; |
| 907 |
} |
| 908 |
|
| 909 |
// BOZ typeless literals |
| 910 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::BOZLiteralConstant &x) { |
| 911 |
const char *p{x.v.c_str()}; |
| 912 |
std::uint64_t base{16}; |
| 913 |
switch (*p++) { |
| 914 |
case 'b': |
| 915 |
base = 2; |
| 916 |
break; |
| 917 |
case 'o': |
| 918 |
base = 8; |
| 919 |
break; |
| 920 |
case 'z': |
| 921 |
break; |
| 922 |
case 'x': |
| 923 |
break; |
| 924 |
default: |
| 925 |
CRASH_NO_CASE; |
| 926 |
} |
| 927 |
CHECK(*p == '"'); |
| 928 |
++p; |
| 929 |
auto value{BOZLiteralConstant::Read(p, base, false /*unsigned*/)}; |
| 930 |
if (*p != '"') { |
| 931 |
Say("Invalid digit ('%c') in BOZ literal '%s'"_err_en_US, *p, |
| 932 |
x.v); // C7107, C7108 |
| 933 |
return std::nullopt; |
| 934 |
} |
| 935 |
if (value.overflow) { |
| 936 |
Say("BOZ literal '%s' too large"_err_en_US, x.v); |
| 937 |
return std::nullopt; |
| 938 |
} |
| 939 |
return AsGenericExpr(std::move(value.value)); |
| 940 |
} |
| 941 |
|
| 942 |
// Names and named constants |
| 943 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Name &n) { |
| 944 |
auto restorer{GetContextualMessages().SetLocation(n.source)}; |
| 945 |
if (std::optional<int> kind{IsImpliedDo(n.source)}) { |
| 946 |
return AsMaybeExpr(ConvertToKind<TypeCategory::Integer>( |
| 947 |
*kind, AsExpr(ImpliedDoIndex{n.source}))); |
| 948 |
} |
| 949 |
if (context_.HasError(n.symbol)) { // includes case of no symbol |
| 950 |
return std::nullopt; |
| 951 |
} else { |
| 952 |
const Symbol &ultimate{n.symbol->GetUltimate()}; |
| 953 |
if (ultimate.has<semantics::TypeParamDetails>()) { |
| 954 |
// A bare reference to a derived type parameter within a parameterized |
| 955 |
// derived type definition. |
| 956 |
auto dyType{DynamicType::From(ultimate)}; |
| 957 |
if (!dyType) { |
| 958 |
// When the integer kind of this type parameter is not known now, |
| 959 |
// it's either an error or because it depends on earlier-declared kind |
| 960 |
// type parameters. So assume that it's a subscript integer for now |
| 961 |
// while processing other specification expressions in the PDT |
| 962 |
// definition; the right kind value will be used later in each of its |
| 963 |
// instantiations. |
| 964 |
int kind{SubscriptInteger::kind}; |
| 965 |
if (const auto *typeSpec{ultimate.GetType()}) { |
| 966 |
if (const semantics::IntrinsicTypeSpec * |
| 967 |
intrinType{typeSpec->AsIntrinsic()}) { |
| 968 |
if (auto k{ToInt64(Fold(semantics::KindExpr{intrinType->kind()}))}; |
| 969 |
k && IsValidKindOfIntrinsicType(TypeCategory::Integer, *k)) { |
| 970 |
kind = *k; |
| 971 |
} |
| 972 |
} |
| 973 |
} |
| 974 |
dyType = DynamicType{TypeCategory::Integer, kind}; |
| 975 |
} |
| 976 |
return Fold(ConvertToType( |
| 977 |
*dyType, AsGenericExpr(TypeParamInquiry{std::nullopt, ultimate}))); |
| 978 |
} else { |
| 979 |
if (n.symbol->attrs().test(semantics::Attr::VOLATILE)) { |
| 980 |
if (const semantics::Scope *pure{semantics::FindPureProcedureContaining( |
| 981 |
context_.FindScope(n.source))}) { |
| 982 |
SayAt(n, |
| 983 |
"VOLATILE variable '%s' may not be referenced in pure subprogram '%s'"_err_en_US, |
| 984 |
n.source, DEREF(pure->symbol()).name()); |
| 985 |
n.symbol->attrs().reset(semantics::Attr::VOLATILE); |
| 986 |
} |
| 987 |
} |
| 988 |
if (!isWholeAssumedSizeArrayOk_ && |
| 989 |
semantics::IsAssumedSizeArray( |
| 990 |
ResolveAssociations(*n.symbol))) { // C1002, C1014, C1231 |
| 991 |
AttachDeclaration( |
| 992 |
SayAt(n, |
| 993 |
"Whole assumed-size array '%s' may not appear here without subscripts"_err_en_US, |
| 994 |
n.source), |
| 995 |
*n.symbol); |
| 996 |
} |
| 997 |
return Designate(DataRef{*n.symbol}); |
| 998 |
} |
| 999 |
} |
| 1000 |
} |
| 1001 |
|
| 1002 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::NamedConstant &n) { |
| 1003 |
auto restorer{GetContextualMessages().SetLocation(n.v.source)}; |
| 1004 |
if (MaybeExpr value{Analyze(n.v)}) { |
| 1005 |
Expr<SomeType> folded{Fold(std::move(*value))}; |
| 1006 |
if (IsConstantExpr(folded)) { |
| 1007 |
return folded; |
| 1008 |
} |
| 1009 |
Say(n.v.source, "must be a constant"_err_en_US); // C718 |
| 1010 |
} |
| 1011 |
return std::nullopt; |
| 1012 |
} |
| 1013 |
|
| 1014 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::NullInit &n) { |
| 1015 |
auto restorer{AllowNullPointer()}; |
| 1016 |
if (MaybeExpr value{Analyze(n.v.value())}) { |
| 1017 |
// Subtle: when the NullInit is a DataStmtConstant, it might |
| 1018 |
// be a misparse of a structure constructor without parameters |
| 1019 |
// or components (e.g., T()). Checking the result to ensure |
| 1020 |
// that a "=>" data entity initializer actually resolved to |
| 1021 |
// a null pointer has to be done by the caller. |
| 1022 |
return Fold(std::move(*value)); |
| 1023 |
} |
| 1024 |
return std::nullopt; |
| 1025 |
} |
| 1026 |
|
| 1027 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 1028 |
const parser::StmtFunctionStmt &stmtFunc) { |
| 1029 |
inStmtFunctionDefinition_ = true; |
| 1030 |
return Analyze(std::get<parser::Scalar<parser::Expr>>(stmtFunc.t)); |
| 1031 |
} |
| 1032 |
|
| 1033 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::InitialDataTarget &x) { |
| 1034 |
return Analyze(x.value()); |
| 1035 |
} |
| 1036 |
|
| 1037 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::DataStmtValue &x) { |
| 1038 |
if (const auto &repeat{ |
| 1039 |
std::get<std::optional<parser::DataStmtRepeat>>(x.t)}) { |
| 1040 |
x.repetitions = -1; |
| 1041 |
if (MaybeExpr expr{Analyze(repeat->u)}) { |
| 1042 |
Expr<SomeType> folded{Fold(std::move(*expr))}; |
| 1043 |
if (auto value{ToInt64(folded)}) { |
| 1044 |
if (*value >= 0) { // C882 |
| 1045 |
x.repetitions = *value; |
| 1046 |
} else { |
| 1047 |
Say(FindSourceLocation(repeat), |
| 1048 |
"Repeat count (%jd) for data value must not be negative"_err_en_US, |
| 1049 |
*value); |
| 1050 |
} |
| 1051 |
} |
| 1052 |
} |
| 1053 |
} |
| 1054 |
return Analyze(std::get<parser::DataStmtConstant>(x.t)); |
| 1055 |
} |
| 1056 |
|
| 1057 |
// Substring references |
| 1058 |
std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::GetSubstringBound( |
| 1059 |
const std::optional<parser::ScalarIntExpr> &bound) { |
| 1060 |
if (bound) { |
| 1061 |
if (MaybeExpr expr{Analyze(*bound)}) { |
| 1062 |
if (expr->Rank() > 1) { |
| 1063 |
Say("substring bound expression has rank %d"_err_en_US, expr->Rank()); |
| 1064 |
} |
| 1065 |
if (auto *intExpr{std::get_if<Expr<SomeInteger>>(&expr->u)}) { |
| 1066 |
if (auto *ssIntExpr{std::get_if<Expr<SubscriptInteger>>(&intExpr->u)}) { |
| 1067 |
return {std::move(*ssIntExpr)}; |
| 1068 |
} |
| 1069 |
return {Expr<SubscriptInteger>{ |
| 1070 |
Convert<SubscriptInteger, TypeCategory::Integer>{ |
| 1071 |
std::move(*intExpr)}}}; |
| 1072 |
} else { |
| 1073 |
Say("substring bound expression is not INTEGER"_err_en_US); |
| 1074 |
} |
| 1075 |
} |
| 1076 |
} |
| 1077 |
return std::nullopt; |
| 1078 |
} |
| 1079 |
|
| 1080 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Substring &ss) { |
| 1081 |
if (MaybeExpr baseExpr{Analyze(std::get<parser::DataRef>(ss.t))}) { |
| 1082 |
if (std::optional<DataRef> dataRef{ExtractDataRef(std::move(*baseExpr))}) { |
| 1083 |
if (MaybeExpr newBaseExpr{Designate(std::move(*dataRef))}) { |
| 1084 |
if (std::optional<DataRef> checked{ |
| 1085 |
ExtractDataRef(std::move(*newBaseExpr))}) { |
| 1086 |
const parser::SubstringRange &range{ |
| 1087 |
std::get<parser::SubstringRange>(ss.t)}; |
| 1088 |
std::optional<Expr<SubscriptInteger>> first{ |
| 1089 |
Fold(GetSubstringBound(std::get<0>(range.t)))}; |
| 1090 |
std::optional<Expr<SubscriptInteger>> last{ |
| 1091 |
Fold(GetSubstringBound(std::get<1>(range.t)))}; |
| 1092 |
const Symbol &symbol{checked->GetLastSymbol()}; |
| 1093 |
if (std::optional<DynamicType> dynamicType{ |
| 1094 |
DynamicType::From(symbol)}) { |
| 1095 |
if (dynamicType->category() == TypeCategory::Character) { |
| 1096 |
auto lbValue{ToInt64(first)}; |
| 1097 |
if (!lbValue) { |
| 1098 |
lbValue = 1; |
| 1099 |
} |
| 1100 |
auto ubValue{ToInt64(last)}; |
| 1101 |
auto len{dynamicType->knownLength()}; |
| 1102 |
if (!ubValue) { |
| 1103 |
ubValue = len; |
| 1104 |
} |
| 1105 |
if (lbValue && ubValue && *lbValue > *ubValue) { |
| 1106 |
// valid, substring is empty |
| 1107 |
} else if (lbValue && *lbValue < 1 && (ubValue || !last)) { |
| 1108 |
Say("Substring must begin at 1 or later, not %jd"_err_en_US, |
| 1109 |
static_cast<std::intmax_t>(*lbValue)); |
| 1110 |
return std::nullopt; |
| 1111 |
} else if (ubValue && len && *ubValue > *len && |
| 1112 |
(lbValue || !first)) { |
| 1113 |
Say("Substring must end at %zd or earlier, not %jd"_err_en_US, |
| 1114 |
static_cast<std::intmax_t>(*len), |
| 1115 |
static_cast<std::intmax_t>(*ubValue)); |
| 1116 |
return std::nullopt; |
| 1117 |
} |
| 1118 |
return WrapperHelper<TypeCategory::Character, Designator, |
| 1119 |
Substring>(dynamicType->kind(), |
| 1120 |
Substring{std::move(checked.value()), std::move(first), |
| 1121 |
std::move(last)}); |
| 1122 |
} |
| 1123 |
} |
| 1124 |
Say("substring may apply only to CHARACTER"_err_en_US); |
| 1125 |
} |
| 1126 |
} |
| 1127 |
} |
| 1128 |
} |
| 1129 |
return std::nullopt; |
| 1130 |
} |
| 1131 |
|
| 1132 |
// CHARACTER literal substrings |
| 1133 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 1134 |
const parser::CharLiteralConstantSubstring &x) { |
| 1135 |
const parser::SubstringRange &range{std::get<parser::SubstringRange>(x.t)}; |
| 1136 |
std::optional<Expr<SubscriptInteger>> lower{ |
| 1137 |
GetSubstringBound(std::get<0>(range.t))}; |
| 1138 |
std::optional<Expr<SubscriptInteger>> upper{ |
| 1139 |
GetSubstringBound(std::get<1>(range.t))}; |
| 1140 |
if (MaybeExpr string{Analyze(std::get<parser::CharLiteralConstant>(x.t))}) { |
| 1141 |
if (auto *charExpr{std::get_if<Expr<SomeCharacter>>(&string->u)}) { |
| 1142 |
Expr<SubscriptInteger> length{ |
| 1143 |
common::visit([](const auto &ckExpr) { return ckExpr.LEN().value(); }, |
| 1144 |
charExpr->u)}; |
| 1145 |
if (!lower) { |
| 1146 |
lower = Expr<SubscriptInteger>{1}; |
| 1147 |
} |
| 1148 |
if (!upper) { |
| 1149 |
upper = Expr<SubscriptInteger>{ |
| 1150 |
static_cast<std::int64_t>(ToInt64(length).value())}; |
| 1151 |
} |
| 1152 |
return common::visit( |
| 1153 |
[&](auto &&ckExpr) -> MaybeExpr { |
| 1154 |
using Result = ResultType<decltype(ckExpr)>; |
| 1155 |
auto *cp{std::get_if<Constant<Result>>(&ckExpr.u)}; |
| 1156 |
CHECK(DEREF(cp).size() == 1); |
| 1157 |
StaticDataObject::Pointer staticData{StaticDataObject::Create()}; |
| 1158 |
staticData->set_alignment(Result::kind) |
| 1159 |
.set_itemBytes(Result::kind) |
| 1160 |
.Push(cp->GetScalarValue().value(), |
| 1161 |
foldingContext_.targetCharacteristics().isBigEndian()); |
| 1162 |
Substring substring{std::move(staticData), std::move(lower.value()), |
| 1163 |
std::move(upper.value())}; |
| 1164 |
return AsGenericExpr( |
| 1165 |
Expr<Result>{Designator<Result>{std::move(substring)}}); |
| 1166 |
}, |
| 1167 |
std::move(charExpr->u)); |
| 1168 |
} |
| 1169 |
} |
| 1170 |
return std::nullopt; |
| 1171 |
} |
| 1172 |
|
| 1173 |
// substring%KIND/LEN |
| 1174 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::SubstringInquiry &x) { |
| 1175 |
if (MaybeExpr substring{Analyze(x.v)}) { |
| 1176 |
CHECK(x.source.size() >= 8); |
| 1177 |
int nameLen{x.source.end()[-1] == 'n' ? 3 /*LEN*/ : 4 /*KIND*/}; |
| 1178 |
parser::CharBlock name{ |
| 1179 |
x.source.end() - nameLen, static_cast<std::size_t>(nameLen)}; |
| 1180 |
CHECK(name == "len" || name == "kind"); |
| 1181 |
return MakeFunctionRef( |
| 1182 |
name, ActualArguments{ActualArgument{std::move(*substring)}}); |
| 1183 |
} else { |
| 1184 |
return std::nullopt; |
| 1185 |
} |
| 1186 |
} |
| 1187 |
|
| 1188 |
// Subscripted array references |
| 1189 |
std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::AsSubscript( |
| 1190 |
MaybeExpr &&expr) { |
| 1191 |
if (expr) { |
| 1192 |
if (expr->Rank() > 1) { |
| 1193 |
Say("Subscript expression has rank %d greater than 1"_err_en_US, |
| 1194 |
expr->Rank()); |
| 1195 |
} |
| 1196 |
if (auto *intExpr{std::get_if<Expr<SomeInteger>>(&expr->u)}) { |
| 1197 |
if (auto *ssIntExpr{std::get_if<Expr<SubscriptInteger>>(&intExpr->u)}) { |
| 1198 |
return std::move(*ssIntExpr); |
| 1199 |
} else { |
| 1200 |
return Expr<SubscriptInteger>{ |
| 1201 |
Convert<SubscriptInteger, TypeCategory::Integer>{ |
| 1202 |
std::move(*intExpr)}}; |
| 1203 |
} |
| 1204 |
} else { |
| 1205 |
Say("Subscript expression is not INTEGER"_err_en_US); |
| 1206 |
} |
| 1207 |
} |
| 1208 |
return std::nullopt; |
| 1209 |
} |
| 1210 |
|
| 1211 |
std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::TripletPart( |
| 1212 |
const std::optional<parser::Subscript> &s) { |
| 1213 |
if (s) { |
| 1214 |
return AsSubscript(Analyze(*s)); |
| 1215 |
} else { |
| 1216 |
return std::nullopt; |
| 1217 |
} |
| 1218 |
} |
| 1219 |
|
| 1220 |
std::optional<Subscript> ExpressionAnalyzer::AnalyzeSectionSubscript( |
| 1221 |
const parser::SectionSubscript &ss) { |
| 1222 |
return common::visit( |
| 1223 |
common::visitors{ |
| 1224 |
[&](const parser::SubscriptTriplet &t) -> std::optional<Subscript> { |
| 1225 |
const auto &lower{std::get<0>(t.t)}; |
| 1226 |
const auto &upper{std::get<1>(t.t)}; |
| 1227 |
const auto &stride{std::get<2>(t.t)}; |
| 1228 |
auto result{Triplet{ |
| 1229 |
TripletPart(lower), TripletPart(upper), TripletPart(stride)}}; |
| 1230 |
if ((lower && !result.lower()) || (upper && !result.upper())) { |
| 1231 |
return std::nullopt; |
| 1232 |
} else { |
| 1233 |
return std::make_optional<Subscript>(result); |
| 1234 |
} |
| 1235 |
}, |
| 1236 |
[&](const auto &s) -> std::optional<Subscript> { |
| 1237 |
if (auto subscriptExpr{AsSubscript(Analyze(s))}) { |
| 1238 |
return Subscript{std::move(*subscriptExpr)}; |
| 1239 |
} else { |
| 1240 |
return std::nullopt; |
| 1241 |
} |
| 1242 |
}, |
| 1243 |
}, |
| 1244 |
ss.u); |
| 1245 |
} |
| 1246 |
|
| 1247 |
// Empty result means an error occurred |
| 1248 |
std::vector<Subscript> ExpressionAnalyzer::AnalyzeSectionSubscripts( |
| 1249 |
const std::list<parser::SectionSubscript> &sss) { |
| 1250 |
bool error{false}; |
| 1251 |
std::vector<Subscript> subscripts; |
| 1252 |
for (const auto &s : sss) { |
| 1253 |
if (auto subscript{AnalyzeSectionSubscript(s)}) { |
| 1254 |
subscripts.emplace_back(std::move(*subscript)); |
| 1255 |
} else { |
| 1256 |
error = true; |
| 1257 |
} |
| 1258 |
} |
| 1259 |
return !error ? subscripts : std::vector<Subscript>{}; |
| 1260 |
} |
| 1261 |
|
| 1262 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::ArrayElement &ae) { |
| 1263 |
MaybeExpr baseExpr; |
| 1264 |
{ |
| 1265 |
auto restorer{AllowWholeAssumedSizeArray()}; |
| 1266 |
baseExpr = Analyze(ae.base); |
| 1267 |
} |
| 1268 |
if (baseExpr) { |
| 1269 |
if (ae.subscripts.empty()) { |
| 1270 |
// will be converted to function call later or error reported |
| 1271 |
} else if (baseExpr->Rank() == 0) { |
| 1272 |
if (const Symbol *symbol{GetLastSymbol(*baseExpr)}) { |
| 1273 |
if (!context_.HasError(symbol)) { |
| 1274 |
if (inDataStmtConstant_) { |
| 1275 |
// Better error for NULL(X) with a MOLD= argument |
| 1276 |
Say("'%s' must be an array or structure constructor if used with non-empty parentheses as a DATA statement constant"_err_en_US, |
| 1277 |
symbol->name()); |
| 1278 |
} else { |
| 1279 |
Say("'%s' is not an array"_err_en_US, symbol->name()); |
| 1280 |
} |
| 1281 |
context_.SetError(*symbol); |
| 1282 |
} |
| 1283 |
} |
| 1284 |
} else if (std::optional<DataRef> dataRef{ |
| 1285 |
ExtractDataRef(std::move(*baseExpr))}) { |
| 1286 |
return ApplySubscripts( |
| 1287 |
std::move(*dataRef), AnalyzeSectionSubscripts(ae.subscripts)); |
| 1288 |
} else { |
| 1289 |
Say("Subscripts may be applied only to an object, component, or array constant"_err_en_US); |
| 1290 |
} |
| 1291 |
} |
| 1292 |
// error was reported: analyze subscripts without reporting more errors |
| 1293 |
auto restorer{GetContextualMessages().DiscardMessages()}; |
| 1294 |
AnalyzeSectionSubscripts(ae.subscripts); |
| 1295 |
return std::nullopt; |
| 1296 |
} |
| 1297 |
|
| 1298 |
// Type parameter inquiries apply to data references, but don't depend |
| 1299 |
// on any trailing (co)subscripts. |
| 1300 |
static NamedEntity IgnoreAnySubscripts(Designator<SomeDerived> &&designator) { |
| 1301 |
return common::visit( |
| 1302 |
common::visitors{ |
| 1303 |
[](SymbolRef &&symbol) { return NamedEntity{symbol}; }, |
| 1304 |
[](Component &&component) { |
| 1305 |
return NamedEntity{std::move(component)}; |
| 1306 |
}, |
| 1307 |
[](ArrayRef &&arrayRef) { return std::move(arrayRef.base()); }, |
| 1308 |
[](CoarrayRef &&coarrayRef) { |
| 1309 |
return NamedEntity{coarrayRef.GetLastSymbol()}; |
| 1310 |
}, |
| 1311 |
}, |
| 1312 |
std::move(designator.u)); |
| 1313 |
} |
| 1314 |
|
| 1315 |
// Components, but not bindings, of parent derived types are explicitly |
| 1316 |
// represented as such. |
| 1317 |
std::optional<Component> ExpressionAnalyzer::CreateComponent(DataRef &&base, |
| 1318 |
const Symbol &component, const semantics::Scope &scope, |
| 1319 |
bool C919bAlreadyEnforced) { |
| 1320 |
if (!C919bAlreadyEnforced && IsAllocatableOrPointer(component) && |
| 1321 |
base.Rank() > 0) { // C919b |
| 1322 |
Say("An allocatable or pointer component reference must be applied to a scalar base"_err_en_US); |
| 1323 |
} |
| 1324 |
if (&component.owner() == &scope || |
| 1325 |
component.has<semantics::ProcBindingDetails>()) { |
| 1326 |
return Component{std::move(base), component}; |
| 1327 |
} |
| 1328 |
if (const Symbol *typeSymbol{scope.GetSymbol()}) { |
| 1329 |
if (const Symbol *parentComponent{typeSymbol->GetParentComponent(&scope)}) { |
| 1330 |
if (const auto *object{ |
| 1331 |
parentComponent->detailsIf<semantics::ObjectEntityDetails>()}) { |
| 1332 |
if (const auto *parentType{object->type()}) { |
| 1333 |
if (const semantics::Scope *parentScope{ |
| 1334 |
parentType->derivedTypeSpec().scope()}) { |
| 1335 |
return CreateComponent( |
| 1336 |
DataRef{Component{std::move(base), *parentComponent}}, |
| 1337 |
component, *parentScope, C919bAlreadyEnforced); |
| 1338 |
} |
| 1339 |
} |
| 1340 |
} |
| 1341 |
} |
| 1342 |
} |
| 1343 |
return std::nullopt; |
| 1344 |
} |
| 1345 |
|
| 1346 |
// Derived type component references and type parameter inquiries |
| 1347 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::StructureComponent &sc) { |
| 1348 |
Symbol *sym{sc.component.symbol}; |
| 1349 |
if (context_.HasError(sym)) { |
| 1350 |
return std::nullopt; |
| 1351 |
} |
| 1352 |
const auto *misc{sym->detailsIf<semantics::MiscDetails>()}; |
| 1353 |
bool isTypeParamInquiry{sym->has<semantics::TypeParamDetails>() || |
| 1354 |
(misc && |
| 1355 |
(misc->kind() == semantics::MiscDetails::Kind::KindParamInquiry || |
| 1356 |
misc->kind() == semantics::MiscDetails::Kind::LenParamInquiry))}; |
| 1357 |
MaybeExpr base; |
| 1358 |
if (isTypeParamInquiry) { |
| 1359 |
auto restorer{AllowWholeAssumedSizeArray()}; |
| 1360 |
base = Analyze(sc.base); |
| 1361 |
} else { |
| 1362 |
base = Analyze(sc.base); |
| 1363 |
} |
| 1364 |
if (!base) { |
| 1365 |
return std::nullopt; |
| 1366 |
} |
| 1367 |
const auto &name{sc.component.source}; |
| 1368 |
if (auto *dtExpr{UnwrapExpr<Expr<SomeDerived>>(*base)}) { |
| 1369 |
const auto *dtSpec{GetDerivedTypeSpec(dtExpr->GetType())}; |
| 1370 |
if (isTypeParamInquiry) { |
| 1371 |
if (auto *designator{UnwrapExpr<Designator<SomeDerived>>(*dtExpr)}) { |
| 1372 |
if (std::optional<DynamicType> dyType{DynamicType::From(*sym)}) { |
| 1373 |
if (dyType->category() == TypeCategory::Integer) { |
| 1374 |
auto restorer{GetContextualMessages().SetLocation(name)}; |
| 1375 |
return Fold(ConvertToType(*dyType, |
| 1376 |
AsGenericExpr(TypeParamInquiry{ |
| 1377 |
IgnoreAnySubscripts(std::move(*designator)), *sym}))); |
| 1378 |
} |
| 1379 |
} |
| 1380 |
Say(name, "Type parameter is not INTEGER"_err_en_US); |
| 1381 |
} else { |
| 1382 |
Say(name, |
| 1383 |
"A type parameter inquiry must be applied to a designator"_err_en_US); |
| 1384 |
} |
| 1385 |
} else if (!dtSpec || !dtSpec->scope()) { |
| 1386 |
CHECK(context_.AnyFatalError() || !foldingContext_.messages().empty()); |
| 1387 |
return std::nullopt; |
| 1388 |
} else if (std::optional<DataRef> dataRef{ |
| 1389 |
ExtractDataRef(std::move(*dtExpr))}) { |
| 1390 |
auto restorer{GetContextualMessages().SetLocation(name)}; |
| 1391 |
if (auto component{ |
| 1392 |
CreateComponent(std::move(*dataRef), *sym, *dtSpec->scope())}) { |
| 1393 |
return Designate(DataRef{std::move(*component)}); |
| 1394 |
} else { |
| 1395 |
Say(name, "Component is not in scope of derived TYPE(%s)"_err_en_US, |
| 1396 |
dtSpec->typeSymbol().name()); |
| 1397 |
} |
| 1398 |
} else { |
| 1399 |
Say(name, |
| 1400 |
"Base of component reference must be a data reference"_err_en_US); |
| 1401 |
} |
| 1402 |
} else if (auto *details{sym->detailsIf<semantics::MiscDetails>()}) { |
| 1403 |
// special part-ref: %re, %im, %kind, %len |
| 1404 |
// Type errors on the base of %re/%im/%len are detected and |
| 1405 |
// reported in name resolution. |
| 1406 |
using MiscKind = semantics::MiscDetails::Kind; |
| 1407 |
MiscKind kind{details->kind()}; |
| 1408 |
if (kind == MiscKind::ComplexPartRe || kind == MiscKind::ComplexPartIm) { |
| 1409 |
if (auto *zExpr{std::get_if<Expr<SomeComplex>>(&base->u)}) { |
| 1410 |
if (std::optional<DataRef> dataRef{ExtractDataRef(*zExpr)}) { |
| 1411 |
// Represent %RE/%IM as a designator |
| 1412 |
Expr<SomeReal> realExpr{common::visit( |
| 1413 |
[&](const auto &z) { |
| 1414 |
using PartType = typename ResultType<decltype(z)>::Part; |
| 1415 |
auto part{kind == MiscKind::ComplexPartRe |
| 1416 |
? ComplexPart::Part::RE |
| 1417 |
: ComplexPart::Part::IM}; |
| 1418 |
return AsCategoryExpr(Designator<PartType>{ |
| 1419 |
ComplexPart{std::move(*dataRef), part}}); |
| 1420 |
}, |
| 1421 |
zExpr->u)}; |
| 1422 |
return AsGenericExpr(std::move(realExpr)); |
| 1423 |
} |
| 1424 |
} |
| 1425 |
} else if (isTypeParamInquiry) { // %kind or %len |
| 1426 |
ActualArgument arg{std::move(*base)}; |
| 1427 |
SetArgSourceLocation(arg, name); |
| 1428 |
return MakeFunctionRef(name, ActualArguments{std::move(arg)}); |
| 1429 |
} else { |
| 1430 |
DIE("unexpected MiscDetails::Kind"); |
| 1431 |
} |
| 1432 |
} else { |
| 1433 |
Say(name, "derived type required before component reference"_err_en_US); |
| 1434 |
} |
| 1435 |
return std::nullopt; |
| 1436 |
} |
| 1437 |
|
| 1438 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::CoindexedNamedObject &x) { |
| 1439 |
if (auto maybeDataRef{ExtractDataRef(Analyze(x.base))}) { |
| 1440 |
DataRef *dataRef{&*maybeDataRef}; |
| 1441 |
std::vector<Subscript> subscripts; |
| 1442 |
SymbolVector reversed; |
| 1443 |
if (auto *aRef{std::get_if<ArrayRef>(&dataRef->u)}) { |
| 1444 |
subscripts = std::move(aRef->subscript()); |
| 1445 |
reversed.push_back(aRef->GetLastSymbol()); |
| 1446 |
if (Component *component{aRef->base().UnwrapComponent()}) { |
| 1447 |
dataRef = &component->base(); |
| 1448 |
} else { |
| 1449 |
dataRef = nullptr; |
| 1450 |
} |
| 1451 |
} |
| 1452 |
if (dataRef) { |
| 1453 |
while (auto *component{std::get_if<Component>(&dataRef->u)}) { |
| 1454 |
reversed.push_back(component->GetLastSymbol()); |
| 1455 |
dataRef = &component->base(); |
| 1456 |
} |
| 1457 |
if (auto *baseSym{std::get_if<SymbolRef>(&dataRef->u)}) { |
| 1458 |
reversed.push_back(*baseSym); |
| 1459 |
} else { |
| 1460 |
Say("Base of coindexed named object has subscripts or cosubscripts"_err_en_US); |
| 1461 |
} |
| 1462 |
} |
| 1463 |
std::vector<Expr<SubscriptInteger>> cosubscripts; |
| 1464 |
bool cosubsOk{true}; |
| 1465 |
for (const auto &cosub : |
| 1466 |
std::get<std::list<parser::Cosubscript>>(x.imageSelector.t)) { |
| 1467 |
MaybeExpr coex{Analyze(cosub)}; |
| 1468 |
if (auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(coex)}) { |
| 1469 |
cosubscripts.push_back( |
| 1470 |
ConvertToType<SubscriptInteger>(std::move(*intExpr))); |
| 1471 |
} else { |
| 1472 |
cosubsOk = false; |
| 1473 |
} |
| 1474 |
} |
| 1475 |
if (cosubsOk && !reversed.empty()) { |
| 1476 |
int numCosubscripts{static_cast<int>(cosubscripts.size())}; |
| 1477 |
const Symbol &symbol{reversed.front()}; |
| 1478 |
if (numCosubscripts != symbol.Corank()) { |
| 1479 |
Say("'%s' has corank %d, but coindexed reference has %d cosubscripts"_err_en_US, |
| 1480 |
symbol.name(), symbol.Corank(), numCosubscripts); |
| 1481 |
} |
| 1482 |
} |
| 1483 |
for (const auto &imageSelSpec : |
| 1484 |
std::get<std::list<parser::ImageSelectorSpec>>(x.imageSelector.t)) { |
| 1485 |
common::visit( |
| 1486 |
common::visitors{ |
| 1487 |
[&](const auto &x) { Analyze(x.v); }, |
| 1488 |
}, |
| 1489 |
imageSelSpec.u); |
| 1490 |
} |
| 1491 |
// Reverse the chain of symbols so that the base is first and coarray |
| 1492 |
// ultimate component is last. |
| 1493 |
if (cosubsOk) { |
| 1494 |
return Designate( |
| 1495 |
DataRef{CoarrayRef{SymbolVector{reversed.crbegin(), reversed.crend()}, |
| 1496 |
std::move(subscripts), std::move(cosubscripts)}}); |
| 1497 |
} |
| 1498 |
} |
| 1499 |
return std::nullopt; |
| 1500 |
} |
| 1501 |
|
| 1502 |
int ExpressionAnalyzer::IntegerTypeSpecKind( |
| 1503 |
const parser::IntegerTypeSpec &spec) { |
| 1504 |
Expr<SubscriptInteger> value{ |
| 1505 |
AnalyzeKindSelector(TypeCategory::Integer, spec.v)}; |
| 1506 |
if (auto kind{ToInt64(value)}) { |
| 1507 |
return static_cast<int>(*kind); |
| 1508 |
} |
| 1509 |
SayAt(spec, "Constant INTEGER kind value required here"_err_en_US); |
| 1510 |
return GetDefaultKind(TypeCategory::Integer); |
| 1511 |
} |
| 1512 |
|
| 1513 |
// Array constructors |
| 1514 |
|
| 1515 |
// Inverts a collection of generic ArrayConstructorValues<SomeType> that |
| 1516 |
// all happen to have the same actual type T into one ArrayConstructor<T>. |
| 1517 |
template <typename T> |
| 1518 |
ArrayConstructorValues<T> MakeSpecific( |
| 1519 |
ArrayConstructorValues<SomeType> &&from) { |
| 1520 |
ArrayConstructorValues<T> to; |
| 1521 |
for (ArrayConstructorValue<SomeType> &x : from) { |
| 1522 |
common::visit( |
| 1523 |
common::visitors{ |
| 1524 |
[&](common::CopyableIndirection<Expr<SomeType>> &&expr) { |
| 1525 |
auto *typed{UnwrapExpr<Expr<T>>(expr.value())}; |
| 1526 |
to.Push(std::move(DEREF(typed))); |
| 1527 |
}, |
| 1528 |
[&](ImpliedDo<SomeType> &&impliedDo) { |
| 1529 |
to.Push(ImpliedDo<T>{impliedDo.name(), |
| 1530 |
std::move(impliedDo.lower()), std::move(impliedDo.upper()), |
| 1531 |
std::move(impliedDo.stride()), |
| 1532 |
MakeSpecific<T>(std::move(impliedDo.values()))}); |
| 1533 |
}, |
| 1534 |
}, |
| 1535 |
std::move(x.u)); |
| 1536 |
} |
| 1537 |
return to; |
| 1538 |
} |
| 1539 |
|
| 1540 |
class ArrayConstructorContext { |
| 1541 |
public: |
| 1542 |
ArrayConstructorContext( |
| 1543 |
ExpressionAnalyzer &c, std::optional<DynamicTypeWithLength> &&t) |
| 1544 |
: exprAnalyzer_{c}, type_{std::move(t)} {} |
| 1545 |
|
| 1546 |
void Add(const parser::AcValue &); |
| 1547 |
MaybeExpr ToExpr(); |
| 1548 |
|
| 1549 |
// These interfaces allow *this to be used as a type visitor argument to |
| 1550 |
// common::SearchTypes() to convert the array constructor to a typed |
| 1551 |
// expression in ToExpr(). |
| 1552 |
using Result = MaybeExpr; |
| 1553 |
using Types = AllTypes; |
| 1554 |
template <typename T> Result Test() { |
| 1555 |
if (type_ && type_->category() == T::category) { |
| 1556 |
if constexpr (T::category == TypeCategory::Derived) { |
| 1557 |
if (!type_->IsUnlimitedPolymorphic()) { |
| 1558 |
return AsMaybeExpr(ArrayConstructor<T>{type_->GetDerivedTypeSpec(), |
| 1559 |
MakeSpecific<T>(std::move(values_))}); |
| 1560 |
} |
| 1561 |
} else if (type_->kind() == T::kind) { |
| 1562 |
ArrayConstructor<T> result{MakeSpecific<T>(std::move(values_))}; |
| 1563 |
if constexpr (T::category == TypeCategory::Character) { |
| 1564 |
if (auto len{LengthIfGood()}) { |
| 1565 |
// The ac-do-variables may be treated as constant expressions, |
| 1566 |
// if some conditions on ac-implied-do-control hold (10.1.12 (12)). |
| 1567 |
// At the same time, they may be treated as constant expressions |
| 1568 |
// only in the context of the ac-implied-do, but setting |
| 1569 |
// the character length here may result in complete elimination |
| 1570 |
// of the ac-implied-do. For example: |
| 1571 |
// character(10) :: c |
| 1572 |
// ... len([(c(i:i), integer(8)::i = 1,4)]) |
| 1573 |
// would be evaulated into: |
| 1574 |
// ... int(max(0_8,i-i+1_8),kind=4) |
| 1575 |
// with a dangling reference to the ac-do-variable. |
| 1576 |
// Prevent this by checking for the ac-do-variable references |
| 1577 |
// in the 'len' expression. |
| 1578 |
result.set_LEN(std::move(*len)); |
| 1579 |
} |
| 1580 |
} |
| 1581 |
return AsMaybeExpr(std::move(result)); |
| 1582 |
} |
| 1583 |
} |
| 1584 |
return std::nullopt; |
| 1585 |
} |
| 1586 |
|
| 1587 |
private: |
| 1588 |
using ImpliedDoIntType = ResultType<ImpliedDoIndex>; |
| 1589 |
|
| 1590 |
std::optional<Expr<SubscriptInteger>> LengthIfGood() const { |
| 1591 |
if (type_) { |
| 1592 |
auto len{type_->LEN()}; |
| 1593 |
if (explicitType_ || |
| 1594 |
(len && IsConstantExpr(*len) && !ContainsAnyImpliedDoIndex(*len))) { |
| 1595 |
return len; |
| 1596 |
} |
| 1597 |
} |
| 1598 |
return std::nullopt; |
| 1599 |
} |
| 1600 |
bool NeedLength() const { |
| 1601 |
return type_ && type_->category() == TypeCategory::Character && |
| 1602 |
!LengthIfGood(); |
| 1603 |
} |
| 1604 |
void Push(MaybeExpr &&); |
| 1605 |
void Add(const parser::AcValue::Triplet &); |
| 1606 |
void Add(const parser::Expr &); |
| 1607 |
void Add(const parser::AcImpliedDo &); |
| 1608 |
void UnrollConstantImpliedDo(const parser::AcImpliedDo &, |
| 1609 |
parser::CharBlock name, std::int64_t lower, std::int64_t upper, |
| 1610 |
std::int64_t stride); |
| 1611 |
|
| 1612 |
template <int KIND> |
| 1613 |
std::optional<Expr<Type<TypeCategory::Integer, KIND>>> ToSpecificInt( |
| 1614 |
MaybeExpr &&y) { |
| 1615 |
if (y) { |
| 1616 |
Expr<SomeInteger> *intExpr{UnwrapExpr<Expr<SomeInteger>>(*y)}; |
| 1617 |
return Fold(exprAnalyzer_.GetFoldingContext(), |
| 1618 |
ConvertToType<Type<TypeCategory::Integer, KIND>>( |
| 1619 |
std::move(DEREF(intExpr)))); |
| 1620 |
} else { |
| 1621 |
return std::nullopt; |
| 1622 |
} |
| 1623 |
} |
| 1624 |
|
| 1625 |
template <int KIND, typename A> |
| 1626 |
std::optional<Expr<Type<TypeCategory::Integer, KIND>>> GetSpecificIntExpr( |
| 1627 |
const A &x) { |
| 1628 |
return ToSpecificInt<KIND>(exprAnalyzer_.Analyze(x)); |
| 1629 |
} |
| 1630 |
|
| 1631 |
// Nested array constructors all reference the same ExpressionAnalyzer, |
| 1632 |
// which represents the nest of active implied DO loop indices. |
| 1633 |
ExpressionAnalyzer &exprAnalyzer_; |
| 1634 |
std::optional<DynamicTypeWithLength> type_; |
| 1635 |
bool explicitType_{type_.has_value()}; |
| 1636 |
std::optional<std::int64_t> constantLength_; |
| 1637 |
ArrayConstructorValues<SomeType> values_; |
| 1638 |
std::uint64_t messageDisplayedSet_{0}; |
| 1639 |
}; |
| 1640 |
|
| 1641 |
void ArrayConstructorContext::Push(MaybeExpr &&x) { |
| 1642 |
if (!x) { |
| 1643 |
return; |
| 1644 |
} |
| 1645 |
if (!type_) { |
| 1646 |
if (auto *boz{std::get_if<BOZLiteralConstant>(&x->u)}) { |
| 1647 |
// Treat an array constructor of BOZ as if default integer. |
| 1648 |
if (exprAnalyzer_.context().ShouldWarn( |
| 1649 |
common::LanguageFeature::BOZAsDefaultInteger)) { |
| 1650 |
exprAnalyzer_.Say( |
| 1651 |
"BOZ literal in array constructor without explicit type is assumed to be default INTEGER"_port_en_US); |
| 1652 |
} |
| 1653 |
x = AsGenericExpr(ConvertToKind<TypeCategory::Integer>( |
| 1654 |
exprAnalyzer_.GetDefaultKind(TypeCategory::Integer), |
| 1655 |
std::move(*boz))); |
| 1656 |
} |
| 1657 |
} |
| 1658 |
std::optional<DynamicType> dyType{x->GetType()}; |
| 1659 |
if (!dyType) { |
| 1660 |
if (auto *boz{std::get_if<BOZLiteralConstant>(&x->u)}) { |
| 1661 |
if (!type_) { |
| 1662 |
// Treat an array constructor of BOZ as if default integer. |
| 1663 |
if (exprAnalyzer_.context().ShouldWarn( |
| 1664 |
common::LanguageFeature::BOZAsDefaultInteger)) { |
| 1665 |
exprAnalyzer_.Say( |
| 1666 |
"BOZ literal in array constructor without explicit type is assumed to be default INTEGER"_port_en_US); |
| 1667 |
} |
| 1668 |
x = AsGenericExpr(ConvertToKind<TypeCategory::Integer>( |
| 1669 |
exprAnalyzer_.GetDefaultKind(TypeCategory::Integer), |
| 1670 |
std::move(*boz))); |
| 1671 |
dyType = x.value().GetType(); |
| 1672 |
} else if (auto cast{ConvertToType(*type_, std::move(*x))}) { |
| 1673 |
x = std::move(cast); |
| 1674 |
dyType = *type_; |
| 1675 |
} else { |
| 1676 |
if (!(messageDisplayedSet_ & 0x80)) { |
| 1677 |
exprAnalyzer_.Say( |
| 1678 |
"BOZ literal is not suitable for use in this array constructor"_err_en_US); |
| 1679 |
messageDisplayedSet_ |= 0x80; |
| 1680 |
} |
| 1681 |
return; |
| 1682 |
} |
| 1683 |
} else { // procedure name, &c. |
| 1684 |
if (!(messageDisplayedSet_ & 0x40)) { |
| 1685 |
exprAnalyzer_.Say( |
| 1686 |
"Item is not suitable for use in an array constructor"_err_en_US); |
| 1687 |
messageDisplayedSet_ |= 0x40; |
| 1688 |
} |
| 1689 |
return; |
| 1690 |
} |
| 1691 |
} else if (dyType->IsUnlimitedPolymorphic()) { |
| 1692 |
if (!(messageDisplayedSet_ & 8)) { |
| 1693 |
exprAnalyzer_.Say("Cannot have an unlimited polymorphic value in an " |
| 1694 |
"array constructor"_err_en_US); // C7113 |
| 1695 |
messageDisplayedSet_ |= 8; |
| 1696 |
} |
| 1697 |
return; |
| 1698 |
} else if (dyType->category() == TypeCategory::Derived && |
| 1699 |
dyType->GetDerivedTypeSpec().typeSymbol().attrs().test( |
| 1700 |
semantics::Attr::ABSTRACT)) { // F'2023 C7125 |
| 1701 |
if (!(messageDisplayedSet_ & 0x200)) { |
| 1702 |
exprAnalyzer_.Say( |
| 1703 |
"An item whose declared type is ABSTRACT may not appear in an array constructor"_err_en_US); |
| 1704 |
messageDisplayedSet_ |= 0x200; |
| 1705 |
} |
| 1706 |
} |
| 1707 |
DynamicTypeWithLength xType{dyType.value()}; |
| 1708 |
if (Expr<SomeCharacter> * charExpr{UnwrapExpr<Expr<SomeCharacter>>(*x)}) { |
| 1709 |
CHECK(xType.category() == TypeCategory::Character); |
| 1710 |
xType.length = |
| 1711 |
common::visit([](const auto &kc) { return kc.LEN(); }, charExpr->u); |
| 1712 |
} |
| 1713 |
if (!type_) { |
| 1714 |
// If there is no explicit type-spec in an array constructor, the type |
| 1715 |
// of the array is the declared type of all of the elements, which must |
| 1716 |
// be well-defined and all match. |
| 1717 |
// TODO: Possible language extension: use the most general type of |
| 1718 |
// the values as the type of a numeric constructed array, convert all |
| 1719 |
// of the other values to that type. Alternative: let the first value |
| 1720 |
// determine the type, and convert the others to that type. |
| 1721 |
CHECK(!explicitType_); |
| 1722 |
type_ = std::move(xType); |
| 1723 |
constantLength_ = ToInt64(type_->length); |
| 1724 |
values_.Push(std::move(*x)); |
| 1725 |
} else if (!explicitType_) { |
| 1726 |
if (type_->IsTkCompatibleWith(xType) && xType.IsTkCompatibleWith(*type_)) { |
| 1727 |
values_.Push(std::move(*x)); |
| 1728 |
auto xLen{xType.LEN()}; |
| 1729 |
if (auto thisLen{ToInt64(xLen)}) { |
| 1730 |
if (constantLength_) { |
| 1731 |
if (exprAnalyzer_.context().ShouldWarn( |
| 1732 |
common::LanguageFeature::DistinctArrayConstructorLengths) && |
| 1733 |
*thisLen != *constantLength_) { |
| 1734 |
if (!(messageDisplayedSet_ & 1)) { |
| 1735 |
exprAnalyzer_.Say( |
| 1736 |
"Character literal in array constructor without explicit " |
| 1737 |
"type has different length than earlier elements"_port_en_US); |
| 1738 |
messageDisplayedSet_ |= 1; |
| 1739 |
} |
| 1740 |
} |
| 1741 |
if (*thisLen > *constantLength_) { |
| 1742 |
// Language extension: use the longest literal to determine the |
| 1743 |
// length of the array constructor's character elements, not the |
| 1744 |
// first, when there is no explicit type. |
| 1745 |
*constantLength_ = *thisLen; |
| 1746 |
type_->length = std::move(xLen); |
| 1747 |
} |
| 1748 |
} else { |
| 1749 |
constantLength_ = *thisLen; |
| 1750 |
type_->length = std::move(xLen); |
| 1751 |
} |
| 1752 |
} else if (xLen && NeedLength()) { |
| 1753 |
type_->length = std::move(xLen); |
| 1754 |
} |
| 1755 |
} else { |
| 1756 |
if (!(messageDisplayedSet_ & 2)) { |
| 1757 |
exprAnalyzer_.Say( |
| 1758 |
"Values in array constructor must have the same declared type " |
| 1759 |
"when no explicit type appears"_err_en_US); // C7110 |
| 1760 |
messageDisplayedSet_ |= 2; |
| 1761 |
} |
| 1762 |
} |
| 1763 |
} else { |
| 1764 |
if (auto cast{ConvertToType(*type_, std::move(*x))}) { |
| 1765 |
values_.Push(std::move(*cast)); |
| 1766 |
} else if (!(messageDisplayedSet_ & 4)) { |
| 1767 |
exprAnalyzer_.Say("Value in array constructor of type '%s' could not " |
| 1768 |
"be converted to the type of the array '%s'"_err_en_US, |
| 1769 |
x->GetType()->AsFortran(), type_->AsFortran()); // C7111, C7112 |
| 1770 |
messageDisplayedSet_ |= 4; |
| 1771 |
} |
| 1772 |
} |
| 1773 |
} |
| 1774 |
|
| 1775 |
void ArrayConstructorContext::Add(const parser::AcValue &x) { |
| 1776 |
common::visit( |
| 1777 |
common::visitors{ |
| 1778 |
[&](const parser::AcValue::Triplet &triplet) { Add(triplet); }, |
| 1779 |
[&](const common::Indirection<parser::Expr> &expr) { |
| 1780 |
Add(expr.value()); |
| 1781 |
}, |
| 1782 |
[&](const common::Indirection<parser::AcImpliedDo> &impliedDo) { |
| 1783 |
Add(impliedDo.value()); |
| 1784 |
}, |
| 1785 |
}, |
| 1786 |
x.u); |
| 1787 |
} |
| 1788 |
|
| 1789 |
// Transforms l:u(:s) into (_,_=l,u(,s)) with an anonymous index '_' |
| 1790 |
void ArrayConstructorContext::Add(const parser::AcValue::Triplet &triplet) { |
| 1791 |
MaybeExpr lowerExpr{exprAnalyzer_.Analyze(std::get<0>(triplet.t))}; |
| 1792 |
MaybeExpr upperExpr{exprAnalyzer_.Analyze(std::get<1>(triplet.t))}; |
| 1793 |
MaybeExpr strideExpr{exprAnalyzer_.Analyze(std::get<2>(triplet.t))}; |
| 1794 |
if (lowerExpr && upperExpr) { |
| 1795 |
auto lowerType{lowerExpr->GetType()}; |
| 1796 |
auto upperType{upperExpr->GetType()}; |
| 1797 |
auto strideType{strideExpr ? strideExpr->GetType() : lowerType}; |
| 1798 |
if (lowerType && upperType && strideType) { |
| 1799 |
int kind{lowerType->kind()}; |
| 1800 |
if (upperType->kind() > kind) { |
| 1801 |
kind = upperType->kind(); |
| 1802 |
} |
| 1803 |
if (strideType->kind() > kind) { |
| 1804 |
kind = strideType->kind(); |
| 1805 |
} |
| 1806 |
auto lower{ToSpecificInt<ImpliedDoIntType::kind>(std::move(lowerExpr))}; |
| 1807 |
auto upper{ToSpecificInt<ImpliedDoIntType::kind>(std::move(upperExpr))}; |
| 1808 |
if (lower && upper) { |
| 1809 |
auto stride{ |
| 1810 |
ToSpecificInt<ImpliedDoIntType::kind>(std::move(strideExpr))}; |
| 1811 |
if (!stride) { |
| 1812 |
stride = Expr<ImpliedDoIntType>{1}; |
| 1813 |
} |
| 1814 |
DynamicType type{TypeCategory::Integer, kind}; |
| 1815 |
if (!type_) { |
| 1816 |
type_ = DynamicTypeWithLength{type}; |
| 1817 |
} |
| 1818 |
parser::CharBlock anonymous; |
| 1819 |
if (auto converted{ConvertToType(type, |
| 1820 |
AsGenericExpr( |
| 1821 |
Expr<ImpliedDoIntType>{ImpliedDoIndex{anonymous}}))}) { |
| 1822 |
auto v{std::move(values_)}; |
| 1823 |
Push(std::move(converted)); |
| 1824 |
std::swap(v, values_); |
| 1825 |
values_.Push(ImpliedDo<SomeType>{anonymous, std::move(*lower), |
| 1826 |
std::move(*upper), std::move(*stride), std::move(v)}); |
| 1827 |
} |
| 1828 |
} |
| 1829 |
} |
| 1830 |
} |
| 1831 |
} |
| 1832 |
|
| 1833 |
void ArrayConstructorContext::Add(const parser::Expr &expr) { |
| 1834 |
auto restorer{exprAnalyzer_.GetContextualMessages().SetLocation(expr.source)}; |
| 1835 |
Push(exprAnalyzer_.Analyze(expr)); |
| 1836 |
} |
| 1837 |
|
| 1838 |
void ArrayConstructorContext::Add(const parser::AcImpliedDo &impliedDo) { |
| 1839 |
const auto &control{std::get<parser::AcImpliedDoControl>(impliedDo.t)}; |
| 1840 |
const auto &bounds{std::get<parser::AcImpliedDoControl::Bounds>(control.t)}; |
| 1841 |
exprAnalyzer_.Analyze(bounds.name); |
| 1842 |
parser::CharBlock name{bounds.name.thing.thing.source}; |
| 1843 |
int kind{ImpliedDoIntType::kind}; |
| 1844 |
if (const Symbol * symbol{bounds.name.thing.thing.symbol}) { |
| 1845 |
if (auto dynamicType{DynamicType::From(symbol)}) { |
| 1846 |
if (dynamicType->category() == TypeCategory::Integer) { |
| 1847 |
kind = dynamicType->kind(); |
| 1848 |
} |
| 1849 |
} |
| 1850 |
} |
| 1851 |
std::optional<Expr<ImpliedDoIntType>> lower{ |
| 1852 |
GetSpecificIntExpr<ImpliedDoIntType::kind>(bounds.lower)}; |
| 1853 |
std::optional<Expr<ImpliedDoIntType>> upper{ |
| 1854 |
GetSpecificIntExpr<ImpliedDoIntType::kind>(bounds.upper)}; |
| 1855 |
if (lower && upper) { |
| 1856 |
std::optional<Expr<ImpliedDoIntType>> stride{ |
| 1857 |
GetSpecificIntExpr<ImpliedDoIntType::kind>(bounds.step)}; |
| 1858 |
if (!stride) { |
| 1859 |
stride = Expr<ImpliedDoIntType>{1}; |
| 1860 |
} |
| 1861 |
if (exprAnalyzer_.AddImpliedDo(name, kind)) { |
| 1862 |
// Check for constant bounds; the loop may require complete unrolling |
| 1863 |
// of the parse tree if all bounds are constant in order to allow the |
| 1864 |
// implied DO loop index to qualify as a constant expression. |
| 1865 |
auto cLower{ToInt64(lower)}; |
| 1866 |
auto cUpper{ToInt64(upper)}; |
| 1867 |
auto cStride{ToInt64(stride)}; |
| 1868 |
if (!(messageDisplayedSet_ & 0x10) && cStride && *cStride == 0) { |
| 1869 |
exprAnalyzer_.SayAt(bounds.step.value().thing.thing.value().source, |
| 1870 |
"The stride of an implied DO loop must not be zero"_err_en_US); |
| 1871 |
messageDisplayedSet_ |= 0x10; |
| 1872 |
} |
| 1873 |
bool isConstant{cLower && cUpper && cStride && *cStride != 0}; |
| 1874 |
bool isNonemptyConstant{isConstant && |
| 1875 |
((*cStride > 0 && *cLower <= *cUpper) || |
| 1876 |
(*cStride < 0 && *cLower >= *cUpper))}; |
| 1877 |
bool isEmpty{isConstant && !isNonemptyConstant}; |
| 1878 |
bool unrollConstantLoop{false}; |
| 1879 |
parser::Messages buffer; |
| 1880 |
auto saveMessagesDisplayed{messageDisplayedSet_}; |
| 1881 |
{ |
| 1882 |
auto messageRestorer{ |
| 1883 |
exprAnalyzer_.GetContextualMessages().SetMessages(buffer)}; |
| 1884 |
auto v{std::move(values_)}; |
| 1885 |
for (const auto &value : |
| 1886 |
std::get<std::list<parser::AcValue>>(impliedDo.t)) { |
| 1887 |
Add(value); |
| 1888 |
} |
| 1889 |
std::swap(v, values_); |
| 1890 |
if (isNonemptyConstant && buffer.AnyFatalError()) { |
| 1891 |
unrollConstantLoop = true; |
| 1892 |
} else { |
| 1893 |
values_.Push(ImpliedDo<SomeType>{name, std::move(*lower), |
| 1894 |
std::move(*upper), std::move(*stride), std::move(v)}); |
| 1895 |
} |
| 1896 |
} |
| 1897 |
// F'2023 7.8 p5 |
| 1898 |
if (!(messageDisplayedSet_ & 0x100) && isEmpty && NeedLength()) { |
| 1899 |
exprAnalyzer_.SayAt(name, |
| 1900 |
"Array constructor implied DO loop has no iterations and indeterminate character length"_err_en_US); |
| 1901 |
messageDisplayedSet_ |= 0x100; |
| 1902 |
} |
| 1903 |
if (unrollConstantLoop) { |
| 1904 |
messageDisplayedSet_ = saveMessagesDisplayed; |
| 1905 |
UnrollConstantImpliedDo(impliedDo, name, *cLower, *cUpper, *cStride); |
| 1906 |
} else if (auto *messages{ |
| 1907 |
exprAnalyzer_.GetContextualMessages().messages()}) { |
| 1908 |
messages->Annex(std::move(buffer)); |
| 1909 |
} |
| 1910 |
exprAnalyzer_.RemoveImpliedDo(name); |
| 1911 |
} else if (!(messageDisplayedSet_ & 0x20)) { |
| 1912 |
exprAnalyzer_.SayAt(name, |
| 1913 |
"Implied DO index '%s' is active in a surrounding implied DO loop " |
| 1914 |
"and may not have the same name"_err_en_US, |
| 1915 |
name); // C7115 |
| 1916 |
messageDisplayedSet_ |= 0x20; |
| 1917 |
} |
| 1918 |
} |
| 1919 |
} |
| 1920 |
|
| 1921 |
// Fortran considers an implied DO index of an array constructor to be |
| 1922 |
// a constant expression if the bounds of the implied DO loop are constant. |
| 1923 |
// Usually this doesn't matter, but if we emitted spurious messages as a |
| 1924 |
// result of not using constant values for the index while analyzing the |
| 1925 |
// items, we need to do it again the "hard" way with multiple iterations over |
| 1926 |
// the parse tree. |
| 1927 |
void ArrayConstructorContext::UnrollConstantImpliedDo( |
| 1928 |
const parser::AcImpliedDo &impliedDo, parser::CharBlock name, |
| 1929 |
std::int64_t lower, std::int64_t upper, std::int64_t stride) { |
| 1930 |
auto &foldingContext{exprAnalyzer_.GetFoldingContext()}; |
| 1931 |
auto restorer{exprAnalyzer_.DoNotUseSavedTypedExprs()}; |
| 1932 |
for (auto &at{foldingContext.StartImpliedDo(name, lower)}; |
| 1933 |
(stride > 0 && at <= upper) || (stride < 0 && at >= upper); |
| 1934 |
at += stride) { |
| 1935 |
for (const auto &value : |
| 1936 |
std::get<std::list<parser::AcValue>>(impliedDo.t)) { |
| 1937 |
Add(value); |
| 1938 |
} |
| 1939 |
} |
| 1940 |
foldingContext.EndImpliedDo(name); |
| 1941 |
} |
| 1942 |
|
| 1943 |
MaybeExpr ArrayConstructorContext::ToExpr() { |
| 1944 |
return common::SearchTypes(std::move(*this)); |
| 1945 |
} |
| 1946 |
|
| 1947 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::ArrayConstructor &array) { |
| 1948 |
const parser::AcSpec &acSpec{array.v}; |
| 1949 |
ArrayConstructorContext acContext{ |
| 1950 |
*this, AnalyzeTypeSpec(acSpec.type, GetFoldingContext())}; |
| 1951 |
for (const parser::AcValue &value : acSpec.values) { |
| 1952 |
acContext.Add(value); |
| 1953 |
} |
| 1954 |
return acContext.ToExpr(); |
| 1955 |
} |
| 1956 |
|
| 1957 |
// Check if implicit conversion of expr to the symbol type is legal (if needed), |
| 1958 |
// and make it explicit if requested. |
| 1959 |
static MaybeExpr implicitConvertTo(const semantics::Symbol &sym, |
| 1960 |
Expr<SomeType> &&expr, bool keepConvertImplicit) { |
| 1961 |
if (!keepConvertImplicit) { |
| 1962 |
return ConvertToType(sym, std::move(expr)); |
| 1963 |
} else { |
| 1964 |
// Test if a convert could be inserted, but do not make it explicit to |
| 1965 |
// preserve the information that expr is a variable. |
| 1966 |
if (ConvertToType(sym, common::Clone(expr))) { |
| 1967 |
return MaybeExpr{std::move(expr)}; |
| 1968 |
} |
| 1969 |
} |
| 1970 |
// Illegal implicit convert. |
| 1971 |
return std::nullopt; |
| 1972 |
} |
| 1973 |
|
| 1974 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 1975 |
const parser::StructureConstructor &structure) { |
| 1976 |
auto &parsedType{std::get<parser::DerivedTypeSpec>(structure.t)}; |
| 1977 |
parser::Name structureType{std::get<parser::Name>(parsedType.t)}; |
| 1978 |
parser::CharBlock &typeName{structureType.source}; |
| 1979 |
if (semantics::Symbol *typeSymbol{structureType.symbol}) { |
| 1980 |
if (typeSymbol->has<semantics::DerivedTypeDetails>()) { |
| 1981 |
semantics::DerivedTypeSpec dtSpec{typeName, typeSymbol->GetUltimate()}; |
| 1982 |
if (!CheckIsValidForwardReference(dtSpec)) { |
| 1983 |
return std::nullopt; |
| 1984 |
} |
| 1985 |
} |
| 1986 |
} |
| 1987 |
if (!parsedType.derivedTypeSpec) { |
| 1988 |
return std::nullopt; |
| 1989 |
} |
| 1990 |
const auto &spec{*parsedType.derivedTypeSpec}; |
| 1991 |
const Symbol &typeSymbol{spec.typeSymbol()}; |
| 1992 |
if (!spec.scope() || !typeSymbol.has<semantics::DerivedTypeDetails>()) { |
| 1993 |
return std::nullopt; // error recovery |
| 1994 |
} |
| 1995 |
const semantics::Scope &scope{context_.FindScope(typeName)}; |
| 1996 |
const semantics::Scope *pureContext{FindPureProcedureContaining(scope)}; |
| 1997 |
const auto &typeDetails{typeSymbol.get<semantics::DerivedTypeDetails>()}; |
| 1998 |
const Symbol *parentComponent{typeDetails.GetParentComponent(*spec.scope())}; |
| 1999 |
|
| 2000 |
if (typeSymbol.attrs().test(semantics::Attr::ABSTRACT)) { // C796 |
| 2001 |
AttachDeclaration(Say(typeName, |
| 2002 |
"ABSTRACT derived type '%s' may not be used in a " |
| 2003 |
"structure constructor"_err_en_US, |
| 2004 |
typeName), |
| 2005 |
typeSymbol); // C7114 |
| 2006 |
} |
| 2007 |
|
| 2008 |
// This iterator traverses all of the components in the derived type and its |
| 2009 |
// parents. The symbols for whole parent components appear after their |
| 2010 |
// own components and before the components of the types that extend them. |
| 2011 |
// E.g., TYPE :: A; REAL X; END TYPE |
| 2012 |
// TYPE, EXTENDS(A) :: B; REAL Y; END TYPE |
| 2013 |
// produces the component list X, A, Y. |
| 2014 |
// The order is important below because a structure constructor can |
| 2015 |
// initialize X or A by name, but not both. |
| 2016 |
auto components{semantics::OrderedComponentIterator{spec}}; |
| 2017 |
auto nextAnonymous{components.begin()}; |
| 2018 |
|
| 2019 |
std::set<parser::CharBlock> unavailable; |
| 2020 |
bool anyKeyword{false}; |
| 2021 |
StructureConstructor result{spec}; |
| 2022 |
bool checkConflicts{true}; // until we hit one |
| 2023 |
auto &messages{GetContextualMessages()}; |
| 2024 |
|
| 2025 |
// NULL() can be a valid component |
| 2026 |
auto restorer{AllowNullPointer()}; |
| 2027 |
|
| 2028 |
for (const auto &component : |
| 2029 |
std::get<std::list<parser::ComponentSpec>>(structure.t)) { |
| 2030 |
const parser::Expr &expr{ |
| 2031 |
std::get<parser::ComponentDataSource>(component.t).v.value()}; |
| 2032 |
parser::CharBlock source{expr.source}; |
| 2033 |
auto restorer{messages.SetLocation(source)}; |
| 2034 |
const Symbol *symbol{nullptr}; |
| 2035 |
MaybeExpr value{Analyze(expr)}; |
| 2036 |
std::optional<DynamicType> valueType{DynamicType::From(value)}; |
| 2037 |
if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) { |
| 2038 |
anyKeyword = true; |
| 2039 |
source = kw->v.source; |
| 2040 |
symbol = kw->v.symbol; |
| 2041 |
if (!symbol) { |
| 2042 |
// Skip overridden inaccessible parent components in favor of |
| 2043 |
// their later overrides. |
| 2044 |
for (const Symbol &sym : components) { |
| 2045 |
if (sym.name() == source) { |
| 2046 |
symbol = &sym; |
| 2047 |
} |
| 2048 |
} |
| 2049 |
} |
| 2050 |
if (!symbol) { // C7101 |
| 2051 |
Say(source, |
| 2052 |
"Keyword '%s=' does not name a component of derived type '%s'"_err_en_US, |
| 2053 |
source, typeName); |
| 2054 |
} |
| 2055 |
} else { |
| 2056 |
if (anyKeyword) { // C7100 |
| 2057 |
Say(source, |
| 2058 |
"Value in structure constructor lacks a component name"_err_en_US); |
| 2059 |
checkConflicts = false; // stem cascade |
| 2060 |
} |
| 2061 |
// Here's a regrettably common extension of the standard: anonymous |
| 2062 |
// initialization of parent components, e.g., T(PT(1)) rather than |
| 2063 |
// T(1) or T(PT=PT(1)). |
| 2064 |
if (nextAnonymous == components.begin() && parentComponent && |
| 2065 |
valueType == DynamicType::From(*parentComponent) && |
| 2066 |
context().IsEnabled(LanguageFeature::AnonymousParents)) { |
| 2067 |
auto iter{ |
| 2068 |
std::find(components.begin(), components.end(), *parentComponent)}; |
| 2069 |
if (iter != components.end()) { |
| 2070 |
symbol = parentComponent; |
| 2071 |
nextAnonymous = ++iter; |
| 2072 |
if (context().ShouldWarn(LanguageFeature::AnonymousParents)) { |
| 2073 |
Say(source, |
| 2074 |
"Whole parent component '%s' in structure " |
| 2075 |
"constructor should not be anonymous"_port_en_US, |
| 2076 |
symbol->name()); |
| 2077 |
} |
| 2078 |
} |
| 2079 |
} |
| 2080 |
while (!symbol && nextAnonymous != components.end()) { |
| 2081 |
const Symbol &next{*nextAnonymous}; |
| 2082 |
++nextAnonymous; |
| 2083 |
if (!next.test(Symbol::Flag::ParentComp)) { |
| 2084 |
symbol = &next; |
| 2085 |
} |
| 2086 |
} |
| 2087 |
if (!symbol) { |
| 2088 |
Say(source, "Unexpected value in structure constructor"_err_en_US); |
| 2089 |
} |
| 2090 |
} |
| 2091 |
if (symbol) { |
| 2092 |
const semantics::Scope &innermost{context_.FindScope(expr.source)}; |
| 2093 |
if (auto msg{CheckAccessibleSymbol(innermost, *symbol)}) { |
| 2094 |
Say(expr.source, std::move(*msg)); |
| 2095 |
} |
| 2096 |
if (checkConflicts) { |
| 2097 |
auto componentIter{ |
| 2098 |
std::find(components.begin(), components.end(), *symbol)}; |
| 2099 |
if (unavailable.find(symbol->name()) != unavailable.cend()) { |
| 2100 |
// C797, C798 |
| 2101 |
Say(source, |
| 2102 |
"Component '%s' conflicts with another component earlier in " |
| 2103 |
"this structure constructor"_err_en_US, |
| 2104 |
symbol->name()); |
| 2105 |
} else if (symbol->test(Symbol::Flag::ParentComp)) { |
| 2106 |
// Make earlier components unavailable once a whole parent appears. |
| 2107 |
for (auto it{components.begin()}; it != componentIter; ++it) { |
| 2108 |
unavailable.insert(it->name()); |
| 2109 |
} |
| 2110 |
} else { |
| 2111 |
// Make whole parent components unavailable after any of their |
| 2112 |
// constituents appear. |
| 2113 |
for (auto it{componentIter}; it != components.end(); ++it) { |
| 2114 |
if (it->test(Symbol::Flag::ParentComp)) { |
| 2115 |
unavailable.insert(it->name()); |
| 2116 |
} |
| 2117 |
} |
| 2118 |
} |
| 2119 |
} |
| 2120 |
unavailable.insert(symbol->name()); |
| 2121 |
if (value) { |
| 2122 |
if (symbol->has<semantics::TypeParamDetails>()) { |
| 2123 |
Say(expr.source, |
| 2124 |
"Type parameter '%s' may not appear as a component of a structure constructor"_err_en_US, |
| 2125 |
symbol->name()); |
| 2126 |
} |
| 2127 |
if (!(symbol->has<semantics::ProcEntityDetails>() || |
| 2128 |
symbol->has<semantics::ObjectEntityDetails>())) { |
| 2129 |
continue; // recovery |
| 2130 |
} |
| 2131 |
if (IsPointer(*symbol)) { // C7104, C7105, C1594(4) |
| 2132 |
semantics::CheckStructConstructorPointerComponent( |
| 2133 |
context_, *symbol, *value, innermost); |
| 2134 |
result.Add(*symbol, Fold(std::move(*value))); |
| 2135 |
continue; |
| 2136 |
} |
| 2137 |
if (IsNullPointer(*value)) { |
| 2138 |
if (IsAllocatable(*symbol)) { |
| 2139 |
if (IsBareNullPointer(&*value)) { |
| 2140 |
// NULL() with no arguments allowed by 7.5.10 para 6 for |
| 2141 |
// ALLOCATABLE. |
| 2142 |
result.Add(*symbol, Expr<SomeType>{NullPointer{}}); |
| 2143 |
continue; |
| 2144 |
} |
| 2145 |
if (IsNullObjectPointer(*value)) { |
| 2146 |
if (context().ShouldWarn(common::LanguageFeature:: |
| 2147 |
NullMoldAllocatableComponentValue)) { |
| 2148 |
AttachDeclaration( |
| 2149 |
Say(expr.source, |
| 2150 |
"NULL() with arguments is not standard conforming as the value for allocatable component '%s'"_port_en_US, |
| 2151 |
symbol->name()), |
| 2152 |
*symbol); |
| 2153 |
} |
| 2154 |
// proceed to check type & shape |
| 2155 |
} else { |
| 2156 |
AttachDeclaration( |
| 2157 |
Say(expr.source, |
| 2158 |
"A NULL procedure pointer may not be used as the value for component '%s'"_err_en_US, |
| 2159 |
symbol->name()), |
| 2160 |
*symbol); |
| 2161 |
continue; |
| 2162 |
} |
| 2163 |
} else { |
| 2164 |
AttachDeclaration( |
| 2165 |
Say(expr.source, |
| 2166 |
"A NULL pointer may not be used as the value for component '%s'"_err_en_US, |
| 2167 |
symbol->name()), |
| 2168 |
*symbol); |
| 2169 |
continue; |
| 2170 |
} |
| 2171 |
} else if (const Symbol * pointer{FindPointerComponent(*symbol)}; |
| 2172 |
pointer && pureContext) { // C1594(4) |
| 2173 |
if (const Symbol * |
| 2174 |
visible{semantics::FindExternallyVisibleObject( |
| 2175 |
*value, *pureContext)}) { |
| 2176 |
Say(expr.source, |
| 2177 |
"The externally visible object '%s' may not be used in a pure procedure as the value for component '%s' which has the pointer component '%s'"_err_en_US, |
| 2178 |
visible->name(), symbol->name(), pointer->name()); |
| 2179 |
} |
| 2180 |
} |
| 2181 |
// Make implicit conversion explicit to allow folding of the structure |
| 2182 |
// constructors and help semantic checking, unless the component is |
| 2183 |
// allocatable, in which case the value could be an unallocated |
| 2184 |
// allocatable (see Fortran 2018 7.5.10 point 7). The explicit |
| 2185 |
// convert would cause a segfault. Lowering will deal with |
| 2186 |
// conditionally converting and preserving the lower bounds in this |
| 2187 |
// case. |
| 2188 |
if (MaybeExpr converted{implicitConvertTo( |
| 2189 |
*symbol, std::move(*value), IsAllocatable(*symbol))}) { |
| 2190 |
if (auto componentShape{GetShape(GetFoldingContext(), *symbol)}) { |
| 2191 |
if (auto valueShape{GetShape(GetFoldingContext(), *converted)}) { |
| 2192 |
if (GetRank(*componentShape) == 0 && GetRank(*valueShape) > 0) { |
| 2193 |
AttachDeclaration( |
| 2194 |
Say(expr.source, |
| 2195 |
"Rank-%d array value is not compatible with scalar component '%s'"_err_en_US, |
| 2196 |
GetRank(*valueShape), symbol->name()), |
| 2197 |
*symbol); |
| 2198 |
} else { |
| 2199 |
auto checked{ |
| 2200 |
CheckConformance(messages, *componentShape, *valueShape, |
| 2201 |
CheckConformanceFlags::RightIsExpandableDeferred, |
| 2202 |
"component", "value")}; |
| 2203 |
if (checked && *checked && GetRank(*componentShape) > 0 && |
| 2204 |
GetRank(*valueShape) == 0 && |
| 2205 |
(IsDeferredShape(*symbol) || |
| 2206 |
!IsExpandableScalar(*converted, GetFoldingContext(), |
| 2207 |
*componentShape, true /*admit PURE call*/))) { |
| 2208 |
AttachDeclaration( |
| 2209 |
Say(expr.source, |
| 2210 |
"Scalar value cannot be expanded to shape of array component '%s'"_err_en_US, |
| 2211 |
symbol->name()), |
| 2212 |
*symbol); |
| 2213 |
} |
| 2214 |
if (checked.value_or(true)) { |
| 2215 |
result.Add(*symbol, std::move(*converted)); |
| 2216 |
} |
| 2217 |
} |
| 2218 |
} else { |
| 2219 |
Say(expr.source, "Shape of value cannot be determined"_err_en_US); |
| 2220 |
} |
| 2221 |
} else { |
| 2222 |
AttachDeclaration( |
| 2223 |
Say(expr.source, |
| 2224 |
"Shape of component '%s' cannot be determined"_err_en_US, |
| 2225 |
symbol->name()), |
| 2226 |
*symbol); |
| 2227 |
} |
| 2228 |
} else if (auto symType{DynamicType::From(symbol)}) { |
| 2229 |
if (IsAllocatable(*symbol) && symType->IsUnlimitedPolymorphic() && |
| 2230 |
valueType) { |
| 2231 |
// ok |
| 2232 |
} else if (valueType) { |
| 2233 |
AttachDeclaration( |
| 2234 |
Say(expr.source, |
| 2235 |
"Value in structure constructor of type '%s' is " |
| 2236 |
"incompatible with component '%s' of type '%s'"_err_en_US, |
| 2237 |
valueType->AsFortran(), symbol->name(), |
| 2238 |
symType->AsFortran()), |
| 2239 |
*symbol); |
| 2240 |
} else { |
| 2241 |
AttachDeclaration( |
| 2242 |
Say(expr.source, |
| 2243 |
"Value in structure constructor is incompatible with " |
| 2244 |
"component '%s' of type %s"_err_en_US, |
| 2245 |
symbol->name(), symType->AsFortran()), |
| 2246 |
*symbol); |
| 2247 |
} |
| 2248 |
} |
| 2249 |
} |
| 2250 |
} |
| 2251 |
} |
| 2252 |
|
| 2253 |
// Ensure that unmentioned component objects have default initializers. |
| 2254 |
for (const Symbol &symbol : components) { |
| 2255 |
if (!symbol.test(Symbol::Flag::ParentComp) && |
| 2256 |
unavailable.find(symbol.name()) == unavailable.cend()) { |
| 2257 |
if (IsAllocatable(symbol)) { |
| 2258 |
// Set all remaining allocatables to explicit NULL(). |
| 2259 |
result.Add(symbol, Expr<SomeType>{NullPointer{}}); |
| 2260 |
} else { |
| 2261 |
const auto *object{symbol.detailsIf<semantics::ObjectEntityDetails>()}; |
| 2262 |
if (object && object->init()) { |
| 2263 |
result.Add(symbol, common::Clone(*object->init())); |
| 2264 |
} else if (IsPointer(symbol)) { |
| 2265 |
result.Add(symbol, Expr<SomeType>{NullPointer{}}); |
| 2266 |
} else if (object) { // C799 |
| 2267 |
AttachDeclaration(Say(typeName, |
| 2268 |
"Structure constructor lacks a value for " |
| 2269 |
"component '%s'"_err_en_US, |
| 2270 |
symbol.name()), |
| 2271 |
symbol); |
| 2272 |
} |
| 2273 |
} |
| 2274 |
} |
| 2275 |
} |
| 2276 |
|
| 2277 |
return AsMaybeExpr(Expr<SomeDerived>{std::move(result)}); |
| 2278 |
} |
| 2279 |
|
| 2280 |
static std::optional<parser::CharBlock> GetPassName( |
| 2281 |
const semantics::Symbol &proc) { |
| 2282 |
return common::visit( |
| 2283 |
[](const auto &details) { |
| 2284 |
if constexpr (std::is_base_of_v<semantics::WithPassArg, |
| 2285 |
std::decay_t<decltype(details)>>) { |
| 2286 |
return details.passName(); |
| 2287 |
} else { |
| 2288 |
return std::optional<parser::CharBlock>{}; |
| 2289 |
} |
| 2290 |
}, |
| 2291 |
proc.details()); |
| 2292 |
} |
| 2293 |
|
| 2294 |
static std::optional<int> GetPassIndex(const Symbol &proc) { |
| 2295 |
CHECK(!proc.attrs().test(semantics::Attr::NOPASS)); |
| 2296 |
std::optional<parser::CharBlock> passName{GetPassName(proc)}; |
| 2297 |
const auto *interface { |
| 2298 |
semantics::FindInterface(proc) |
| 2299 |
}; |
| 2300 |
if (!passName || !interface) { |
| 2301 |
return 0; // first argument is passed-object |
| 2302 |
} |
| 2303 |
const auto &subp{interface->get<semantics::SubprogramDetails>()}; |
| 2304 |
int index{0}; |
| 2305 |
for (const auto *arg : subp.dummyArgs()) { |
| 2306 |
if (arg && arg->name() == passName) { |
| 2307 |
return index; |
| 2308 |
} |
| 2309 |
++index; |
| 2310 |
} |
| 2311 |
return std::nullopt; |
| 2312 |
} |
| 2313 |
|
| 2314 |
// Injects an expression into an actual argument list as the "passed object" |
| 2315 |
// for a type-bound procedure reference that is not NOPASS. Adds an |
| 2316 |
// argument keyword if possible, but not when the passed object goes |
| 2317 |
// before a positional argument. |
| 2318 |
// e.g., obj%tbp(x) -> tbp(obj,x). |
| 2319 |
static void AddPassArg(ActualArguments &actuals, const Expr<SomeDerived> &expr, |
| 2320 |
const Symbol &component, bool isPassedObject = true) { |
| 2321 |
if (component.attrs().test(semantics::Attr::NOPASS)) { |
| 2322 |
return; |
| 2323 |
} |
| 2324 |
std::optional<int> passIndex{GetPassIndex(component)}; |
| 2325 |
if (!passIndex) { |
| 2326 |
return; // error recovery |
| 2327 |
} |
| 2328 |
auto iter{actuals.begin()}; |
| 2329 |
int at{0}; |
| 2330 |
while (iter < actuals.end() && at < *passIndex) { |
| 2331 |
if (*iter && (*iter)->keyword()) { |
| 2332 |
iter = actuals.end(); |
| 2333 |
break; |
| 2334 |
} |
| 2335 |
++iter; |
| 2336 |
++at; |
| 2337 |
} |
| 2338 |
ActualArgument passed{AsGenericExpr(common::Clone(expr))}; |
| 2339 |
passed.set_isPassedObject(isPassedObject); |
| 2340 |
if (iter == actuals.end()) { |
| 2341 |
if (auto passName{GetPassName(component)}) { |
| 2342 |
passed.set_keyword(*passName); |
| 2343 |
} |
| 2344 |
} |
| 2345 |
actuals.emplace(iter, std::move(passed)); |
| 2346 |
} |
| 2347 |
|
| 2348 |
// Return the compile-time resolution of a procedure binding, if possible. |
| 2349 |
static const Symbol *GetBindingResolution( |
| 2350 |
const std::optional<DynamicType> &baseType, const Symbol &component) { |
| 2351 |
const auto *binding{component.detailsIf<semantics::ProcBindingDetails>()}; |
| 2352 |
if (!binding) { |
| 2353 |
return nullptr; |
| 2354 |
} |
| 2355 |
if (!component.attrs().test(semantics::Attr::NON_OVERRIDABLE) && |
| 2356 |
(!baseType || baseType->IsPolymorphic())) { |
| 2357 |
return nullptr; |
| 2358 |
} |
| 2359 |
return &binding->symbol(); |
| 2360 |
} |
| 2361 |
|
| 2362 |
auto ExpressionAnalyzer::AnalyzeProcedureComponentRef( |
| 2363 |
const parser::ProcComponentRef &pcr, ActualArguments &&arguments, |
| 2364 |
bool isSubroutine) -> std::optional<CalleeAndArguments> { |
| 2365 |
const parser::StructureComponent &sc{pcr.v.thing}; |
| 2366 |
if (MaybeExpr base{Analyze(sc.base)}) { |
| 2367 |
if (const Symbol *sym{sc.component.symbol}) { |
| 2368 |
if (context_.HasError(sym)) { |
| 2369 |
return std::nullopt; |
| 2370 |
} |
| 2371 |
if (!IsProcedure(*sym)) { |
| 2372 |
AttachDeclaration( |
| 2373 |
Say(sc.component.source, "'%s' is not a procedure"_err_en_US, |
| 2374 |
sc.component.source), |
| 2375 |
*sym); |
| 2376 |
return std::nullopt; |
| 2377 |
} |
| 2378 |
if (auto *dtExpr{UnwrapExpr<Expr<SomeDerived>>(*base)}) { |
| 2379 |
if (sym->has<semantics::GenericDetails>()) { |
| 2380 |
const Symbol &generic{*sym}; |
| 2381 |
auto dyType{dtExpr->GetType()}; |
| 2382 |
AdjustActuals adjustment{ |
| 2383 |
[&](const Symbol &proc, ActualArguments &actuals) { |
| 2384 |
if (!proc.attrs().test(semantics::Attr::NOPASS)) { |
| 2385 |
AddPassArg(actuals, std::move(*dtExpr), proc); |
| 2386 |
} |
| 2387 |
return true; |
| 2388 |
}}; |
| 2389 |
auto pair{ |
| 2390 |
ResolveGeneric(generic, arguments, adjustment, isSubroutine)}; |
| 2391 |
sym = pair.first; |
| 2392 |
if (!sym) { |
| 2393 |
EmitGenericResolutionError(generic, pair.second, isSubroutine); |
| 2394 |
return std::nullopt; |
| 2395 |
} |
| 2396 |
// re-resolve the name to the specific binding |
| 2397 |
CHECK(sym->has<semantics::ProcBindingDetails>()); |
| 2398 |
// Use the most recent override of a binding, respecting |
| 2399 |
// the rule that inaccessible bindings may not be overridden |
| 2400 |
// outside their module. Fortran doesn't allow a PUBLIC |
| 2401 |
// binding to be overridden by a PRIVATE one. |
| 2402 |
CHECK(dyType && dyType->category() == TypeCategory::Derived && |
| 2403 |
!dyType->IsUnlimitedPolymorphic()); |
| 2404 |
if (const Symbol * |
| 2405 |
latest{DEREF(dyType->GetDerivedTypeSpec().typeSymbol().scope()) |
| 2406 |
.FindComponent(sym->name())}) { |
| 2407 |
if (sym->attrs().test(semantics::Attr::PRIVATE)) { |
| 2408 |
const auto *bindingModule{FindModuleContaining(generic.owner())}; |
| 2409 |
const Symbol *s{latest}; |
| 2410 |
while (s && FindModuleContaining(s->owner()) != bindingModule) { |
| 2411 |
if (const auto *parent{s->owner().GetDerivedTypeParent()}) { |
| 2412 |
s = parent->FindComponent(sym->name()); |
| 2413 |
} else { |
| 2414 |
s = nullptr; |
| 2415 |
} |
| 2416 |
} |
| 2417 |
if (s && !s->attrs().test(semantics::Attr::PRIVATE)) { |
| 2418 |
// The latest override in the same module as the binding |
| 2419 |
// is public, so it can be overridden. |
| 2420 |
} else { |
| 2421 |
latest = s; |
| 2422 |
} |
| 2423 |
} |
| 2424 |
if (latest) { |
| 2425 |
sym = latest; |
| 2426 |
} |
| 2427 |
} |
| 2428 |
sc.component.symbol = const_cast<Symbol *>(sym); |
| 2429 |
} |
| 2430 |
std::optional<DataRef> dataRef{ExtractDataRef(std::move(*dtExpr))}; |
| 2431 |
if (dataRef && !CheckDataRef(*dataRef)) { |
| 2432 |
return std::nullopt; |
| 2433 |
} |
| 2434 |
if (dataRef && dataRef->Rank() > 0) { |
| 2435 |
if (sym->has<semantics::ProcBindingDetails>() && |
| 2436 |
sym->attrs().test(semantics::Attr::NOPASS)) { |
| 2437 |
// F'2023 C1529 seems unnecessary and most compilers don't |
| 2438 |
// enforce it. |
| 2439 |
if (context().ShouldWarn( |
| 2440 |
common::LanguageFeature::NopassScalarBase)) { |
| 2441 |
AttachDeclaration( |
| 2442 |
Say(sc.component.source, |
| 2443 |
"Base of NOPASS type-bound procedure reference should be scalar"_port_en_US), |
| 2444 |
*sym); |
| 2445 |
} |
| 2446 |
} else if (IsProcedurePointer(*sym)) { // C919 |
| 2447 |
Say(sc.component.source, |
| 2448 |
"Base of procedure component reference must be scalar"_err_en_US); |
| 2449 |
} |
| 2450 |
} |
| 2451 |
if (const Symbol *resolution{ |
| 2452 |
GetBindingResolution(dtExpr->GetType(), *sym)}) { |
| 2453 |
AddPassArg(arguments, std::move(*dtExpr), *sym, false); |
| 2454 |
return CalleeAndArguments{ |
| 2455 |
ProcedureDesignator{*resolution}, std::move(arguments)}; |
| 2456 |
} else if (dataRef.has_value()) { |
| 2457 |
if (sym->attrs().test(semantics::Attr::NOPASS)) { |
| 2458 |
const auto *dtSpec{GetDerivedTypeSpec(dtExpr->GetType())}; |
| 2459 |
if (dtSpec && dtSpec->scope()) { |
| 2460 |
if (auto component{CreateComponent(std::move(*dataRef), *sym, |
| 2461 |
*dtSpec->scope(), /*C919bAlreadyEnforced=*/true)}) { |
| 2462 |
return CalleeAndArguments{ |
| 2463 |
ProcedureDesignator{std::move(*component)}, |
| 2464 |
std::move(arguments)}; |
| 2465 |
} |
| 2466 |
} |
| 2467 |
Say(sc.component.source, |
| 2468 |
"Component is not in scope of base derived type"_err_en_US); |
| 2469 |
return std::nullopt; |
| 2470 |
} else { |
| 2471 |
AddPassArg(arguments, |
| 2472 |
Expr<SomeDerived>{Designator<SomeDerived>{std::move(*dataRef)}}, |
| 2473 |
*sym); |
| 2474 |
return CalleeAndArguments{ |
| 2475 |
ProcedureDesignator{*sym}, std::move(arguments)}; |
| 2476 |
} |
| 2477 |
} |
| 2478 |
} |
| 2479 |
Say(sc.component.source, |
| 2480 |
"Base of procedure component reference is not a derived-type object"_err_en_US); |
| 2481 |
} |
| 2482 |
} |
| 2483 |
CHECK(context_.AnyFatalError()); |
| 2484 |
return std::nullopt; |
| 2485 |
} |
| 2486 |
|
| 2487 |
// Can actual be argument associated with dummy? |
| 2488 |
static bool CheckCompatibleArgument(bool isElemental, |
| 2489 |
const ActualArgument &actual, const characteristics::DummyArgument &dummy) { |
| 2490 |
const auto *expr{actual.UnwrapExpr()}; |
| 2491 |
return common::visit( |
| 2492 |
common::visitors{ |
| 2493 |
[&](const characteristics::DummyDataObject &x) { |
| 2494 |
if (x.attrs.test(characteristics::DummyDataObject::Attr::Pointer) && |
| 2495 |
IsBareNullPointer(expr)) { |
| 2496 |
// NULL() without MOLD= is compatible with any dummy data pointer |
| 2497 |
// but cannot be allowed to lead to ambiguity. |
| 2498 |
return true; |
| 2499 |
} else if (!isElemental && actual.Rank() != x.type.Rank() && |
| 2500 |
!x.type.attrs().test( |
| 2501 |
characteristics::TypeAndShape::Attr::AssumedRank) && |
| 2502 |
!x.ignoreTKR.test(common::IgnoreTKR::Rank)) { |
| 2503 |
return false; |
| 2504 |
} else if (auto actualType{actual.GetType()}) { |
| 2505 |
return x.type.type().IsTkCompatibleWith(*actualType, x.ignoreTKR); |
| 2506 |
} |
| 2507 |
return false; |
| 2508 |
}, |
| 2509 |
[&](const characteristics::DummyProcedure &) { |
| 2510 |
return expr && IsProcedurePointerTarget(*expr); |
| 2511 |
}, |
| 2512 |
[&](const characteristics::AlternateReturn &) { |
| 2513 |
return actual.isAlternateReturn(); |
| 2514 |
}, |
| 2515 |
}, |
| 2516 |
dummy.u); |
| 2517 |
} |
| 2518 |
|
| 2519 |
// Are the actual arguments compatible with the dummy arguments of procedure? |
| 2520 |
static bool CheckCompatibleArguments( |
| 2521 |
const characteristics::Procedure &procedure, |
| 2522 |
const ActualArguments &actuals) { |
| 2523 |
bool isElemental{procedure.IsElemental()}; |
| 2524 |
const auto &dummies{procedure.dummyArguments}; |
| 2525 |
CHECK(dummies.size() == actuals.size()); |
| 2526 |
for (std::size_t i{0}; i < dummies.size(); ++i) { |
| 2527 |
const characteristics::DummyArgument &dummy{dummies[i]}; |
| 2528 |
const std::optional<ActualArgument> &actual{actuals[i]}; |
| 2529 |
if (actual && !CheckCompatibleArgument(isElemental, *actual, dummy)) { |
| 2530 |
return false; |
| 2531 |
} |
| 2532 |
} |
| 2533 |
return true; |
| 2534 |
} |
| 2535 |
|
| 2536 |
static constexpr int cudaInfMatchingValue{std::numeric_limits<int>::max()}; |
| 2537 |
|
| 2538 |
// Compute the matching distance as described in section 3.2.3 of the CUDA |
| 2539 |
// Fortran references. |
| 2540 |
static int GetMatchingDistance(const common::LanguageFeatureControl &features, |
| 2541 |
const characteristics::DummyArgument &dummy, |
| 2542 |
const std::optional<ActualArgument> &actual) { |
| 2543 |
bool isCudaManaged{features.IsEnabled(common::LanguageFeature::CudaManaged)}; |
| 2544 |
bool isCudaUnified{features.IsEnabled(common::LanguageFeature::CudaUnified)}; |
| 2545 |
CHECK(!(isCudaUnified && isCudaManaged) && "expect only one enabled."); |
| 2546 |
|
| 2547 |
std::optional<common::CUDADataAttr> actualDataAttr, dummyDataAttr; |
| 2548 |
if (actual) { |
| 2549 |
if (auto *expr{actual->UnwrapExpr()}) { |
| 2550 |
const auto *actualLastSymbol{evaluate::GetLastSymbol(*expr)}; |
| 2551 |
if (actualLastSymbol) { |
| 2552 |
actualLastSymbol = &semantics::ResolveAssociations(*actualLastSymbol); |
| 2553 |
if (const auto *actualObject{actualLastSymbol |
| 2554 |
? actualLastSymbol |
| 2555 |
->detailsIf<semantics::ObjectEntityDetails>() |
| 2556 |
: nullptr}) { |
| 2557 |
actualDataAttr = actualObject->cudaDataAttr(); |
| 2558 |
} |
| 2559 |
} |
| 2560 |
} |
| 2561 |
} |
| 2562 |
|
| 2563 |
common::visit(common::visitors{ |
| 2564 |
[&](const characteristics::DummyDataObject &object) { |
| 2565 |
dummyDataAttr = object.cudaDataAttr; |
| 2566 |
}, |
| 2567 |
[&](const auto &) {}, |
| 2568 |
}, |
| 2569 |
dummy.u); |
| 2570 |
|
| 2571 |
if (!dummyDataAttr) { |
| 2572 |
if (!actualDataAttr) { |
| 2573 |
if (isCudaUnified || isCudaManaged) { |
| 2574 |
return 3; |
| 2575 |
} |
| 2576 |
return 0; |
| 2577 |
} else if (*actualDataAttr == common::CUDADataAttr::Device) { |
| 2578 |
return cudaInfMatchingValue; |
| 2579 |
} else if (*actualDataAttr == common::CUDADataAttr::Managed || |
| 2580 |
*actualDataAttr == common::CUDADataAttr::Unified) { |
| 2581 |
return 3; |
| 2582 |
} |
| 2583 |
} else if (*dummyDataAttr == common::CUDADataAttr::Device) { |
| 2584 |
if (!actualDataAttr) { |
| 2585 |
if (isCudaUnified || isCudaManaged) { |
| 2586 |
return 2; |
| 2587 |
} |
| 2588 |
return cudaInfMatchingValue; |
| 2589 |
} else if (*actualDataAttr == common::CUDADataAttr::Device) { |
| 2590 |
return 0; |
| 2591 |
} else if (*actualDataAttr == common::CUDADataAttr::Managed || |
| 2592 |
*actualDataAttr == common::CUDADataAttr::Unified) { |
| 2593 |
return 2; |
| 2594 |
} |
| 2595 |
} else if (*dummyDataAttr == common::CUDADataAttr::Managed) { |
| 2596 |
if (!actualDataAttr) { |
| 2597 |
return isCudaUnified ? 1 : isCudaManaged ? 0 : cudaInfMatchingValue; |
| 2598 |
} |
| 2599 |
if (*actualDataAttr == common::CUDADataAttr::Device) { |
| 2600 |
return cudaInfMatchingValue; |
| 2601 |
} else if (*actualDataAttr == common::CUDADataAttr::Managed) { |
| 2602 |
return 0; |
| 2603 |
} else if (*actualDataAttr == common::CUDADataAttr::Unified) { |
| 2604 |
return 1; |
| 2605 |
} |
| 2606 |
} else if (*dummyDataAttr == common::CUDADataAttr::Unified) { |
| 2607 |
if (!actualDataAttr) { |
| 2608 |
return isCudaUnified ? 0 : isCudaManaged ? 1 : cudaInfMatchingValue; |
| 2609 |
} |
| 2610 |
if (*actualDataAttr == common::CUDADataAttr::Device) { |
| 2611 |
return cudaInfMatchingValue; |
| 2612 |
} else if (*actualDataAttr == common::CUDADataAttr::Managed) { |
| 2613 |
return 1; |
| 2614 |
} else if (*actualDataAttr == common::CUDADataAttr::Unified) { |
| 2615 |
return 0; |
| 2616 |
} |
| 2617 |
} |
| 2618 |
return cudaInfMatchingValue; |
| 2619 |
} |
| 2620 |
|
| 2621 |
static int ComputeCudaMatchingDistance( |
| 2622 |
const common::LanguageFeatureControl &features, |
| 2623 |
const characteristics::Procedure &procedure, |
| 2624 |
const ActualArguments &actuals) { |
| 2625 |
const auto &dummies{procedure.dummyArguments}; |
| 2626 |
CHECK(dummies.size() == actuals.size()); |
| 2627 |
int distance{0}; |
| 2628 |
for (std::size_t i{0}; i < dummies.size(); ++i) { |
| 2629 |
const characteristics::DummyArgument &dummy{dummies[i]}; |
| 2630 |
const std::optional<ActualArgument> &actual{actuals[i]}; |
| 2631 |
int d{GetMatchingDistance(features, dummy, actual)}; |
| 2632 |
if (d == cudaInfMatchingValue) |
| 2633 |
return d; |
| 2634 |
distance += d; |
| 2635 |
} |
| 2636 |
return distance; |
| 2637 |
} |
| 2638 |
|
| 2639 |
// Handles a forward reference to a module function from what must |
| 2640 |
// be a specification expression. Return false if the symbol is |
| 2641 |
// an invalid forward reference. |
| 2642 |
bool ExpressionAnalyzer::ResolveForward(const Symbol &symbol) { |
| 2643 |
if (context_.HasError(symbol)) { |
| 2644 |
return false; |
| 2645 |
} |
| 2646 |
if (const auto *details{ |
| 2647 |
symbol.detailsIf<semantics::SubprogramNameDetails>()}) { |
| 2648 |
if (details->kind() == semantics::SubprogramKind::Module) { |
| 2649 |
// If this symbol is still a SubprogramNameDetails, we must be |
| 2650 |
// checking a specification expression in a sibling module |
| 2651 |
// procedure. Resolve its names now so that its interface |
| 2652 |
// is known. |
| 2653 |
semantics::ResolveSpecificationParts(context_, symbol); |
| 2654 |
if (symbol.has<semantics::SubprogramNameDetails>()) { |
| 2655 |
// When the symbol hasn't had its details updated, we must have |
| 2656 |
// already been in the process of resolving the function's |
| 2657 |
// specification part; but recursive function calls are not |
| 2658 |
// allowed in specification parts (10.1.11 para 5). |
| 2659 |
Say("The module function '%s' may not be referenced recursively in a specification expression"_err_en_US, |
| 2660 |
symbol.name()); |
| 2661 |
context_.SetError(symbol); |
| 2662 |
return false; |
| 2663 |
} |
| 2664 |
} else if (inStmtFunctionDefinition_) { |
| 2665 |
semantics::ResolveSpecificationParts(context_, symbol); |
| 2666 |
CHECK(symbol.has<semantics::SubprogramDetails>()); |
| 2667 |
} else { // 10.1.11 para 4 |
| 2668 |
Say("The internal function '%s' may not be referenced in a specification expression"_err_en_US, |
| 2669 |
symbol.name()); |
| 2670 |
context_.SetError(symbol); |
| 2671 |
return false; |
| 2672 |
} |
| 2673 |
} |
| 2674 |
return true; |
| 2675 |
} |
| 2676 |
|
| 2677 |
// Resolve a call to a generic procedure with given actual arguments. |
| 2678 |
// adjustActuals is called on procedure bindings to handle pass arg. |
| 2679 |
std::pair<const Symbol *, bool> ExpressionAnalyzer::ResolveGeneric( |
| 2680 |
const Symbol &symbol, const ActualArguments &actuals, |
| 2681 |
const AdjustActuals &adjustActuals, bool isSubroutine, |
| 2682 |
bool mightBeStructureConstructor) { |
| 2683 |
const Symbol *elemental{nullptr}; // matching elemental specific proc |
| 2684 |
const Symbol *nonElemental{nullptr}; // matching non-elemental specific |
| 2685 |
const Symbol &ultimate{symbol.GetUltimate()}; |
| 2686 |
int crtMatchingDistance{cudaInfMatchingValue}; |
| 2687 |
// Check for a match with an explicit INTRINSIC |
| 2688 |
if (ultimate.attrs().test(semantics::Attr::INTRINSIC)) { |
| 2689 |
parser::Messages buffer; |
| 2690 |
auto restorer{foldingContext_.messages().SetMessages(buffer)}; |
| 2691 |
ActualArguments localActuals{actuals}; |
| 2692 |
if (context_.intrinsics().Probe( |
| 2693 |
CallCharacteristics{ultimate.name().ToString(), isSubroutine}, |
| 2694 |
localActuals, foldingContext_) && |
| 2695 |
!buffer.AnyFatalError()) { |
| 2696 |
return {&ultimate, false}; |
| 2697 |
} |
| 2698 |
} |
| 2699 |
if (const auto *details{ultimate.detailsIf<semantics::GenericDetails>()}) { |
| 2700 |
for (const Symbol &specific0 : details->specificProcs()) { |
| 2701 |
const Symbol &specific{BypassGeneric(specific0)}; |
| 2702 |
if (isSubroutine != !IsFunction(specific)) { |
| 2703 |
continue; |
| 2704 |
} |
| 2705 |
if (!ResolveForward(specific)) { |
| 2706 |
continue; |
| 2707 |
} |
| 2708 |
if (std::optional<characteristics::Procedure> procedure{ |
| 2709 |
characteristics::Procedure::Characterize( |
| 2710 |
ProcedureDesignator{specific}, context_.foldingContext(), |
| 2711 |
/*emitError=*/false)}) { |
| 2712 |
ActualArguments localActuals{actuals}; |
| 2713 |
if (specific.has<semantics::ProcBindingDetails>()) { |
| 2714 |
if (!adjustActuals.value()(specific, localActuals)) { |
| 2715 |
continue; |
| 2716 |
} |
| 2717 |
} |
| 2718 |
if (semantics::CheckInterfaceForGeneric(*procedure, localActuals, |
| 2719 |
context_, false /* no integer conversions */) && |
| 2720 |
CheckCompatibleArguments(*procedure, localActuals)) { |
| 2721 |
if ((procedure->IsElemental() && elemental) || |
| 2722 |
(!procedure->IsElemental() && nonElemental)) { |
| 2723 |
int d{ComputeCudaMatchingDistance( |
| 2724 |
context_.languageFeatures(), *procedure, localActuals)}; |
| 2725 |
llvm::errs() << "matching distance: " << d << "\n"; |
| 2726 |
if (d != crtMatchingDistance) { |
| 2727 |
if (d > crtMatchingDistance) { |
| 2728 |
continue; |
| 2729 |
} |
| 2730 |
// Matching distance is smaller than the previously matched |
| 2731 |
// specific. Let it go thourgh so the current procedure is picked. |
| 2732 |
} else { |
| 2733 |
// 16.9.144(6): a bare NULL() is not allowed as an actual |
| 2734 |
// argument to a generic procedure if the specific procedure |
| 2735 |
// cannot be unambiguously distinguished |
| 2736 |
// Underspecified external procedure actual arguments can |
| 2737 |
// also lead to ambiguity. |
| 2738 |
return {nullptr, true /* due to ambiguity */}; |
| 2739 |
} |
| 2740 |
} |
| 2741 |
if (!procedure->IsElemental()) { |
| 2742 |
// takes priority over elemental match |
| 2743 |
nonElemental = &specific; |
| 2744 |
} else { |
| 2745 |
elemental = &specific; |
| 2746 |
} |
| 2747 |
crtMatchingDistance = ComputeCudaMatchingDistance( |
| 2748 |
context_.languageFeatures(), *procedure, localActuals); |
| 2749 |
} |
| 2750 |
} |
| 2751 |
} |
| 2752 |
if (nonElemental) { |
| 2753 |
return {&AccessSpecific(symbol, *nonElemental), false}; |
| 2754 |
} else if (elemental) { |
| 2755 |
return {&AccessSpecific(symbol, *elemental), false}; |
| 2756 |
} |
| 2757 |
// Check parent derived type |
| 2758 |
if (const auto *parentScope{symbol.owner().GetDerivedTypeParent()}) { |
| 2759 |
if (const Symbol *extended{parentScope->FindComponent(symbol.name())}) { |
| 2760 |
auto pair{ResolveGeneric( |
| 2761 |
*extended, actuals, adjustActuals, isSubroutine, false)}; |
| 2762 |
if (pair.first) { |
| 2763 |
return pair; |
| 2764 |
} |
| 2765 |
} |
| 2766 |
} |
| 2767 |
if (mightBeStructureConstructor && details->derivedType()) { |
| 2768 |
return {details->derivedType(), false}; |
| 2769 |
} |
| 2770 |
} |
| 2771 |
// Check for generic or explicit INTRINSIC of the same name in outer scopes. |
| 2772 |
// See 15.5.5.2 for details. |
| 2773 |
if (!symbol.owner().IsGlobal() && !symbol.owner().IsDerivedType()) { |
| 2774 |
for (const std::string &n : GetAllNames(context_, symbol.name())) { |
| 2775 |
if (const Symbol *outer{symbol.owner().parent().FindSymbol(n)}) { |
| 2776 |
auto pair{ResolveGeneric(*outer, actuals, adjustActuals, isSubroutine, |
| 2777 |
mightBeStructureConstructor)}; |
| 2778 |
if (pair.first) { |
| 2779 |
return pair; |
| 2780 |
} |
| 2781 |
} |
| 2782 |
} |
| 2783 |
} |
| 2784 |
return {nullptr, false}; |
| 2785 |
} |
| 2786 |
|
| 2787 |
const Symbol &ExpressionAnalyzer::AccessSpecific( |
| 2788 |
const Symbol &originalGeneric, const Symbol &specific) { |
| 2789 |
if (const auto *hosted{ |
| 2790 |
originalGeneric.detailsIf<semantics::HostAssocDetails>()}) { |
| 2791 |
return AccessSpecific(hosted->symbol(), specific); |
| 2792 |
} else if (const auto *used{ |
| 2793 |
originalGeneric.detailsIf<semantics::UseDetails>()}) { |
| 2794 |
const auto &scope{originalGeneric.owner()}; |
| 2795 |
if (auto iter{scope.find(specific.name())}; iter != scope.end()) { |
| 2796 |
if (const auto *useDetails{ |
| 2797 |
iter->second->detailsIf<semantics::UseDetails>()}) { |
| 2798 |
const Symbol &usedSymbol{useDetails->symbol()}; |
| 2799 |
const auto *usedGeneric{ |
| 2800 |
usedSymbol.detailsIf<semantics::GenericDetails>()}; |
| 2801 |
if (&usedSymbol == &specific || |
| 2802 |
(usedGeneric && usedGeneric->specific() == &specific)) { |
| 2803 |
return specific; |
| 2804 |
} |
| 2805 |
} |
| 2806 |
} |
| 2807 |
// Create a renaming USE of the specific procedure. |
| 2808 |
auto rename{context_.SaveTempName( |
| 2809 |
used->symbol().owner().GetName().value().ToString() + "$" + |
| 2810 |
specific.owner().GetName().value().ToString() + "$" + |
| 2811 |
specific.name().ToString())}; |
| 2812 |
return *const_cast<semantics::Scope &>(scope) |
| 2813 |
.try_emplace(rename, specific.attrs(), |
| 2814 |
semantics::UseDetails{rename, specific}) |
| 2815 |
.first->second; |
| 2816 |
} else { |
| 2817 |
return specific; |
| 2818 |
} |
| 2819 |
} |
| 2820 |
|
| 2821 |
void ExpressionAnalyzer::EmitGenericResolutionError( |
| 2822 |
const Symbol &symbol, bool dueToAmbiguity, bool isSubroutine) { |
| 2823 |
Say(dueToAmbiguity |
| 2824 |
? "The actual arguments to the generic procedure '%s' matched multiple specific procedures, perhaps due to use of NULL() without MOLD= or an actual procedure with an implicit interface"_err_en_US |
| 2825 |
: semantics::IsGenericDefinedOp(symbol) |
| 2826 |
? "No specific procedure of generic operator '%s' matches the actual arguments"_err_en_US |
| 2827 |
: isSubroutine |
| 2828 |
? "No specific subroutine of generic '%s' matches the actual arguments"_err_en_US |
| 2829 |
: "No specific function of generic '%s' matches the actual arguments"_err_en_US, |
| 2830 |
symbol.name()); |
| 2831 |
} |
| 2832 |
|
| 2833 |
auto ExpressionAnalyzer::GetCalleeAndArguments( |
| 2834 |
const parser::ProcedureDesignator &pd, ActualArguments &&arguments, |
| 2835 |
bool isSubroutine, bool mightBeStructureConstructor) |
| 2836 |
-> std::optional<CalleeAndArguments> { |
| 2837 |
return common::visit(common::visitors{ |
| 2838 |
[&](const parser::Name &name) { |
| 2839 |
return GetCalleeAndArguments(name, |
| 2840 |
std::move(arguments), isSubroutine, |
| 2841 |
mightBeStructureConstructor); |
| 2842 |
}, |
| 2843 |
[&](const parser::ProcComponentRef &pcr) { |
| 2844 |
return AnalyzeProcedureComponentRef( |
| 2845 |
pcr, std::move(arguments), isSubroutine); |
| 2846 |
}, |
| 2847 |
}, |
| 2848 |
pd.u); |
| 2849 |
} |
| 2850 |
|
| 2851 |
auto ExpressionAnalyzer::GetCalleeAndArguments(const parser::Name &name, |
| 2852 |
ActualArguments &&arguments, bool isSubroutine, |
| 2853 |
bool mightBeStructureConstructor) -> std::optional<CalleeAndArguments> { |
| 2854 |
const Symbol *symbol{name.symbol}; |
| 2855 |
if (context_.HasError(symbol)) { |
| 2856 |
return std::nullopt; // also handles null symbol |
| 2857 |
} |
| 2858 |
const Symbol &ultimate{DEREF(symbol).GetUltimate()}; |
| 2859 |
CheckForBadRecursion(name.source, ultimate); |
| 2860 |
bool dueToAmbiguity{false}; |
| 2861 |
bool isGenericInterface{ultimate.has<semantics::GenericDetails>()}; |
| 2862 |
bool isExplicitIntrinsic{ultimate.attrs().test(semantics::Attr::INTRINSIC)}; |
| 2863 |
const Symbol *resolution{nullptr}; |
| 2864 |
if (isGenericInterface || isExplicitIntrinsic) { |
| 2865 |
ExpressionAnalyzer::AdjustActuals noAdjustment; |
| 2866 |
auto pair{ResolveGeneric(*symbol, arguments, noAdjustment, isSubroutine, |
| 2867 |
mightBeStructureConstructor)}; |
| 2868 |
resolution = pair.first; |
| 2869 |
dueToAmbiguity = pair.second; |
| 2870 |
if (resolution) { |
| 2871 |
if (context_.GetPPCBuiltinsScope() && |
| 2872 |
resolution->name().ToString().rfind("__ppc_", 0) == 0) { |
| 2873 |
semantics::CheckPPCIntrinsic( |
| 2874 |
*symbol, *resolution, arguments, GetFoldingContext()); |
| 2875 |
} |
| 2876 |
// re-resolve name to the specific procedure |
| 2877 |
name.symbol = const_cast<Symbol *>(resolution); |
| 2878 |
} |
| 2879 |
} else if (IsProcedure(ultimate) && |
| 2880 |
ultimate.attrs().test(semantics::Attr::ABSTRACT)) { |
| 2881 |
Say("Abstract procedure interface '%s' may not be referenced"_err_en_US, |
| 2882 |
name.source); |
| 2883 |
} else { |
| 2884 |
resolution = symbol; |
| 2885 |
} |
| 2886 |
if (!resolution || resolution->attrs().test(semantics::Attr::INTRINSIC)) { |
| 2887 |
auto name{resolution ? resolution->name() : ultimate.name()}; |
| 2888 |
if (std::optional<SpecificCall> specificCall{context_.intrinsics().Probe( |
| 2889 |
CallCharacteristics{name.ToString(), isSubroutine}, arguments, |
| 2890 |
GetFoldingContext())}) { |
| 2891 |
CheckBadExplicitType(*specificCall, *symbol); |
| 2892 |
return CalleeAndArguments{ |
| 2893 |
ProcedureDesignator{std::move(specificCall->specificIntrinsic)}, |
| 2894 |
std::move(specificCall->arguments)}; |
| 2895 |
} else { |
| 2896 |
if (isGenericInterface) { |
| 2897 |
EmitGenericResolutionError(*symbol, dueToAmbiguity, isSubroutine); |
| 2898 |
} |
| 2899 |
return std::nullopt; |
| 2900 |
} |
| 2901 |
} |
| 2902 |
if (resolution->GetUltimate().has<semantics::DerivedTypeDetails>()) { |
| 2903 |
if (mightBeStructureConstructor) { |
| 2904 |
return CalleeAndArguments{ |
| 2905 |
semantics::SymbolRef{*resolution}, std::move(arguments)}; |
| 2906 |
} |
| 2907 |
} else if (IsProcedure(*resolution)) { |
| 2908 |
return CalleeAndArguments{ |
| 2909 |
ProcedureDesignator{*resolution}, std::move(arguments)}; |
| 2910 |
} |
| 2911 |
if (!context_.HasError(*resolution)) { |
| 2912 |
AttachDeclaration( |
| 2913 |
Say(name.source, "'%s' is not a callable procedure"_err_en_US, |
| 2914 |
name.source), |
| 2915 |
*resolution); |
| 2916 |
} |
| 2917 |
return std::nullopt; |
| 2918 |
} |
| 2919 |
|
| 2920 |
// Fortran 2018 expressly states (8.2 p3) that any declared type for a |
| 2921 |
// generic intrinsic function "has no effect" on the result type of a |
| 2922 |
// call to that intrinsic. So one can declare "character*8 cos" and |
| 2923 |
// still get a real result from "cos(1.)". This is a dangerous feature, |
| 2924 |
// especially since implementations are free to extend their sets of |
| 2925 |
// intrinsics, and in doing so might clash with a name in a program. |
| 2926 |
// So we emit a warning in this situation, and perhaps it should be an |
| 2927 |
// error -- any correctly working program can silence the message by |
| 2928 |
// simply deleting the pointless type declaration. |
| 2929 |
void ExpressionAnalyzer::CheckBadExplicitType( |
| 2930 |
const SpecificCall &call, const Symbol &intrinsic) { |
| 2931 |
if (intrinsic.GetUltimate().GetType()) { |
| 2932 |
const auto &procedure{call.specificIntrinsic.characteristics.value()}; |
| 2933 |
if (const auto &result{procedure.functionResult}) { |
| 2934 |
if (const auto *typeAndShape{result->GetTypeAndShape()}) { |
| 2935 |
if (auto declared{ |
| 2936 |
typeAndShape->Characterize(intrinsic, GetFoldingContext())}) { |
| 2937 |
if (!declared->type().IsTkCompatibleWith(typeAndShape->type()) && |
| 2938 |
context_.ShouldWarn( |
| 2939 |
common::UsageWarning::IgnoredIntrinsicFunctionType)) { |
| 2940 |
if (auto *msg{Say( |
| 2941 |
"The result type '%s' of the intrinsic function '%s' is not the explicit declared type '%s'"_warn_en_US, |
| 2942 |
typeAndShape->AsFortran(), intrinsic.name(), |
| 2943 |
declared->AsFortran())}) { |
| 2944 |
msg->Attach(intrinsic.name(), |
| 2945 |
"Ignored declaration of intrinsic function '%s'"_en_US, |
| 2946 |
intrinsic.name()); |
| 2947 |
} |
| 2948 |
} |
| 2949 |
} |
| 2950 |
} |
| 2951 |
} |
| 2952 |
} |
| 2953 |
} |
| 2954 |
|
| 2955 |
void ExpressionAnalyzer::CheckForBadRecursion( |
| 2956 |
parser::CharBlock callSite, const semantics::Symbol &proc) { |
| 2957 |
if (const auto *scope{proc.scope()}) { |
| 2958 |
if (scope->sourceRange().Contains(callSite)) { |
| 2959 |
parser::Message *msg{nullptr}; |
| 2960 |
if (proc.attrs().test(semantics::Attr::NON_RECURSIVE)) { // 15.6.2.1(3) |
| 2961 |
msg = Say("NON_RECURSIVE procedure '%s' cannot call itself"_err_en_US, |
| 2962 |
callSite); |
| 2963 |
} else if (IsAssumedLengthCharacter(proc) && IsExternal(proc)) { |
| 2964 |
// TODO: Also catch assumed PDT type parameters |
| 2965 |
msg = Say( // 15.6.2.1(3) |
| 2966 |
"Assumed-length CHARACTER(*) function '%s' cannot call itself"_err_en_US, |
| 2967 |
callSite); |
| 2968 |
} else if (FindCUDADeviceContext(scope)) { |
| 2969 |
msg = Say( |
| 2970 |
"Device subprogram '%s' cannot call itself"_err_en_US, callSite); |
| 2971 |
} |
| 2972 |
AttachDeclaration(msg, proc); |
| 2973 |
} |
| 2974 |
} |
| 2975 |
} |
| 2976 |
|
| 2977 |
template <typename A> static const Symbol *AssumedTypeDummy(const A &x) { |
| 2978 |
if (const auto *designator{ |
| 2979 |
std::get_if<common::Indirection<parser::Designator>>(&x.u)}) { |
| 2980 |
if (const auto *dataRef{ |
| 2981 |
std::get_if<parser::DataRef>(&designator->value().u)}) { |
| 2982 |
if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) { |
| 2983 |
return AssumedTypeDummy(*name); |
| 2984 |
} |
| 2985 |
} |
| 2986 |
} |
| 2987 |
return nullptr; |
| 2988 |
} |
| 2989 |
template <> |
| 2990 |
const Symbol *AssumedTypeDummy<parser::Name>(const parser::Name &name) { |
| 2991 |
if (const Symbol *symbol{name.symbol}) { |
| 2992 |
if (const auto *type{symbol->GetType()}) { |
| 2993 |
if (type->category() == semantics::DeclTypeSpec::TypeStar) { |
| 2994 |
return symbol; |
| 2995 |
} |
| 2996 |
} |
| 2997 |
} |
| 2998 |
return nullptr; |
| 2999 |
} |
| 3000 |
template <typename A> |
| 3001 |
static const Symbol *AssumedTypePointerOrAllocatableDummy(const A &object) { |
| 3002 |
// It is illegal for allocatable of pointer objects to be TYPE(*), but at that |
| 3003 |
// point it is not guaranteed that it has been checked the object has |
| 3004 |
// POINTER or ALLOCATABLE attribute, so do not assume nullptr can be directly |
| 3005 |
// returned. |
| 3006 |
return common::visit( |
| 3007 |
common::visitors{ |
| 3008 |
[&](const parser::StructureComponent &x) { |
| 3009 |
return AssumedTypeDummy(x.component); |
| 3010 |
}, |
| 3011 |
[&](const parser::Name &x) { return AssumedTypeDummy(x); }, |
| 3012 |
}, |
| 3013 |
object.u); |
| 3014 |
} |
| 3015 |
template <> |
| 3016 |
const Symbol *AssumedTypeDummy<parser::AllocateObject>( |
| 3017 |
const parser::AllocateObject &x) { |
| 3018 |
return AssumedTypePointerOrAllocatableDummy(x); |
| 3019 |
} |
| 3020 |
template <> |
| 3021 |
const Symbol *AssumedTypeDummy<parser::PointerObject>( |
| 3022 |
const parser::PointerObject &x) { |
| 3023 |
return AssumedTypePointerOrAllocatableDummy(x); |
| 3024 |
} |
| 3025 |
|
| 3026 |
bool ExpressionAnalyzer::CheckIsValidForwardReference( |
| 3027 |
const semantics::DerivedTypeSpec &dtSpec) { |
| 3028 |
if (dtSpec.IsForwardReferenced()) { |
| 3029 |
Say("Cannot construct value for derived type '%s' " |
| 3030 |
"before it is defined"_err_en_US, |
| 3031 |
dtSpec.name()); |
| 3032 |
return false; |
| 3033 |
} |
| 3034 |
return true; |
| 3035 |
} |
| 3036 |
|
| 3037 |
std::optional<Chevrons> ExpressionAnalyzer::AnalyzeChevrons( |
| 3038 |
const parser::CallStmt &call) { |
| 3039 |
Chevrons result; |
| 3040 |
auto checkLaunchArg{[&](const Expr<SomeType> &expr, const char *which) { |
| 3041 |
if (auto dyType{expr.GetType()}) { |
| 3042 |
if (dyType->category() == TypeCategory::Integer) { |
| 3043 |
return true; |
| 3044 |
} |
| 3045 |
if (dyType->category() == TypeCategory::Derived && |
| 3046 |
!dyType->IsPolymorphic() && |
| 3047 |
IsBuiltinDerivedType(&dyType->GetDerivedTypeSpec(), "dim3")) { |
| 3048 |
return true; |
| 3049 |
} |
| 3050 |
} |
| 3051 |
Say("Kernel launch %s parameter must be either integer or TYPE(dim3)"_err_en_US, |
| 3052 |
which); |
| 3053 |
return false; |
| 3054 |
}}; |
| 3055 |
if (const auto &chevrons{call.chevrons}) { |
| 3056 |
if (auto expr{Analyze(std::get<0>(chevrons->t))}; |
| 3057 |
expr && checkLaunchArg(*expr, "grid")) { |
| 3058 |
result.emplace_back(*expr); |
| 3059 |
} else { |
| 3060 |
return std::nullopt; |
| 3061 |
} |
| 3062 |
if (auto expr{Analyze(std::get<1>(chevrons->t))}; |
| 3063 |
expr && checkLaunchArg(*expr, "block")) { |
| 3064 |
result.emplace_back(*expr); |
| 3065 |
} else { |
| 3066 |
return std::nullopt; |
| 3067 |
} |
| 3068 |
if (const auto &maybeExpr{std::get<2>(chevrons->t)}) { |
| 3069 |
if (auto expr{Analyze(*maybeExpr)}) { |
| 3070 |
result.emplace_back(*expr); |
| 3071 |
} else { |
| 3072 |
return std::nullopt; |
| 3073 |
} |
| 3074 |
} |
| 3075 |
if (const auto &maybeExpr{std::get<3>(chevrons->t)}) { |
| 3076 |
if (auto expr{Analyze(*maybeExpr)}) { |
| 3077 |
result.emplace_back(*expr); |
| 3078 |
} else { |
| 3079 |
return std::nullopt; |
| 3080 |
} |
| 3081 |
} |
| 3082 |
} |
| 3083 |
return std::move(result); |
| 3084 |
} |
| 3085 |
|
| 3086 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::FunctionReference &funcRef, |
| 3087 |
std::optional<parser::StructureConstructor> *structureConstructor) { |
| 3088 |
const parser::Call &call{funcRef.v}; |
| 3089 |
auto restorer{GetContextualMessages().SetLocation(funcRef.source)}; |
| 3090 |
ArgumentAnalyzer analyzer{*this, funcRef.source, true /* isProcedureCall */}; |
| 3091 |
for (const auto &arg : std::get<std::list<parser::ActualArgSpec>>(call.t)) { |
| 3092 |
analyzer.Analyze(arg, false /* not subroutine call */); |
| 3093 |
} |
| 3094 |
if (analyzer.fatalErrors()) { |
| 3095 |
return std::nullopt; |
| 3096 |
} |
| 3097 |
bool mightBeStructureConstructor{structureConstructor != nullptr}; |
| 3098 |
if (std::optional<CalleeAndArguments> callee{GetCalleeAndArguments( |
| 3099 |
std::get<parser::ProcedureDesignator>(call.t), analyzer.GetActuals(), |
| 3100 |
false /* not subroutine */, mightBeStructureConstructor)}) { |
| 3101 |
if (auto *proc{std::get_if<ProcedureDesignator>(&callee->u)}) { |
| 3102 |
return MakeFunctionRef( |
| 3103 |
funcRef.source, std::move(*proc), std::move(callee->arguments)); |
| 3104 |
} |
| 3105 |
CHECK(std::holds_alternative<semantics::SymbolRef>(callee->u)); |
| 3106 |
const Symbol &symbol{*std::get<semantics::SymbolRef>(callee->u)}; |
| 3107 |
if (mightBeStructureConstructor) { |
| 3108 |
// Structure constructor misparsed as function reference? |
| 3109 |
const auto &designator{std::get<parser::ProcedureDesignator>(call.t)}; |
| 3110 |
if (const auto *name{std::get_if<parser::Name>(&designator.u)}) { |
| 3111 |
semantics::Scope &scope{context_.FindScope(name->source)}; |
| 3112 |
semantics::DerivedTypeSpec dtSpec{name->source, symbol.GetUltimate()}; |
| 3113 |
if (!CheckIsValidForwardReference(dtSpec)) { |
| 3114 |
return std::nullopt; |
| 3115 |
} |
| 3116 |
const semantics::DeclTypeSpec &type{ |
| 3117 |
semantics::FindOrInstantiateDerivedType(scope, std::move(dtSpec))}; |
| 3118 |
auto &mutableRef{const_cast<parser::FunctionReference &>(funcRef)}; |
| 3119 |
*structureConstructor = |
| 3120 |
mutableRef.ConvertToStructureConstructor(type.derivedTypeSpec()); |
| 3121 |
return Analyze(structureConstructor->value()); |
| 3122 |
} |
| 3123 |
} |
| 3124 |
if (!context_.HasError(symbol)) { |
| 3125 |
AttachDeclaration( |
| 3126 |
Say("'%s' is called like a function but is not a procedure"_err_en_US, |
| 3127 |
symbol.name()), |
| 3128 |
symbol); |
| 3129 |
context_.SetError(symbol); |
| 3130 |
} |
| 3131 |
} |
| 3132 |
return std::nullopt; |
| 3133 |
} |
| 3134 |
|
| 3135 |
static bool HasAlternateReturns(const evaluate::ActualArguments &args) { |
| 3136 |
for (const auto &arg : args) { |
| 3137 |
if (arg && arg->isAlternateReturn()) { |
| 3138 |
return true; |
| 3139 |
} |
| 3140 |
} |
| 3141 |
return false; |
| 3142 |
} |
| 3143 |
|
| 3144 |
void ExpressionAnalyzer::Analyze(const parser::CallStmt &callStmt) { |
| 3145 |
const parser::Call &call{callStmt.call}; |
| 3146 |
auto restorer{GetContextualMessages().SetLocation(callStmt.source)}; |
| 3147 |
ArgumentAnalyzer analyzer{*this, callStmt.source, true /* isProcedureCall */}; |
| 3148 |
const auto &actualArgList{std::get<std::list<parser::ActualArgSpec>>(call.t)}; |
| 3149 |
for (const auto &arg : actualArgList) { |
| 3150 |
analyzer.Analyze(arg, true /* is subroutine call */); |
| 3151 |
} |
| 3152 |
if (auto chevrons{AnalyzeChevrons(callStmt)}; |
| 3153 |
chevrons && !analyzer.fatalErrors()) { |
| 3154 |
if (std::optional<CalleeAndArguments> callee{ |
| 3155 |
GetCalleeAndArguments(std::get<parser::ProcedureDesignator>(call.t), |
| 3156 |
analyzer.GetActuals(), true /* subroutine */)}) { |
| 3157 |
ProcedureDesignator *proc{std::get_if<ProcedureDesignator>(&callee->u)}; |
| 3158 |
CHECK(proc); |
| 3159 |
bool isKernel{false}; |
| 3160 |
if (const Symbol * procSym{proc->GetSymbol()}) { |
| 3161 |
const Symbol &ultimate{procSym->GetUltimate()}; |
| 3162 |
if (const auto *subpDetails{ |
| 3163 |
ultimate.detailsIf<semantics::SubprogramDetails>()}) { |
| 3164 |
if (auto attrs{subpDetails->cudaSubprogramAttrs()}) { |
| 3165 |
isKernel = *attrs == common::CUDASubprogramAttrs::Global || |
| 3166 |
*attrs == common::CUDASubprogramAttrs::Grid_Global; |
| 3167 |
} |
| 3168 |
} else if (const auto *procDetails{ |
| 3169 |
ultimate.detailsIf<semantics::ProcEntityDetails>()}) { |
| 3170 |
isKernel = procDetails->isCUDAKernel(); |
| 3171 |
} |
| 3172 |
if (isKernel && chevrons->empty()) { |
| 3173 |
Say("'%s' is a kernel subroutine and must be called with kernel launch parameters in chevrons"_err_en_US, |
| 3174 |
procSym->name()); |
| 3175 |
} |
| 3176 |
} |
| 3177 |
if (!isKernel && !chevrons->empty()) { |
| 3178 |
Say("Kernel launch parameters in chevrons may not be used unless calling a kernel subroutine"_err_en_US); |
| 3179 |
} |
| 3180 |
if (CheckCall(callStmt.source, *proc, callee->arguments)) { |
| 3181 |
callStmt.typedCall.Reset( |
| 3182 |
new ProcedureRef{std::move(*proc), std::move(callee->arguments), |
| 3183 |
HasAlternateReturns(callee->arguments)}, |
| 3184 |
ProcedureRef::Deleter); |
| 3185 |
DEREF(callStmt.typedCall.get()).set_chevrons(std::move(*chevrons)); |
| 3186 |
return; |
| 3187 |
} |
| 3188 |
} |
| 3189 |
if (!context_.AnyFatalError()) { |
| 3190 |
std::string buf; |
| 3191 |
llvm::raw_string_ostream dump{buf}; |
| 3192 |
parser::DumpTree(dump, callStmt); |
| 3193 |
Say("Internal error: Expression analysis failed on CALL statement: %s"_err_en_US, |
| 3194 |
dump.str()); |
| 3195 |
} |
| 3196 |
} |
| 3197 |
} |
| 3198 |
|
| 3199 |
const Assignment *ExpressionAnalyzer::Analyze(const parser::AssignmentStmt &x) { |
| 3200 |
if (!x.typedAssignment) { |
| 3201 |
ArgumentAnalyzer analyzer{*this}; |
| 3202 |
const auto &variable{std::get<parser::Variable>(x.t)}; |
| 3203 |
analyzer.Analyze(variable); |
| 3204 |
analyzer.Analyze(std::get<parser::Expr>(x.t)); |
| 3205 |
std::optional<Assignment> assignment; |
| 3206 |
if (!analyzer.fatalErrors()) { |
| 3207 |
auto restorer{GetContextualMessages().SetLocation(variable.GetSource())}; |
| 3208 |
std::optional<ProcedureRef> procRef{analyzer.TryDefinedAssignment()}; |
| 3209 |
if (!procRef) { |
| 3210 |
analyzer.CheckForNullPointer( |
| 3211 |
"in a non-pointer intrinsic assignment statement"); |
| 3212 |
analyzer.CheckForAssumedRank("in an assignment statement"); |
| 3213 |
const Expr<SomeType> &lhs{analyzer.GetExpr(0)}; |
| 3214 |
if (auto dyType{lhs.GetType()}; |
| 3215 |
dyType && dyType->IsPolymorphic()) { // 10.2.1.2p1(1) |
| 3216 |
const Symbol *lastWhole0{UnwrapWholeSymbolOrComponentDataRef(lhs)}; |
| 3217 |
const Symbol *lastWhole{ |
| 3218 |
lastWhole0 ? &lastWhole0->GetUltimate() : nullptr}; |
| 3219 |
if (!lastWhole || !IsAllocatable(*lastWhole)) { |
| 3220 |
Say("Left-hand side of assignment may not be polymorphic unless assignment is to an entire allocatable"_err_en_US); |
| 3221 |
} else if (evaluate::IsCoarray(*lastWhole)) { |
| 3222 |
Say("Left-hand side of assignment may not be polymorphic if it is a coarray"_err_en_US); |
| 3223 |
} |
| 3224 |
} |
| 3225 |
} |
| 3226 |
assignment.emplace(analyzer.MoveExpr(0), analyzer.MoveExpr(1)); |
| 3227 |
if (procRef) { |
| 3228 |
assignment->u = std::move(*procRef); |
| 3229 |
} |
| 3230 |
} |
| 3231 |
x.typedAssignment.Reset(new GenericAssignmentWrapper{std::move(assignment)}, |
| 3232 |
GenericAssignmentWrapper::Deleter); |
| 3233 |
} |
| 3234 |
return common::GetPtrFromOptional(x.typedAssignment->v); |
| 3235 |
} |
| 3236 |
|
| 3237 |
const Assignment *ExpressionAnalyzer::Analyze( |
| 3238 |
const parser::PointerAssignmentStmt &x) { |
| 3239 |
if (!x.typedAssignment) { |
| 3240 |
MaybeExpr lhs{Analyze(std::get<parser::DataRef>(x.t))}; |
| 3241 |
MaybeExpr rhs; |
| 3242 |
{ |
| 3243 |
auto restorer{AllowNullPointer()}; |
| 3244 |
rhs = Analyze(std::get<parser::Expr>(x.t)); |
| 3245 |
} |
| 3246 |
if (!lhs || !rhs) { |
| 3247 |
x.typedAssignment.Reset( |
| 3248 |
new GenericAssignmentWrapper{}, GenericAssignmentWrapper::Deleter); |
| 3249 |
} else { |
| 3250 |
Assignment assignment{std::move(*lhs), std::move(*rhs)}; |
| 3251 |
common::visit( |
| 3252 |
common::visitors{ |
| 3253 |
[&](const std::list<parser::BoundsRemapping> &list) { |
| 3254 |
Assignment::BoundsRemapping bounds; |
| 3255 |
for (const auto &elem : list) { |
| 3256 |
auto lower{AsSubscript(Analyze(std::get<0>(elem.t)))}; |
| 3257 |
auto upper{AsSubscript(Analyze(std::get<1>(elem.t)))}; |
| 3258 |
if (lower && upper) { |
| 3259 |
bounds.emplace_back( |
| 3260 |
Fold(std::move(*lower)), Fold(std::move(*upper))); |
| 3261 |
} |
| 3262 |
} |
| 3263 |
assignment.u = std::move(bounds); |
| 3264 |
}, |
| 3265 |
[&](const std::list<parser::BoundsSpec> &list) { |
| 3266 |
Assignment::BoundsSpec bounds; |
| 3267 |
for (const auto &bound : list) { |
| 3268 |
if (auto lower{AsSubscript(Analyze(bound.v))}) { |
| 3269 |
bounds.emplace_back(Fold(std::move(*lower))); |
| 3270 |
} |
| 3271 |
} |
| 3272 |
assignment.u = std::move(bounds); |
| 3273 |
}, |
| 3274 |
}, |
| 3275 |
std::get<parser::PointerAssignmentStmt::Bounds>(x.t).u); |
| 3276 |
x.typedAssignment.Reset( |
| 3277 |
new GenericAssignmentWrapper{std::move(assignment)}, |
| 3278 |
GenericAssignmentWrapper::Deleter); |
| 3279 |
} |
| 3280 |
} |
| 3281 |
return common::GetPtrFromOptional(x.typedAssignment->v); |
| 3282 |
} |
| 3283 |
|
| 3284 |
static bool IsExternalCalledImplicitly( |
| 3285 |
parser::CharBlock callSite, const Symbol *symbol) { |
| 3286 |
return symbol && symbol->owner().IsGlobal() && |
| 3287 |
symbol->has<semantics::SubprogramDetails>() && |
| 3288 |
(!symbol->scope() /*ENTRY*/ || |
| 3289 |
!symbol->scope()->sourceRange().Contains(callSite)); |
| 3290 |
} |
| 3291 |
|
| 3292 |
std::optional<characteristics::Procedure> ExpressionAnalyzer::CheckCall( |
| 3293 |
parser::CharBlock callSite, const ProcedureDesignator &proc, |
| 3294 |
ActualArguments &arguments) { |
| 3295 |
bool treatExternalAsImplicit{ |
| 3296 |
IsExternalCalledImplicitly(callSite, proc.GetSymbol())}; |
| 3297 |
const Symbol *procSymbol{proc.GetSymbol()}; |
| 3298 |
std::optional<characteristics::Procedure> chars; |
| 3299 |
if (procSymbol && procSymbol->has<semantics::ProcEntityDetails>() && |
| 3300 |
procSymbol->owner().IsGlobal()) { |
| 3301 |
// Unknown global external, implicit interface; assume |
| 3302 |
// characteristics from the actual arguments, and check |
| 3303 |
// for consistency with other references. |
| 3304 |
chars = characteristics::Procedure::FromActuals( |
| 3305 |
proc, arguments, context_.foldingContext()); |
| 3306 |
if (chars && procSymbol) { |
| 3307 |
// Ensure calls over implicit interfaces are consistent |
| 3308 |
auto name{procSymbol->name()}; |
| 3309 |
if (auto iter{implicitInterfaces_.find(name)}; |
| 3310 |
iter != implicitInterfaces_.end()) { |
| 3311 |
std::string whyNot; |
| 3312 |
if (!chars->IsCompatibleWith(iter->second.second, |
| 3313 |
/*ignoreImplicitVsExplicit=*/false, &whyNot) && |
| 3314 |
context_.ShouldWarn( |
| 3315 |
common::UsageWarning::IncompatibleImplicitInterfaces)) { |
| 3316 |
if (auto *msg{Say(callSite, |
| 3317 |
"Reference to the procedure '%s' has an implicit interface that is distinct from another reference: %s"_warn_en_US, |
| 3318 |
name, whyNot)}) { |
| 3319 |
msg->Attach( |
| 3320 |
iter->second.first, "previous reference to '%s'"_en_US, name); |
| 3321 |
} |
| 3322 |
} |
| 3323 |
} else { |
| 3324 |
implicitInterfaces_.insert( |
| 3325 |
std::make_pair(name, std::make_pair(callSite, *chars))); |
| 3326 |
} |
| 3327 |
} |
| 3328 |
} |
| 3329 |
if (!chars) { |
| 3330 |
chars = characteristics::Procedure::Characterize( |
| 3331 |
proc, context_.foldingContext(), /*emitError=*/true); |
| 3332 |
} |
| 3333 |
bool ok{true}; |
| 3334 |
if (chars) { |
| 3335 |
std::string whyNot; |
| 3336 |
if (treatExternalAsImplicit && |
| 3337 |
!chars->CanBeCalledViaImplicitInterface(&whyNot)) { |
| 3338 |
if (auto *msg{Say(callSite, |
| 3339 |
"References to the procedure '%s' require an explicit interface"_err_en_US, |
| 3340 |
DEREF(procSymbol).name())}; |
| 3341 |
msg && !whyNot.empty()) { |
| 3342 |
msg->Attach(callSite, "%s"_because_en_US, whyNot); |
| 3343 |
} |
| 3344 |
} |
| 3345 |
const SpecificIntrinsic *specificIntrinsic{proc.GetSpecificIntrinsic()}; |
| 3346 |
bool procIsDummy{procSymbol && IsDummy(*procSymbol)}; |
| 3347 |
if (chars->functionResult && |
| 3348 |
chars->functionResult->IsAssumedLengthCharacter() && |
| 3349 |
!specificIntrinsic && !procIsDummy) { |
| 3350 |
Say(callSite, |
| 3351 |
"Assumed-length character function must be defined with a length to be called"_err_en_US); |
| 3352 |
} |
| 3353 |
ok &= semantics::CheckArguments(*chars, arguments, context_, |
| 3354 |
context_.FindScope(callSite), treatExternalAsImplicit, |
| 3355 |
/*ignoreImplicitVsExplicit=*/false, specificIntrinsic); |
| 3356 |
} |
| 3357 |
if (procSymbol && !IsPureProcedure(*procSymbol)) { |
| 3358 |
if (const semantics::Scope * |
| 3359 |
pure{semantics::FindPureProcedureContaining( |
| 3360 |
context_.FindScope(callSite))}) { |
| 3361 |
Say(callSite, |
| 3362 |
"Procedure '%s' referenced in pure subprogram '%s' must be pure too"_err_en_US, |
| 3363 |
procSymbol->name(), DEREF(pure->symbol()).name()); |
| 3364 |
} |
| 3365 |
} |
| 3366 |
if (ok && !treatExternalAsImplicit && procSymbol && |
| 3367 |
!(chars && chars->HasExplicitInterface())) { |
| 3368 |
if (const Symbol *global{FindGlobal(*procSymbol)}; |
| 3369 |
global && global != procSymbol && IsProcedure(*global)) { |
| 3370 |
// Check a known global definition behind a local interface |
| 3371 |
if (auto globalChars{characteristics::Procedure::Characterize( |
| 3372 |
*global, context_.foldingContext())}) { |
| 3373 |
semantics::CheckArguments(*globalChars, arguments, context_, |
| 3374 |
context_.FindScope(callSite), /*treatExternalAsImplicit=*/true, |
| 3375 |
/*ignoreImplicitVsExplicit=*/false, |
| 3376 |
nullptr /*not specific intrinsic*/); |
| 3377 |
} |
| 3378 |
} |
| 3379 |
} |
| 3380 |
return chars; |
| 3381 |
} |
| 3382 |
|
| 3383 |
// Unary operations |
| 3384 |
|
| 3385 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Parentheses &x) { |
| 3386 |
if (MaybeExpr operand{Analyze(x.v.value())}) { |
| 3387 |
if (const semantics::Symbol *symbol{GetLastSymbol(*operand)}) { |
| 3388 |
if (const semantics::Symbol *result{FindFunctionResult(*symbol)}) { |
| 3389 |
if (semantics::IsProcedurePointer(*result)) { |
| 3390 |
Say("A function reference that returns a procedure " |
| 3391 |
"pointer may not be parenthesized"_err_en_US); // C1003 |
| 3392 |
} |
| 3393 |
} |
| 3394 |
} |
| 3395 |
return Parenthesize(std::move(*operand)); |
| 3396 |
} |
| 3397 |
return std::nullopt; |
| 3398 |
} |
| 3399 |
|
| 3400 |
static MaybeExpr NumericUnaryHelper(ExpressionAnalyzer &context, |
| 3401 |
NumericOperator opr, const parser::Expr::IntrinsicUnary &x) { |
| 3402 |
ArgumentAnalyzer analyzer{context}; |
| 3403 |
analyzer.Analyze(x.v); |
| 3404 |
if (!analyzer.fatalErrors()) { |
| 3405 |
if (analyzer.IsIntrinsicNumeric(opr)) { |
| 3406 |
analyzer.CheckForNullPointer(); |
| 3407 |
analyzer.CheckForAssumedRank(); |
| 3408 |
if (opr == NumericOperator::Add) { |
| 3409 |
return analyzer.MoveExpr(0); |
| 3410 |
} else { |
| 3411 |
return Negation(context.GetContextualMessages(), analyzer.MoveExpr(0)); |
| 3412 |
} |
| 3413 |
} else { |
| 3414 |
return analyzer.TryDefinedOp(AsFortran(opr), |
| 3415 |
"Operand of unary %s must be numeric; have %s"_err_en_US); |
| 3416 |
} |
| 3417 |
} |
| 3418 |
return std::nullopt; |
| 3419 |
} |
| 3420 |
|
| 3421 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::UnaryPlus &x) { |
| 3422 |
return NumericUnaryHelper(*this, NumericOperator::Add, x); |
| 3423 |
} |
| 3424 |
|
| 3425 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Negate &x) { |
| 3426 |
if (const auto *litConst{ |
| 3427 |
std::get_if<parser::LiteralConstant>(&x.v.value().u)}) { |
| 3428 |
if (const auto *intConst{ |
| 3429 |
std::get_if<parser::IntLiteralConstant>(&litConst->u)}) { |
| 3430 |
return Analyze(*intConst, true); |
| 3431 |
} |
| 3432 |
} |
| 3433 |
return NumericUnaryHelper(*this, NumericOperator::Subtract, x); |
| 3434 |
} |
| 3435 |
|
| 3436 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NOT &x) { |
| 3437 |
ArgumentAnalyzer analyzer{*this}; |
| 3438 |
analyzer.Analyze(x.v); |
| 3439 |
if (!analyzer.fatalErrors()) { |
| 3440 |
if (analyzer.IsIntrinsicLogical()) { |
| 3441 |
analyzer.CheckForNullPointer(); |
| 3442 |
analyzer.CheckForAssumedRank(); |
| 3443 |
return AsGenericExpr( |
| 3444 |
LogicalNegation(std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u))); |
| 3445 |
} else { |
| 3446 |
return analyzer.TryDefinedOp(LogicalOperator::Not, |
| 3447 |
"Operand of %s must be LOGICAL; have %s"_err_en_US); |
| 3448 |
} |
| 3449 |
} |
| 3450 |
return std::nullopt; |
| 3451 |
} |
| 3452 |
|
| 3453 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::PercentLoc &x) { |
| 3454 |
// Represent %LOC() exactly as if it had been a call to the LOC() extension |
| 3455 |
// intrinsic function. |
| 3456 |
// Use the actual source for the name of the call for error reporting. |
| 3457 |
std::optional<ActualArgument> arg; |
| 3458 |
if (const Symbol *assumedTypeDummy{AssumedTypeDummy(x.v.value())}) { |
| 3459 |
arg = ActualArgument{ActualArgument::AssumedType{*assumedTypeDummy}}; |
| 3460 |
} else if (MaybeExpr argExpr{Analyze(x.v.value())}) { |
| 3461 |
arg = ActualArgument{std::move(*argExpr)}; |
| 3462 |
} else { |
| 3463 |
return std::nullopt; |
| 3464 |
} |
| 3465 |
parser::CharBlock at{GetContextualMessages().at()}; |
| 3466 |
CHECK(at.size() >= 4); |
| 3467 |
parser::CharBlock loc{at.begin() + 1, 3}; |
| 3468 |
CHECK(loc == "loc"); |
| 3469 |
return MakeFunctionRef(loc, ActualArguments{std::move(*arg)}); |
| 3470 |
} |
| 3471 |
|
| 3472 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedUnary &x) { |
| 3473 |
const auto &name{std::get<parser::DefinedOpName>(x.t).v}; |
| 3474 |
ArgumentAnalyzer analyzer{*this, name.source}; |
| 3475 |
analyzer.Analyze(std::get<1>(x.t)); |
| 3476 |
return analyzer.TryDefinedOp(name.source.ToString().c_str(), |
| 3477 |
"No operator %s defined for %s"_err_en_US, true); |
| 3478 |
} |
| 3479 |
|
| 3480 |
// Binary (dyadic) operations |
| 3481 |
|
| 3482 |
template <template <typename> class OPR> |
| 3483 |
MaybeExpr NumericBinaryHelper(ExpressionAnalyzer &context, NumericOperator opr, |
| 3484 |
const parser::Expr::IntrinsicBinary &x) { |
| 3485 |
ArgumentAnalyzer analyzer{context}; |
| 3486 |
analyzer.Analyze(std::get<0>(x.t)); |
| 3487 |
analyzer.Analyze(std::get<1>(x.t)); |
| 3488 |
if (!analyzer.fatalErrors()) { |
| 3489 |
if (analyzer.IsIntrinsicNumeric(opr)) { |
| 3490 |
analyzer.CheckForNullPointer(); |
| 3491 |
analyzer.CheckForAssumedRank(); |
| 3492 |
analyzer.CheckConformance(); |
| 3493 |
return NumericOperation<OPR>(context.GetContextualMessages(), |
| 3494 |
analyzer.MoveExpr(0), analyzer.MoveExpr(1), |
| 3495 |
context.GetDefaultKind(TypeCategory::Real)); |
| 3496 |
} else { |
| 3497 |
return analyzer.TryDefinedOp(AsFortran(opr), |
| 3498 |
"Operands of %s must be numeric; have %s and %s"_err_en_US); |
| 3499 |
} |
| 3500 |
} |
| 3501 |
return std::nullopt; |
| 3502 |
} |
| 3503 |
|
| 3504 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Power &x) { |
| 3505 |
return NumericBinaryHelper<Power>(*this, NumericOperator::Power, x); |
| 3506 |
} |
| 3507 |
|
| 3508 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Multiply &x) { |
| 3509 |
return NumericBinaryHelper<Multiply>(*this, NumericOperator::Multiply, x); |
| 3510 |
} |
| 3511 |
|
| 3512 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Divide &x) { |
| 3513 |
return NumericBinaryHelper<Divide>(*this, NumericOperator::Divide, x); |
| 3514 |
} |
| 3515 |
|
| 3516 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Add &x) { |
| 3517 |
return NumericBinaryHelper<Add>(*this, NumericOperator::Add, x); |
| 3518 |
} |
| 3519 |
|
| 3520 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Subtract &x) { |
| 3521 |
return NumericBinaryHelper<Subtract>(*this, NumericOperator::Subtract, x); |
| 3522 |
} |
| 3523 |
|
| 3524 |
MaybeExpr ExpressionAnalyzer::Analyze( |
| 3525 |
const parser::Expr::ComplexConstructor &z) { |
| 3526 |
if (context_.ShouldWarn(common::LanguageFeature::ComplexConstructor)) { |
| 3527 |
context_.Say( |
| 3528 |
"nonstandard usage: generalized COMPLEX constructor"_port_en_US); |
| 3529 |
} |
| 3530 |
return AnalyzeComplex(Analyze(std::get<0>(z.t).value()), |
| 3531 |
Analyze(std::get<1>(z.t).value()), "complex constructor"); |
| 3532 |
} |
| 3533 |
|
| 3534 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::Concat &x) { |
| 3535 |
ArgumentAnalyzer analyzer{*this}; |
| 3536 |
analyzer.Analyze(std::get<0>(x.t)); |
| 3537 |
analyzer.Analyze(std::get<1>(x.t)); |
| 3538 |
if (!analyzer.fatalErrors()) { |
| 3539 |
if (analyzer.IsIntrinsicConcat()) { |
| 3540 |
analyzer.CheckForNullPointer(); |
| 3541 |
analyzer.CheckForAssumedRank(); |
| 3542 |
return common::visit( |
| 3543 |
[&](auto &&x, auto &&y) -> MaybeExpr { |
| 3544 |
using T = ResultType<decltype(x)>; |
| 3545 |
if constexpr (std::is_same_v<T, ResultType<decltype(y)>>) { |
| 3546 |
return AsGenericExpr(Concat<T::kind>{std::move(x), std::move(y)}); |
| 3547 |
} else { |
| 3548 |
DIE("different types for intrinsic concat"); |
| 3549 |
} |
| 3550 |
}, |
| 3551 |
std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(0).u).u), |
| 3552 |
std::move(std::get<Expr<SomeCharacter>>(analyzer.MoveExpr(1).u).u)); |
| 3553 |
} else { |
| 3554 |
return analyzer.TryDefinedOp("//", |
| 3555 |
"Operands of %s must be CHARACTER with the same kind; have %s and %s"_err_en_US); |
| 3556 |
} |
| 3557 |
} |
| 3558 |
return std::nullopt; |
| 3559 |
} |
| 3560 |
|
| 3561 |
// The Name represents a user-defined intrinsic operator. |
| 3562 |
// If the actuals match one of the specific procedures, return a function ref. |
| 3563 |
// Otherwise report the error in messages. |
| 3564 |
MaybeExpr ExpressionAnalyzer::AnalyzeDefinedOp( |
| 3565 |
const parser::Name &name, ActualArguments &&actuals) { |
| 3566 |
if (auto callee{GetCalleeAndArguments(name, std::move(actuals))}) { |
| 3567 |
CHECK(std::holds_alternative<ProcedureDesignator>(callee->u)); |
| 3568 |
return MakeFunctionRef(name.source, |
| 3569 |
std::move(std::get<ProcedureDesignator>(callee->u)), |
| 3570 |
std::move(callee->arguments)); |
| 3571 |
} else { |
| 3572 |
return std::nullopt; |
| 3573 |
} |
| 3574 |
} |
| 3575 |
|
| 3576 |
MaybeExpr RelationHelper(ExpressionAnalyzer &context, RelationalOperator opr, |
| 3577 |
const parser::Expr::IntrinsicBinary &x) { |
| 3578 |
ArgumentAnalyzer analyzer{context}; |
| 3579 |
analyzer.Analyze(std::get<0>(x.t)); |
| 3580 |
analyzer.Analyze(std::get<1>(x.t)); |
| 3581 |
if (!analyzer.fatalErrors()) { |
| 3582 |
std::optional<DynamicType> leftType{analyzer.GetType(0)}; |
| 3583 |
std::optional<DynamicType> rightType{analyzer.GetType(1)}; |
| 3584 |
analyzer.ConvertBOZ(&leftType, 0, rightType); |
| 3585 |
analyzer.ConvertBOZ(&rightType, 1, leftType); |
| 3586 |
if (leftType && rightType && |
| 3587 |
analyzer.IsIntrinsicRelational(opr, *leftType, *rightType)) { |
| 3588 |
analyzer.CheckForNullPointer("as a relational operand"); |
| 3589 |
analyzer.CheckForAssumedRank("as a relational operand"); |
| 3590 |
return AsMaybeExpr(Relate(context.GetContextualMessages(), opr, |
| 3591 |
analyzer.MoveExpr(0), analyzer.MoveExpr(1))); |
| 3592 |
} else { |
| 3593 |
return analyzer.TryDefinedOp(opr, |
| 3594 |
leftType && leftType->category() == TypeCategory::Logical && |
| 3595 |
rightType && rightType->category() == TypeCategory::Logical |
| 3596 |
? "LOGICAL operands must be compared using .EQV. or .NEQV."_err_en_US |
| 3597 |
: "Operands of %s must have comparable types; have %s and %s"_err_en_US); |
| 3598 |
} |
| 3599 |
} |
| 3600 |
return std::nullopt; |
| 3601 |
} |
| 3602 |
|
| 3603 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LT &x) { |
| 3604 |
return RelationHelper(*this, RelationalOperator::LT, x); |
| 3605 |
} |
| 3606 |
|
| 3607 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::LE &x) { |
| 3608 |
return RelationHelper(*this, RelationalOperator::LE, x); |
| 3609 |
} |
| 3610 |
|
| 3611 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQ &x) { |
| 3612 |
return RelationHelper(*this, RelationalOperator::EQ, x); |
| 3613 |
} |
| 3614 |
|
| 3615 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NE &x) { |
| 3616 |
return RelationHelper(*this, RelationalOperator::NE, x); |
| 3617 |
} |
| 3618 |
|
| 3619 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GE &x) { |
| 3620 |
return RelationHelper(*this, RelationalOperator::GE, x); |
| 3621 |
} |
| 3622 |
|
| 3623 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::GT &x) { |
| 3624 |
return RelationHelper(*this, RelationalOperator::GT, x); |
| 3625 |
} |
| 3626 |
|
| 3627 |
MaybeExpr LogicalBinaryHelper(ExpressionAnalyzer &context, LogicalOperator opr, |
| 3628 |
const parser::Expr::IntrinsicBinary &x) { |
| 3629 |
ArgumentAnalyzer analyzer{context}; |
| 3630 |
analyzer.Analyze(std::get<0>(x.t)); |
| 3631 |
analyzer.Analyze(std::get<1>(x.t)); |
| 3632 |
if (!analyzer.fatalErrors()) { |
| 3633 |
if (analyzer.IsIntrinsicLogical()) { |
| 3634 |
analyzer.CheckForNullPointer("as a logical operand"); |
| 3635 |
analyzer.CheckForAssumedRank("as a logical operand"); |
| 3636 |
return AsGenericExpr(BinaryLogicalOperation(opr, |
| 3637 |
std::get<Expr<SomeLogical>>(analyzer.MoveExpr(0).u), |
| 3638 |
std::get<Expr<SomeLogical>>(analyzer.MoveExpr(1).u))); |
| 3639 |
} else { |
| 3640 |
return analyzer.TryDefinedOp( |
| 3641 |
opr, "Operands of %s must be LOGICAL; have %s and %s"_err_en_US); |
| 3642 |
} |
| 3643 |
} |
| 3644 |
return std::nullopt; |
| 3645 |
} |
| 3646 |
|
| 3647 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::AND &x) { |
| 3648 |
return LogicalBinaryHelper(*this, LogicalOperator::And, x); |
| 3649 |
} |
| 3650 |
|
| 3651 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::OR &x) { |
| 3652 |
return LogicalBinaryHelper(*this, LogicalOperator::Or, x); |
| 3653 |
} |
| 3654 |
|
| 3655 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::EQV &x) { |
| 3656 |
return LogicalBinaryHelper(*this, LogicalOperator::Eqv, x); |
| 3657 |
} |
| 3658 |
|
| 3659 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::NEQV &x) { |
| 3660 |
return LogicalBinaryHelper(*this, LogicalOperator::Neqv, x); |
| 3661 |
} |
| 3662 |
|
| 3663 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr::DefinedBinary &x) { |
| 3664 |
const auto &name{std::get<parser::DefinedOpName>(x.t).v}; |
| 3665 |
ArgumentAnalyzer analyzer{*this, name.source}; |
| 3666 |
analyzer.Analyze(std::get<1>(x.t)); |
| 3667 |
analyzer.Analyze(std::get<2>(x.t)); |
| 3668 |
return analyzer.TryDefinedOp(name.source.ToString().c_str(), |
| 3669 |
"No operator %s defined for %s and %s"_err_en_US, true); |
| 3670 |
} |
| 3671 |
|
| 3672 |
// Returns true if a parsed function reference should be converted |
| 3673 |
// into an array element reference. |
| 3674 |
static bool CheckFuncRefToArrayElement(semantics::SemanticsContext &context, |
| 3675 |
const parser::FunctionReference &funcRef) { |
| 3676 |
// Emit message if the function reference fix will end up an array element |
| 3677 |
// reference with no subscripts, or subscripts on a scalar, because it will |
| 3678 |
// not be possible to later distinguish in expressions between an empty |
| 3679 |
// subscript list due to bad subscripts error recovery or because the |
| 3680 |
// user did not put any. |
| 3681 |
auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)}; |
| 3682 |
const auto *name{std::get_if<parser::Name>(&proc.u)}; |
| 3683 |
if (!name) { |
| 3684 |
name = &std::get<parser::ProcComponentRef>(proc.u).v.thing.component; |
| 3685 |
} |
| 3686 |
if (!name->symbol) { |
| 3687 |
return false; |
| 3688 |
} else if (name->symbol->Rank() == 0) { |
| 3689 |
if (const Symbol *function{ |
| 3690 |
semantics::IsFunctionResultWithSameNameAsFunction(*name->symbol)}) { |
| 3691 |
auto &msg{context.Say(funcRef.source, |
| 3692 |
function->flags().test(Symbol::Flag::StmtFunction) |
| 3693 |
? "Recursive call to statement function '%s' is not allowed"_err_en_US |
| 3694 |
: "Recursive call to '%s' requires a distinct RESULT in its declaration"_err_en_US, |
| 3695 |
name->source)}; |
| 3696 |
AttachDeclaration(&msg, *function); |
| 3697 |
name->symbol = const_cast<Symbol *>(function); |
| 3698 |
} |
| 3699 |
return false; |
| 3700 |
} else { |
| 3701 |
if (std::get<std::list<parser::ActualArgSpec>>(funcRef.v.t).empty()) { |
| 3702 |
auto &msg{context.Say(funcRef.source, |
| 3703 |
"Reference to array '%s' with empty subscript list"_err_en_US, |
| 3704 |
name->source)}; |
| 3705 |
if (name->symbol) { |
| 3706 |
AttachDeclaration(&msg, *name->symbol); |
| 3707 |
} |
| 3708 |
} |
| 3709 |
return true; |
| 3710 |
} |
| 3711 |
} |
| 3712 |
|
| 3713 |
// Converts, if appropriate, an original misparse of ambiguous syntax like |
| 3714 |
// A(1) as a function reference into an array reference. |
| 3715 |
// Misparsed structure constructors are detected elsewhere after generic |
| 3716 |
// function call resolution fails. |
| 3717 |
template <typename... A> |
| 3718 |
static void FixMisparsedFunctionReference( |
| 3719 |
semantics::SemanticsContext &context, const std::variant<A...> &constU) { |
| 3720 |
// The parse tree is updated in situ when resolving an ambiguous parse. |
| 3721 |
using uType = std::decay_t<decltype(constU)>; |
| 3722 |
auto &u{const_cast<uType &>(constU)}; |
| 3723 |
if (auto *func{ |
| 3724 |
std::get_if<common::Indirection<parser::FunctionReference>>(&u)}) { |
| 3725 |
parser::FunctionReference &funcRef{func->value()}; |
| 3726 |
// Ensure that there are no argument keywords |
| 3727 |
for (const auto &arg : |
| 3728 |
std::get<std::list<parser::ActualArgSpec>>(funcRef.v.t)) { |
| 3729 |
if (std::get<std::optional<parser::Keyword>>(arg.t)) { |
| 3730 |
return; |
| 3731 |
} |
| 3732 |
} |
| 3733 |
auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)}; |
| 3734 |
if (Symbol *origSymbol{ |
| 3735 |
common::visit(common::visitors{ |
| 3736 |
[&](parser::Name &name) { return name.symbol; }, |
| 3737 |
[&](parser::ProcComponentRef &pcr) { |
| 3738 |
return pcr.v.thing.component.symbol; |
| 3739 |
}, |
| 3740 |
}, |
| 3741 |
proc.u)}) { |
| 3742 |
Symbol &symbol{origSymbol->GetUltimate()}; |
| 3743 |
if (symbol.has<semantics::ObjectEntityDetails>() || |
| 3744 |
symbol.has<semantics::AssocEntityDetails>()) { |
| 3745 |
// Note that expression in AssocEntityDetails cannot be a procedure |
| 3746 |
// pointer as per C1105 so this cannot be a function reference. |
| 3747 |
if constexpr (common::HasMember<common::Indirection<parser::Designator>, |
| 3748 |
uType>) { |
| 3749 |
if (CheckFuncRefToArrayElement(context, funcRef)) { |
| 3750 |
u = common::Indirection{funcRef.ConvertToArrayElementRef()}; |
| 3751 |
} |
| 3752 |
} else { |
| 3753 |
DIE("can't fix misparsed function as array reference"); |
| 3754 |
} |
| 3755 |
} |
| 3756 |
} |
| 3757 |
} |
| 3758 |
} |
| 3759 |
|
| 3760 |
// Common handling of parse tree node types that retain the |
| 3761 |
// representation of the analyzed expression. |
| 3762 |
template <typename PARSED> |
| 3763 |
MaybeExpr ExpressionAnalyzer::ExprOrVariable( |
| 3764 |
const PARSED &x, parser::CharBlock source) { |
| 3765 |
auto restorer{GetContextualMessages().SetLocation(source)}; |
| 3766 |
if constexpr (std::is_same_v<PARSED, parser::Expr> || |
| 3767 |
std::is_same_v<PARSED, parser::Variable>) { |
| 3768 |
FixMisparsedFunctionReference(context_, x.u); |
| 3769 |
} |
| 3770 |
if (AssumedTypeDummy(x)) { // C710 |
| 3771 |
Say("TYPE(*) dummy argument may only be used as an actual argument"_err_en_US); |
| 3772 |
ResetExpr(x); |
| 3773 |
return std::nullopt; |
| 3774 |
} |
| 3775 |
MaybeExpr result; |
| 3776 |
if constexpr (common::HasMember<parser::StructureConstructor, |
| 3777 |
std::decay_t<decltype(x.u)>> && |
| 3778 |
common::HasMember<common::Indirection<parser::FunctionReference>, |
| 3779 |
std::decay_t<decltype(x.u)>>) { |
| 3780 |
if (const auto *funcRef{ |
| 3781 |
std::get_if<common::Indirection<parser::FunctionReference>>( |
| 3782 |
&x.u)}) { |
| 3783 |
// Function references in Exprs might turn out to be misparsed structure |
| 3784 |
// constructors; we have to try generic procedure resolution |
| 3785 |
// first to be sure. |
| 3786 |
std::optional<parser::StructureConstructor> ctor; |
| 3787 |
result = Analyze(funcRef->value(), &ctor); |
| 3788 |
if (result && ctor) { |
| 3789 |
// A misparsed function reference is really a structure |
| 3790 |
// constructor. Repair the parse tree in situ. |
| 3791 |
const_cast<PARSED &>(x).u = std::move(*ctor); |
| 3792 |
} |
| 3793 |
} else { |
| 3794 |
result = Analyze(x.u); |
| 3795 |
} |
| 3796 |
} else { |
| 3797 |
result = Analyze(x.u); |
| 3798 |
} |
| 3799 |
if (result) { |
| 3800 |
if constexpr (std::is_same_v<PARSED, parser::Expr>) { |
| 3801 |
if (!isNullPointerOk_ && IsNullPointer(*result)) { |
| 3802 |
Say(source, |
| 3803 |
"NULL() may not be used as an expression in this context"_err_en_US); |
| 3804 |
} |
| 3805 |
} |
| 3806 |
SetExpr(x, Fold(std::move(*result))); |
| 3807 |
return x.typedExpr->v; |
| 3808 |
} else { |
| 3809 |
ResetExpr(x); |
| 3810 |
if (!context_.AnyFatalError()) { |
| 3811 |
std::string buf; |
| 3812 |
llvm::raw_string_ostream dump{buf}; |
| 3813 |
parser::DumpTree(dump, x); |
| 3814 |
Say("Internal error: Expression analysis failed on: %s"_err_en_US, |
| 3815 |
dump.str()); |
| 3816 |
} |
| 3817 |
return std::nullopt; |
| 3818 |
} |
| 3819 |
} |
| 3820 |
|
| 3821 |
// This is an optional preliminary pass over parser::Expr subtrees. |
| 3822 |
// Given an expression tree, iteratively traverse it in a bottom-up order |
| 3823 |
// to analyze all of its subexpressions. A later normal top-down analysis |
| 3824 |
// will then be able to use the results that will have been saved in the |
| 3825 |
// parse tree without having to recurse deeply. This technique keeps |
| 3826 |
// absurdly deep expression parse trees from causing the analyzer to overflow |
| 3827 |
// its stack. |
| 3828 |
MaybeExpr ExpressionAnalyzer::IterativelyAnalyzeSubexpressions( |
| 3829 |
const parser::Expr &top) { |
| 3830 |
std::vector<const parser::Expr *> queue, finish; |
| 3831 |
queue.push_back(&top); |
| 3832 |
do { |
| 3833 |
const parser::Expr &expr{*queue.back()}; |
| 3834 |
queue.pop_back(); |
| 3835 |
if (!expr.typedExpr) { |
| 3836 |
const parser::Expr::IntrinsicUnary *unary{nullptr}; |
| 3837 |
const parser::Expr::IntrinsicBinary *binary{nullptr}; |
| 3838 |
common::visit( |
| 3839 |
[&unary, &binary](auto &y) { |
| 3840 |
if constexpr (std::is_convertible_v<decltype(&y), |
| 3841 |
decltype(unary)>) { |
| 3842 |
// Don't evaluate a constant operand to Negate |
| 3843 |
if (!std::holds_alternative<parser::LiteralConstant>( |
| 3844 |
y.v.value().u)) { |
| 3845 |
unary = &y; |
| 3846 |
} |
| 3847 |
} else if constexpr (std::is_convertible_v<decltype(&y), |
| 3848 |
decltype(binary)>) { |
| 3849 |
binary = &y; |
| 3850 |
} |
| 3851 |
}, |
| 3852 |
expr.u); |
| 3853 |
if (unary) { |
| 3854 |
queue.push_back(&unary->v.value()); |
| 3855 |
} else if (binary) { |
| 3856 |
queue.push_back(&std::get<0>(binary->t).value()); |
| 3857 |
queue.push_back(&std::get<1>(binary->t).value()); |
| 3858 |
} |
| 3859 |
finish.push_back(&expr); |
| 3860 |
} |
| 3861 |
} while (!queue.empty()); |
| 3862 |
// Analyze the collected subexpressions in bottom-up order. |
| 3863 |
// On an error, bail out and leave partial results in place. |
| 3864 |
MaybeExpr result; |
| 3865 |
for (auto riter{finish.rbegin()}; riter != finish.rend(); ++riter) { |
| 3866 |
const parser::Expr &expr{**riter}; |
| 3867 |
result = ExprOrVariable(expr, expr.source); |
| 3868 |
if (!result) { |
| 3869 |
return result; |
| 3870 |
} |
| 3871 |
} |
| 3872 |
return result; // last value was from analysis of "top" |
| 3873 |
} |
| 3874 |
|
| 3875 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Expr &expr) { |
| 3876 |
bool wasIterativelyAnalyzing{iterativelyAnalyzingSubexpressions_}; |
| 3877 |
MaybeExpr result; |
| 3878 |
if (useSavedTypedExprs_) { |
| 3879 |
if (expr.typedExpr) { |
| 3880 |
return expr.typedExpr->v; |
| 3881 |
} |
| 3882 |
if (!wasIterativelyAnalyzing) { |
| 3883 |
iterativelyAnalyzingSubexpressions_ = true; |
| 3884 |
result = IterativelyAnalyzeSubexpressions(expr); |
| 3885 |
} |
| 3886 |
} |
| 3887 |
if (!result) { |
| 3888 |
result = ExprOrVariable(expr, expr.source); |
| 3889 |
} |
| 3890 |
iterativelyAnalyzingSubexpressions_ = wasIterativelyAnalyzing; |
| 3891 |
return result; |
| 3892 |
} |
| 3893 |
|
| 3894 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Variable &variable) { |
| 3895 |
if (useSavedTypedExprs_ && variable.typedExpr) { |
| 3896 |
return variable.typedExpr->v; |
| 3897 |
} |
| 3898 |
return ExprOrVariable(variable, variable.GetSource()); |
| 3899 |
} |
| 3900 |
|
| 3901 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::Selector &selector) { |
| 3902 |
if (const auto *var{std::get_if<parser::Variable>(&selector.u)}) { |
| 3903 |
if (!useSavedTypedExprs_ || !var->typedExpr) { |
| 3904 |
parser::CharBlock source{var->GetSource()}; |
| 3905 |
auto restorer{GetContextualMessages().SetLocation(source)}; |
| 3906 |
FixMisparsedFunctionReference(context_, var->u); |
| 3907 |
if (const auto *funcRef{ |
| 3908 |
std::get_if<common::Indirection<parser::FunctionReference>>( |
| 3909 |
&var->u)}) { |
| 3910 |
// A Selector that parsed as a Variable might turn out during analysis |
| 3911 |
// to actually be a structure constructor. In that case, repair the |
| 3912 |
// Variable parse tree node into an Expr |
| 3913 |
std::optional<parser::StructureConstructor> ctor; |
| 3914 |
if (MaybeExpr result{Analyze(funcRef->value(), &ctor)}) { |
| 3915 |
if (ctor) { |
| 3916 |
auto &writable{const_cast<parser::Selector &>(selector)}; |
| 3917 |
writable.u = parser::Expr{std::move(*ctor)}; |
| 3918 |
auto &expr{std::get<parser::Expr>(writable.u)}; |
| 3919 |
expr.source = source; |
| 3920 |
SetExpr(expr, Fold(std::move(*result))); |
| 3921 |
return expr.typedExpr->v; |
| 3922 |
} else { |
| 3923 |
SetExpr(*var, Fold(std::move(*result))); |
| 3924 |
return var->typedExpr->v; |
| 3925 |
} |
| 3926 |
} else { |
| 3927 |
ResetExpr(*var); |
| 3928 |
if (context_.AnyFatalError()) { |
| 3929 |
return std::nullopt; |
| 3930 |
} |
| 3931 |
} |
| 3932 |
} |
| 3933 |
} |
| 3934 |
// Not a Variable -> FunctionReference |
| 3935 |
auto restorer{AllowWholeAssumedSizeArray()}; |
| 3936 |
return Analyze(selector.u); |
| 3937 |
} else { // Expr |
| 3938 |
return Analyze(selector.u); |
| 3939 |
} |
| 3940 |
} |
| 3941 |
|
| 3942 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::DataStmtConstant &x) { |
| 3943 |
auto restorer{common::ScopedSet(inDataStmtConstant_, true)}; |
| 3944 |
return ExprOrVariable(x, x.source); |
| 3945 |
} |
| 3946 |
|
| 3947 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::AllocateObject &x) { |
| 3948 |
return ExprOrVariable(x, parser::FindSourceLocation(x)); |
| 3949 |
} |
| 3950 |
|
| 3951 |
MaybeExpr ExpressionAnalyzer::Analyze(const parser::PointerObject &x) { |
| 3952 |
return ExprOrVariable(x, parser::FindSourceLocation(x)); |
| 3953 |
} |
| 3954 |
|
| 3955 |
Expr<SubscriptInteger> ExpressionAnalyzer::AnalyzeKindSelector( |
| 3956 |
TypeCategory category, |
| 3957 |
const std::optional<parser::KindSelector> &selector) { |
| 3958 |
int defaultKind{GetDefaultKind(category)}; |
| 3959 |
if (!selector) { |
| 3960 |
return Expr<SubscriptInteger>{defaultKind}; |
| 3961 |
} |
| 3962 |
return common::visit( |
| 3963 |
common::visitors{ |
| 3964 |
[&](const parser::ScalarIntConstantExpr &x) { |
| 3965 |
if (MaybeExpr kind{Analyze(x)}) { |
| 3966 |
if (std::optional<std::int64_t> code{ToInt64(*kind)}) { |
| 3967 |
if (CheckIntrinsicKind(category, *code)) { |
| 3968 |
return Expr<SubscriptInteger>{*code}; |
| 3969 |
} |
| 3970 |
} else if (auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(*kind)}) { |
| 3971 |
return ConvertToType<SubscriptInteger>(std::move(*intExpr)); |
| 3972 |
} |
| 3973 |
} |
| 3974 |
return Expr<SubscriptInteger>{defaultKind}; |
| 3975 |
}, |
| 3976 |
[&](const parser::KindSelector::StarSize &x) { |
| 3977 |
std::intmax_t size = x.v; |
| 3978 |
if (!CheckIntrinsicSize(category, size)) { |
| 3979 |
size = defaultKind; |
| 3980 |
} else if (category == TypeCategory::Complex) { |
| 3981 |
size /= 2; |
| 3982 |
} |
| 3983 |
return Expr<SubscriptInteger>{size}; |
| 3984 |
}, |
| 3985 |
}, |
| 3986 |
selector->u); |
| 3987 |
} |
| 3988 |
|
| 3989 |
int ExpressionAnalyzer::GetDefaultKind(common::TypeCategory category) { |
| 3990 |
return context_.GetDefaultKind(category); |
| 3991 |
} |
| 3992 |
|
| 3993 |
DynamicType ExpressionAnalyzer::GetDefaultKindOfType( |
| 3994 |
common::TypeCategory category) { |
| 3995 |
return {category, GetDefaultKind(category)}; |
| 3996 |
} |
| 3997 |
|
| 3998 |
bool ExpressionAnalyzer::CheckIntrinsicKind( |
| 3999 |
TypeCategory category, std::int64_t kind) { |
| 4000 |
if (foldingContext_.targetCharacteristics().IsTypeEnabled( |
| 4001 |
category, kind)) { // C712, C714, C715, C727 |
| 4002 |
return true; |
| 4003 |
} else if (foldingContext_.targetCharacteristics().CanSupportType( |
| 4004 |
category, kind)) { |
| 4005 |
if (context_.ShouldWarn(common::UsageWarning::BadTypeForTarget)) { |
| 4006 |
Say("%s(KIND=%jd) is not an enabled type for this target"_warn_en_US, |
| 4007 |
ToUpperCase(EnumToString(category)), kind); |
| 4008 |
} |
| 4009 |
return true; |
| 4010 |
} else { |
| 4011 |
Say("%s(KIND=%jd) is not a supported type"_err_en_US, |
| 4012 |
ToUpperCase(EnumToString(category)), kind); |
| 4013 |
return false; |
| 4014 |
} |
| 4015 |
} |
| 4016 |
|
| 4017 |
bool ExpressionAnalyzer::CheckIntrinsicSize( |
| 4018 |
TypeCategory category, std::int64_t size) { |
| 4019 |
std::int64_t kind{size}; |
| 4020 |
if (category == TypeCategory::Complex) { |
| 4021 |
// COMPLEX*16 == COMPLEX(KIND=8) |
| 4022 |
if (size % 2 == 0) { |
| 4023 |
kind = size / 2; |
| 4024 |
} else { |
| 4025 |
Say("COMPLEX*%jd is not a supported type"_err_en_US, size); |
| 4026 |
return false; |
| 4027 |
} |
| 4028 |
} |
| 4029 |
if (foldingContext_.targetCharacteristics().IsTypeEnabled( |
| 4030 |
category, kind)) { // C712, C714, C715, C727 |
| 4031 |
return true; |
| 4032 |
} else if (foldingContext_.targetCharacteristics().CanSupportType( |
| 4033 |
category, kind)) { |
| 4034 |
if (context_.ShouldWarn(common::UsageWarning::BadTypeForTarget)) { |
| 4035 |
Say("%s*%jd is not an enabled type for this target"_warn_en_US, |
| 4036 |
ToUpperCase(EnumToString(category)), size); |
| 4037 |
} |
| 4038 |
return true; |
| 4039 |
} else { |
| 4040 |
Say("%s*%jd is not a supported type"_err_en_US, |
| 4041 |
ToUpperCase(EnumToString(category)), size); |
| 4042 |
return false; |
| 4043 |
} |
| 4044 |
} |
| 4045 |
|
| 4046 |
bool ExpressionAnalyzer::AddImpliedDo(parser::CharBlock name, int kind) { |
| 4047 |
return impliedDos_.insert(std::make_pair(name, kind)).second; |
| 4048 |
} |
| 4049 |
|
| 4050 |
void ExpressionAnalyzer::RemoveImpliedDo(parser::CharBlock name) { |
| 4051 |
auto iter{impliedDos_.find(name)}; |
| 4052 |
if (iter != impliedDos_.end()) { |
| 4053 |
impliedDos_.erase(iter); |
| 4054 |
} |
| 4055 |
} |
| 4056 |
|
| 4057 |
std::optional<int> ExpressionAnalyzer::IsImpliedDo( |
| 4058 |
parser::CharBlock name) const { |
| 4059 |
auto iter{impliedDos_.find(name)}; |
| 4060 |
if (iter != impliedDos_.cend()) { |
| 4061 |
return {iter->second}; |
| 4062 |
} else { |
| 4063 |
return std::nullopt; |
| 4064 |
} |
| 4065 |
} |
| 4066 |
|
| 4067 |
bool ExpressionAnalyzer::EnforceTypeConstraint(parser::CharBlock at, |
| 4068 |
const MaybeExpr &result, TypeCategory category, bool defaultKind) { |
| 4069 |
if (result) { |
| 4070 |
if (auto type{result->GetType()}) { |
| 4071 |
if (type->category() != category) { // C885 |
| 4072 |
Say(at, "Must have %s type, but is %s"_err_en_US, |
| 4073 |
ToUpperCase(EnumToString(category)), |
| 4074 |
ToUpperCase(type->AsFortran())); |
| 4075 |
return false; |
| 4076 |
} else if (defaultKind) { |
| 4077 |
int kind{context_.GetDefaultKind(category)}; |
| 4078 |
if (type->kind() != kind) { |
| 4079 |
Say(at, "Must have default kind(%d) of %s type, but is %s"_err_en_US, |
| 4080 |
kind, ToUpperCase(EnumToString(category)), |
| 4081 |
ToUpperCase(type->AsFortran())); |
| 4082 |
return false; |
| 4083 |
} |
| 4084 |
} |
| 4085 |
} else { |
| 4086 |
Say(at, "Must have %s type, but is typeless"_err_en_US, |
| 4087 |
ToUpperCase(EnumToString(category))); |
| 4088 |
return false; |
| 4089 |
} |
| 4090 |
} |
| 4091 |
return true; |
| 4092 |
} |
| 4093 |
|
| 4094 |
MaybeExpr ExpressionAnalyzer::MakeFunctionRef(parser::CharBlock callSite, |
| 4095 |
ProcedureDesignator &&proc, ActualArguments &&arguments) { |
| 4096 |
if (const auto *intrinsic{std::get_if<SpecificIntrinsic>(&proc.u)}) { |
| 4097 |
if (intrinsic->characteristics.value().attrs.test( |
| 4098 |
characteristics::Procedure::Attr::NullPointer) && |
| 4099 |
arguments.empty()) { |
| 4100 |
return Expr<SomeType>{NullPointer{}}; |
| 4101 |
} |
| 4102 |
} |
| 4103 |
if (const Symbol *symbol{proc.GetSymbol()}) { |
| 4104 |
if (!ResolveForward(*symbol)) { |
| 4105 |
return std::nullopt; |
| 4106 |
} |
| 4107 |
} |
| 4108 |
if (auto chars{CheckCall(callSite, proc, arguments)}) { |
| 4109 |
if (chars->functionResult) { |
| 4110 |
const auto &result{*chars->functionResult}; |
| 4111 |
ProcedureRef procRef{std::move(proc), std::move(arguments)}; |
| 4112 |
if (result.IsProcedurePointer()) { |
| 4113 |
return Expr<SomeType>{std::move(procRef)}; |
| 4114 |
} else { |
| 4115 |
// Not a procedure pointer, so type and shape are known. |
| 4116 |
return TypedWrapper<FunctionRef, ProcedureRef>( |
| 4117 |
DEREF(result.GetTypeAndShape()).type(), std::move(procRef)); |
| 4118 |
} |
| 4119 |
} else { |
| 4120 |
Say("Function result characteristics are not known"_err_en_US); |
| 4121 |
} |
| 4122 |
} |
| 4123 |
return std::nullopt; |
| 4124 |
} |
| 4125 |
|
| 4126 |
MaybeExpr ExpressionAnalyzer::MakeFunctionRef( |
| 4127 |
parser::CharBlock intrinsic, ActualArguments &&arguments) { |
| 4128 |
if (std::optional<SpecificCall> specificCall{ |
| 4129 |
context_.intrinsics().Probe(CallCharacteristics{intrinsic.ToString()}, |
| 4130 |
arguments, GetFoldingContext())}) { |
| 4131 |
return MakeFunctionRef(intrinsic, |
| 4132 |
ProcedureDesignator{std::move(specificCall->specificIntrinsic)}, |
| 4133 |
std::move(specificCall->arguments)); |
| 4134 |
} else { |
| 4135 |
return std::nullopt; |
| 4136 |
} |
| 4137 |
} |
| 4138 |
|
| 4139 |
MaybeExpr ExpressionAnalyzer::AnalyzeComplex( |
| 4140 |
MaybeExpr &&re, MaybeExpr &&im, const char *what) { |
| 4141 |
if (context().ShouldWarn(common::LanguageFeature::ComplexConstructor)) { |
| 4142 |
if (re && re->Rank() > 0) { |
| 4143 |
Say("Real part of %s is not scalar"_port_en_US, what); |
| 4144 |
} |
| 4145 |
if (im && im->Rank() > 0) { |
| 4146 |
Say("Imaginary part of %s is not scalar"_port_en_US, what); |
| 4147 |
} |
| 4148 |
} |
| 4149 |
if (re && im) { |
| 4150 |
ConformabilityCheck(GetContextualMessages(), *re, *im); |
| 4151 |
} |
| 4152 |
return AsMaybeExpr(ConstructComplex(GetContextualMessages(), std::move(re), |
| 4153 |
std::move(im), GetDefaultKind(TypeCategory::Real))); |
| 4154 |
} |
| 4155 |
|
| 4156 |
std::optional<ActualArgument> ArgumentAnalyzer::AnalyzeVariable( |
| 4157 |
const parser::Variable &x) { |
| 4158 |
source_.ExtendToCover(x.GetSource()); |
| 4159 |
if (MaybeExpr expr{context_.Analyze(x)}) { |
| 4160 |
if (!IsConstantExpr(*expr)) { |
| 4161 |
ActualArgument actual{std::move(*expr)}; |
| 4162 |
SetArgSourceLocation(actual, x.GetSource()); |
| 4163 |
return actual; |
| 4164 |
} |
| 4165 |
const Symbol *symbol{GetLastSymbol(*expr)}; |
| 4166 |
if (!symbol) { |
| 4167 |
context_.SayAt(x, "Assignment to constant '%s' is not allowed"_err_en_US, |
| 4168 |
x.GetSource()); |
| 4169 |
} else if (IsProcedure(*symbol)) { |
| 4170 |
if (auto *msg{context_.SayAt(x, |
| 4171 |
"Assignment to procedure '%s' is not allowed"_err_en_US, |
| 4172 |
symbol->name())}) { |
| 4173 |
if (auto *subp{symbol->detailsIf<semantics::SubprogramDetails>()}) { |
| 4174 |
if (subp->isFunction()) { |
| 4175 |
const auto &result{subp->result().name()}; |
| 4176 |
msg->Attach(result, "Function result is '%s'"_en_US, result); |
| 4177 |
} |
| 4178 |
} |
| 4179 |
} |
| 4180 |
} else { |
| 4181 |
context_.SayAt( |
| 4182 |
x, "Assignment to '%s' is not allowed"_err_en_US, symbol->name()); |
| 4183 |
} |
| 4184 |
} |
| 4185 |
fatalErrors_ = true; |
| 4186 |
return std::nullopt; |
| 4187 |
} |
| 4188 |
|
| 4189 |
void ArgumentAnalyzer::Analyze(const parser::Variable &x) { |
| 4190 |
if (auto actual = AnalyzeVariable(x)) { |
| 4191 |
actuals_.emplace_back(std::move(actual)); |
| 4192 |
} |
| 4193 |
} |
| 4194 |
|
| 4195 |
void ArgumentAnalyzer::Analyze( |
| 4196 |
const parser::ActualArgSpec &arg, bool isSubroutine) { |
| 4197 |
// TODO: C1534: Don't allow a "restricted" specific intrinsic to be passed. |
| 4198 |
std::optional<ActualArgument> actual; |
| 4199 |
auto restorer{context_.AllowWholeAssumedSizeArray()}; |
| 4200 |
common::visit( |
| 4201 |
common::visitors{ |
| 4202 |
[&](const common::Indirection<parser::Expr> &x) { |
| 4203 |
actual = AnalyzeExpr(x.value()); |
| 4204 |
}, |
| 4205 |
[&](const parser::AltReturnSpec &label) { |
| 4206 |
if (!isSubroutine) { |
| 4207 |
context_.Say( |
| 4208 |
"alternate return specification may not appear on function reference"_err_en_US); |
| 4209 |
} |
| 4210 |
actual = ActualArgument(label.v); |
| 4211 |
}, |
| 4212 |
[&](const parser::ActualArg::PercentRef &percentRef) { |
| 4213 |
actual = AnalyzeExpr(percentRef.v); |
| 4214 |
if (actual.has_value()) { |
| 4215 |
actual->set_isPercentRef(); |
| 4216 |
} |
| 4217 |
}, |
| 4218 |
[&](const parser::ActualArg::PercentVal &percentVal) { |
| 4219 |
actual = AnalyzeExpr(percentVal.v); |
| 4220 |
if (actual.has_value()) { |
| 4221 |
actual->set_isPercentVal(); |
| 4222 |
} |
| 4223 |
}, |
| 4224 |
}, |
| 4225 |
std::get<parser::ActualArg>(arg.t).u); |
| 4226 |
if (actual) { |
| 4227 |
if (const auto &argKW{std::get<std::optional<parser::Keyword>>(arg.t)}) { |
| 4228 |
actual->set_keyword(argKW->v.source); |
| 4229 |
} |
| 4230 |
actuals_.emplace_back(std::move(*actual)); |
| 4231 |
} else { |
| 4232 |
fatalErrors_ = true; |
| 4233 |
} |
| 4234 |
} |
| 4235 |
|
| 4236 |
bool ArgumentAnalyzer::IsIntrinsicRelational(RelationalOperator opr, |
| 4237 |
const DynamicType &leftType, const DynamicType &rightType) const { |
| 4238 |
CHECK(actuals_.size() == 2); |
| 4239 |
return semantics::IsIntrinsicRelational( |
| 4240 |
opr, leftType, GetRank(0), rightType, GetRank(1)); |
| 4241 |
} |
| 4242 |
|
| 4243 |
bool ArgumentAnalyzer::IsIntrinsicNumeric(NumericOperator opr) const { |
| 4244 |
std::optional<DynamicType> leftType{GetType(0)}; |
| 4245 |
if (actuals_.size() == 1) { |
| 4246 |
if (IsBOZLiteral(0)) { |
| 4247 |
return opr == NumericOperator::Add; // unary '+' |
| 4248 |
} else { |
| 4249 |
return leftType && semantics::IsIntrinsicNumeric(*leftType); |
| 4250 |
} |
| 4251 |
} else { |
| 4252 |
std::optional<DynamicType> rightType{GetType(1)}; |
| 4253 |
if (IsBOZLiteral(0) && rightType) { // BOZ opr Integer/Real |
| 4254 |
auto cat1{rightType->category()}; |
| 4255 |
return cat1 == TypeCategory::Integer || cat1 == TypeCategory::Real; |
| 4256 |
} else if (IsBOZLiteral(1) && leftType) { // Integer/Real opr BOZ |
| 4257 |
auto cat0{leftType->category()}; |
| 4258 |
return cat0 == TypeCategory::Integer || cat0 == TypeCategory::Real; |
| 4259 |
} else { |
| 4260 |
return leftType && rightType && |
| 4261 |
semantics::IsIntrinsicNumeric( |
| 4262 |
*leftType, GetRank(0), *rightType, GetRank(1)); |
| 4263 |
} |
| 4264 |
} |
| 4265 |
} |
| 4266 |
|
| 4267 |
bool ArgumentAnalyzer::IsIntrinsicLogical() const { |
| 4268 |
if (std::optional<DynamicType> leftType{GetType(0)}) { |
| 4269 |
if (actuals_.size() == 1) { |
| 4270 |
return semantics::IsIntrinsicLogical(*leftType); |
| 4271 |
} else if (std::optional<DynamicType> rightType{GetType(1)}) { |
| 4272 |
return semantics::IsIntrinsicLogical( |
| 4273 |
*leftType, GetRank(0), *rightType, GetRank(1)); |
| 4274 |
} |
| 4275 |
} |
| 4276 |
return false; |
| 4277 |
} |
| 4278 |
|
| 4279 |
bool ArgumentAnalyzer::IsIntrinsicConcat() const { |
| 4280 |
if (std::optional<DynamicType> leftType{GetType(0)}) { |
| 4281 |
if (std::optional<DynamicType> rightType{GetType(1)}) { |
| 4282 |
return semantics::IsIntrinsicConcat( |
| 4283 |
*leftType, GetRank(0), *rightType, GetRank(1)); |
| 4284 |
} |
| 4285 |
} |
| 4286 |
return false; |
| 4287 |
} |
| 4288 |
|
| 4289 |
bool ArgumentAnalyzer::CheckConformance() { |
| 4290 |
if (actuals_.size() == 2) { |
| 4291 |
const auto *lhs{actuals_.at(0).value().UnwrapExpr()}; |
| 4292 |
const auto *rhs{actuals_.at(1).value().UnwrapExpr()}; |
| 4293 |
if (lhs && rhs) { |
| 4294 |
auto &foldingContext{context_.GetFoldingContext()}; |
| 4295 |
auto lhShape{GetShape(foldingContext, *lhs)}; |
| 4296 |
auto rhShape{GetShape(foldingContext, *rhs)}; |
| 4297 |
if (lhShape && rhShape) { |
| 4298 |
if (!evaluate::CheckConformance(foldingContext.messages(), *lhShape, |
| 4299 |
*rhShape, CheckConformanceFlags::EitherScalarExpandable, |
| 4300 |
"left operand", "right operand") |
| 4301 |
.value_or(false /*fail when conformance is not known now*/)) { |
| 4302 |
fatalErrors_ = true; |
| 4303 |
return false; |
| 4304 |
} |
| 4305 |
} |
| 4306 |
} |
| 4307 |
} |
| 4308 |
return true; // no proven problem |
| 4309 |
} |
| 4310 |
|
| 4311 |
bool ArgumentAnalyzer::CheckAssignmentConformance() { |
| 4312 |
if (actuals_.size() == 2) { |
| 4313 |
const auto *lhs{actuals_.at(0).value().UnwrapExpr()}; |
| 4314 |
const auto *rhs{actuals_.at(1).value().UnwrapExpr()}; |
| 4315 |
if (lhs && rhs) { |
| 4316 |
auto &foldingContext{context_.GetFoldingContext()}; |
| 4317 |
auto lhShape{GetShape(foldingContext, *lhs)}; |
| 4318 |
auto rhShape{GetShape(foldingContext, *rhs)}; |
| 4319 |
if (lhShape && rhShape) { |
| 4320 |
if (!evaluate::CheckConformance(foldingContext.messages(), *lhShape, |
| 4321 |
*rhShape, CheckConformanceFlags::RightScalarExpandable, |
| 4322 |
"left-hand side", "right-hand side") |
| 4323 |
.value_or(true /*ok when conformance is not known now*/)) { |
| 4324 |
fatalErrors_ = true; |
| 4325 |
return false; |
| 4326 |
} |
| 4327 |
} |
| 4328 |
} |
| 4329 |
} |
| 4330 |
return true; // no proven problem |
| 4331 |
} |
| 4332 |
|
| 4333 |
bool ArgumentAnalyzer::CheckForNullPointer(const char *where) { |
| 4334 |
for (const std::optional<ActualArgument> &arg : actuals_) { |
| 4335 |
if (arg) { |
| 4336 |
if (const Expr<SomeType> *expr{arg->UnwrapExpr()}) { |
| 4337 |
if (IsNullPointer(*expr)) { |
| 4338 |
context_.Say( |
| 4339 |
source_, "A NULL() pointer is not allowed %s"_err_en_US, where); |
| 4340 |
fatalErrors_ = true; |
| 4341 |
return false; |
| 4342 |
} |
| 4343 |
} |
| 4344 |
} |
| 4345 |
} |
| 4346 |
return true; |
| 4347 |
} |
| 4348 |
|
| 4349 |
bool ArgumentAnalyzer::CheckForAssumedRank(const char *where) { |
| 4350 |
for (const std::optional<ActualArgument> &arg : actuals_) { |
| 4351 |
if (arg && IsAssumedRank(arg->UnwrapExpr())) { |
| 4352 |
context_.Say(source_, |
| 4353 |
"An assumed-rank dummy argument is not allowed %s"_err_en_US, where); |
| 4354 |
fatalErrors_ = true; |
| 4355 |
return false; |
| 4356 |
} |
| 4357 |
} |
| 4358 |
return true; |
| 4359 |
} |
| 4360 |
|
| 4361 |
MaybeExpr ArgumentAnalyzer::TryDefinedOp( |
| 4362 |
const char *opr, parser::MessageFixedText error, bool isUserOp) { |
| 4363 |
if (AnyUntypedOrMissingOperand()) { |
| 4364 |
context_.Say(error, ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1)); |
| 4365 |
return std::nullopt; |
| 4366 |
} |
| 4367 |
MaybeExpr result; |
| 4368 |
bool anyPossibilities{false}; |
| 4369 |
std::optional<parser::MessageFormattedText> inaccessible; |
| 4370 |
std::vector<const Symbol *> hit; |
| 4371 |
std::string oprNameString{ |
| 4372 |
isUserOp ? std::string{opr} : "operator("s + opr + ')'}; |
| 4373 |
parser::CharBlock oprName{oprNameString}; |
| 4374 |
parser::Messages hitBuffer; |
| 4375 |
{ |
| 4376 |
parser::Messages buffer; |
| 4377 |
auto restorer{context_.GetContextualMessages().SetMessages(buffer)}; |
| 4378 |
const auto &scope{context_.context().FindScope(source_)}; |
| 4379 |
if (Symbol *symbol{scope.FindSymbol(oprName)}) { |
| 4380 |
anyPossibilities = true; |
| 4381 |
parser::Name name{symbol->name(), symbol}; |
| 4382 |
if (!fatalErrors_) { |
| 4383 |
result = context_.AnalyzeDefinedOp(name, GetActuals()); |
| 4384 |
} |
| 4385 |
if (result) { |
| 4386 |
inaccessible = CheckAccessibleSymbol(scope, *symbol); |
| 4387 |
if (inaccessible) { |
| 4388 |
result.reset(); |
| 4389 |
} else { |
| 4390 |
hit.push_back(symbol); |
| 4391 |
hitBuffer = std::move(buffer); |
| 4392 |
} |
| 4393 |
} |
| 4394 |
} |
| 4395 |
for (std::size_t passIndex{0}; passIndex < actuals_.size(); ++passIndex) { |
| 4396 |
buffer.clear(); |
| 4397 |
const Symbol *generic{nullptr}; |
| 4398 |
if (const Symbol *binding{ |
| 4399 |
FindBoundOp(oprName, passIndex, generic, false)}) { |
| 4400 |
anyPossibilities = true; |
| 4401 |
if (MaybeExpr thisResult{TryBoundOp(*binding, passIndex)}) { |
| 4402 |
if (auto thisInaccessible{ |
| 4403 |
CheckAccessibleSymbol(scope, DEREF(generic))}) { |
| 4404 |
inaccessible = thisInaccessible; |
| 4405 |
} else { |
| 4406 |
result = std::move(thisResult); |
| 4407 |
hit.push_back(binding); |
| 4408 |
hitBuffer = std::move(buffer); |
| 4409 |
} |
| 4410 |
} |
| 4411 |
} |
| 4412 |
} |
| 4413 |
} |
| 4414 |
if (result) { |
| 4415 |
if (hit.size() > 1) { |
| 4416 |
if (auto *msg{context_.Say( |
| 4417 |
"%zd matching accessible generic interfaces for %s were found"_err_en_US, |
| 4418 |
hit.size(), ToUpperCase(opr))}) { |
| 4419 |
for (const Symbol *symbol : hit) { |
| 4420 |
AttachDeclaration(*msg, *symbol); |
| 4421 |
} |
| 4422 |
} |
| 4423 |
} |
| 4424 |
if (auto *msgs{context_.GetContextualMessages().messages()}) { |
| 4425 |
msgs->Annex(std::move(hitBuffer)); |
| 4426 |
} |
| 4427 |
} else if (inaccessible) { |
| 4428 |
context_.Say(source_, std::move(*inaccessible)); |
| 4429 |
} else if (anyPossibilities) { |
| 4430 |
SayNoMatch(ToUpperCase(oprNameString), false); |
| 4431 |
} else if (actuals_.size() == 2 && !AreConformable()) { |
| 4432 |
context_.Say( |
| 4433 |
"Operands of %s are not conformable; have rank %d and rank %d"_err_en_US, |
| 4434 |
ToUpperCase(opr), actuals_[0]->Rank(), actuals_[1]->Rank()); |
| 4435 |
} else if (CheckForNullPointer() && CheckForAssumedRank()) { |
| 4436 |
context_.Say(error, ToUpperCase(opr), TypeAsFortran(0), TypeAsFortran(1)); |
| 4437 |
} |
| 4438 |
return result; |
| 4439 |
} |
| 4440 |
|
| 4441 |
MaybeExpr ArgumentAnalyzer::TryDefinedOp( |
| 4442 |
const std::vector<const char *> &oprs, parser::MessageFixedText error) { |
| 4443 |
if (oprs.size() == 1) { |
| 4444 |
return TryDefinedOp(oprs[0], error); |
| 4445 |
} |
| 4446 |
MaybeExpr result; |
| 4447 |
std::vector<const char *> hit; |
| 4448 |
parser::Messages hitBuffer; |
| 4449 |
{ |
| 4450 |
for (std::size_t i{0}; i < oprs.size(); ++i) { |
| 4451 |
parser::Messages buffer; |
| 4452 |
auto restorer{context_.GetContextualMessages().SetMessages(buffer)}; |
| 4453 |
if (MaybeExpr thisResult{TryDefinedOp(oprs[i], error)}) { |
| 4454 |
result = std::move(thisResult); |
| 4455 |
hit.push_back(oprs[i]); |
| 4456 |
hitBuffer = std::move(buffer); |
| 4457 |
} |
| 4458 |
} |
| 4459 |
} |
| 4460 |
if (hit.empty()) { // for the error |
| 4461 |
result = TryDefinedOp(oprs[0], error); |
| 4462 |
} else if (hit.size() > 1) { |
| 4463 |
context_.Say( |
| 4464 |
"Matching accessible definitions were found with %zd variant spellings of the generic operator ('%s', '%s')"_err_en_US, |
| 4465 |
hit.size(), ToUpperCase(hit[0]), ToUpperCase(hit[1])); |
| 4466 |
} else { // one hit; preserve errors |
| 4467 |
context_.context().messages().Annex(std::move(hitBuffer)); |
| 4468 |
} |
| 4469 |
return result; |
| 4470 |
} |
| 4471 |
|
| 4472 |
MaybeExpr ArgumentAnalyzer::TryBoundOp(const Symbol &symbol, int passIndex) { |
| 4473 |
ActualArguments localActuals{actuals_}; |
| 4474 |
const Symbol *proc{GetBindingResolution(GetType(passIndex), symbol)}; |
| 4475 |
if (!proc) { |
| 4476 |
proc = &symbol; |
| 4477 |
localActuals.at(passIndex).value().set_isPassedObject(); |
| 4478 |
} |
| 4479 |
CheckConformance(); |
| 4480 |
return context_.MakeFunctionRef( |
| 4481 |
source_, ProcedureDesignator{*proc}, std::move(localActuals)); |
| 4482 |
} |
| 4483 |
|
| 4484 |
std::optional<ProcedureRef> ArgumentAnalyzer::TryDefinedAssignment() { |
| 4485 |
using semantics::Tristate; |
| 4486 |
const Expr<SomeType> &lhs{GetExpr(0)}; |
| 4487 |
const Expr<SomeType> &rhs{GetExpr(1)}; |
| 4488 |
std::optional<DynamicType> lhsType{lhs.GetType()}; |
| 4489 |
std::optional<DynamicType> rhsType{rhs.GetType()}; |
| 4490 |
int lhsRank{lhs.Rank()}; |
| 4491 |
int rhsRank{rhs.Rank()}; |
| 4492 |
Tristate isDefined{ |
| 4493 |
semantics::IsDefinedAssignment(lhsType, lhsRank, rhsType, rhsRank)}; |
| 4494 |
if (isDefined == Tristate::No) { |
| 4495 |
// Make implicit conversion explicit, unless it is an assignment to a whole |
| 4496 |
// allocatable (the explicit conversion would prevent the propagation of the |
| 4497 |
// right hand side if it is a variable). Lowering will deal with the |
| 4498 |
// conversion in this case. |
| 4499 |
if (lhsType) { |
| 4500 |
if (rhsType) { |
| 4501 |
if (!IsAllocatableDesignator(lhs) || context_.inWhereBody()) { |
| 4502 |
AddAssignmentConversion(*lhsType, *rhsType); |
| 4503 |
} |
| 4504 |
} else { |
| 4505 |
if (lhsType->category() == TypeCategory::Integer || |
| 4506 |
lhsType->category() == TypeCategory::Real) { |
| 4507 |
ConvertBOZ(nullptr, 1, lhsType); |
| 4508 |
} |
| 4509 |
if (IsBOZLiteral(1)) { |
| 4510 |
context_.Say( |
| 4511 |
"Right-hand side of this assignment may not be BOZ"_err_en_US); |
| 4512 |
fatalErrors_ = true; |
| 4513 |
} |
| 4514 |
} |
| 4515 |
} |
| 4516 |
if (!fatalErrors_) { |
| 4517 |
CheckAssignmentConformance(); |
| 4518 |
} |
| 4519 |
return std::nullopt; // user-defined assignment not allowed for these args |
| 4520 |
} |
| 4521 |
auto restorer{context_.GetContextualMessages().SetLocation(source_)}; |
| 4522 |
if (std::optional<ProcedureRef> procRef{GetDefinedAssignmentProc()}) { |
| 4523 |
if (context_.inWhereBody() && !procRef->proc().IsElemental()) { // C1032 |
| 4524 |
context_.Say( |
| 4525 |
"Defined assignment in WHERE must be elemental, but '%s' is not"_err_en_US, |
| 4526 |
DEREF(procRef->proc().GetSymbol()).name()); |
| 4527 |
} |
| 4528 |
context_.CheckCall(source_, procRef->proc(), procRef->arguments()); |
| 4529 |
return std::move(*procRef); |
| 4530 |
} |
| 4531 |
if (isDefined == Tristate::Yes) { |
| 4532 |
if (!lhsType || !rhsType || (lhsRank != rhsRank && rhsRank != 0) || |
| 4533 |
!OkLogicalIntegerAssignment(lhsType->category(), rhsType->category())) { |
| 4534 |
SayNoMatch("ASSIGNMENT(=)", true); |
| 4535 |
} |
| 4536 |
} else if (!fatalErrors_) { |
| 4537 |
CheckAssignmentConformance(); |
| 4538 |
} |
| 4539 |
return std::nullopt; |
| 4540 |
} |
| 4541 |
|
| 4542 |
bool ArgumentAnalyzer::OkLogicalIntegerAssignment( |
| 4543 |
TypeCategory lhs, TypeCategory rhs) { |
| 4544 |
if (!context_.context().languageFeatures().IsEnabled( |
| 4545 |
common::LanguageFeature::LogicalIntegerAssignment)) { |
| 4546 |
return false; |
| 4547 |
} |
| 4548 |
std::optional<parser::MessageFixedText> msg; |
| 4549 |
if (lhs == TypeCategory::Integer && rhs == TypeCategory::Logical) { |
| 4550 |
// allow assignment to LOGICAL from INTEGER as a legacy extension |
| 4551 |
msg = "assignment of LOGICAL to INTEGER"_port_en_US; |
| 4552 |
} else if (lhs == TypeCategory::Logical && rhs == TypeCategory::Integer) { |
| 4553 |
// ... and assignment to LOGICAL from INTEGER |
| 4554 |
msg = "assignment of INTEGER to LOGICAL"_port_en_US; |
| 4555 |
} else { |
| 4556 |
return false; |
| 4557 |
} |
| 4558 |
if (context_.context().ShouldWarn( |
| 4559 |
common::LanguageFeature::LogicalIntegerAssignment)) { |
| 4560 |
context_.Say(std::move(*msg)); |
| 4561 |
} |
| 4562 |
return true; |
| 4563 |
} |
| 4564 |
|
| 4565 |
std::optional<ProcedureRef> ArgumentAnalyzer::GetDefinedAssignmentProc() { |
| 4566 |
const Symbol *proc{nullptr}; |
| 4567 |
std::optional<int> passedObjectIndex; |
| 4568 |
std::string oprNameString{"assignment(=)"}; |
| 4569 |
parser::CharBlock oprName{oprNameString}; |
| 4570 |
const auto &scope{context_.context().FindScope(source_)}; |
| 4571 |
// If multiple resolutions were possible, they will have been already |
| 4572 |
// diagnosed. |
| 4573 |
{ |
| 4574 |
auto restorer{context_.GetContextualMessages().DiscardMessages()}; |
| 4575 |
if (const Symbol *symbol{scope.FindSymbol(oprName)}) { |
| 4576 |
ExpressionAnalyzer::AdjustActuals noAdjustment; |
| 4577 |
proc = |
| 4578 |
context_.ResolveGeneric(*symbol, actuals_, noAdjustment, true).first; |
| 4579 |
} |
| 4580 |
for (std::size_t i{0}; !proc && i < actuals_.size(); ++i) { |
| 4581 |
const Symbol *generic{nullptr}; |
| 4582 |
if (const Symbol *binding{FindBoundOp(oprName, i, generic, true)}) { |
| 4583 |
if (CheckAccessibleSymbol(scope, DEREF(generic))) { |
| 4584 |
// ignore inaccessible type-bound ASSIGNMENT(=) generic |
| 4585 |
} else if (const Symbol * |
| 4586 |
resolution{GetBindingResolution(GetType(i), *binding)}) { |
| 4587 |
proc = resolution; |
| 4588 |
} else { |
| 4589 |
proc = binding; |
| 4590 |
passedObjectIndex = i; |
| 4591 |
} |
| 4592 |
} |
| 4593 |
} |
| 4594 |
} |
| 4595 |
if (!proc) { |
| 4596 |
return std::nullopt; |
| 4597 |
} |
| 4598 |
ActualArguments actualsCopy{actuals_}; |
| 4599 |
// Ensure that the RHS argument is not passed as a variable unless |
| 4600 |
// the dummy argument has the VALUE attribute. |
| 4601 |
if (evaluate::IsVariable(actualsCopy.at(1).value().UnwrapExpr())) { |
| 4602 |
auto chars{evaluate::characteristics::Procedure::Characterize( |
| 4603 |
*proc, context_.GetFoldingContext())}; |
| 4604 |
const auto *rhsDummy{chars && chars->dummyArguments.size() == 2 |
| 4605 |
? std::get_if<evaluate::characteristics::DummyDataObject>( |
| 4606 |
&chars->dummyArguments.at(1).u) |
| 4607 |
: nullptr}; |
| 4608 |
if (!rhsDummy || |
| 4609 |
!rhsDummy->attrs.test( |
| 4610 |
evaluate::characteristics::DummyDataObject::Attr::Value)) { |
| 4611 |
actualsCopy.at(1).value().Parenthesize(); |
| 4612 |
} |
| 4613 |
} |
| 4614 |
if (passedObjectIndex) { |
| 4615 |
actualsCopy[*passedObjectIndex]->set_isPassedObject(); |
| 4616 |
} |
| 4617 |
return ProcedureRef{ProcedureDesignator{*proc}, std::move(actualsCopy)}; |
| 4618 |
} |
| 4619 |
|
| 4620 |
void ArgumentAnalyzer::Dump(llvm::raw_ostream &os) { |
| 4621 |
os << "source_: " << source_.ToString() << " fatalErrors_ = " << fatalErrors_ |
| 4622 |
<< '\n'; |
| 4623 |
for (const auto &actual : actuals_) { |
| 4624 |
if (!actual.has_value()) { |
| 4625 |
os << "- error\n"; |
| 4626 |
} else if (const Symbol *symbol{actual->GetAssumedTypeDummy()}) { |
| 4627 |
os << "- assumed type: " << symbol->name().ToString() << '\n'; |
| 4628 |
} else if (const Expr<SomeType> *expr{actual->UnwrapExpr()}) { |
| 4629 |
expr->AsFortran(os << "- expr: ") << '\n'; |
| 4630 |
} else { |
| 4631 |
DIE("bad ActualArgument"); |
| 4632 |
} |
| 4633 |
} |
| 4634 |
} |
| 4635 |
|
| 4636 |
std::optional<ActualArgument> ArgumentAnalyzer::AnalyzeExpr( |
| 4637 |
const parser::Expr &expr) { |
| 4638 |
source_.ExtendToCover(expr.source); |
| 4639 |
if (const Symbol *assumedTypeDummy{AssumedTypeDummy(expr)}) { |
| 4640 |
ResetExpr(expr); |
| 4641 |
if (isProcedureCall_) { |
| 4642 |
ActualArgument arg{ActualArgument::AssumedType{*assumedTypeDummy}}; |
| 4643 |
SetArgSourceLocation(arg, expr.source); |
| 4644 |
return std::move(arg); |
| 4645 |
} |
| 4646 |
context_.SayAt(expr.source, |
| 4647 |
"TYPE(*) dummy argument may only be used as an actual argument"_err_en_US); |
| 4648 |
} else if (MaybeExpr argExpr{AnalyzeExprOrWholeAssumedSizeArray(expr)}) { |
| 4649 |
if (isProcedureCall_ || !IsProcedureDesignator(*argExpr)) { |
| 4650 |
ActualArgument arg{std::move(*argExpr)}; |
| 4651 |
SetArgSourceLocation(arg, expr.source); |
| 4652 |
return std::move(arg); |
| 4653 |
} |
| 4654 |
context_.SayAt(expr.source, |
| 4655 |
IsFunctionDesignator(*argExpr) |
| 4656 |
? "Function call must have argument list"_err_en_US |
| 4657 |
: "Subroutine name is not allowed here"_err_en_US); |
| 4658 |
} |
| 4659 |
return std::nullopt; |
| 4660 |
} |
| 4661 |
|
| 4662 |
MaybeExpr ArgumentAnalyzer::AnalyzeExprOrWholeAssumedSizeArray( |
| 4663 |
const parser::Expr &expr) { |
| 4664 |
// If an expression's parse tree is a whole assumed-size array: |
| 4665 |
// Expr -> Designator -> DataRef -> Name |
| 4666 |
// treat it as a special case for argument passing and bypass |
| 4667 |
// the C1002/C1014 constraint checking in expression semantics. |
| 4668 |
if (const auto *name{parser::Unwrap<parser::Name>(expr)}) { |
| 4669 |
if (name->symbol && semantics::IsAssumedSizeArray(*name->symbol)) { |
| 4670 |
auto restorer{context_.AllowWholeAssumedSizeArray()}; |
| 4671 |
return context_.Analyze(expr); |
| 4672 |
} |
| 4673 |
} |
| 4674 |
auto restorer{context_.AllowNullPointer()}; |
| 4675 |
return context_.Analyze(expr); |
| 4676 |
} |
| 4677 |
|
| 4678 |
bool ArgumentAnalyzer::AreConformable() const { |
| 4679 |
CHECK(actuals_.size() == 2); |
| 4680 |
return actuals_[0] && actuals_[1] && |
| 4681 |
evaluate::AreConformable(*actuals_[0], *actuals_[1]); |
| 4682 |
} |
| 4683 |
|
| 4684 |
// Look for a type-bound operator in the type of arg number passIndex. |
| 4685 |
const Symbol *ArgumentAnalyzer::FindBoundOp(parser::CharBlock oprName, |
| 4686 |
int passIndex, const Symbol *&generic, bool isSubroutine) { |
| 4687 |
const auto *type{GetDerivedTypeSpec(GetType(passIndex))}; |
| 4688 |
const semantics::Scope *scope{type ? type->scope() : nullptr}; |
| 4689 |
if (scope) { |
| 4690 |
// Use the original type definition's scope, since PDT |
| 4691 |
// instantiations don't have redundant copies of bindings or |
| 4692 |
// generics. |
| 4693 |
scope = DEREF(scope->derivedTypeSpec()).typeSymbol().scope(); |
| 4694 |
} |
| 4695 |
generic = scope ? scope->FindComponent(oprName) : nullptr; |
| 4696 |
if (generic) { |
| 4697 |
ExpressionAnalyzer::AdjustActuals adjustment{ |
| 4698 |
[&](const Symbol &proc, ActualArguments &) { |
| 4699 |
return passIndex == GetPassIndex(proc).value_or(-1); |
| 4700 |
}}; |
| 4701 |
auto pair{ |
| 4702 |
context_.ResolveGeneric(*generic, actuals_, adjustment, isSubroutine)}; |
| 4703 |
if (const Symbol *binding{pair.first}) { |
| 4704 |
CHECK(binding->has<semantics::ProcBindingDetails>()); |
| 4705 |
// Use the most recent override of the binding, if any |
| 4706 |
return scope->FindComponent(binding->name()); |
| 4707 |
} else { |
| 4708 |
context_.EmitGenericResolutionError(*generic, pair.second, isSubroutine); |
| 4709 |
} |
| 4710 |
} |
| 4711 |
return nullptr; |
| 4712 |
} |
| 4713 |
|
| 4714 |
// If there is an implicit conversion between intrinsic types, make it explicit |
| 4715 |
void ArgumentAnalyzer::AddAssignmentConversion( |
| 4716 |
const DynamicType &lhsType, const DynamicType &rhsType) { |
| 4717 |
if (lhsType.category() == rhsType.category() && |
| 4718 |
(lhsType.category() == TypeCategory::Derived || |
| 4719 |
lhsType.kind() == rhsType.kind())) { |
| 4720 |
// no conversion necessary |
| 4721 |
} else if (auto rhsExpr{evaluate::Fold(context_.GetFoldingContext(), |
| 4722 |
evaluate::ConvertToType(lhsType, MoveExpr(1)))}) { |
| 4723 |
std::optional<parser::CharBlock> source; |
| 4724 |
if (actuals_[1]) { |
| 4725 |
source = actuals_[1]->sourceLocation(); |
| 4726 |
} |
| 4727 |
actuals_[1] = ActualArgument{*rhsExpr}; |
| 4728 |
SetArgSourceLocation(actuals_[1], source); |
| 4729 |
} else { |
| 4730 |
actuals_[1] = std::nullopt; |
| 4731 |
} |
| 4732 |
} |
| 4733 |
|
| 4734 |
std::optional<DynamicType> ArgumentAnalyzer::GetType(std::size_t i) const { |
| 4735 |
return i < actuals_.size() ? actuals_[i].value().GetType() : std::nullopt; |
| 4736 |
} |
| 4737 |
int ArgumentAnalyzer::GetRank(std::size_t i) const { |
| 4738 |
return i < actuals_.size() ? actuals_[i].value().Rank() : 0; |
| 4739 |
} |
| 4740 |
|
| 4741 |
// If the argument at index i is a BOZ literal, convert its type to match the |
| 4742 |
// otherType. If it's REAL convert to REAL, otherwise convert to INTEGER. |
| 4743 |
// Note that IBM supports comparing BOZ literals to CHARACTER operands. That |
| 4744 |
// is not currently supported. |
| 4745 |
void ArgumentAnalyzer::ConvertBOZ(std::optional<DynamicType> *thisType, |
| 4746 |
std::size_t i, std::optional<DynamicType> otherType) { |
| 4747 |
if (IsBOZLiteral(i)) { |
| 4748 |
Expr<SomeType> &&argExpr{MoveExpr(i)}; |
| 4749 |
auto *boz{std::get_if<BOZLiteralConstant>(&argExpr.u)}; |
| 4750 |
if (otherType && otherType->category() == TypeCategory::Real) { |
| 4751 |
int kind{context_.context().GetDefaultKind(TypeCategory::Real)}; |
| 4752 |
MaybeExpr realExpr{ |
| 4753 |
ConvertToKind<TypeCategory::Real>(kind, std::move(*boz))}; |
| 4754 |
actuals_[i] = std::move(*realExpr); |
| 4755 |
if (thisType) { |
| 4756 |
thisType->emplace(TypeCategory::Real, kind); |
| 4757 |
} |
| 4758 |
} else { |
| 4759 |
int kind{context_.context().GetDefaultKind(TypeCategory::Integer)}; |
| 4760 |
MaybeExpr intExpr{ |
| 4761 |
ConvertToKind<TypeCategory::Integer>(kind, std::move(*boz))}; |
| 4762 |
actuals_[i] = std::move(*intExpr); |
| 4763 |
if (thisType) { |
| 4764 |
thisType->emplace(TypeCategory::Integer, kind); |
| 4765 |
} |
| 4766 |
} |
| 4767 |
} |
| 4768 |
} |
| 4769 |
|
| 4770 |
// Report error resolving opr when there is a user-defined one available |
| 4771 |
void ArgumentAnalyzer::SayNoMatch(const std::string &opr, bool isAssignment) { |
| 4772 |
std::string type0{TypeAsFortran(0)}; |
| 4773 |
auto rank0{actuals_[0]->Rank()}; |
| 4774 |
if (actuals_.size() == 1) { |
| 4775 |
if (rank0 > 0) { |
| 4776 |
context_.Say("No intrinsic or user-defined %s matches " |
| 4777 |
"rank %d array of %s"_err_en_US, |
| 4778 |
opr, rank0, type0); |
| 4779 |
} else { |
| 4780 |
context_.Say("No intrinsic or user-defined %s matches " |
| 4781 |
"operand type %s"_err_en_US, |
| 4782 |
opr, type0); |
| 4783 |
} |
| 4784 |
} else { |
| 4785 |
std::string type1{TypeAsFortran(1)}; |
| 4786 |
auto rank1{actuals_[1]->Rank()}; |
| 4787 |
if (rank0 > 0 && rank1 > 0 && rank0 != rank1) { |
| 4788 |
context_.Say("No intrinsic or user-defined %s matches " |
| 4789 |
"rank %d array of %s and rank %d array of %s"_err_en_US, |
| 4790 |
opr, rank0, type0, rank1, type1); |
| 4791 |
} else if (isAssignment && rank0 != rank1) { |
| 4792 |
if (rank0 == 0) { |
| 4793 |
context_.Say("No intrinsic or user-defined %s matches " |
| 4794 |
"scalar %s and rank %d array of %s"_err_en_US, |
| 4795 |
opr, type0, rank1, type1); |
| 4796 |
} else { |
| 4797 |
context_.Say("No intrinsic or user-defined %s matches " |
| 4798 |
"rank %d array of %s and scalar %s"_err_en_US, |
| 4799 |
opr, rank0, type0, type1); |
| 4800 |
} |
| 4801 |
} else { |
| 4802 |
context_.Say("No intrinsic or user-defined %s matches " |
| 4803 |
"operand types %s and %s"_err_en_US, |
| 4804 |
opr, type0, type1); |
| 4805 |
} |
| 4806 |
} |
| 4807 |
} |
| 4808 |
|
| 4809 |
std::string ArgumentAnalyzer::TypeAsFortran(std::size_t i) { |
| 4810 |
if (i >= actuals_.size() || !actuals_[i]) { |
| 4811 |
return "missing argument"; |
| 4812 |
} else if (std::optional<DynamicType> type{GetType(i)}) { |
| 4813 |
return type->IsAssumedType() ? "TYPE(*)"s |
| 4814 |
: type->IsUnlimitedPolymorphic() ? "CLASS(*)"s |
| 4815 |
: type->IsPolymorphic() ? type->AsFortran() |
| 4816 |
: type->category() == TypeCategory::Derived |
| 4817 |
? "TYPE("s + type->AsFortran() + ')' |
| 4818 |
: type->category() == TypeCategory::Character |
| 4819 |
? "CHARACTER(KIND="s + std::to_string(type->kind()) + ')' |
| 4820 |
: ToUpperCase(type->AsFortran()); |
| 4821 |
} else { |
| 4822 |
return "untyped"; |
| 4823 |
} |
| 4824 |
} |
| 4825 |
|
| 4826 |
bool ArgumentAnalyzer::AnyUntypedOrMissingOperand() { |
| 4827 |
for (const auto &actual : actuals_) { |
| 4828 |
if (!actual || |
| 4829 |
(!actual->GetType() && !IsBareNullPointer(actual->UnwrapExpr()))) { |
| 4830 |
return true; |
| 4831 |
} |
| 4832 |
} |
| 4833 |
return false; |
| 4834 |
} |
| 4835 |
} // namespace Fortran::evaluate |
| 4836 |
|
| 4837 |
namespace Fortran::semantics { |
| 4838 |
evaluate::Expr<evaluate::SubscriptInteger> AnalyzeKindSelector( |
| 4839 |
SemanticsContext &context, common::TypeCategory category, |
| 4840 |
const std::optional<parser::KindSelector> &selector) { |
| 4841 |
evaluate::ExpressionAnalyzer analyzer{context}; |
| 4842 |
CHECK(context.location().has_value()); |
| 4843 |
auto restorer{ |
| 4844 |
analyzer.GetContextualMessages().SetLocation(*context.location())}; |
| 4845 |
return analyzer.AnalyzeKindSelector(category, selector); |
| 4846 |
} |
| 4847 |
|
| 4848 |
ExprChecker::ExprChecker(SemanticsContext &context) : context_{context} {} |
| 4849 |
|
| 4850 |
bool ExprChecker::Pre(const parser::DataStmtObject &obj) { |
| 4851 |
exprAnalyzer_.set_inDataStmtObject(true); |
| 4852 |
return true; |
| 4853 |
} |
| 4854 |
|
| 4855 |
void ExprChecker::Post(const parser::DataStmtObject &obj) { |
| 4856 |
exprAnalyzer_.set_inDataStmtObject(false); |
| 4857 |
} |
| 4858 |
|
| 4859 |
bool ExprChecker::Pre(const parser::DataImpliedDo &ido) { |
| 4860 |
parser::Walk(std::get<parser::DataImpliedDo::Bounds>(ido.t), *this); |
| 4861 |
const auto &bounds{std::get<parser::DataImpliedDo::Bounds>(ido.t)}; |
| 4862 |
auto name{bounds.name.thing.thing}; |
| 4863 |
int kind{evaluate::ResultType<evaluate::ImpliedDoIndex>::kind}; |
| 4864 |
if (const auto dynamicType{evaluate::DynamicType::From(*name.symbol)}) { |
| 4865 |
if (dynamicType->category() == TypeCategory::Integer) { |
| 4866 |
kind = dynamicType->kind(); |
| 4867 |
} |
| 4868 |
} |
| 4869 |
exprAnalyzer_.AddImpliedDo(name.source, kind); |
| 4870 |
parser::Walk(std::get<std::list<parser::DataIDoObject>>(ido.t), *this); |
| 4871 |
exprAnalyzer_.RemoveImpliedDo(name.source); |
| 4872 |
return false; |
| 4873 |
} |
| 4874 |
|
| 4875 |
bool ExprChecker::Walk(const parser::Program &program) { |
| 4876 |
parser::Walk(program, *this); |
| 4877 |
return !context_.AnyFatalError(); |
| 4878 |
} |
| 4879 |
} // namespace Fortran::semantics |