[flang] Remove most comparisons to nullptr

Remove needless usage of has_value()

Original-commit: flang-compiler/f18@1da7fcf7a5
Reviewed-on: https://github.com/flang-compiler/f18/pull/822
This commit is contained in:
peter klausler 2019-11-09 09:29:31 -08:00
parent e2437596a4
commit 18f5ce5964
69 changed files with 487 additions and 495 deletions

View file

@ -188,6 +188,11 @@ contents, and it is assumed that the contents are present, validate that
assumption by using `x.value()` instead.
1. We use `c_str()` rather than `data()` when converting a `std::string`
to a `const char *` when the result is expected to be NUL-terminated.
1. Avoid explicit comparisions of pointers to `nullptr` and tests of
presence of `optional<>` values with `.has_value()` in the predicate
expressions of control flow statements, but prefer them to implicit
conversions to `bool` when initializing `bool` variables and arguments,
and to the use of the idiom `!!`.
#### Classes
1. Define POD structures with `struct`.

View file

@ -145,7 +145,7 @@ template<typename A> struct ListItemCount {
#define DEREF(p) Fortran::common::Deref(p, __FILE__, __LINE__)
template<typename T> constexpr T &Deref(T *p, const char *file, int line) {
if (p == nullptr) {
if (!p) {
Fortran::common::die("nullptr dereference at %s(%d)", file, line);
}
return *p;

View file

@ -105,7 +105,7 @@ constexpr bool HasMember{
// std::optional<std::optional<A>> -> std::optional<A>
template<typename A>
std::optional<A> JoinOptional(std::optional<std::optional<A>> &&x) {
if (x.has_value()) {
if (x) {
return std::move(*x);
}
return std::nullopt;
@ -113,7 +113,7 @@ std::optional<A> JoinOptional(std::optional<std::optional<A>> &&x) {
// Convert an std::optional to an ordinary pointer
template<typename A> const A *GetPtrFromOptional(const std::optional<A> &x) {
if (x.has_value()) {
if (x) {
return &*x;
} else {
return nullptr;
@ -258,7 +258,7 @@ template<typename A>
std::optional<std::vector<A>> AllElementsPresent(
std::vector<std::optional<A>> &&v) {
for (const auto &maybeA : v) {
if (!maybeA.has_value()) {
if (!maybeA) {
return std::nullopt;
}
}

View file

@ -64,7 +64,7 @@ struct UnwrapperHelper {
// Implementations of specializations
template<typename A, typename B>
static auto Unwrap(B *p) -> Constify<A, B> * {
if (p != nullptr) {
if (p) {
return Unwrap<A>(*p);
} else {
return nullptr;
@ -73,7 +73,7 @@ struct UnwrapperHelper {
template<typename A, typename B>
static auto Unwrap(const std::unique_ptr<B> &p) -> Constify<A, B> * {
if (p.get() != nullptr) {
if (p.get()) {
return Unwrap<A>(*p);
} else {
return nullptr;
@ -82,7 +82,7 @@ struct UnwrapperHelper {
template<typename A, typename B>
static auto Unwrap(const std::shared_ptr<B> &p) -> Constify<A, B> * {
if (p.get() != nullptr) {
if (p.get()) {
return Unwrap<A>(*p);
} else {
return nullptr;
@ -91,7 +91,7 @@ struct UnwrapperHelper {
template<typename A, typename B>
static auto Unwrap(std::optional<B> &x) -> Constify<A, B> * {
if (x.has_value()) {
if (x) {
return Unwrap<A>(*x);
} else {
return nullptr;
@ -100,7 +100,7 @@ struct UnwrapperHelper {
template<typename A, typename B>
static auto Unwrap(const std::optional<B> &x) -> Constify<A, B> * {
if (x.has_value()) {
if (x) {
return Unwrap<A>(*x);
} else {
return nullptr;
@ -139,7 +139,7 @@ struct UnwrapperHelper {
template<typename A, typename B>
static auto Unwrap(const CountedReference<B> &p) -> Constify<A, B> * {
if (p.get() != nullptr) {
if (p.get()) {
return Unwrap<A>(*p);
} else {
return nullptr;

View file

@ -55,7 +55,7 @@ bool BigRadixFloatingPointNumber<PREC, LOG10RADIX>::ParseNumber(
// the first character afterward.
p = q;
// Strip off trailing zeroes
if (point != nullptr) {
if (point) {
while (q[-1] == '0') {
--q;
}
@ -64,7 +64,7 @@ bool BigRadixFloatingPointNumber<PREC, LOG10RADIX>::ParseNumber(
--q;
}
}
if (point == nullptr) {
if (!point) {
while (q > first && q[-1] == '0') {
--q;
++exponent_;
@ -78,12 +78,12 @@ bool BigRadixFloatingPointNumber<PREC, LOG10RADIX>::ParseNumber(
q = point;
point = nullptr;
}
if (point == nullptr) {
if (!point) {
exponent_ += q - limit;
}
q = limit;
}
if (point != nullptr) {
if (point) {
exponent_ -= static_cast<int>(q - point - 1);
}
if (q == first) {

View file

@ -30,8 +30,7 @@ ActualArgument::~ActualArgument() {}
ActualArgument::AssumedType::AssumedType(const Symbol &symbol)
: symbol_{symbol} {
const semantics::DeclTypeSpec *type{symbol.GetType()};
CHECK(
type != nullptr && type->category() == semantics::DeclTypeSpec::TypeStar);
CHECK(type && type->category() == semantics::DeclTypeSpec::TypeStar);
}
int ActualArgument::AssumedType::Rank() const { return symbol_->Rank(); }
@ -179,7 +178,7 @@ std::optional<Expr<SubscriptInteger>> ProcedureRef::LEN() const {
UnwrapExpr<Expr<SomeCharacter>>(arguments_[0].value())};
const auto *nCopiesArg{
UnwrapExpr<Expr<SomeInteger>>(arguments_[1].value())};
CHECK(stringArg != nullptr && nCopiesArg != nullptr);
CHECK(stringArg && nCopiesArg);
if (auto stringLen{stringArg->LEN()}) {
auto converted{ConvertTo(*stringLen, common::Clone(*nCopiesArg))};
return *std::move(stringLen) * std::move(converted);

View file

@ -186,9 +186,9 @@ void TypeAndShape::AcquireShape(const semantics::ObjectEntityDetails &object) {
attrs_.set(Attr::Coarray);
}
for (const semantics::ShapeSpec &dim : object.shape()) {
if (dim.ubound().GetExplicit().has_value()) {
if (dim.ubound().GetExplicit()) {
Expr<SubscriptInteger> extent{*dim.ubound().GetExplicit()};
if (dim.lbound().GetExplicit().has_value()) {
if (dim.lbound().GetExplicit()) {
extent = std::move(extent) +
common::Clone(*dim.lbound().GetExplicit()) -
Expr<SubscriptInteger>{1};
@ -212,7 +212,7 @@ void TypeAndShape::AcquireLEN() {
std::ostream &TypeAndShape::Dump(std::ostream &o) const {
std::stringstream LENstr;
if (LEN_.has_value()) {
if (LEN_) {
LEN_->AsFortran(LENstr);
}
o << type_.AsFortran(LENstr.str());
@ -223,7 +223,7 @@ std::ostream &TypeAndShape::Dump(std::ostream &o) const {
for (const auto &expr : shape_) {
o << sep;
sep = ',';
if (expr.has_value()) {
if (expr) {
expr->AsFortran(o);
} else {
o << ':';
@ -698,7 +698,7 @@ bool Procedure::CanBeCalledViaImplicitInterface() const {
std::ostream &Procedure::Dump(std::ostream &o) const {
attrs.Dump(o, EnumToString);
if (functionResult.has_value()) {
if (functionResult) {
functionResult->Dump(o << "TYPE(") << ") FUNCTION";
} else {
o << "SUBROUTINE";

View file

@ -66,7 +66,7 @@ public:
AcquireLEN();
}
TypeAndShape(DynamicType t, std::optional<Shape> &&s) : type_{t} {
if (s.has_value()) {
if (s) {
shape_ = std::move(*s);
}
AcquireLEN();

View file

@ -192,7 +192,7 @@ public:
symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
// TODO: what about EQUIVALENCE with data in COMMON?
// TODO: does this work for blank COMMON?
if (object->commonBlock() != nullptr) {
if (object->commonBlock()) {
return std::nullopt;
}
}
@ -298,7 +298,7 @@ public:
template<typename T> Result operator()(const FunctionRef<T> &x) const {
if (auto chars{
characteristics::Procedure::Characterize(x.proc(), table_)}) {
if (chars->functionResult.has_value()) {
if (chars->functionResult) {
const auto &result{*chars->functionResult};
return !result.IsProcedurePointer() &&
result.attrs.test(characteristics::FunctionResult::Attr::Pointer) &&
@ -317,7 +317,7 @@ private:
if (!triplet->IsStrideOne()) {
return false;
} else if (anyTriplet) {
if (triplet->lower().has_value() || triplet->upper().has_value()) {
if (triplet->lower() || triplet->upper()) {
return false; // all triplets before the last one must be just ":"
}
} else {

View file

@ -210,7 +210,7 @@ template<typename T>
static inline Constant<T> *FoldConvertedArg(
FoldingContext &context, std::optional<ActualArgument> &arg) {
if (auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
if (UnwrapExpr<Expr<T>>(*expr) == nullptr) {
if (!UnwrapExpr<Expr<T>>(*expr)) {
if (auto converted{ConvertToType(T::GetType(), std::move(*expr))}) {
*expr = Fold(context, std::move(*converted));
}
@ -230,7 +230,7 @@ static inline Expr<TR> FoldElementalIntrinsicHelper(FoldingContext &context,
static_assert(sizeof...(TA) > 0);
std::tuple<const Constant<TA> *...> args{
FoldConvertedArg<TA>(context, funcRef.arguments()[I])...};
if ((... && (std::get<I>(args) != nullptr))) {
if ((... && (std::get<I>(args)))) {
// Compute the shape of the result based on shapes of arguments
ConstantSubscripts shape;
int rank{0};
@ -312,7 +312,7 @@ static std::optional<std::int64_t> GetInt64Arg(
static std::optional<std::int64_t> GetInt64ArgOr(
const std::optional<ActualArgument> &arg, std::int64_t defaultValue) {
if (!arg.has_value()) {
if (!arg) {
return defaultValue;
} else if (const auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(arg)}) {
return ToInt64(*intExpr);
@ -365,8 +365,7 @@ Expr<T> Reshape(FoldingContext &context, FunctionRef<T> &&funcRef) {
GetIntegerVector<ConstantSubscript>(args[1])};
std::optional<std::vector<int>> order{GetIntegerVector<int>(args[3])};
if (!source || !shape || (args[2].has_value() && !pad) ||
(args[3].has_value() && !order)) {
if (!source || !shape || (args[2] && !pad) || (args[3] && !order)) {
return Expr<T>{std::move(funcRef)}; // Non-constant arguments
} else if (!IsValidShape(shape.value())) {
context.messages().Say("Invalid SHAPE in RESHAPE"_en_US);
@ -374,12 +373,11 @@ Expr<T> Reshape(FoldingContext &context, FunctionRef<T> &&funcRef) {
int rank{GetRank(shape.value())};
std::size_t resultElements{TotalElementCount(shape.value())};
std::optional<std::vector<int>> dimOrder;
if (order.has_value()) {
if (order) {
dimOrder = ValidateDimensionOrder(rank, *order);
}
std::vector<int> *dimOrderPtr{
dimOrder.has_value() ? &dimOrder.value() : nullptr};
if (order.has_value() && !dimOrder.has_value()) {
std::vector<int> *dimOrderPtr{dimOrder ? &dimOrder.value() : nullptr};
if (order && !dimOrder) {
context.messages().Say("Invalid ORDER in RESHAPE"_en_US);
} else if (resultElements > source->size() && (!pad || pad->empty())) {
context.messages().Say("Too few SOURCE elements in RESHAPE and PAD"
@ -433,7 +431,7 @@ Expr<Type<TypeCategory::Integer, KIND>> LBOUND(FoldingContext &context,
const Symbol &symbol{named->GetLastSymbol()};
if (symbol.Rank() == rank) {
lowerBoundsAreOne = false;
if (dim.has_value()) {
if (dim) {
return Fold(context,
ConvertToType<T>(GetLowerBound(context, *named, *dim)));
} else if (auto extents{
@ -446,7 +444,7 @@ Expr<Type<TypeCategory::Integer, KIND>> LBOUND(FoldingContext &context,
}
}
if (lowerBoundsAreOne) {
if (dim.has_value()) {
if (dim) {
return Expr<T>{1};
} else {
std::vector<Scalar<T>> ones(rank, Scalar<T>{1});
@ -488,7 +486,7 @@ Expr<Type<TypeCategory::Integer, KIND>> UBOUND(FoldingContext &context,
const Symbol &symbol{named->GetLastSymbol()};
if (symbol.Rank() == rank) {
takeBoundsFromShape = false;
if (dim.has_value()) {
if (dim) {
if (semantics::IsAssumedSizeArray(symbol) && *dim == rank) {
return Expr<T>{-1};
} else if (auto ub{GetUpperBound(context, *named, *dim)}) {
@ -497,7 +495,7 @@ Expr<Type<TypeCategory::Integer, KIND>> UBOUND(FoldingContext &context,
} else {
Shape ubounds{GetUpperBounds(context, *named)};
if (semantics::IsAssumedSizeArray(symbol)) {
CHECK(!ubounds.back().has_value());
CHECK(!ubounds.back());
ubounds.back() = ExtentExpr{-1};
}
if (auto extents{AsExtentArrayExpr(ubounds)}) {
@ -511,7 +509,7 @@ Expr<Type<TypeCategory::Integer, KIND>> UBOUND(FoldingContext &context,
}
if (takeBoundsFromShape) {
if (auto shape{GetShape(context, *array)}) {
if (dim.has_value()) {
if (dim) {
if (auto &dimSize{shape->at(*dim)}) {
return Fold(context,
ConvertToType<T>(Expr<ExtentType>{std::move(*dimSize)}));
@ -639,7 +637,7 @@ Expr<Type<TypeCategory::Integer, KIND>> FoldIntrinsicFunction(
return Expr<T>{Scalar<T>::HUGE()};
} else if (name == "iachar" || name == "ichar") {
auto *someChar{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
CHECK(someChar != nullptr);
CHECK(someChar);
if (auto len{ToInt64(someChar->LEN())}) {
if (len.value() != 1) {
// Do not die, this was not checked before
@ -921,7 +919,7 @@ Expr<Type<TypeCategory::Real, KIND>> ToReal(
From original{x};
result = ConvertToType<Result>(std::move(x));
const auto *constant{UnwrapExpr<Constant<Result>>(*result)};
CHECK(constant != nullptr);
CHECK(constant);
Scalar<Result> real{constant->GetScalarValue().value()};
From converted{From::ConvertUnsigned(real.RawBits()).value};
if (original != converted) { // C1601
@ -1097,9 +1095,8 @@ Expr<Type<TypeCategory::Complex, KIND>> FoldIntrinsicFunction(
}
CHECK(args.size() == 2 || args.size() == 3);
Expr<SomeType> re{std::move(*args[0].value().UnwrapExpr())};
Expr<SomeType> im{args[1].has_value()
? std::move(*args[1].value().UnwrapExpr())
: AsGenericExpr(Constant<Part>{Scalar<Part>{}})};
Expr<SomeType> im{args[1] ? std::move(*args[1].value().UnwrapExpr())
: AsGenericExpr(Constant<Part>{Scalar<Part>{}})};
return Fold(context,
Expr<T>{ComplexConstructor<KIND>{ToReal<KIND>(context, std::move(re)),
ToReal<KIND>(context, std::move(im))}});
@ -1119,7 +1116,7 @@ Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
CHECK(intrinsic);
std::string name{intrinsic->name};
if (name == "all") {
if (!args[1].has_value()) { // TODO: ALL(x,DIM=d)
if (!args[1]) { // TODO: ALL(x,DIM=d)
if (const auto *constant{UnwrapConstantValue<T>(args[0])}) {
bool result{true};
for (const auto &element : constant->values()) {
@ -1132,7 +1129,7 @@ Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
}
}
} else if (name == "any") {
if (!args[1].has_value()) { // TODO: ANY(x,DIM=d)
if (!args[1]) { // TODO: ANY(x,DIM=d)
if (const auto *constant{UnwrapConstantValue<T>(args[0])}) {
bool result{false};
for (const auto &element : constant->values()) {
@ -1224,7 +1221,7 @@ std::optional<Expr<T>> GetNamedConstantValue(
symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
if (object->initWasValidated()) {
const auto *constant{UnwrapConstantValue<T>(object->init())};
CHECK(constant != nullptr);
CHECK(constant);
return Expr<T>{*constant};
}
if (const auto &init{object->init()}) {
@ -1236,10 +1233,10 @@ std::optional<Expr<T>> GetNamedConstantValue(
// Reset expression now to prevent infinite loops if the init
// expression depends on symbol itself.
mutableObject->set_init(std::nullopt);
if (converted.has_value()) {
if (converted) {
*converted = Fold(context, std::move(*converted));
auto *unwrapped{UnwrapExpr<Expr<T>>(*converted)};
CHECK(unwrapped != nullptr);
CHECK(unwrapped);
if (auto *constant{UnwrapConstantValue<T>(*unwrapped)}) {
if (symbol.Rank() > 0) {
if (constant->Rank() == 0) {
@ -1329,17 +1326,16 @@ static std::optional<Constant<SubscriptInteger>> GetConstantSubscript(
[&](Triplet &triplet) -> std::optional<Constant<SubscriptInteger>> {
auto lower{triplet.lower()}, upper{triplet.upper()};
std::optional<ConstantSubscript> stride{ToInt64(triplet.stride())};
if (!lower.has_value()) {
if (!lower) {
lower = GetLowerBound(context, base, dim);
}
if (!upper.has_value()) {
if (!upper) {
upper =
ComputeUpperBound(context, GetLowerBound(context, base, dim),
GetExtent(context, base, dim));
}
auto lbi{ToInt64(lower)}, ubi{ToInt64(upper)};
if (lbi.has_value() && ubi.has_value() && stride.has_value() &&
*stride != 0) {
if (lbi && ubi && stride && *stride != 0) {
std::vector<SubscriptInteger::Scalar> values;
while ((*stride > 0 && *lbi <= *ubi) ||
(*stride < 0 && *lbi >= *ubi)) {
@ -1430,7 +1426,7 @@ std::optional<Constant<T>> ApplyComponent(FoldingContext &context,
if (auto scalar{structures.GetScalarValue()}) {
if (auto *expr{scalar->Find(component)}) {
if (const Constant<T> *value{UnwrapConstantValue<T>(*expr)}) {
if (subscripts == nullptr) {
if (!subscripts) {
return std::move(*value);
} else {
return ApplySubscripts<T>(context.messages(), *value, *subscripts);
@ -1448,14 +1444,14 @@ std::optional<Constant<T>> ApplyComponent(FoldingContext &context,
StructureConstructor scalar{structures.At(at)};
if (auto *expr{scalar.Find(component)}) {
if (const Constant<T> *value{UnwrapConstantValue<T>(*expr)}) {
if (array.get() == nullptr) {
if (!array.get()) {
// This technique ensures that character length or derived type
// information is propagated to the array constructor.
auto *typedExpr{UnwrapExpr<Expr<T>>(*expr)};
CHECK(typedExpr != nullptr);
CHECK(typedExpr);
array = std::make_unique<ArrayConstructor<T>>(*typedExpr);
}
if (subscripts != nullptr) {
if (subscripts) {
if (auto element{ApplySubscripts<T>(
context.messages(), *value, *subscripts)}) {
CHECK(element->Rank() == 0);
@ -1647,7 +1643,7 @@ private:
Fold(context_, Expr<SubscriptInteger>{iDo.stride()})};
std::optional<ConstantSubscript> start{ToInt64(lower)}, end{ToInt64(upper)},
step{ToInt64(stride)};
if (start.has_value() && end.has_value() && step.has_value()) {
if (start && end && step) {
if (*step == 0) {
return false;
}
@ -1703,7 +1699,7 @@ template<int KIND>
Expr<Type<TypeCategory::Integer, KIND>> FoldOperation(
FoldingContext &context, TypeParamInquiry<KIND> &&inquiry) {
using IntKIND = Type<TypeCategory::Integer, KIND>;
if (!inquiry.base().has_value()) {
if (!inquiry.base()) {
// A "bare" type parameter: replace with its value, if that's now known.
if (const auto *pdt{context.pdtInstance()}) {
if (const semantics::Scope * scope{context.pdtInstance()->scope()}) {
@ -1711,7 +1707,7 @@ Expr<Type<TypeCategory::Integer, KIND>> FoldOperation(
if (iter != scope->end()) {
const Symbol &symbol{*iter->second};
const auto *details{symbol.detailsIf<semantics::TypeParamDetails>()};
if (details && details->init().has_value()) {
if (details && details->init()) {
Expr<SomeInteger> expr{*details->init()};
return Fold(context,
Expr<IntKIND>{
@ -1793,7 +1789,7 @@ template<typename T>
Expr<T> FromArrayConstructor(FoldingContext &context,
ArrayConstructor<T> &&values, std::optional<ConstantSubscripts> &&shape) {
Expr<T> result{Fold(context, Expr<T>{std::move(values)})};
if (shape.has_value()) {
if (shape) {
if (auto *constant{UnwrapConstantValue<T>(result)}) {
return Expr<T>{constant->Reshape(std::move(*shape))};
}

View file

@ -41,8 +41,8 @@ template<typename T> Expr<T> Fold(FoldingContext &context, Expr<T> &&expr) {
template<typename T>
std::optional<Expr<T>> Fold(
FoldingContext &context, std::optional<Expr<T>> &&expr) {
if (expr.has_value()) {
return {Fold(context, std::move(*expr))};
if (expr) {
return Fold(context, std::move(*expr));
} else {
return std::nullopt;
}
@ -96,7 +96,7 @@ std::optional<std::int64_t> ToInt64(const Expr<SomeType> &);
template<typename A>
std::optional<std::int64_t> ToInt64(const std::optional<A> &x) {
if (x.has_value()) {
if (x) {
return ToInt64(*x);
} else {
return std::nullopt;

View file

@ -109,7 +109,7 @@ std::ostream &ActualArgument::AssumedType::AsFortran(std::ostream &o) const {
}
std::ostream &ActualArgument::AsFortran(std::ostream &o) const {
if (keyword.has_value()) {
if (keyword) {
o << keyword->ToString() << '=';
}
if (isAlternateReturn) {
@ -130,7 +130,7 @@ std::ostream &ProcedureRef::AsFortran(std::ostream &o) const {
proc_.AsFortran(o);
char separator{'('};
for (const auto &arg : arguments_) {
if (arg.has_value()) {
if (arg) {
arg->AsFortran(o << separator);
separator = ',';
}
@ -382,10 +382,10 @@ std::ostream &StructureConstructor::AsFortran(std::ostream &o) const {
}
std::string DynamicType::AsFortran() const {
if (derived_ != nullptr) {
if (derived_) {
CHECK(category_ == TypeCategory::Derived);
return DerivedTypeSpecAsFortran(*derived_);
} else if (charLength_ != nullptr) {
} else if (charLength_) {
std::string result{"CHARACTER(KIND="s + std::to_string(kind_) + ",LEN="};
if (charLength_->isAssumed()) {
result += '*';
@ -473,8 +473,8 @@ std::ostream &EmitVar(std::ostream &o, common::Reference<A> x) {
template<typename A>
std::ostream &EmitVar(std::ostream &o, const A *p, const char *kw = nullptr) {
if (p != nullptr) {
if (kw != nullptr) {
if (p) {
if (kw) {
o << kw;
}
EmitVar(o, *p);
@ -485,8 +485,8 @@ std::ostream &EmitVar(std::ostream &o, const A *p, const char *kw = nullptr) {
template<typename A>
std::ostream &EmitVar(
std::ostream &o, const std::optional<A> &x, const char *kw = nullptr) {
if (x.has_value()) {
if (kw != nullptr) {
if (x) {
if (kw) {
o << kw;
}
EmitVar(o, *x);
@ -497,7 +497,7 @@ std::ostream &EmitVar(
template<typename A, bool COPY>
std::ostream &EmitVar(std::ostream &o, const common::Indirection<A, COPY> &p,
const char *kw = nullptr) {
if (kw != nullptr) {
if (kw) {
o << kw;
}
EmitVar(o, p.value());
@ -506,7 +506,7 @@ std::ostream &EmitVar(std::ostream &o, const common::Indirection<A, COPY> &p,
template<typename A>
std::ostream &EmitVar(std::ostream &o, const std::shared_ptr<A> &p) {
CHECK(p != nullptr);
CHECK(p);
return EmitVar(o, *p);
}
@ -522,7 +522,7 @@ std::ostream &BaseObject::AsFortran(std::ostream &o) const {
template<int KIND>
std::ostream &TypeParamInquiry<KIND>::AsFortran(std::ostream &o) const {
if (base_.has_value()) {
if (base_) {
return base_->AsFortran(o) << '%';
}
return EmitVar(o, parameter_);
@ -587,11 +587,11 @@ std::ostream &CoarrayRef::AsFortran(std::ostream &o) const {
EmitVar(o << separator, css);
separator = ',';
}
if (stat_.has_value()) {
if (stat_) {
EmitVar(o << separator, stat_, "STAT=");
separator = ',';
}
if (team_.has_value()) {
if (team_) {
EmitVar(
o << separator, team_, teamIsTeamNumber_ ? "TEAM_NUMBER=" : "TEAM=");
}

View file

@ -54,7 +54,7 @@ auto operator<<(
template<typename A>
auto operator<<(std::ostream &o, const std::optional<A> &x)
-> decltype(o << *x) {
if (x.has_value()) {
if (x) {
o << *x;
} else {
o << "(nullopt)";

View file

@ -238,7 +238,7 @@ struct IntrinsicInterface {
int IntrinsicInterface::CountArguments() const {
int n{0};
while (n < maxArguments && dummy[n].keyword != nullptr) {
while (n < maxArguments && dummy[n].keyword) {
++n;
}
return n;
@ -972,8 +972,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
// a particular intrinsic procedure's generic interface and the actual
// arguments in a procedure reference.
std::size_t dummyArgPatterns{0};
for (; dummyArgPatterns < maxArguments &&
dummy[dummyArgPatterns].keyword != nullptr;
for (; dummyArgPatterns < maxArguments && dummy[dummyArgPatterns].keyword;
++dummyArgPatterns) {
}
// MAX and MIN (and others that map to them) allow their last argument to
@ -988,7 +987,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
std::vector<ActualArgument *> actualForDummy(nonRepeatedDummies, nullptr);
int missingActualArguments{0};
for (std::optional<ActualArgument> &arg : arguments) {
if (!arg.has_value()) {
if (!arg) {
++missingActualArguments;
} else {
if (arg->isAlternateReturn) {
@ -1000,11 +999,11 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
bool found{false};
int slot{missingActualArguments};
for (std::size_t j{0}; j < nonRepeatedDummies && !found; ++j) {
if (arg->keyword.has_value()) {
if (arg->keyword) {
found = *arg->keyword == dummy[j].keyword;
if (found) {
if (const auto *previous{actualForDummy[j]}) {
if (previous->keyword.has_value()) {
if (previous->keyword) {
messages.Say(*arg->keyword,
"repeated keyword argument to intrinsic '%s'"_err_en_US,
name);
@ -1018,18 +1017,18 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
}
}
} else {
found = actualForDummy[j] == nullptr && slot-- == 0;
found = !actualForDummy[j] && slot-- == 0;
}
if (found) {
actualForDummy[j] = &*arg;
}
}
if (!found) {
if (repeatLastDummy && !arg->keyword.has_value()) {
if (repeatLastDummy && !arg->keyword) {
// MAX/MIN argument after the 2nd
actualForDummy.push_back(&*arg);
} else {
if (arg->keyword.has_value()) {
if (arg->keyword) {
messages.Say(*arg->keyword,
"unknown keyword argument to intrinsic '%s'"_err_en_US, name);
} else {
@ -1056,7 +1055,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
for (std::size_t j{0}; j < dummies; ++j) {
const IntrinsicDummyArgument &d{dummy[std::min(j, dummyArgPatterns - 1)]};
if (d.typePattern.kindCode == KindCode::kindArg) {
CHECK(kindDummyArg == nullptr);
CHECK(!kindDummyArg);
kindDummyArg = &d;
}
const ActualArgument *arg{actualForDummy[j]};
@ -1083,10 +1082,10 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
}
}
std::optional<DynamicType> type{arg->GetType()};
if (!type.has_value()) {
if (!type) {
CHECK(arg->Rank() == 0);
const Expr<SomeType> *expr{arg->UnwrapExpr()};
CHECK(expr != nullptr);
CHECK(expr);
if (std::holds_alternative<BOZLiteralConstant>(expr->u)) {
if (d.typePattern.kindCode == KindCode::typeless ||
d.rank == Rank::elementalOrBOZ) {
@ -1136,7 +1135,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
case KindCode::any: argOk = true; break;
case KindCode::kindArg:
CHECK(type->category() == TypeCategory::Integer);
CHECK(kindArg == nullptr);
CHECK(!kindArg);
kindArg = arg;
argOk = true;
break;
@ -1146,13 +1145,13 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
argOk = true;
break;
case KindCode::same:
if (sameArg == nullptr) {
if (!sameArg) {
sameArg = arg;
}
argOk = type->IsTkCompatibleWith(sameArg->GetType().value());
break;
case KindCode::operand:
if (operandArg == nullptr) {
if (!operandArg) {
operandArg = arg;
} else if (auto prev{operandArg->GetType()}) {
if (type->category() == prev->category()) {
@ -1208,7 +1207,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
case Rank::scalar: argOk = rank == 0; break;
case Rank::vector: argOk = rank == 1; break;
case Rank::shape:
CHECK(!shapeArgSize.has_value());
CHECK(!shapeArgSize);
if (rank == 1) {
if (auto shape{GetShape(context, *arg)}) {
if (auto constShape{AsConstantShape(context, *shape)}) {
@ -1234,18 +1233,18 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
}
break;
case Rank::known:
if (knownArg == nullptr) {
if (!knownArg) {
knownArg = arg;
}
argOk = rank == knownArg->Rank();
break;
case Rank::anyOrAssumedRank: argOk = true; break;
case Rank::conformable:
CHECK(arrayArg != nullptr);
CHECK(arrayArg);
argOk = rank == 0 || rank == arrayArg->Rank();
break;
case Rank::dimRemoved:
CHECK(arrayArg != nullptr);
CHECK(arrayArg);
if (hasDimArg) {
argOk = rank == 0 || rank + 1 == arrayArg->Rank();
} else {
@ -1255,7 +1254,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
case Rank::reduceOperation:
// TODO: Confirm that the argument is a pure function
// of two arguments with several constraints
CHECK(arrayArg != nullptr);
CHECK(arrayArg);
argOk = rank == 0;
break;
case Rank::dimReduced:
@ -1311,7 +1310,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
defaults.GetDefaultKind(TypeCategory::Logical)};
break;
case KindCode::same:
CHECK(sameArg != nullptr);
CHECK(sameArg);
if (std::optional<DynamicType> aType{sameArg->GetType()}) {
if (result.categorySet.test(aType->category())) {
resultType = *aType;
@ -1321,14 +1320,14 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
}
break;
case KindCode::operand:
CHECK(operandArg != nullptr);
CHECK(operandArg);
resultType = operandArg->GetType();
CHECK(!resultType || result.categorySet.test(resultType->category()));
break;
case KindCode::effectiveKind:
CHECK(kindDummyArg != nullptr);
CHECK(kindDummyArg);
CHECK(result.categorySet == CategorySet{*category});
if (kindArg != nullptr) {
if (kindArg) {
if (auto *expr{kindArg->UnwrapExpr()}) {
CHECK(expr->Rank() == 0);
if (auto code{ToInt64(*expr)}) {
@ -1343,7 +1342,7 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
"intrinsic result type"_err_en_US);
return std::nullopt;
} else if (kindDummyArg->optionality == Optionality::defaultsToSameKind) {
CHECK(sameArg != nullptr);
CHECK(sameArg);
resultType = *sameArg->GetType();
} else if (kindDummyArg->optionality ==
Optionality::defaultsToSubscriptKind) {
@ -1358,8 +1357,8 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
break;
case KindCode::likeMultiply:
CHECK(dummies >= 2);
CHECK(actualForDummy[0] != nullptr);
CHECK(actualForDummy[1] != nullptr);
CHECK(actualForDummy[0]);
CHECK(actualForDummy[1]);
resultType = actualForDummy[0]->GetType()->ResultTypeForMultiply(
*actualForDummy[1]->GetType());
break;
@ -1395,23 +1394,23 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
case Rank::vector: resultRank = 1; break;
case Rank::matrix: resultRank = 2; break;
case Rank::conformable:
CHECK(arrayArg != nullptr);
CHECK(arrayArg);
resultRank = arrayArg->Rank();
break;
case Rank::dimReduced:
CHECK(arrayArg != nullptr);
CHECK(arrayArg);
resultRank = hasDimArg ? arrayArg->Rank() - 1 : 0;
break;
case Rank::dimRemoved:
CHECK(arrayArg != nullptr);
CHECK(arrayArg);
resultRank = arrayArg->Rank() - 1;
break;
case Rank::rankPlus1:
CHECK(knownArg != nullptr);
CHECK(knownArg);
resultRank = knownArg->Rank() + 1;
break;
case Rank::shaped:
CHECK(shapeArgSize.has_value());
CHECK(shapeArgSize);
resultRank = *shapeArgSize;
break;
case Rank::elementalOrBOZ:
@ -1442,14 +1441,13 @@ std::optional<SpecificCall> IntrinsicInterface::Match(
if (const Expr<SomeType> *expr{arg->UnwrapExpr()}) {
auto dc{characteristics::DummyArgument::FromActual(
std::string{d.keyword}, *expr, context)};
CHECK(dc.has_value());
CHECK(dc);
dummyArgs.emplace_back(std::move(*dc));
if (d.typePattern.kindCode == KindCode::same &&
!sameDummyArg.has_value()) {
if (d.typePattern.kindCode == KindCode::same && !sameDummyArg) {
sameDummyArg = j;
}
} else {
CHECK(arg->GetAssumedTypeDummy() != nullptr);
CHECK(arg->GetAssumedTypeDummy());
dummyArgs.emplace_back(std::string{d.keyword},
characteristics::DummyDataObject{DynamicType::AssumedType()});
}
@ -1548,7 +1546,7 @@ SpecificCall IntrinsicProcTable::Implementation::HandleNull(
if (!arguments.empty()) {
if (arguments.size() > 1) {
context.messages().Say("Too many arguments to NULL()"_err_en_US);
} else if (arguments[0].has_value() && arguments[0]->keyword.has_value() &&
} else if (arguments[0] && arguments[0]->keyword &&
arguments[0]->keyword->ToString() != "mold") {
context.messages().Say("Unknown argument '%s' to NULL()"_err_en_US,
arguments[0]->keyword->ToString());
@ -1560,10 +1558,10 @@ SpecificCall IntrinsicProcTable::Implementation::HandleNull(
if (IsProcedurePointer(*mold)) {
// MOLD= procedure pointer
const Symbol *last{GetLastSymbol(*mold)};
CHECK(last != nullptr);
CHECK(last);
auto procPointer{
characteristics::Procedure::Characterize(*last, intrinsics)};
CHECK(procPointer.has_value());
CHECK(procPointer);
args.emplace_back("mold"s,
characteristics::DummyProcedure{common::Clone(*procPointer)});
fResult.emplace(std::move(*procPointer));
@ -1632,8 +1630,7 @@ static bool ApplySpecificChecks(
}
} else if (name == "loc") {
if (const auto &arg{call.arguments[0]}) {
ok = arg->GetAssumedTypeDummy() != nullptr ||
GetLastSymbol(arg->UnwrapExpr()) != nullptr;
ok = arg->GetAssumedTypeDummy() || GetLastSymbol(arg->UnwrapExpr());
}
if (!ok) {
messages.Say(
@ -1706,7 +1703,7 @@ std::optional<SpecificCall> IntrinsicProcTable::Implementation::Probe(
parser::Messages &buffer) -> std::optional<SpecificCall> {
if (auto specificCall{
intrinsic.Match(call, defaults_, arguments, localContext)}) {
if (finalBuffer != nullptr) {
if (finalBuffer) {
finalBuffer->Annex(std::move(localBuffer));
}
return specificCall;
@ -1778,7 +1775,7 @@ std::optional<SpecificCall> IntrinsicProcTable::Implementation::Probe(
}
// No match; report the right errors, if any
if (finalBuffer != nullptr) {
if (finalBuffer) {
if (specificBuffer.empty()) {
finalBuffer->Annex(std::move(genericBuffer));
} else {
@ -1796,7 +1793,7 @@ IntrinsicProcTable::Implementation::IsUnrestrictedSpecificIntrinsicFunction(
const SpecificIntrinsicInterface &specific{*iter->second};
if (!specific.isRestrictedSpecific) {
std::string genericName{name};
if (specific.generic != nullptr) {
if (specific.generic) {
genericName = std::string(specific.generic);
}
characteristics::FunctionResult fResult{GetSpecificType(specific.result)};

View file

@ -272,7 +272,7 @@ RealFlags Real<W, P, IM>::Normalize(bool negative, int exponent,
const Fraction &fraction, Rounding rounding, RoundingBits *roundingBits) {
int lshift{fraction.LEADZ()};
if (lshift == fraction.bits /* fraction is zero */ &&
(roundingBits == nullptr || roundingBits->empty())) {
(!roundingBits || roundingBits->empty())) {
// No fraction, no rounding bits -> +/-0.0
exponent = lshift = 0;
} else if (lshift < exponent) {
@ -309,7 +309,7 @@ RealFlags Real<W, P, IM>::Normalize(bool negative, int exponent,
word_ = Word::ConvertUnsigned(fraction).value;
if (lshift > 0) {
word_ = word_.SHIFTL(lshift);
if (roundingBits != nullptr) {
if (roundingBits) {
for (; lshift > 0; --lshift) {
if (roundingBits->ShiftLeft()) {
word_ = word_.IBSET(lshift - 1);

View file

@ -30,8 +30,7 @@ namespace Fortran::evaluate {
bool IsImpliedShape(const Symbol &symbol0) {
const Symbol &symbol{ResolveAssociations(symbol0)};
if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
if (symbol.attrs().test(semantics::Attr::PARAMETER) &&
details->init().has_value()) {
if (symbol.attrs().test(semantics::Attr::PARAMETER) && details->init()) {
return details->shape().IsImpliedShape();
}
}
@ -84,7 +83,7 @@ std::optional<Shape> AsShape(FoldingContext &context, ExtentExpr &&arrayExpr) {
std::optional<ExtentExpr> AsExtentArrayExpr(const Shape &shape) {
ArrayConstructorValues<ExtentType> values;
for (const auto &dim : shape) {
if (dim.has_value()) {
if (dim) {
values.Push(common::Clone(*dim));
} else {
return std::nullopt;
@ -164,7 +163,7 @@ MaybeExtentExpr CountTrips(FoldingContext &context, MaybeExtentExpr &&lower,
MaybeExtentExpr GetSize(Shape &&shape) {
ExtentExpr extent{1};
for (auto &&dim : std::move(shape)) {
if (dim.has_value()) {
if (dim) {
extent = std::move(extent) * std::move(*dim);
} else {
return std::nullopt;
@ -272,11 +271,11 @@ MaybeExtentExpr GetExtent(FoldingContext &context, const Subscript &subscript,
common::visitors{
[&](const Triplet &triplet) -> MaybeExtentExpr {
MaybeExtentExpr upper{triplet.upper()};
if (!upper.has_value()) {
if (!upper) {
upper = GetUpperBound(context, base, dimension);
}
MaybeExtentExpr lower{triplet.lower()};
if (!lower.has_value()) {
if (!lower) {
lower = GetLowerBound(context, base, dimension);
}
return CountTrips(context, std::move(lower), std::move(upper),
@ -297,7 +296,7 @@ MaybeExtentExpr GetExtent(FoldingContext &context, const Subscript &subscript,
MaybeExtentExpr ComputeUpperBound(
FoldingContext &context, ExtentExpr &&lower, MaybeExtentExpr &&extent) {
if (extent.has_value()) {
if (extent) {
return Fold(context, std::move(*extent) - std::move(lower) + ExtentExpr{1});
} else {
return std::nullopt;
@ -461,7 +460,7 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
return Scalar();
} else if (call.IsElemental()) {
for (const auto &arg : call.arguments()) {
if (arg.has_value() && arg->Rank() > 0) {
if (arg && arg->Rank() > 0) {
return (*this)(*arg);
}
}
@ -473,7 +472,7 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
intrinsic->name == "ubound") {
// These are the array-valued cases for LBOUND and UBOUND (no DIM=).
const auto *expr{call.arguments().front().value().UnwrapExpr()};
CHECK(expr != nullptr);
CHECK(expr);
return Shape{MaybeExtentExpr{ExtentExpr{expr->Rank()}}};
} else if (intrinsic->name == "all" || intrinsic->name == "any" ||
intrinsic->name == "count" || intrinsic->name == "iall" ||
@ -487,7 +486,7 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
auto arrayShape{
(*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
if (arrayShape.has_value() && dimArg != nullptr) {
if (arrayShape && dimArg) {
if (auto dim{ToInt64(*dimArg)}) {
if (*dim >= 1 &&
static_cast<std::size_t>(*dim) <= arrayShape->size()) {
@ -502,7 +501,7 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
return (*this)(call.arguments()[0]);
}
} else if (intrinsic->name == "reshape") {
if (call.arguments().size() >= 2 && call.arguments().at(1).has_value()) {
if (call.arguments().size() >= 2 && call.arguments().at(1)) {
// SHAPE(RESHAPE(array,shape)) -> shape
if (const auto *shapeExpr{
call.arguments().at(1).value().UnwrapExpr()}) {
@ -519,7 +518,7 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
const auto *nCopies{
UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))};
if (arrayShape.has_value() && dimArg != nullptr && nCopies != nullptr) {
if (arrayShape && dimArg && nCopies) {
if (auto dim{ToInt64(*dimArg)}) {
if (*dim >= 1 &&
static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {

View file

@ -106,7 +106,7 @@ std::optional<Expr<SomeType>> Package(Expr<SomeKind<CAT>> &&catExpr) {
template<TypeCategory CAT>
std::optional<Expr<SomeType>> Package(
std::optional<Expr<SomeKind<CAT>>> &&catExpr) {
if (catExpr.has_value()) {
if (catExpr) {
return {AsGenericExpr(std::move(*catExpr))};
}
return NoExpr();
@ -553,7 +553,7 @@ std::optional<Expr<SomeType>> ConvertToType(
if (auto *cx{UnwrapExpr<Expr<SomeCharacter>>(x)}) {
auto converted{
ConvertToKind<TypeCategory::Character>(type.kind(), std::move(*cx))};
if (type.charLength() != nullptr) {
if (type.charLength()) {
if (const auto &len{type.charLength()->GetExplicit()}) {
Expr<SomeInteger> lenParam{*len};
Expr<SubscriptInteger> length{Convert<SubscriptInteger>{lenParam}};
@ -590,7 +590,7 @@ std::optional<Expr<SomeType>> ConvertToType(
std::optional<Expr<SomeType>> ConvertToType(
const DynamicType &to, std::optional<Expr<SomeType>> &&x) {
if (x.has_value()) {
if (x) {
return ConvertToType(to, std::move(*x));
} else {
return std::nullopt;
@ -612,7 +612,7 @@ std::optional<Expr<SomeType>> ConvertToType(
std::optional<Expr<SomeType>> ConvertToType(
const Symbol &to, std::optional<Expr<SomeType>> &&x) {
if (x.has_value()) {
if (x) {
return ConvertToType(to, std::move(*x));
} else {
return std::nullopt;
@ -633,7 +633,7 @@ bool IsAssumedRank(const ActualArgument &arg) {
return IsAssumedRank(*expr);
} else {
const Symbol *assumedTypeDummy{arg.GetAssumedTypeDummy()};
CHECK(assumedTypeDummy != nullptr);
CHECK(assumedTypeDummy);
return IsAssumedRank(*assumedTypeDummy);
}
}

View file

@ -52,7 +52,7 @@ std::optional<Variable<A>> AsVariable(const Expr<A> &expr) {
template<typename A>
std::optional<Variable<A>> AsVariable(const std::optional<Expr<A>> &expr) {
if (expr.has_value()) {
if (expr) {
return AsVariable(*expr);
} else {
return std::nullopt;
@ -116,7 +116,7 @@ template<typename T> bool IsAssumedRank(const Expr<T> &expr) {
return std::visit([](const auto &x) { return IsAssumedRank(x); }, expr.u);
}
template<typename A> bool IsAssumedRank(const std::optional<A> &x) {
return x.has_value() && IsAssumedRank(*x);
return x && IsAssumedRank(*x);
}
// Generalizing packagers: these take operations and expressions of more
@ -195,7 +195,7 @@ auto UnwrapExpr(B &x) -> common::Constify<A, B> * {
template<typename A, typename B>
const A *UnwrapExpr(const std::optional<B> &x) {
if (x.has_value()) {
if (x) {
return UnwrapExpr<A>(*x);
} else {
return nullptr;
@ -203,7 +203,7 @@ const A *UnwrapExpr(const std::optional<B> &x) {
}
template<typename A, typename B> A *UnwrapExpr(std::optional<B> &x) {
if (x.has_value()) {
if (x) {
return UnwrapExpr<A>(*x);
} else {
return nullptr;
@ -232,7 +232,7 @@ std::optional<DataRef> ExtractDataRef(const Expr<T> &expr) {
}
template<typename A>
std::optional<DataRef> ExtractDataRef(const std::optional<A> &x) {
if (x.has_value()) {
if (x) {
return ExtractDataRef(*x);
} else {
return std::nullopt;
@ -748,7 +748,7 @@ template<typename T> std::optional<BaseObject> GetBaseObject(const Expr<T> &x) {
}
template<typename A>
std::optional<BaseObject> GetBaseObject(const std::optional<A> &x) {
if (x.has_value()) {
if (x) {
return GetBaseObject(*x);
} else {
return std::nullopt;

View file

@ -66,14 +66,14 @@ public:
return visitor_(x.get());
}
template<typename A> Result operator()(const A *x) const {
if (x != nullptr) {
if (x) {
return visitor_(*x);
} else {
return visitor_.Default();
}
}
template<typename A> Result operator()(const std::optional<A> &x) const {
if (x.has_value()) {
if (x) {
return visitor_(*x);
} else {
return visitor_.Default();

View file

@ -93,7 +93,7 @@ bool IsDescriptor(const Symbol &symbol0) {
namespace Fortran::evaluate {
template<typename A> inline bool PointeeComparison(const A *x, const A *y) {
return x == y || (x != nullptr && y != nullptr && *x == *y);
return x == y || (x && y && *x == *y);
}
bool DynamicType::operator==(const DynamicType &that) const {
@ -103,7 +103,7 @@ bool DynamicType::operator==(const DynamicType &that) const {
}
bool DynamicType::IsAssumedLengthCharacter() const {
return category_ == TypeCategory::Character && charLength_ != nullptr &&
return category_ == TypeCategory::Character && charLength_ &&
charLength_->isAssumed();
}
@ -192,7 +192,7 @@ static bool AreSameDerivedType(const semantics::DerivedTypeSpec &x,
for (auto xComponentName{xDetails.componentNames().cbegin()};
xComponentName != xEnd; ++xComponentName, ++yComponentName) {
if (yComponentName == yEnd || *xComponentName != *yComponentName ||
xSymbol.scope() == nullptr || ySymbol.scope() == nullptr) {
!xSymbol.scope() || !ySymbol.scope()) {
return false;
}
const auto xLookup{xSymbol.scope()->find(*xComponentName)};
@ -237,7 +237,7 @@ else {
static bool AreCompatibleDerivedTypes(const semantics::DerivedTypeSpec *x,
const semantics::DerivedTypeSpec *y, bool isPolymorphic) {
if (x == nullptr || y == nullptr) {
if (!x || !y) {
return false;
} else {
SetOfDerivedTypePairs inProgress;
@ -262,7 +262,7 @@ static bool IsKindTypeParameter(
}
bool DynamicType::IsTypeCompatibleWith(const DynamicType &that) const {
if (derived_ != nullptr) {
if (derived_) {
if (!AreCompatibleDerivedTypes(derived_, that.derived_, IsPolymorphic())) {
return false;
}

View file

@ -156,7 +156,7 @@ public:
return kind_ == ClassKind || IsAssumedType();
}
constexpr bool IsUnlimitedPolymorphic() const { // TYPE(*) or CLASS(*)
return IsPolymorphic() && derived_ == nullptr;
return IsPolymorphic() && !derived_;
}
constexpr const semantics::DerivedTypeSpec &GetDerivedTypeSpec() const {
return DEREF(derived_);
@ -179,7 +179,7 @@ public:
return x.GetType();
}
template<typename A> static std::optional<DynamicType> From(const A *p) {
if (p == nullptr) {
if (!p) {
return std::nullopt;
} else {
return From(*p);
@ -187,7 +187,7 @@ public:
}
template<typename A>
static std::optional<DynamicType> From(const std::optional<A> &x) {
if (x.has_value()) {
if (x) {
return From(*x);
} else {
return std::nullopt;
@ -392,16 +392,16 @@ public:
: SomeKind(dt.GetDerivedTypeSpec()) {}
CONSTEXPR_CONSTRUCTORS_AND_ASSIGNMENTS(SomeKind)
bool IsUnlimitedPolymorphic() const { return derivedTypeSpec_ == nullptr; }
bool IsUnlimitedPolymorphic() const { return !derivedTypeSpec_; }
constexpr DynamicType GetType() const {
if (derivedTypeSpec_ == nullptr) {
if (!derivedTypeSpec_) {
return DynamicType::UnlimitedPolymorphic();
} else {
return DynamicType{*derivedTypeSpec_};
}
}
const semantics::DerivedTypeSpec &derivedTypeSpec() const {
CHECK(derivedTypeSpec_ != nullptr);
CHECK(derivedTypeSpec_);
return *derivedTypeSpec_;
}
bool operator==(const SomeKind &) const;

View file

@ -34,11 +34,11 @@ Triplet::Triplet() : stride_{Expr<SubscriptInteger>{1}} {}
Triplet::Triplet(std::optional<Expr<SubscriptInteger>> &&l,
std::optional<Expr<SubscriptInteger>> &&u,
std::optional<Expr<SubscriptInteger>> &&s)
: stride_{s.has_value() ? std::move(*s) : Expr<SubscriptInteger>{1}} {
if (l.has_value()) {
: stride_{s ? std::move(*s) : Expr<SubscriptInteger>{1}} {
if (l) {
lower_.emplace(std::move(*l));
}
if (u.has_value()) {
if (u) {
upper_.emplace(std::move(*u));
}
}
@ -91,16 +91,16 @@ CoarrayRef::CoarrayRef(SymbolVector &&base, std::vector<Subscript> &&ss,
}
std::optional<Expr<SomeInteger>> CoarrayRef::stat() const {
if (stat_.has_value()) {
return {stat_.value().value()};
if (stat_) {
return stat_.value().value();
} else {
return std::nullopt;
}
}
std::optional<Expr<SomeInteger>> CoarrayRef::team() const {
if (team_.has_value()) {
return {team_.value().value()};
if (team_) {
return team_.value().value();
} else {
return std::nullopt;
}
@ -125,16 +125,16 @@ const Symbol &CoarrayRef::GetLastSymbol() const { return base_.back(); }
void Substring::SetBounds(std::optional<Expr<SubscriptInteger>> &lower,
std::optional<Expr<SubscriptInteger>> &upper) {
if (lower.has_value()) {
if (lower) {
set_lower(std::move(lower.value()));
}
if (upper.has_value()) {
if (upper) {
set_upper(std::move(upper.value()));
}
}
Expr<SubscriptInteger> Substring::lower() const {
if (lower_.has_value()) {
if (lower_) {
return lower_.value().value();
} else {
return AsExpr(Constant<SubscriptInteger>{1});
@ -147,7 +147,7 @@ Substring &Substring::set_lower(Expr<SubscriptInteger> &&expr) {
}
std::optional<Expr<SubscriptInteger>> Substring::upper() const {
if (upper_.has_value()) {
if (upper_) {
return upper_.value().value();
} else {
return std::visit(
@ -168,21 +168,21 @@ Substring &Substring::set_upper(Expr<SubscriptInteger> &&expr) {
}
std::optional<Expr<SomeCharacter>> Substring::Fold(FoldingContext &context) {
if (!lower_.has_value()) {
if (!lower_) {
lower_ = AsExpr(Constant<SubscriptInteger>{1});
}
lower_.value() = evaluate::Fold(context, std::move(lower_.value().value()));
std::optional<ConstantSubscript> lbi{ToInt64(lower_.value().value())};
if (lbi.has_value() && *lbi < 1) {
if (lbi && *lbi < 1) {
context.messages().Say(
"Lower bound (%jd) on substring is less than one"_en_US,
static_cast<std::intmax_t>(*lbi));
*lbi = 1;
lower_ = AsExpr(Constant<SubscriptInteger>{1});
}
if (!upper_.has_value()) {
if (!upper_) {
upper_ = upper();
if (!upper_.has_value()) {
if (!upper_) {
return std::nullopt;
}
}
@ -190,7 +190,7 @@ std::optional<Expr<SomeCharacter>> Substring::Fold(FoldingContext &context) {
if (std::optional<ConstantSubscript> ubi{ToInt64(upper_.value().value())}) {
auto *literal{std::get_if<StaticDataObject::Pointer>(&parent_)};
std::optional<ConstantSubscript> length;
if (literal != nullptr) {
if (literal) {
length = (*literal)->data().size();
} else if (const Symbol * symbol{GetLastSymbol()}) {
if (const semantics::DeclTypeSpec * type{symbol->GetType()}) {
@ -199,19 +199,19 @@ std::optional<Expr<SomeCharacter>> Substring::Fold(FoldingContext &context) {
}
}
}
if (*ubi < 1 || (lbi.has_value() && *ubi < *lbi)) {
if (*ubi < 1 || (lbi && *ubi < *lbi)) {
// Zero-length string: canonicalize
*lbi = 1, *ubi = 0;
lower_ = AsExpr(Constant<SubscriptInteger>{*lbi});
upper_ = AsExpr(Constant<SubscriptInteger>{*ubi});
} else if (length.has_value() && *ubi > *length) {
} else if (length && *ubi > *length) {
context.messages().Say("Upper bound (%jd) on substring is greater "
"than character length (%jd)"_en_US,
static_cast<std::intmax_t>(*ubi),
static_cast<std::intmax_t>(*length));
*ubi = *length;
}
if (lbi.has_value() && literal != nullptr) {
if (lbi && literal) {
CHECK(*ubi >= *lbi);
auto newStaticData{StaticDataObject::Create()};
auto items{*ubi - *lbi + 1};

View file

@ -43,6 +43,7 @@
#include <optional>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
namespace Fortran::parser {
@ -76,7 +77,7 @@ public:
using resultType = A;
constexpr PureParser(const PureParser &) = default;
constexpr explicit PureParser(A &&x) : value_(std::move(x)) {}
std::optional<A> Parse(ParseState &) const { return {value_}; }
std::optional<A> Parse(ParseState &) const { return value_; }
private:
const A value_;
@ -97,7 +98,7 @@ public:
Messages messages{std::move(state.messages())};
ParseState backtrack{state};
std::optional<resultType> result{parser_.Parse(state)};
if (result.has_value()) {
if (result) {
state.messages().Restore(std::move(messages));
} else {
state = std::move(backtrack);
@ -127,14 +128,15 @@ public:
if (parser_.Parse(forked)) {
return std::nullopt;
}
return {Success{}};
return Success{};
}
private:
const PA parser_;
};
template<typename PA> inline constexpr auto operator!(PA p) {
template<typename PA, typename = typename PA::resultType>
constexpr auto operator!(PA p) {
return NegatedParser<PA>(p);
}
@ -149,7 +151,7 @@ public:
ParseState forked{state};
forked.set_deferMessages(true);
if (parser_.Parse(forked)) {
return {Success{}};
return Success{};
}
return std::nullopt;
}
@ -202,7 +204,7 @@ public:
state.set_anyTokenMatched(false);
std::optional<resultType> result{parser_.Parse(state)};
bool emitMessage{false};
if (result.has_value()) {
if (result) {
messages.Annex(std::move(state.messages()));
if (backtrack.anyTokenMatched()) {
state.set_anyTokenMatched();
@ -296,7 +298,7 @@ public:
ParseState backtrack{state};
std::optional<resultType> result{std::get<0>(ps_).Parse(state)};
if constexpr (sizeof...(Ps) > 0) {
if (!result.has_value()) {
if (!result) {
ParseRest<1>(result, state, backtrack);
}
}
@ -311,7 +313,7 @@ private:
ParseState prevState{std::move(state)};
state = backtrack;
result = std::get<J>(ps_).Parse(state);
if (!result.has_value()) {
if (!result) {
state.CombineFailedParses(std::move(prevState));
if constexpr (J < sizeof...(Ps)) {
ParseRest<J + 1>(result, state, backtrack);
@ -377,7 +379,7 @@ public:
if (hadDeferredMessages) {
state.set_anyDeferredMessages();
}
if (bx.has_value()) {
if (bx) {
// Error recovery situations must also produce messages.
CHECK(state.anyDeferredMessages() || state.messages().AnyFatalError());
state.set_anyErrorRecovery();
@ -469,7 +471,7 @@ public:
parser_.Parse(state) && state.GetLocation() > at;
at = state.GetLocation()) {
}
return {Success{}};
return Success{};
}
private:
@ -491,7 +493,7 @@ public:
std::optional<Success> Parse(ParseState &state) const {
while (parser_.Parse(state)) {
}
return {Success{}};
return Success{};
}
private:
@ -513,9 +515,10 @@ public:
constexpr MaybeParser(PA parser) : parser_{parser} {}
std::optional<resultType> Parse(ParseState &state) const {
if (resultType result{parser_.Parse(state)}) {
// permit optional<optional<...>>
return {std::move(result)};
}
return {resultType{}};
return resultType{};
}
private:
@ -536,10 +539,10 @@ public:
constexpr DefaultedParser(PA p) : parser_{p} {}
std::optional<resultType> Parse(ParseState &state) const {
std::optional<std::optional<resultType>> ax{maybe(parser_).Parse(state)};
if (ax.value().has_value()) { // maybe() always succeeds
if (ax.value()) { // maybe() always succeeds
return std::move(*ax);
}
return {resultType{}};
return resultType{};
}
private:
@ -610,8 +613,8 @@ public:
ApplyArgs<PARSER...> results;
using Sequence = std::index_sequence_for<PARSER...>;
if (ApplyHelperArgs(parsers_, results, state, Sequence{})) {
return {ApplyHelperFunction<FUNCTION, RESULT, PARSER...>(
function_, std::move(results), Sequence{})};
return ApplyHelperFunction<FUNCTION, RESULT, PARSER...>(
function_, std::move(results), Sequence{});
} else {
return std::nullopt;
}
@ -669,8 +672,8 @@ public:
using Sequence1 = std::index_sequence_for<OBJPARSER, PARSER...>;
using Sequence2 = std::index_sequence_for<PARSER...>;
if (ApplyHelperArgs(parsers_, results, state, Sequence1{})) {
return {ApplyHelperMember<OBJPARSER, PARSER...>(
function_, std::move(results), Sequence2{})};
return ApplyHelperMember<OBJPARSER, PARSER...>(
function_, std::move(results), Sequence2{});
} else {
return std::nullopt;
}
@ -799,7 +802,7 @@ template<bool pass> struct FixedParser {
constexpr FixedParser() {}
static constexpr std::optional<Success> Parse(ParseState &) {
if constexpr (pass) {
return {Success{}};
return Success{};
} else {
return std::nullopt;
}
@ -848,7 +851,7 @@ public:
}
auto at{state.GetLocation()};
auto result{parser_.Parse(state)};
if (result.has_value()) {
if (result) {
state.Nonstandard(
CharBlock{at, state.GetLocation()}, LF, "nonstandard usage"_en_US);
}
@ -880,7 +883,7 @@ public:
}
auto at{state.GetLocation()};
auto result{parser_.Parse(state)};
if (result.has_value()) {
if (result) {
state.Nonstandard(
CharBlock{at, state.GetLocation()}, LF, "deprecated usage"_en_US);
}
@ -905,7 +908,7 @@ public:
std::optional<resultType> Parse(ParseState &state) const {
const char *start{state.GetLocation()};
auto result{parser_.Parse(state)};
if (result.has_value()) {
if (result) {
const char *end{state.GetLocation()};
for (; start < end && start[0] == ' '; ++start) {
}

View file

@ -47,7 +47,7 @@ void MessageFormattedText::Format(const MessageFixedText *text, ...) {
CHECK(need >= 0);
char *buffer{
static_cast<char *>(std::malloc(static_cast<std::size_t>(need) + 1))};
CHECK(buffer != nullptr);
CHECK(buffer);
va_end(ap);
va_start(ap, text);
int need2{vsnprintf(buffer, need + 1, p, ap)};
@ -204,7 +204,7 @@ void Message::Emit(
const AllSources &sources{cooked.allSources()};
sources.EmitMessage(o, provenanceRange, text, echoSourceLine);
if (attachmentIsContext_) {
for (const Message *context{attachment_.get()}; context != nullptr;
for (const Message *context{attachment_.get()}; context;
context = context->attachment_.get()) {
std::optional<ProvenanceRange> contextProvenance{
context->GetProvenanceRange(cooked)};
@ -217,7 +217,7 @@ void Message::Emit(
provenanceRange = contextProvenance;
}
} else {
for (const Message *attachment{attachment_.get()}; attachment != nullptr;
for (const Message *attachment{attachment_.get()}; attachment;
attachment = attachment->attachment_.get()) {
sources.EmitMessage(o, attachment->GetProvenanceRange(cooked),
attachment->ToString(), echoSourceLine);

View file

@ -158,12 +158,12 @@ public:
void Nonstandard(
CharBlock range, LanguageFeature lf, const MessageFixedText &msg) {
anyConformanceViolation_ = true;
if (userState_ != nullptr && userState_->features().ShouldWarn(lf)) {
if (userState_ && userState_->features().ShouldWarn(lf)) {
Say(range, msg);
}
}
bool IsNonstandardOk(LanguageFeature lf, const MessageFixedText &msg) {
if (userState_ != nullptr && !userState_->features().IsEnabled(lf)) {
if (userState_ && !userState_->features().IsEnabled(lf)) {
return false;
}
Nonstandard(lf, msg);

View file

@ -66,12 +66,12 @@ template<typename M> void Walk(format::IntrinsicTypeDataEditDesc &, M &);
// Traversal of needed STL template classes (optional, list, tuple, variant)
template<typename T, typename V>
void Walk(const std::optional<T> &x, V &visitor) {
if (x.has_value()) {
if (x) {
Walk(*x, visitor);
}
}
template<typename T, typename M> void Walk(std::optional<T> &x, M &mutator) {
if (x.has_value()) {
if (x) {
Walk(*x, mutator);
}
}

View file

@ -67,7 +67,7 @@ DataRef::DataRef(std::list<PartRef> &&prl) : u{std::move(prl.front().name)} {
u = common::Indirection<ArrayElement>::Make(
std::move(*this), std::move(pr.subscripts));
}
if (pr.imageSelector.has_value()) {
if (pr.imageSelector) {
u = common::Indirection<CoindexedNamedObject>::Make(
std::move(*this), std::move(*pr.imageSelector));
}
@ -193,7 +193,7 @@ Substring ArrayElement::ConvertToSubstring() {
auto iter{subscripts.begin()};
CHECK(iter != subscripts.end());
auto &triplet{std::get<SubscriptTriplet>(iter->u)};
CHECK(!std::get<2>(triplet.t).has_value());
CHECK(!std::get<2>(triplet.t));
CHECK(++iter == subscripts.end());
return Substring{std::move(base),
SubstringRange{std::get<0>(std::move(triplet.t)),

View file

@ -68,7 +68,7 @@ const SourceFile *Parsing::Prescan(const std::string &path, Options options) {
Preprocessor preprocessor{allSources};
for (const auto &predef : options.predefinitions) {
if (predef.second.has_value()) {
if (predef.second) {
preprocessor.Define(predef.first, *predef.second);
} else {
preprocessor.Undefine(predef.first);

View file

@ -582,7 +582,7 @@ void Preprocessor::Directive(const TokenSequence &dir, Prescanner *prescanner) {
}
std::stringstream error;
const SourceFile *included{allSources_.Open(include, &error)};
if (included == nullptr) {
if (!included) {
prescanner->Say(dir.GetTokenProvenanceRange(dirOffset),
"#include: %s"_err_en_US, error.str());
} else if (included->bytes() > 0) {
@ -808,7 +808,7 @@ static std::int64_t ExpressionValue(const TokenSequence &token,
++*atToken;
if (op != CONST) {
left = ExpressionValue(token, operandPrecedence[op], atToken, error);
if (error->has_value()) {
if (*error) {
return 0;
}
switch (op) {
@ -856,7 +856,7 @@ static std::int64_t ExpressionValue(const TokenSequence &token,
std::int64_t right{
ExpressionValue(token, operandPrecedence[op], atToken, error)};
if (error->has_value()) {
if (*error) {
return 0;
}
@ -1007,7 +1007,7 @@ bool Preprocessor::IsIfPredicateTrue(const TokenSequence &expr,
std::size_t atToken{0};
std::optional<Message> error;
bool result{ExpressionValue(expr3, 0, &atToken, &error) != 0};
if (error.has_value()) {
if (error) {
prescanner->Say(std::move(*error));
} else if (atToken < expr3.SizeInTokens() &&
expr3.TokenAt(atToken).ToString() != "!") {

View file

@ -68,7 +68,7 @@ void Prescanner::Prescan(ProvenanceRange range) {
startProvenance_ = range.start();
std::size_t offset{0};
const SourceFile *source{allSources.GetSourceFile(startProvenance_, &offset)};
CHECK(source != nullptr);
CHECK(source);
start_ = source->content() + offset;
limit_ = start_ + range.size();
nextLine_ = start_;
@ -241,7 +241,7 @@ TokenSequence Prescanner::TokenizePreprocessorDirective() {
void Prescanner::NextLine() {
void *vstart{static_cast<void *>(const_cast<char *>(nextLine_))};
void *v{std::memchr(vstart, '\n', limit_ - nextLine_)};
if (v == nullptr) {
if (!v) {
nextLine_ = limit_;
} else {
const char *nl{const_cast<const char *>(static_cast<char *>(v))};
@ -746,14 +746,14 @@ void Prescanner::FortranInclude(const char *firstQuote) {
Provenance provenance{GetProvenance(nextLine_)};
AllSources &allSources{cooked_.allSources()};
const SourceFile *currentFile{allSources.GetSourceFile(provenance)};
if (currentFile != nullptr) {
if (currentFile) {
allSources.PushSearchPathDirectory(DirectoryName(currentFile->path()));
}
const SourceFile *included{allSources.Open(path, &error)};
if (currentFile != nullptr) {
if (currentFile) {
allSources.PopSearchPathDirectory();
}
if (included == nullptr) {
if (!included) {
Say(provenance, "INCLUDE: %s"_err_en_US, error.str());
} else if (included->bytes() > 0) {
ProvenanceRange includeLineRange{

View file

@ -73,7 +73,7 @@ public:
template<typename... A> Message &Say(A &&... a) {
Message &m{messages_.Say(std::forward<A>(a)...)};
std::optional<ProvenanceRange> range{m.GetProvenanceRange(cooked_)};
CHECK(!range.has_value() || cooked_.IsValid(*range));
CHECK(!range || cooked_.IsValid(*range));
return m;
}

View file

@ -46,7 +46,7 @@ std::optional<std::size_t> ProvenanceRangeToOffsetMappings::Map(
ProvenanceRange that{iter->first};
if (that.Contains(range)) {
std::size_t offset{iter->second + that.MemberOffset(range.start())};
if (!result.has_value() || offset < *result) {
if (!result || offset < *result) {
result = offset;
}
}
@ -215,7 +215,7 @@ ProvenanceRange AllSources::AddCompilerInsertion(std::string text) {
void AllSources::EmitMessage(std::ostream &o,
const std::optional<ProvenanceRange> &range, const std::string &message,
bool echoSourceLine) const {
if (!range.has_value()) {
if (!range) {
o << message << '\n';
return;
}
@ -286,7 +286,7 @@ const SourceFile *AllSources::GetSourceFile(
return std::visit(
common::visitors{
[&](const Inclusion &inc) {
if (offset != nullptr) {
if (offset) {
*offset = origin.covers.MemberOffset(at);
}
return &inc.source;
@ -295,7 +295,7 @@ const SourceFile *AllSources::GetSourceFile(
return GetSourceFile(origin.replaces.start(), offset);
},
[offset](const CompilerInsertion &) {
if (offset != nullptr) {
if (offset) {
*offset = 0;
}
return static_cast<const SourceFile *>(nullptr);

View file

@ -65,7 +65,7 @@ void SourceFile::RecordLineStarts() {
void SourceFile::IdentifyPayload() {
content_ = address_;
bytes_ = size_;
if (content_ != nullptr) {
if (content_) {
static constexpr int BOMBytes{3};
static const char UTF8_BOM[]{"\xef\xbb\xbf"};
if (bytes_ >= BOMBytes && std::memcmp(content_, UTF8_BOM, BOMBytes) == 0) {
@ -103,7 +103,7 @@ static std::size_t RemoveCarriageReturns(char *buffer, std::size_t bytes) {
void *vp{static_cast<void *>(p)};
void *crvp{std::memchr(vp, '\r', bytes)};
char *crcp{static_cast<char *>(crvp)};
if (crcp == nullptr) {
if (!crcp) {
std::memmove(buffer + wrote, p, bytes);
wrote += bytes;
break;
@ -243,7 +243,7 @@ void SourceFile::Close() {
isMemoryMapped_ = false;
} else if (!normalized_.empty()) {
normalized_.clear();
} else if (address_ != nullptr) {
} else if (address_) {
delete[] address_;
}
address_ = content_ = nullptr;

View file

@ -140,16 +140,16 @@ public:
continue; // redundant; ignore
}
}
if (!at.has_value()) {
if (!at) {
at = nextCh.Parse(state);
if (!at.has_value()) {
if (!at) {
return std::nullopt;
}
}
if (spaceSkipping) {
if (**at == ' ') {
at = nextCh.Parse(state);
if (!at.has_value()) {
if (!at) {
return std::nullopt;
}
} else if constexpr (MandatoryFreeFormSpace) {
@ -259,7 +259,7 @@ template<char quote> struct CharLiteral {
str += '\\';
} else if (ch->first == quote) {
static constexpr auto doubled{attempt(AnyOfChars{SetOfChars{quote}})};
if (!doubled.Parse(state).has_value()) {
if (!doubled.Parse(state)) {
return str;
}
}
@ -289,7 +289,7 @@ struct BOZLiteral {
space.Parse(state);
const char *start{state.GetLocation()};
std::optional<const char *> at{nextCh.Parse(state)};
if (!at.has_value()) {
if (!at) {
return std::nullopt;
}
if (**at == 'x' &&
@ -299,7 +299,7 @@ struct BOZLiteral {
}
if (baseChar(**at)) {
at = nextCh.Parse(state);
if (!at.has_value()) {
if (!at) {
return std::nullopt;
}
}
@ -312,7 +312,7 @@ struct BOZLiteral {
std::string content;
while (true) {
at = nextCh.Parse(state);
if (!at.has_value()) {
if (!at) {
return std::nullopt;
}
if (**at == quote) {
@ -329,7 +329,7 @@ struct BOZLiteral {
if (!base) {
// extension: base allowed to appear as suffix, too
if (!(at = nextCh.Parse(state)).has_value() || !baseChar(**at) ||
if (!(at = nextCh.Parse(state)) || !baseChar(**at) ||
!state.IsNonstandardOk(LanguageFeature::BOZExtensions,
"nonstandard BOZ literal"_en_US)) {
return std::nullopt;
@ -371,7 +371,7 @@ struct SignedIntLiteralConstantWithoutKind {
static std::optional<resultType> Parse(ParseState &state) {
resultType result{state.GetLocation()};
static constexpr auto sign{maybe("+-"_ch / space)};
if (sign.Parse(state).has_value()) {
if (sign.Parse(state)) {
if (auto digits{digitString.Parse(state)}) {
result.ExtendToCover(*digits);
return result;
@ -385,7 +385,7 @@ constexpr struct DigitString64 {
using resultType = std::uint64_t;
static std::optional<std::uint64_t> Parse(ParseState &state) {
std::optional<const char *> firstDigit{digit.Parse(state)};
if (!firstDigit.has_value()) {
if (!firstDigit) {
return std::nullopt;
}
std::uint64_t value = **firstDigit - '0';
@ -416,7 +416,7 @@ constexpr struct DigitString64 {
static std::optional<std::int64_t> SignedInteger(
const std::optional<std::uint64_t> &x, Location at, bool negate,
ParseState &state) {
if (!x.has_value()) {
if (!x) {
return std::nullopt;
}
std::uint64_t limit{std::numeric_limits<std::int64_t>::max()};
@ -437,7 +437,7 @@ struct SignedDigitString {
using resultType = std::int64_t;
static std::optional<std::int64_t> Parse(ParseState &state) {
std::optional<const char *> sign{state.PeekAtNextChar()};
if (!sign.has_value()) {
if (!sign) {
return std::nullopt;
}
bool negate{**sign == '-'};
@ -455,7 +455,7 @@ struct DigitStringIgnoreSpaces {
static std::optional<std::uint64_t> Parse(ParseState &state) {
static constexpr auto getFirstDigit{space >> digit};
std::optional<const char *> firstDigit{getFirstDigit.Parse(state)};
if (!firstDigit.has_value()) {
if (!firstDigit) {
return std::nullopt;
}
std::uint64_t value = **firstDigit - '0';
@ -510,12 +510,12 @@ struct HollerithLiteral {
const char *start{state.GetLocation()};
std::optional<std::uint64_t> charCount{
DigitStringIgnoreSpaces{}.Parse(state)};
if (!charCount.has_value() || *charCount < 1) {
if (!charCount || *charCount < 1) {
return std::nullopt;
}
static constexpr auto letterH{"h"_ch};
std::optional<const char *> h{letterH.Parse(state)};
if (!h.has_value()) {
if (!h) {
return std::nullopt;
}
std::string content;

View file

@ -41,7 +41,7 @@ const Name &GetLastName(const AllocateObject &);
struct UnwrapperHelper {
template<typename A, typename B> static const A *Unwrap(B *p) {
if (p != nullptr) {
if (p) {
return Unwrap<A>(*p);
} else {
return nullptr;
@ -60,7 +60,7 @@ struct UnwrapperHelper {
template<typename A, typename B>
static const A *Unwrap(const std::optional<B> &o) {
if (o.has_value()) {
if (o) {
return Unwrap<A>(*o);
} else {
return nullptr;

View file

@ -245,7 +245,7 @@ public:
decls.begin(), decls.end(), [](const ComponentDecl &d) {
const auto &init{
std::get<std::optional<Initialization>>(d.t)};
return init.has_value() &&
return init &&
std::holds_alternative<
std::list<common::Indirection<DataStmtValue>>>(
init->u);
@ -408,12 +408,12 @@ public:
static const auto hasAssignmentInitializer{[](const EntityDecl &d) {
// Does a declaration have a new-style =x initializer?
const auto &init{std::get<std::optional<Initialization>>(d.t)};
return init.has_value() && !isInitializerOldStyle(*init);
return init && !isInitializerOldStyle(*init);
}};
static const auto hasSlashDelimitedInitializer{[](const EntityDecl &d) {
// Does a declaration have an old-style /x/ initializer?
const auto &init{std::get<std::optional<Initialization>>(d.t)};
return init.has_value() && isInitializerOldStyle(*init);
return init && isInitializerOldStyle(*init);
}};
const auto useDoubledColons{[&]() {
bool isRecord{std::holds_alternative<DeclarationTypeSpec::Record>(dts.u)};
@ -665,7 +665,7 @@ public:
void Unparse(const LetterSpec &x) { // R865
Put(*std::get<const char *>(x.t));
auto second{std::get<std::optional<const char *>>(x.t)};
if (second.has_value()) {
if (second) {
Put('-'), Put(**second);
}
}
@ -803,7 +803,7 @@ public:
// R1001 - R1022
bool Pre(const Expr &x) {
if (typedExprAsFortran_ != nullptr && x.typedExpr.get() != nullptr) {
if (typedExprAsFortran_ && x.typedExpr.get()) {
// Format the expression representation from semantics
(*typedExprAsFortran_)(out_, *x.typedExpr);
return false;
@ -1417,7 +1417,7 @@ public:
Walk("*(", x.unlimitedItems, ",", ")"), Put(')');
}
void Unparse(const format::FormatItem &x) { // R1304, R1306, R1321
if (x.repeatCount.has_value()) {
if (x.repeatCount) {
Walk(*x.repeatCount);
}
std::visit(
@ -2449,7 +2449,7 @@ private:
template<typename A>
void Walk(
const char *prefix, const std::optional<A> &x, const char *suffix = "") {
if (x.has_value()) {
if (x) {
Word(prefix), Walk(*x), Word(suffix);
}
}

View file

@ -27,7 +27,7 @@ std::optional<Success> StartNewSubprogram::Parse(ParseState &state) {
if (auto *ustate{state.userState()}) {
ustate->NewSubprogram();
}
return {Success{}};
return Success{};
}
std::optional<CapturedLabelDoStmt::resultType> CapturedLabelDoStmt::Parse(
@ -47,7 +47,7 @@ EndDoStmtForCapturedLabelDoStmt::Parse(ParseState &state) {
static constexpr auto parser{
statement(indirect(construct<EndDoStmt>("END DO" >> maybe(name))))};
if (auto enddo{parser.Parse(state)}) {
if (enddo->label.has_value()) {
if (enddo->label) {
if (const auto *ustate{state.userState()}) {
if (ustate->IsDoLabel(enddo->label.value())) {
return enddo;
@ -87,7 +87,7 @@ std::optional<DataComponentDefStmt> StructureComponents::Parse(
ParseState &state) {
static constexpr auto stmt{Parser<DataComponentDefStmt>{}};
std::optional<DataComponentDefStmt> defs{stmt.Parse(state)};
if (defs.has_value()) {
if (defs) {
if (auto *ustate{state.userState()}) {
for (const auto &decl : std::get<std::list<ComponentDecl>>(defs->t)) {
ustate->NoteOldStructureComponent(std::get<Name>(decl.t).source);

View file

@ -99,7 +99,7 @@ public:
error =
"%s is associated with the non-existent result of reference to procedure"_err_en_US;
}
if (error.has_value()) {
if (error) {
auto save{common::ScopedSet(pointer_, symbol)};
Say(*error, description_, funcName);
}
@ -126,7 +126,7 @@ public:
"%s associated with object '%s' with incompatible type or shape"_err_en_US;
}
}
if (error.has_value()) {
if (error) {
auto save{common::ScopedSet(pointer_, last)};
Say(*error, description_, last->name());
}
@ -209,9 +209,9 @@ void PointerAssignmentChecker::Check(const ProcedureDesignator &d) {
void PointerAssignmentChecker::Check(const ProcedureRef &ref) {
const characteristics::Procedure *procedure{nullptr};
auto chars{characteristics::Procedure::Characterize(ref, intrinsics_)};
if (chars.has_value()) {
if (chars) {
procedure = &*chars;
if (chars->functionResult.has_value()) {
if (chars->functionResult) {
if (const auto *proc{chars->functionResult->IsProcedurePointer()}) {
procedure = proc;
}

View file

@ -103,7 +103,7 @@ private:
template<typename T>
void CanonicalizeIfMatch(Block &originalBlock, std::vector<LabelInfo> &stack,
Block::iterator &i, Statement<T> &statement) {
if (!stack.empty() && statement.label.has_value() &&
if (!stack.empty() && statement.label &&
stack.back().label == *statement.label) {
auto currentLabel{stack.back().label};
if constexpr (std::is_same_v<T, common::Indirection<EndDoStmt>>) {

View file

@ -85,7 +85,7 @@ private:
nextIt = it;
if (++nextIt != block.end()) {
if (auto *doCons{GetConstructIf<parser::DoConstruct>(*nextIt)}) {
if (doCons->GetLoopControl().has_value()) {
if (doCons->GetLoopControl()) {
// move DoConstruct
std::get<std::optional<parser::DoConstruct>>(x.t) =
std::move(*doCons);

View file

@ -194,7 +194,7 @@ static std::optional<AllocateCheckerInfo> CheckAllocateOptions(
if (info.gotSrc || info.gotMold) {
if (const auto *expr{GetExpr(DEREF(parserSourceExpr))}) {
info.sourceExprType = expr->GetType();
if (!info.sourceExprType.has_value()) {
if (!info.sourceExprType) {
context.Say(parserSourceExpr->source,
"Typeless item not allowed as SOURCE or MOLD in ALLOCATE"_err_en_US);
return std::nullopt;
@ -252,7 +252,7 @@ static bool IsTypeCompatible(
if (type1.category() == DeclTypeSpec::Category::TypeDerived) {
return &derivedType1->typeSymbol() == &derivedType2.typeSymbol();
} else if (type1.category() == DeclTypeSpec::Category::ClassDerived) {
for (const DerivedTypeSpec *parent{&derivedType2}; parent != nullptr;
for (const DerivedTypeSpec *parent{&derivedType2}; parent;
parent = parent->typeSymbol().GetParentTypeSpec()) {
if (&derivedType1->typeSymbol() == &parent->typeSymbol()) {
return true;
@ -404,7 +404,7 @@ static bool HaveCompatibleKindParameters(
}
bool AllocationCheckerHelper::RunChecks(SemanticsContext &context) {
if (symbol_ == nullptr) {
if (!symbol_) {
CHECK(context.AnyFatalError());
return false;
}
@ -413,7 +413,7 @@ bool AllocationCheckerHelper::RunChecks(SemanticsContext &context) {
"Name in ALLOCATE statement must be a variable name"_err_en_US);
return false;
}
if (type_ == nullptr) {
if (!type_) {
// This is done after variable check because a user could have put
// a subroutine name in allocate for instance which is a symbol with
// no type.
@ -535,7 +535,7 @@ bool AllocationCheckerHelper::RunChecks(SemanticsContext &context) {
bool AllocationCheckerHelper::RunCoarrayRelatedChecks(
SemanticsContext &context) const {
if (symbol_ == nullptr) {
if (!symbol_) {
CHECK(context.AnyFatalError());
return false;
}

View file

@ -21,8 +21,7 @@ namespace Fortran::semantics {
bool IsNumericExpr(const SomeExpr &expr) {
auto dynamicType{expr.GetType()};
return dynamicType.has_value() &&
common::IsNumericTypeCategory(dynamicType->category());
return dynamicType && common::IsNumericTypeCategory(dynamicType->category());
}
void ArithmeticIfStmtChecker::Leave(

View file

@ -94,7 +94,7 @@ static void PadShortCharacterActual(evaluate::Expr<evaluate::SomeType> &actual,
"Actual length '%jd' is less than expected length '%jd'"_en_US,
*actualLEN, *dummyLEN);
auto converted{ConvertToType(dummyType.type(), std::move(actual))};
CHECK(converted.has_value());
CHECK(converted);
actual = std::move(*converted);
}
}
@ -606,8 +606,8 @@ static void RearrangeArguments(const characteristics::Procedure &proc,
}
std::map<std::string, evaluate::ActualArgument> kwArgs;
for (auto &x : actuals) {
if (x.has_value()) {
if (x->keyword.has_value()) {
if (x) {
if (x->keyword) {
auto emplaced{
kwArgs.try_emplace(x->keyword->ToString(), std::move(*x))};
if (!emplaced.second) {
@ -626,7 +626,7 @@ static void RearrangeArguments(const characteristics::Procedure &proc,
auto iter{kwArgs.find(dummy.name)};
if (iter != kwArgs.end()) {
evaluate::ActualArgument &x{iter->second};
if (actuals[index].has_value()) {
if (actuals[index]) {
messages.Say(*x.keyword,
"Keyword argument '%s=' has already been specified positionally (#%d) in this procedure reference"_err_en_US,
*x.keyword, index + 1);
@ -658,7 +658,7 @@ static parser::Messages CheckExplicitInterface(
int index{0};
for (auto &actual : actuals) {
const auto &dummy{proc.dummyArguments.at(index++)};
if (actual.has_value()) {
if (actual) {
CheckExplicitInterfaceArg(*actual, dummy, proc, localContext, scope);
} else if (!dummy.IsOptional()) {
if (dummy.name.empty()) {
@ -708,7 +708,7 @@ void CheckArguments(const characteristics::Procedure &proc,
}
if (!explicitInterface || treatingExternalAsImplicit) {
for (auto &actual : actuals) {
if (actual.has_value()) {
if (actual) {
CheckImplicitInterfaceArg(*actual, context.messages());
}
}

View file

@ -95,7 +95,7 @@ void CheckHelper::Check(const Symbol &symbol) {
}
const DeclTypeSpec *type{symbol.GetUltimate().GetType()};
const DerivedTypeSpec *derived{nullptr};
if (type != nullptr) {
if (type) {
derived = type->AsDerived();
}
auto save{messages_.SetLocation(symbol.name())};
@ -107,7 +107,7 @@ void CheckHelper::Check(const Symbol &symbol) {
if (isAssociated) {
return; // only care about checking VOLATILE on associated symbols
}
if (type != nullptr) {
if (type) {
bool canHaveAssumedParameter{IsNamedConstant(symbol) ||
IsAssumedLengthCharacterFunction(symbol) ||
symbol.test(Symbol::Flag::ParentComp)};
@ -234,7 +234,7 @@ void CheckHelper::CheckValue(
messages_.Say(
"VALUE attribute may not apply to an OPTIONAL in a BIND(C) procedure"_err_en_US);
}
if (derived != nullptr) {
if (derived) {
if (FindCoarrayUltimateComponent(*derived)) {
messages_.Say(
"VALUE attribute may not apply to a type with a coarray ultimate component"_err_en_US);
@ -257,7 +257,7 @@ void CheckHelper::CheckVolatile(const Symbol &symbol, bool isAssociated,
messages_.Say(
"VOLATILE attribute may not apply to a coarray accessed by USE or host association"_err_en_US);
}
if (derived != nullptr) {
if (derived) {
if (FindCoarrayUltimateComponent(*derived)) {
messages_.Say(
"VOLATILE attribute may not apply to a type with a coarray ultimate component accessed by USE or host association"_err_en_US);

View file

@ -81,7 +81,7 @@ public:
template<typename T> bool Pre(const parser::Statement<T> &statement) {
currentStatementSourcePosition_ = statement.source;
if (statement.label.has_value()) {
if (statement.label) {
labels_.insert(*statement.label);
}
return true;
@ -402,7 +402,7 @@ private:
CheckDoVariable(bounds.name);
CheckDoExpression(bounds.lower);
CheckDoExpression(bounds.upper);
if (bounds.step.has_value()) {
if (bounds.step) {
CheckDoExpression(bounds.step.value());
}
}
@ -605,7 +605,7 @@ private:
const auto &header{std::get<parser::ConcurrentHeader>(concurrent.t)};
const auto &mask{
std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)};
if (mask.has_value()) {
if (mask) {
CheckMaskIsPure(*mask);
}
CheckConcurrentHeader(header);
@ -689,8 +689,8 @@ void DoChecker::CheckForBadLeave(
static bool StmtMatchesConstruct(const parser::Name *stmtName,
StmtType stmtType, const parser::Name *constructName,
const ConstructNode &construct) {
bool inDoConstruct{MaybeGetDoConstruct(construct) != nullptr};
if (stmtName == nullptr) {
bool inDoConstruct{MaybeGetDoConstruct(construct)};
if (!stmtName) {
return inDoConstruct; // Unlabeled statements match all DO constructs
} else if (constructName && constructName->source == stmtName->source) {
return stmtType == StmtType::EXIT || inDoConstruct;

View file

@ -61,7 +61,7 @@ bool FormatErrorReporter::Say(const common::FormatMessage &msg) {
void IoChecker::Enter(
const parser::Statement<common::Indirection<parser::FormatStmt>> &stmt) {
if (!stmt.label.has_value()) {
if (!stmt.label) {
context_.Say("Format statement must be labeled"_err_en_US); // C1301
}
const char *formatStart{static_cast<const char *>(
@ -222,7 +222,7 @@ void IoChecker::Enter(const parser::IdExpr &) { SetSpecifier(IoSpecKind::Id); }
void IoChecker::Enter(const parser::IdVariable &spec) {
SetSpecifier(IoSpecKind::Id);
auto expr{GetExpr(spec)};
if (expr == nullptr || !expr->GetType()) {
if (!expr || !expr->GetType()) {
return;
}
int kind{expr->GetType()->kind()};

View file

@ -691,7 +691,7 @@ void OmpStructureChecker::Leave(const parser::OmpClauseList &) {
const auto &orderedClause{
std::get<parser::OmpClause::Ordered>(clause->u)};
if (orderedClause.v.has_value()) {
if (orderedClause.v) {
if (FindClause(OmpClause::LINEAR)) {
context_.Say(clause->source,
"A loop directive may not have both a LINEAR clause and "
@ -1003,14 +1003,13 @@ bool OmpStructureChecker::ScheduleModifierHasType(
const parser::OmpScheduleModifierType::ModType &type) {
const auto &modifier{
std::get<std::optional<parser::OmpScheduleModifier>>(x.t)};
if (modifier.has_value()) {
if (modifier) {
const auto &modType1{
std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)};
const auto &modType2{
std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>(
modifier->t)};
if (modType1.v.v == type ||
(modType2.has_value() && modType2->v.v == type)) {
if (modType1.v.v == type || (modType2 && modType2->v.v == type)) {
return true;
}
}
@ -1023,7 +1022,7 @@ void OmpStructureChecker::Enter(const parser::OmpScheduleClause &x) {
if (doSet.test(GetContext().directive)) {
const auto &kind{std::get<1>(x.t)};
const auto &chunk{std::get<2>(x.t)};
if (chunk.has_value()) {
if (chunk) {
if (kind == parser::OmpScheduleClause::ScheduleType::Runtime ||
kind == parser::OmpScheduleClause::ScheduleType::Auto) {
context_.Say(GetContext().clauseSource,

View file

@ -40,13 +40,12 @@ void ReturnStmtChecker::Leave(const parser::ReturnStmt &returnStmt) {
// subroutine subprogram.
const auto &scope{context_.FindScope(context_.location().value())};
const auto *subprogramScope{FindContainingSubprogram(scope)};
if (subprogramScope == nullptr) {
if (!subprogramScope) {
context_.Say(
"RETURN must in the inclusive scope of a SUBPROGRAM"_err_en_US);
return;
}
if (returnStmt.v.has_value() &&
subprogramScope->kind() == Scope::Kind::Subprogram) {
if (returnStmt.v && subprogramScope->kind() == Scope::Kind::Subprogram) {
if (IsFunction(*subprogramScope->GetSymbol())) {
context_.Say(
"RETURN with expression is only allowed in SUBROUTINE subprogram"_err_en_US);

View file

@ -62,7 +62,7 @@ struct DynamicTypeWithLength : public DynamicType {
};
std::optional<Expr<SubscriptInteger>> DynamicTypeWithLength::LEN() const {
if (length.has_value()) {
if (length) {
return length;
}
if (auto *lengthParam{charLength()}) {
@ -75,7 +75,7 @@ std::optional<Expr<SubscriptInteger>> DynamicTypeWithLength::LEN() const {
static std::optional<DynamicTypeWithLength> AnalyzeTypeSpec(
const std::optional<parser::TypeSpec> &spec) {
if (spec.has_value()) {
if (spec) {
if (const semantics::DeclTypeSpec * typeSpec{spec->declTypeSpec}) {
// Name resolution sets TypeSpec::declTypeSpec only when it's valid
// (viz., an intrinsic type with valid known kind or a non-polymorphic
@ -155,7 +155,7 @@ public:
}
void Analyze(const parser::Expr &x) {
actuals_.emplace_back(AnalyzeExpr(x));
fatalErrors_ |= !actuals_.back().has_value();
fatalErrors_ |= !actuals_.back();
}
void Analyze(const parser::ActualArgSpec &, bool isSubroutine);
@ -246,10 +246,10 @@ MaybeExpr ExpressionAnalyzer::CompleteSubscripts(ArrayRef &&ref) {
return std::nullopt;
}
}
} else if (object != nullptr) {
} else if (object) {
// C928 & C1002
if (Triplet * last{std::get_if<Triplet>(&ref.subscript().back().u)}) {
if (!last->upper().has_value() && object->IsAssumedSize()) {
if (!last->upper() && object->IsAssumedSize()) {
Say("Assumed-size array '%s' must have explicit final "
"subscript upper bound value"_err_en_US,
symbol.name());
@ -309,7 +309,7 @@ static void FixMisparsedSubstring(const parser::Designator &d) {
if (!arrElement.subscripts.empty()) {
auto iter{arrElement.subscripts.begin()};
if (auto *triplet{std::get_if<parser::SubscriptTriplet>(&iter->u)}) {
if (!std::get<2>(triplet->t).has_value() /* no stride */ &&
if (!std::get<2>(triplet->t) /* no stride */ &&
++iter == arrElement.subscripts.end() /* one subscript */) {
if (Symbol *
symbol{std::visit(
@ -359,7 +359,7 @@ template<typename A> common::IfNoLvalue<MaybeExpr, A> AsMaybeExpr(A &&x) {
return std::make_optional(AsGenericExpr(std::move(x)));
}
template<typename A> MaybeExpr AsMaybeExpr(std::optional<A> &&x) {
if (x.has_value()) {
if (x) {
return AsMaybeExpr(std::move(*x));
}
return std::nullopt;
@ -368,7 +368,7 @@ template<typename A> MaybeExpr AsMaybeExpr(std::optional<A> &&x) {
// Type kind parameter values for literal constants.
int ExpressionAnalyzer::AnalyzeKindParam(
const std::optional<parser::KindParam> &kindParam, int defaultKind) {
if (!kindParam.has_value()) {
if (!kindParam) {
return defaultKind;
}
return std::visit(
@ -426,7 +426,7 @@ struct IntTypeVisitor {
template<typename PARSED>
MaybeExpr ExpressionAnalyzer::IntLiteralConstant(const PARSED &x) {
const auto &kindParam{std::get<std::optional<parser::KindParam>>(x.t)};
bool isDefaultKind{!kindParam.has_value()};
bool isDefaultKind{!kindParam};
int kind{AnalyzeKindParam(kindParam, GetDefaultKind(TypeCategory::Integer))};
if (CheckIntrinsicKind(TypeCategory::Integer, kind)) {
auto digits{std::get<parser::CharBlock>(x.t)};
@ -513,18 +513,18 @@ MaybeExpr ExpressionAnalyzer::Analyze(const parser::RealLiteralConstant &x) {
break;
}
}
if (letterKind.has_value()) {
if (letterKind) {
defaultKind = *letterKind;
}
auto kind{AnalyzeKindParam(x.kind, defaultKind)};
if (letterKind.has_value() && kind != *letterKind && expoLetter != 'e') {
if (letterKind && kind != *letterKind && expoLetter != 'e') {
Say("Explicit kind parameter on real constant disagrees with "
"exponent letter '%c'"_en_US,
expoLetter);
}
auto result{common::SearchTypes(
RealTypeVisitor{kind, x.real.source, GetFoldingContext()})};
if (!result.has_value()) {
if (!result) {
Say("Unsupported REAL(KIND=%d)"_err_en_US, kind);
}
return AsMaybeExpr(std::move(result));
@ -598,7 +598,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(const parser::LogicalLiteralConstant &x) {
auto result{common::SearchTypes(
TypeKindVisitor<TypeCategory::Logical, Constant, bool>{
kind, std::move(value)})};
if (!result.has_value()) {
if (!result) {
Say("unsupported LOGICAL(KIND=%d)"_err_en_US, kind);
}
return result;
@ -694,7 +694,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(const parser::NamedConstant &n) {
// Substring references
std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::GetSubstringBound(
const std::optional<parser::ScalarIntExpr> &bound) {
if (bound.has_value()) {
if (bound) {
if (MaybeExpr expr{Analyze(*bound)}) {
if (expr->Rank() > 1) {
Say("substring bound expression has rank %d"_err_en_US, expr->Rank());
@ -757,10 +757,10 @@ MaybeExpr ExpressionAnalyzer::Analyze(
Expr<SubscriptInteger> length{
std::visit([](const auto &ckExpr) { return ckExpr.LEN().value(); },
charExpr->u)};
if (!lower.has_value()) {
if (!lower) {
lower = Expr<SubscriptInteger>{1};
}
if (!upper.has_value()) {
if (!upper) {
upper = Expr<SubscriptInteger>{
static_cast<std::int64_t>(ToInt64(length).value())};
}
@ -787,7 +787,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(
// Subscripted array references
std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::AsSubscript(
MaybeExpr &&expr) {
if (expr.has_value()) {
if (expr) {
if (expr->Rank() > 1) {
Say("Subscript expression has rank %d greater than 1"_err_en_US,
expr->Rank());
@ -809,7 +809,7 @@ std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::AsSubscript(
std::optional<Expr<SubscriptInteger>> ExpressionAnalyzer::TripletPart(
const std::optional<parser::Subscript> &s) {
if (s.has_value()) {
if (s) {
return AsSubscript(Analyze(*s));
} else {
return std::nullopt;
@ -930,7 +930,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(const parser::StructureComponent &sc) {
"A type parameter inquiry must be applied to "
"a designator"_err_en_US);
}
} else if (dtSpec == nullptr || dtSpec->scope() == nullptr) {
} else if (!dtSpec || !dtSpec->scope()) {
CHECK(context_.AnyFatalError() || !foldingContext_.messages().empty());
return std::nullopt;
} else if (std::optional<DataRef> dataRef{
@ -994,7 +994,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(const parser::CoindexedNamedObject &x) {
dataRef.reset();
}
}
if (dataRef.has_value()) {
if (dataRef) {
while (auto *component{std::get_if<Component>(&dataRef->u)}) {
reversed.push_back(component->GetLastSymbol());
*dataRef = std::move(component->base());
@ -1065,7 +1065,7 @@ private:
const A &x) {
if (MaybeExpr y{Analyze(x)}) {
Expr<SomeInteger> *intExpr{UnwrapExpr<Expr<SomeInteger>>(*y)};
CHECK(intExpr != nullptr);
CHECK(intExpr);
return ConvertToType<Type<TypeCategory::Integer, KIND>>(
std::move(*intExpr));
}
@ -1079,7 +1079,7 @@ private:
};
void ArrayConstructorContext::Push(MaybeExpr &&x) {
if (!x.has_value()) {
if (!x) {
return;
}
if (auto dyType{x->GetType()}) {
@ -1089,7 +1089,7 @@ void ArrayConstructorContext::Push(MaybeExpr &&x) {
xType.length =
std::visit([](const auto &kc) { return kc.LEN(); }, charExpr->u);
}
if (!type_.has_value()) {
if (!type_) {
// If there is no explicit type-spec in an array constructor, the type
// of the array is the declared type of all of the elements, which must
// be well-defined and all match.
@ -1106,7 +1106,7 @@ void ArrayConstructorContext::Push(MaybeExpr &&x) {
static_cast<const DynamicType &>(xType)) {
values_.Push(std::move(*x));
if (auto thisLen{ToInt64(xType.LEN())}) {
if (constantLength_.has_value()) {
if (constantLength_) {
if (context().warnOnNonstandardUsage() &&
*thisLen != *constantLength_) {
Say("Character literal in array constructor without explicit "
@ -1151,11 +1151,11 @@ void ArrayConstructorContext::Add(const parser::AcValue &x) {
GetSpecificIntExpr<IntType::kind>(std::get<1>(triplet.t))};
std::optional<Expr<IntType>> stride{
GetSpecificIntExpr<IntType::kind>(std::get<2>(triplet.t))};
if (lower.has_value() && upper.has_value()) {
if (!stride.has_value()) {
if (lower && upper) {
if (!stride) {
stride = Expr<IntType>{1};
}
if (!type_.has_value()) {
if (!type_) {
type_ = DynamicTypeWithLength{IntType::GetType()};
}
ArrayConstructorContext nested{*this};
@ -1203,8 +1203,8 @@ void ArrayConstructorContext::Add(const parser::AcValue &x) {
std::get<std::list<parser::AcValue>>(impliedDo.value().t)) {
nested.Add(value);
}
if (lower.has_value() && upper.has_value()) {
if (!stride.has_value()) {
if (lower && upper) {
if (!stride) {
stride = Expr<IntType>{1};
}
values_.Push(ImpliedDo<SomeType>{name, std::move(*lower),
@ -1230,7 +1230,7 @@ ArrayConstructorValues<T> MakeSpecific(
common::visitors{
[&](common::CopyableIndirection<Expr<SomeType>> &&expr) {
auto *typed{UnwrapExpr<Expr<T>>(expr.value())};
CHECK(typed != nullptr);
CHECK(typed);
to.Push(std::move(*typed));
},
[&](ImpliedDo<SomeType> &&impliedDo) {
@ -1278,7 +1278,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(const parser::ArrayConstructor &array) {
for (const parser::AcValue &value : acSpec.values) {
context.Add(value);
}
if (type.has_value()) {
if (type) {
ArrayConstructorTypeVisitor visitor{
std::move(*type), std::move(context.values())};
return common::SearchTypes(std::move(visitor));
@ -1290,13 +1290,12 @@ MaybeExpr ExpressionAnalyzer::Analyze(
const parser::StructureConstructor &structure) {
auto &parsedType{std::get<parser::DerivedTypeSpec>(structure.t)};
parser::CharBlock typeName{std::get<parser::Name>(parsedType.t).source};
if (parsedType.derivedTypeSpec == nullptr) {
if (!parsedType.derivedTypeSpec) {
return std::nullopt;
}
const auto &spec{*parsedType.derivedTypeSpec};
const Symbol &typeSymbol{spec.typeSymbol()};
if (spec.scope() == nullptr ||
!typeSymbol.has<semantics::DerivedTypeDetails>()) {
if (!spec.scope() || !typeSymbol.has<semantics::DerivedTypeDetails>()) {
return std::nullopt; // error recovery
}
const auto &typeDetails{typeSymbol.get<semantics::DerivedTypeDetails>()};
@ -1340,14 +1339,14 @@ MaybeExpr ExpressionAnalyzer::Analyze(
anyKeyword = true;
source = kw->v.source;
symbol = kw->v.symbol;
if (symbol == nullptr) {
if (!symbol) {
auto componentIter{std::find_if(components.begin(), components.end(),
[=](const Symbol &symbol) { return symbol.name() == source; })};
if (componentIter != components.end()) {
symbol = &*componentIter;
}
}
if (symbol == nullptr) { // C7101
if (!symbol) { // C7101
Say(source,
"Keyword '%s=' does not name a component of derived type '%s'"_err_en_US,
source, typeName);
@ -1361,7 +1360,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(
// Here's a regrettably common extension of the standard: anonymous
// initialization of parent components, e.g., T(PT(1)) rather than
// T(1) or T(PT=PT(1)).
if (nextAnonymous == components.begin() && parentComponent != nullptr &&
if (nextAnonymous == components.begin() && parentComponent &&
valueType == DynamicType::From(*parentComponent) &&
context().IsEnabled(LanguageFeature::AnonymousParents)) {
auto iter{
@ -1377,18 +1376,18 @@ MaybeExpr ExpressionAnalyzer::Analyze(
}
}
}
while (symbol == nullptr && nextAnonymous != components.end()) {
while (!symbol && nextAnonymous != components.end()) {
const Symbol &next{*nextAnonymous};
++nextAnonymous;
if (!next.test(Symbol::Flag::ParentComp)) {
symbol = &next;
}
}
if (symbol == nullptr) {
if (!symbol) {
Say(source, "Unexpected value in structure constructor"_err_en_US);
}
}
if (symbol != nullptr) {
if (symbol) {
if (checkConflicts) {
auto componentIter{
std::find(components.begin(), components.end(), *symbol)};
@ -1414,7 +1413,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(
}
}
unavailable.insert(symbol->name());
if (value.has_value()) {
if (value) {
if (symbol->has<semantics::ProcEntityDetails>()) {
CHECK(IsPointer(*symbol));
} else if (symbol->has<semantics::ObjectEntityDetails>()) {
@ -1462,7 +1461,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(
std::holds_alternative<NullPointer>(value->u)) {
// NULL() with no arguments allowed by 7.5.10 para 6 for ALLOCATABLE
} else if (auto symType{DynamicType::From(symbol)}) {
if (valueType.has_value()) {
if (valueType) {
AttachDeclaration(
Say(expr.source,
"Value in structure constructor of type %s is "
@ -1490,7 +1489,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(
!IsAllocatable(symbol)) {
if (const auto *details{
symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
if (details->init().has_value()) {
if (details->init()) {
result.Add(symbol, common::Clone(*details->init()));
} else { // C799
AttachDeclaration(Say(typeName,
@ -1532,7 +1531,7 @@ auto ExpressionAnalyzer::AnalyzeProcedureComponentRef(
dtSpec = &dtDyTy->GetDerivedTypeSpec();
}
}
if (dtSpec != nullptr && dtSpec->scope() != nullptr) {
if (dtSpec && dtSpec->scope()) {
if (std::optional<DataRef> dataRef{
ExtractDataRef(std::move(*dtExpr))}) {
if (auto component{CreateComponent(
@ -1545,7 +1544,7 @@ auto ExpressionAnalyzer::AnalyzeProcedureComponentRef(
auto iter{arguments.begin()};
int at{0};
while (iter < arguments.end() && at < *passIndex) {
if (iter->has_value() && (*iter)->keyword.has_value()) {
if (*iter && (*iter)->keyword) {
iter = arguments.end();
break;
}
@ -1553,7 +1552,7 @@ auto ExpressionAnalyzer::AnalyzeProcedureComponentRef(
++at;
}
ActualArgument passed{AsGenericExpr(std::move(*dtExpr))};
if (iter == arguments.end() && pass->passName().has_value()) {
if (iter == arguments.end() && pass->passName()) {
passed.keyword = *pass->passName();
}
arguments.emplace(iter, std::move(passed));
@ -1793,7 +1792,7 @@ std::optional<characteristics::Procedure> ExpressionAnalyzer::CheckCall(
ActualArguments &arguments) {
auto chars{
characteristics::Procedure::Characterize(proc, context_.intrinsics())};
if (chars.has_value()) {
if (chars) {
bool treatExternalAsImplicit{IsExternalCalledImplicitly(callSite, proc)};
if (treatExternalAsImplicit && !chars->CanBeCalledViaImplicitInterface()) {
Say(callSite,
@ -1954,7 +1953,7 @@ MaybeExpr ExpressionAnalyzer::Analyze(
const parser::Expr::ComplexConstructor &x) {
auto re{Analyze(std::get<0>(x.t).value())};
auto im{Analyze(std::get<1>(x.t).value())};
if (re.has_value() && im.has_value()) {
if (re && im) {
ConformabilityCheck(GetContextualMessages(), *re, *im);
}
return AsMaybeExpr(ConstructComplex(GetContextualMessages(), std::move(re),
@ -2096,7 +2095,7 @@ static void CheckFuncRefToArrayElementRefHasSubscripts(
if (std::get<std::list<parser::ActualArgSpec>>(funcRef.v.t).empty()) {
auto &proc{std::get<parser::ProcedureDesignator>(funcRef.v.t)};
const auto *name{std::get_if<parser::Name>(&proc.u)};
if (name == nullptr) {
if (!name) {
name = &std::get<parser::ProcComponentRef>(proc.u).v.thing.component;
}
auto &msg{context.Say(funcRef.v.source,
@ -2158,7 +2157,7 @@ static void FixMisparsedFunctionReference(
symbol.detailsIf<semantics::GenericDetails>()}) {
derivedType = generic->derivedType();
}
if (derivedType != nullptr) {
if (derivedType) {
if constexpr (common::HasMember<parser::StructureConstructor,
uType>) {
auto &scope{context.FindScope(name->source)};
@ -2193,7 +2192,7 @@ MaybeExpr ExpressionAnalyzer::ExprOrVariable(const PARSED &x) {
result = Analyze(x.u);
}
x.typedExpr.reset(new GenericExprWrapper{std::move(result)});
if (!x.typedExpr->v.has_value()) {
if (!x.typedExpr->v) {
if (!context_.AnyFatalError()) {
#if DUMP_ON_FAILURE
parser::DumpTree(std::cout << "Expression analysis failed on: ", x);
@ -2219,7 +2218,7 @@ Expr<SubscriptInteger> ExpressionAnalyzer::AnalyzeKindSelector(
TypeCategory category,
const std::optional<parser::KindSelector> &selector) {
int defaultKind{GetDefaultKind(category)};
if (!selector.has_value()) {
if (!selector) {
return Expr<SubscriptInteger>{defaultKind};
}
return std::visit(
@ -2311,7 +2310,7 @@ std::optional<int> ExpressionAnalyzer::IsAcImpliedDo(
bool ExpressionAnalyzer::EnforceTypeConstraint(parser::CharBlock at,
const MaybeExpr &result, TypeCategory category, bool defaultKind) {
if (result.has_value()) {
if (result) {
if (auto type{result->GetType()}) {
if (type->category() != category) {
Say(at, "Must have %s type, but is %s"_err_en_US,
@ -2344,7 +2343,7 @@ MaybeExpr ExpressionAnalyzer::MakeFunctionRef(parser::CharBlock callSite,
}
}
if (auto chars{CheckCall(callSite, proc, arguments)}) {
if (chars->functionResult.has_value()) {
if (chars->functionResult) {
const auto &result{*chars->functionResult};
if (result.IsProcedurePointer()) {
return Expr<SomeType>{
@ -2425,7 +2424,7 @@ void ArgumentAnalyzer::Analyze(
},
},
std::get<parser::ActualArg>(arg.t).u);
if (actual.has_value()) {
if (actual) {
if (const auto &argKW{std::get<std::optional<parser::Keyword>>(arg.t)}) {
actual->keyword = argKW->v.source;
}
@ -2590,7 +2589,7 @@ std::string ArgumentAnalyzer::TypeAsFortran(std::size_t i) {
bool ArgumentAnalyzer::AnyUntypedOperand() {
for (const auto &actual : actuals_) {
if (!actual.value().GetType().has_value()) {
if (!actual.value().GetType()) {
return true;
}
}

View file

@ -165,7 +165,7 @@ public:
return Analyze(x.value());
}
template<typename A> MaybeExpr Analyze(const std::optional<A> &x) {
if (x.has_value()) {
if (x) {
return Analyze(*x);
} else {
return std::nullopt;
@ -175,7 +175,7 @@ public:
// Implement constraint-checking wrappers from the Fortran grammar.
template<typename A> MaybeExpr Analyze(const parser::Scalar<A> &x) {
auto result{Analyze(x.thing)};
if (result.has_value()) {
if (result) {
if (int rank{result->Rank()}; rank != 0) {
SayAt(x, "Must be a scalar value, but is a rank-%d array"_err_en_US,
rank);
@ -189,7 +189,7 @@ public:
auto save{
GetFoldingContext().messages().SetLocation(FindSourceLocation(x))};
auto result{Analyze(x.thing)};
if (result.has_value()) {
if (result) {
*result = Fold(GetFoldingContext(), std::move(*result));
if (!IsConstantExpr(*result)) {
SayAt(x, "Must be a constant value"_err_en_US);

View file

@ -218,7 +218,7 @@ void ModFileWriter::PutSymbol(
}
PutPassName(typeBindings, x.passName());
auto attrs{symbol.attrs()};
if (x.passName().has_value()) {
if (x.passName()) {
attrs.reset(Attr::PASS);
}
PutAttrs(typeBindings, attrs);
@ -508,7 +508,7 @@ void PutProcEntity(std::ostream &os, const Symbol &symbol) {
const auto &details{symbol.get<ProcEntityDetails>()};
const ProcInterface &interface{details.interface()};
Attrs attrs{symbol.attrs()};
if (details.passName().has_value()) {
if (details.passName()) {
attrs.reset(Attr::PASS);
}
PutEntity(os, symbol,
@ -763,7 +763,7 @@ Scope *ModFileReader::Read(const SourceName &name, Scope *ancestor) {
options.searchDirectories = context_.searchDirectories();
auto path{ModFileName(name, ancestorName, context_.moduleFileSuffix())};
const auto *sourceFile{parsing.Prescan(path, options)};
if (sourceFile == nullptr) {
if (!sourceFile) {
return nullptr;
} else if (parsing.messages().AnyFatalError()) {
for (auto &msg : parsing.messages().messages()) {
@ -781,7 +781,7 @@ Scope *ModFileReader::Read(const SourceName &name, Scope *ancestor) {
parsing.Parse(nullptr);
auto &parseTree{parsing.parseTree()};
if (!parsing.messages().empty() || !parsing.consumedWholeFile() ||
!parseTree.has_value()) {
!parseTree) {
Say(name, ancestorName, "Module file is corrupt: %s"_err_en_US,
sourceFile->path());
return nullptr;

View file

@ -195,7 +195,7 @@ const parser::CharBlock *GetStmtName(const parser::Statement<A> &stmt) {
} else {
name = &std::get<std::optional<parser::Name>>(stmt.statement.t);
}
if (name && name->has_value()) {
if (name && *name) {
return &(*name)->source;
}
return nullptr;
@ -219,7 +219,7 @@ public:
template<typename A> bool Pre(const parser::Statement<A> &statement) {
currentPosition_ = statement.source;
if (statement.label.has_value()) {
if (statement.label) {
auto label{statement.label.value()};
auto targetFlags{ConstructBranchTargetFlags(statement)};
if constexpr (std::is_same_v<A, parser::AssociateStmt> ||
@ -378,14 +378,14 @@ public:
if (const auto *optionalGenericSpecPointer{
std::get_if<std::optional<parser::GenericSpec>>(
&interfaceStmt.statement.u)}) {
if (optionalGenericSpecPointer->has_value()) {
if (*optionalGenericSpecPointer) {
if (const auto *namePointer{
std::get_if<parser::Name>(&(*optionalGenericSpecPointer)->u)}) {
auto &optionalGenericSpec{
std::get<parser::Statement<parser::EndInterfaceStmt>>(
interfaceBlock.t)
.statement.v};
if (optionalGenericSpec.has_value()) {
if (optionalGenericSpec) {
if (const auto *otherPointer{
std::get_if<parser::Name>(&optionalGenericSpec->u)}) {
if (namePointer->source != otherPointer->source) {
@ -489,12 +489,12 @@ public:
}
}
void Post(const parser::CycleStmt &cycleStmt) {
if (cycleStmt.v.has_value()) {
if (cycleStmt.v) {
CheckLabelContext("CYCLE", cycleStmt.v->source);
}
}
void Post(const parser::ExitStmt &exitStmt) {
if (exitStmt.v.has_value()) {
if (exitStmt.v) {
CheckLabelContext("EXIT", exitStmt.v->source);
}
}
@ -528,7 +528,7 @@ private:
template<typename A> bool PushConstructName(const A &a) {
const auto &optionalName{std::get<0>(std::get<0>(a.t).statement.t)};
if (optionalName.has_value()) {
if (optionalName) {
constructNames_.emplace_back(optionalName->ToString());
}
return PushSubscope();
@ -537,14 +537,14 @@ private:
const auto &optionalName{
std::get<parser::Statement<parser::BlockStmt>>(blockConstruct.t)
.statement.v};
if (optionalName.has_value()) {
if (optionalName) {
constructNames_.emplace_back(optionalName->ToString());
}
return PushSubscope();
}
template<typename A> bool PushConstructNameWithoutBlock(const A &a) {
const auto &optionalName{std::get<0>(std::get<0>(a.t).statement.t)};
if (optionalName.has_value()) {
if (optionalName) {
constructNames_.emplace_back(optionalName->ToString());
}
return true;
@ -556,7 +556,7 @@ private:
}
template<typename A> void PopConstructNameIfPresent(const A &a) {
const auto &optionalName{std::get<0>(std::get<0>(a.t).statement.t)};
if (optionalName.has_value()) {
if (optionalName) {
constructNames_.pop_back();
}
}
@ -564,7 +564,7 @@ private:
const auto &optionalName{
std::get<parser::Statement<parser::BlockStmt>>(blockConstruct.t)
.statement.v};
if (optionalName.has_value()) {
if (optionalName) {
constructNames_.pop_back();
}
}

View file

@ -625,7 +625,7 @@ bool EquivalenceSets::CheckArrayBound(const parser::Expr &bound) {
return false;
}
auto subscript{evaluate::ToInt64(*expr)};
if (!subscript.has_value()) {
if (!subscript) {
context_.Say(bound.source, // C8109
"Array with nonconstant subscript '%s' is not allowed in an equivalence set"_err_en_US,
bound.source);
@ -643,7 +643,7 @@ bool EquivalenceSets::CheckSubstringBound(
return false;
}
auto subscript{evaluate::ToInt64(*expr)};
if (!subscript.has_value()) {
if (!subscript) {
context_.Say(bound.source, // C8109
"Substring with nonconstant bound '%s' is not allowed in an equivalence set"_err_en_US,
bound.source);
@ -665,7 +665,7 @@ bool EquivalenceSets::CheckSubstringBound(
bool EquivalenceSets::IsCharacterSequenceType(const DeclTypeSpec *type) {
return IsSequenceType(type, [&](const IntrinsicTypeSpec &type) {
auto kind{evaluate::ToInt64(type.kind())};
return type.category() == TypeCategory::Character && kind.has_value() &&
return type.category() == TypeCategory::Character && kind &&
kind.value() == context_.GetDefaultKind(TypeCategory::Character);
});
}

View file

@ -1722,12 +1722,12 @@ void ImplicitRulesVisitor::BeginScope(const Scope &scope) {
// TODO: for all of these errors, reference previous statement too
bool ImplicitRulesVisitor::HandleImplicitNone(
const std::list<ImplicitNoneNameSpec> &nameSpecs) {
if (prevImplicitNone_.has_value()) {
if (prevImplicitNone_) {
Say("More than one IMPLICIT NONE statement"_err_en_US);
Say(*prevImplicitNone_, "Previous IMPLICIT NONE statement"_en_US);
return false;
}
if (prevParameterStmt_.has_value()) {
if (prevParameterStmt_) {
Say("IMPLICIT NONE statement after PARAMETER statement"_err_en_US);
return false;
}
@ -2030,7 +2030,7 @@ void ScopeHandler::EraseSymbol(const parser::Name &name) {
}
static bool NeedsType(const Symbol &symbol) {
return symbol.GetType() == nullptr &&
return !symbol.GetType() &&
std::visit(
common::visitors{
[](const EntityDetails &) { return true; },
@ -2039,8 +2039,7 @@ static bool NeedsType(const Symbol &symbol) {
[&](const ProcEntityDetails &p) {
return symbol.test(Symbol::Flag::Function) &&
!symbol.attrs().test(Attr::INTRINSIC) &&
p.interface().type() == nullptr &&
p.interface().symbol() == nullptr;
!p.interface().type() && !p.interface().symbol();
},
[](const auto &) { return false; },
},
@ -2295,7 +2294,7 @@ void ModuleVisitor::AddUse(
}
} else {
auto *genericDetails{localSymbol.detailsIf<GenericDetails>()};
if (genericDetails && genericDetails->useDetails().has_value()) {
if (genericDetails && genericDetails->useDetails()) {
// localSymbol came from merging two use-associated generics
if (auto *useDetails{useSymbol.detailsIf<GenericDetails>()}) {
genericDetails->CopyFrom(*useDetails);
@ -2433,7 +2432,7 @@ bool InterfaceVisitor::inInterfaceBlock() const {
return !genericInfo_.empty() && GetGenericInfo().isInterface;
}
bool InterfaceVisitor::isGeneric() const {
return !genericInfo_.empty() && GetGenericInfo().symbol != nullptr;
return !genericInfo_.empty() && GetGenericInfo().symbol;
}
bool InterfaceVisitor::isAbstract() const {
return !genericInfo_.empty() && GetGenericInfo().isAbstract;
@ -2486,7 +2485,7 @@ void InterfaceVisitor::ResolveSpecificsInGeneric(Symbol &generic) {
} else {
// USE-associated procedure
const auto *sd{symbol->detailsIf<SubprogramDetails>()};
CHECK(sd != nullptr);
CHECK(sd);
if (symbol->owner().kind() != Scope::Kind::Module ||
sd->isInterface()) {
Say(*name, "'%s' is not a module procedure"_err_en_US);
@ -3054,7 +3053,7 @@ bool DeclarationVisitor::Pre(const parser::Enumerator &enumerator) {
}
if (symbol) {
if (enumerationState_.value.has_value()) {
if (enumerationState_.value) {
symbol->get<ObjectEntityDetails>().set_init(SomeExpr{
evaluate::Expr<evaluate::CInteger>{*enumerationState_.value}});
} else {
@ -3174,7 +3173,7 @@ bool DeclarationVisitor::CheckNotInBlock(const char *stmt) {
}
void DeclarationVisitor::Post(const parser::ObjectDecl &x) {
CHECK(objectDeclAttr_.has_value());
CHECK(objectDeclAttr_);
const auto &name{std::get<parser::ObjectName>(x.t)};
DeclareObjectEntity(name, Attrs{*objectDeclAttr_});
}
@ -3359,7 +3358,7 @@ void DeclarationVisitor::Post(const parser::IntrinsicTypeSpec::Character &) {
if (!charInfo_.length) {
charInfo_.length = ParamValue{1, common::TypeParamAttr::Len};
}
if (!charInfo_.kind.has_value()) {
if (!charInfo_.kind) {
charInfo_.kind =
KindExpr{context().GetDefaultKind(TypeCategory::Character)};
}
@ -3448,7 +3447,7 @@ void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) {
std::get<std::optional<parser::Keyword>>(typeParamSpec.t)};
SourceName name;
common::TypeParamAttr attr{common::TypeParamAttr::Kind};
if (optKeyword.has_value()) {
if (optKeyword) {
seenAnyName = true;
name = optKeyword->v.source;
auto it{std::find_if(parameterDecls.begin(), parameterDecls.end(),
@ -3481,7 +3480,7 @@ void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) {
} else {
const auto &value{std::get<parser::TypeParamValue>(typeParamSpec.t)};
ParamValue param{GetParamValue(value, attr)}; // folded
if (!param.isExplicit() || param.GetExplicit().has_value()) {
if (!param.isExplicit() || param.GetExplicit()) {
spec->AddParamValue(name, std::move(param));
}
}
@ -3490,14 +3489,14 @@ void DeclarationVisitor::Post(const parser::DerivedTypeSpec &x) {
// Ensure that any type parameter without an explicit value has a
// default initialization in the derived type's definition.
const Scope *typeScope{typeSymbol->scope()};
CHECK(typeScope != nullptr);
CHECK(typeScope);
for (const SourceName &name : parameterNames) {
if (!spec->FindParameter(name)) {
auto it{std::find_if(parameterDecls.begin(), parameterDecls.end(),
[&](const Symbol &symbol) { return symbol.name() == name; })};
if (it != parameterDecls.end()) {
const auto *details{it->get().detailsIf<TypeParamDetails>()};
if (details == nullptr || !details->init().has_value()) {
if (!details || !details->init()) {
Say(typeName.source,
"Type parameter '%s' lacks a value and has no default"_err_en_US,
name);
@ -3544,7 +3543,7 @@ bool DeclarationVisitor::Pre(const parser::DerivedTypeDef &x) {
Walk(stmt);
Walk(std::get<std::list<parser::Statement<parser::TypeParamDefStmt>>>(x.t));
auto &scope{currScope()};
CHECK(scope.symbol() != nullptr);
CHECK(scope.symbol());
CHECK(scope.symbol()->scope() == &scope);
auto &details{scope.symbol()->get<DerivedTypeDetails>()};
std::set<SourceName> paramNames;
@ -3603,7 +3602,7 @@ void DeclarationVisitor::Post(const parser::DerivedTypeStmt &x) {
symbol.ReplaceName(name.source);
derivedTypeInfo_.type = &symbol;
PushScope(Scope::Kind::DerivedType, &symbol);
if (extendsType.has_value()) {
if (extendsType) {
// Declare the "parent component"; private if the type is
// Any symbol stored in the EXTENDS() clause is temporarily
// hidden so that a new symbol can be created for the parent
@ -3639,7 +3638,7 @@ void DeclarationVisitor::Post(const parser::TypeParamDefStmt &x) {
if (auto maybeExpr{EvaluateConvertedExpr(
*symbol, *init, init->thing.thing.thing.value().source)}) {
auto *intExpr{std::get_if<SomeIntExpr>(&maybeExpr->u)};
CHECK(intExpr != nullptr);
CHECK(intExpr);
symbol->get<TypeParamDetails>().set_init(std::move(*intExpr));
}
}
@ -3740,11 +3739,11 @@ void DeclarationVisitor::Post(const parser::ProcDecl &x) {
if (Symbol * symbol{currScope().symbol()}) {
dtDetails = symbol->detailsIf<DerivedTypeDetails>();
}
if (dtDetails == nullptr) {
if (!dtDetails) {
attrs.set(Attr::EXTERNAL);
}
Symbol &symbol{DeclareProcEntity(name, attrs, interface)};
if (dtDetails != nullptr) {
if (dtDetails) {
dtDetails->add_component(symbol);
}
}
@ -3916,12 +3915,12 @@ void DeclarationVisitor::Post(const parser::AllocateStmt &) {
bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) {
auto &parsedType{std::get<parser::DerivedTypeSpec>(x.t)};
const DeclTypeSpec *type{ProcessTypeSpec(parsedType)};
if (type == nullptr) {
if (!type) {
return false;
}
const DerivedTypeSpec *spec{type->AsDerived()};
const Scope *typeScope{spec ? spec->scope() : nullptr};
if (typeScope == nullptr) {
if (!typeScope) {
return false;
}
@ -3937,7 +3936,7 @@ bool DeclarationVisitor::Pre(const parser::StructureConstructor &x) {
Walk(std::get<parser::ComponentDataSource>(component.t));
if (const auto &kw{std::get<std::optional<parser::Keyword>>(component.t)}) {
if (Symbol * symbol{FindInTypeOrParents(*typeScope, kw->v)}) {
if (kw->v.symbol == nullptr) {
if (!kw->v.symbol) {
kw->v.symbol = symbol;
}
CheckAccessibleComponent(kw->v.source, *symbol);
@ -4262,7 +4261,7 @@ void DeclarationVisitor::CheckCommonBlocks() {
// check objects in common blocks
for (const auto &name : commonBlockInfo_.names) {
const auto *symbol{currScope().FindSymbol(name)};
if (symbol == nullptr) {
if (!symbol) {
continue;
}
const auto &attrs{symbol->attrs()};
@ -4422,7 +4421,7 @@ bool DeclarationVisitor::PassesLocalityChecks(
Symbol &DeclarationVisitor::FindOrDeclareEnclosingEntity(
const parser::Name &name) {
Symbol *prev{FindSymbol(name)};
if (prev == nullptr) {
if (!prev) {
// Declare the name as an object in the enclosing scope so that
// the name can't be repurposed there later as something else.
prev = &MakeSymbol(InclusiveScope(), name.source, Attrs{});
@ -4461,10 +4460,10 @@ Symbol *DeclarationVisitor::DeclareStatementEntity(const parser::Name &name,
if (!symbol.has<ObjectEntityDetails>()) {
return nullptr; // error was reported in DeclareEntity
}
if (type.has_value()) {
if (type) {
declTypeSpec = ProcessTypeSpec(*type);
}
if (declTypeSpec != nullptr) {
if (declTypeSpec) {
// Subtlety: Don't let a "*length" specifier (if any is pending) affect the
// declaration of this implied DO loop control variable.
auto save{common::ScopedSet(charInfo_.length, std::optional<ParamValue>{})};
@ -4480,7 +4479,7 @@ void DeclarationVisitor::SetType(
const parser::Name &name, const DeclTypeSpec &type) {
CHECK(name.symbol);
auto &symbol{*name.symbol};
if (charInfo_.length.has_value()) { // Declaration has "*length" (R723)
if (charInfo_.length) { // Declaration has "*length" (R723)
auto length{std::move(*charInfo_.length)};
charInfo_.length.reset();
if (type.category() == DeclTypeSpec::Character) {
@ -4535,7 +4534,7 @@ std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveDerivedType(
std::optional<DerivedTypeSpec> DeclarationVisitor::ResolveExtendsType(
const parser::Name &typeName, const parser::Name *extendsName) {
if (extendsName == nullptr) {
if (!extendsName) {
return std::nullopt;
} else if (typeName.source == extendsName->source) {
Say(extendsName->source,
@ -4603,11 +4602,11 @@ Symbol *DeclarationVisitor::MakeTypeSymbol(
// Otherwise, emit an error and return false.
bool DeclarationVisitor::OkToAddComponent(
const parser::Name &name, const Symbol *extends) {
for (const Scope *scope{&currScope()}; scope != nullptr;) {
for (const Scope *scope{&currScope()}; scope;) {
CHECK(scope->IsDerivedType());
if (auto *prev{FindInScope(*scope, name)}) {
auto msg{""_en_US};
if (extends != nullptr) {
if (extends) {
msg = "Type cannot be extended as it has a component named"
" '%s'"_err_en_US;
} else if (prev->test(Symbol::Flag::ParentComp)) {
@ -4623,7 +4622,7 @@ bool DeclarationVisitor::OkToAddComponent(
Say2(name, std::move(msg), *prev, "Previous declaration of '%s'"_en_US);
return false;
}
if (scope == &currScope() && extends != nullptr) {
if (scope == &currScope() && extends) {
// The parent component has not yet been added to the scope.
scope = extends->scope();
} else {
@ -4700,7 +4699,7 @@ bool ConstructVisitor::Pre(const parser::ConcurrentHeader &header) {
// Process the type spec, if present
const auto &typeSpec{
std::get<std::optional<parser::IntegerTypeSpec>>(header.t)};
if (typeSpec.has_value()) {
if (typeSpec) {
SetDeclTypeSpec(MakeNumericType(TypeCategory::Integer, typeSpec->v));
}
@ -4994,10 +4993,10 @@ Symbol *ConstructVisitor::MakeAssocEntity() {
void ConstructVisitor::SetTypeFromAssociation(Symbol &symbol) {
auto &details{symbol.get<AssocEntityDetails>()};
const MaybeExpr *pexpr{&details.expr()};
if (!pexpr->has_value()) {
if (!*pexpr) {
pexpr = &GetCurrentAssociation().selector.expr;
}
if (pexpr->has_value()) {
if (*pexpr) {
const SomeExpr &expr{**pexpr};
if (std::optional<evaluate::DynamicType> type{expr.GetType()}) {
if (const auto *charExpr{
@ -5085,7 +5084,7 @@ const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec(
const DeclTypeSpec &ConstructVisitor::ToDeclTypeSpec(
evaluate::DynamicType &&type, MaybeSubscriptIntExpr &&length) {
CHECK(type.category() == common::TypeCategory::Character);
if (length.has_value()) {
if (length) {
return currScope().MakeCharacterType(
ParamValue{SomeIntExpr{*std::move(length)}, common::TypeParamAttr::Len},
KindExpr{type.kind()});
@ -5362,7 +5361,7 @@ void DeclarationVisitor::CheckInitialProcTarget(
void DeclarationVisitor::Initialization(const parser::Name &name,
const parser::Initialization &init, bool inComponentDecl) {
if (name.symbol == nullptr) {
if (!name.symbol) {
return;
}
if (std::holds_alternative<parser::InitialDataTarget>(init.u)) {
@ -5435,11 +5434,11 @@ void DeclarationVisitor::Initialization(const parser::Name &name,
void DeclarationVisitor::PointerInitialization(
const parser::Name &name, const parser::InitialDataTarget &target) {
if (name.symbol != nullptr) {
if (name.symbol) {
Symbol &ultimate{name.symbol->GetUltimate()};
if (IsPointer(ultimate)) {
if (auto *details{ultimate.detailsIf<ObjectEntityDetails>()}) {
CHECK(!details->init().has_value());
CHECK(!details->init());
Walk(target);
if (MaybeExpr expr{EvaluateExpr(target)}) {
CheckInitialDataTarget(ultimate, *expr, target.value().source);
@ -5453,15 +5452,15 @@ void DeclarationVisitor::PointerInitialization(
}
void DeclarationVisitor::PointerInitialization(
const parser::Name &name, const parser::ProcPointerInit &target) {
if (name.symbol != nullptr) {
if (name.symbol) {
Symbol &ultimate{name.symbol->GetUltimate()};
if (IsProcedurePointer(ultimate)) {
auto &details{ultimate.get<ProcEntityDetails>()};
CHECK(!details.init().has_value());
CHECK(!details.init());
Walk(target);
if (const auto *targetName{std::get_if<parser::Name>(&target.u)}) {
CheckInitialProcTarget(ultimate, *targetName, name.source);
if (targetName->symbol != nullptr) {
if (targetName->symbol) {
details.set_init(*targetName->symbol);
}
} else {
@ -5490,7 +5489,7 @@ void ResolveNamesVisitor::HandleProcedureName(
Symbol::Flag flag, const parser::Name &name) {
CHECK(flag == Symbol::Flag::Function || flag == Symbol::Flag::Subroutine);
auto *symbol{FindSymbol(name)};
if (symbol == nullptr) {
if (!symbol) {
if (context().intrinsics().IsIntrinsic(name.source.ToString())) {
symbol =
&MakeSymbol(InclusiveScope(), name.source, Attrs{Attr::INTRINSIC});
@ -5588,7 +5587,7 @@ bool ResolveNamesVisitor::SetProcFlag(
if (flag == Symbol::Flag::Function) {
ApplyImplicitRules(symbol);
}
} else if (symbol.GetType() != nullptr && flag == Symbol::Flag::Subroutine) {
} else if (symbol.GetType() && flag == Symbol::Flag::Subroutine) {
SayWithDecl(
name, symbol, "Cannot call function '%s' like a subroutine"_err_en_US);
}
@ -5664,8 +5663,7 @@ static bool NeedsExplicitType(const Symbol &symbol) {
} else if (const auto *details{symbol.detailsIf<ObjectEntityDetails>()}) {
return !details->type();
} else if (const auto *details{symbol.detailsIf<ProcEntityDetails>()}) {
return details->interface().symbol() == nullptr &&
details->interface().type() == nullptr;
return !details->interface().symbol() && !details->interface().type();
} else {
return false;
}
@ -5702,7 +5700,7 @@ void ResolveNamesVisitor::PreSpecificationConstruct(
y.value().t)};
const auto *spec{std::get_if<std::optional<parser::GenericSpec>>(
&stmt.statement.u)};
if (spec && spec->has_value()) {
if (spec && *spec) {
CreateGeneric(**spec);
}
},
@ -5773,7 +5771,7 @@ void ResolveNamesVisitor::CheckImports() {
for (const auto &pair : scope.parent()) {
auto &name{pair.first};
std::optional<SourceName> scopeName{scope.GetName()};
if (!scopeName.has_value() || name != *scopeName) {
if (!scopeName || name != *scopeName) {
CheckImport(prevImportStmt_.value(), name);
}
}
@ -5891,7 +5889,7 @@ public:
: resolver_{resolver} {}
void Walk(const parser::ExecutionPart *exec) {
if (exec != nullptr) {
if (exec) {
parser::Walk(*exec, *this);
}
}
@ -6044,7 +6042,7 @@ public:
private:
void Init(const parser::Name &name,
const std::optional<parser::Initialization> &init) {
if (init.has_value()) {
if (init) {
if (const auto *target{
std::get_if<parser::InitialDataTarget>(&init->u)}) {
resolver_.PointerInitialization(name, *target);

View file

@ -75,7 +75,7 @@ private:
// Check that name has been resolved to a symbol
void RewriteMutator::Post(parser::Name &name) {
if (name.symbol == nullptr && errorOnUnresolvedName_) {
if (!name.symbol && errorOnUnresolvedName_) {
messages_.Say(name.source, "Internal: no symbol found for '%s'"_err_en_US,
name.source);
}
@ -116,7 +116,7 @@ void RewriteMutator::Post(parser::IoUnit &x) {
if (auto *var{std::get_if<parser::Variable>(&x.u)}) {
const parser::Name &last{parser::GetLastName(*var)};
DeclTypeSpec *type{last.symbol ? last.symbol->GetType() : nullptr};
if (type == nullptr || type->category() != DeclTypeSpec::Character) {
if (!type || type->category() != DeclTypeSpec::Character) {
// If the Variable is not known to be character (any kind), transform
// the I/O unit in situ to a FileUnitNumber so that automatic expression
// constraint checking will be applied.
@ -137,10 +137,10 @@ void RewriteMutator::Post(parser::IoUnit &x) {
// name had appeared with NML=.
template<typename READ_OR_WRITE>
void FixMisparsedUntaggedNamelistName(READ_OR_WRITE &x) {
if (x.iounit.has_value() && x.format.has_value() &&
if (x.iounit && x.format &&
std::holds_alternative<parser::DefaultCharExpr>(x.format->u)) {
if (const parser::Name * name{parser::Unwrap<parser::Name>(x.format)}) {
if (name->symbol != nullptr && name->symbol->has<NamelistDetails>()) {
if (name->symbol && name->symbol->has<NamelistDetails>()) {
x.controls.emplace_front(parser::IoControlSpec{std::move(*name)});
x.format.reset();
}

View file

@ -183,7 +183,7 @@ Scope::ImportKind Scope::GetImportKind() const {
}
std::optional<parser::MessageFixedText> Scope::SetImportKind(ImportKind kind) {
if (!importKind_.has_value()) {
if (!importKind_) {
importKind_ = kind;
return std::nullopt;
}
@ -298,10 +298,10 @@ const DeclTypeSpec *Scope::FindInstantiatedDerivedType(
}
const Symbol *Scope::GetSymbol() const {
if (symbol_ != nullptr) {
if (symbol_) {
return symbol_;
}
if (derivedTypeSpec_ != nullptr) {
if (derivedTypeSpec_) {
return &derivedTypeSpec_->typeSymbol();
}
return nullptr;

View file

@ -207,7 +207,7 @@ public:
DeclTypeSpec::Category = DeclTypeSpec::TypeDerived) const;
bool IsModuleFile() const {
return kind_ == Kind::Module && symbol_ != nullptr &&
return kind_ == Kind::Module && symbol_ &&
symbol_->test(Symbol::Flag::ModFile);
}

View file

@ -128,7 +128,7 @@ public:
void SetError(Symbol &, bool = true);
template<typename... A> parser::Message &Say(A &&... args) {
CHECK(location_.has_value());
CHECK(location_);
return messages_.Say(*location_, std::forward<A>(args)...);
}
template<typename... A>

View file

@ -552,8 +552,8 @@ const DerivedTypeSpec *Symbol::GetParentTypeSpec(const Scope *scope) const {
const Symbol *Symbol::GetParentComponent(const Scope *scope) const {
if (const auto *dtDetails{detailsIf<DerivedTypeDetails>()}) {
if (scope == nullptr) {
CHECK(scope_ != nullptr);
if (!scope) {
CHECK(scope_);
scope = scope_;
}
return dtDetails->GetParentComponent(*scope);
@ -582,7 +582,7 @@ const Symbol *DerivedTypeDetails::GetParentComponent(const Scope &scope) const {
}
void TypeParamDetails::set_type(const DeclTypeSpec &type) {
CHECK(type_ == nullptr);
CHECK(!type_);
type_ = &type;
}

View file

@ -72,7 +72,7 @@ public:
return *result_;
}
void set_result(Symbol &result) {
CHECK(result_ == nullptr);
CHECK(!result_);
result_ = &result;
}
const std::vector<Symbol *> &dummyArgs() const { return dummyArgs_; }
@ -495,7 +495,7 @@ public:
}
template<typename D> const D &get() const {
const auto *p{detailsIf<D>()};
CHECK(p != nullptr);
CHECK(p);
return *p;
}

View file

@ -51,7 +51,7 @@ const Symbol *FindCommonBlockContaining(const Symbol &object) {
const Scope *FindProgramUnitContaining(const Scope &start) {
const Scope *scope{&start};
while (scope != nullptr) {
while (scope) {
switch (scope->kind()) {
case Scope::Kind::Module:
case Scope::Kind::MainProgram:
@ -72,7 +72,7 @@ const Scope *FindProgramUnitContaining(const Symbol &symbol) {
const Scope *FindPureProcedureContaining(const Scope *scope) {
scope = FindProgramUnitContaining(*scope);
while (scope != nullptr) {
while (scope) {
if (IsPureProcedure(*scope)) {
return scope;
}
@ -94,13 +94,13 @@ bool IsCommonBlockContaining(const Symbol &block, const Symbol &object) {
bool IsUseAssociated(const Symbol &symbol, const Scope &scope) {
const Scope *owner{FindProgramUnitContaining(symbol.GetUltimate().owner())};
return owner != nullptr && owner->kind() == Scope::Kind::Module &&
return owner && owner->kind() == Scope::Kind::Module &&
owner != FindProgramUnitContaining(scope);
}
bool DoesScopeContain(
const Scope *maybeAncestor, const Scope &maybeDescendent) {
if (maybeAncestor != nullptr) {
if (maybeAncestor) {
const Scope *scope{&maybeDescendent};
while (!scope->IsGlobal()) {
scope = &scope->parent();
@ -302,13 +302,13 @@ const Symbol *FindExternallyVisibleObject(
bool ExprHasTypeCategory(
const SomeExpr &expr, const common::TypeCategory &type) {
auto dynamicType{expr.GetType()};
return dynamicType.has_value() && dynamicType->category() == type;
return dynamicType && dynamicType->category() == type;
}
bool ExprTypeKindIsDefault(
const SomeExpr &expr, const SemanticsContext &context) {
auto dynamicType{expr.GetType()};
return dynamicType.has_value() &&
return dynamicType &&
dynamicType->category() != common::TypeCategory::Derived &&
dynamicType->kind() == context.GetDefaultKind(dynamicType->category());
}
@ -454,7 +454,7 @@ bool IsSaved(const Symbol &symbol) {
// Check this symbol suitable as a type-bound procedure - C769
bool CanBeTypeBoundProc(const Symbol *symbol) {
if (symbol == nullptr || IsDummy(*symbol) || IsProcedurePointer(*symbol)) {
if (!symbol || IsDummy(*symbol) || IsProcedurePointer(*symbol)) {
return false;
} else if (symbol->has<SubprogramNameDetails>()) {
return symbol->owner().kind() == Scope::Kind::Module;
@ -701,8 +701,8 @@ bool HasCoarray(const parser::Expr &expression) {
static const DeclTypeSpec &InstantiateIntrinsicType(Scope &scope,
const DeclTypeSpec &spec, SemanticsContext &semanticsContext) {
const IntrinsicTypeSpec *intrinsic{spec.AsIntrinsic()};
CHECK(intrinsic != nullptr);
if (evaluate::ToInt64(intrinsic->kind()).has_value()) {
CHECK(intrinsic);
if (evaluate::ToInt64(intrinsic->kind())) {
return spec; // KIND is already a known constant
}
// The expression was not originally constant, but now it must be so
@ -776,7 +776,7 @@ void InstantiateDerivedType(DerivedTypeSpec &spec, Scope &containingScope,
spec.ReplaceScope(newScope);
const Symbol &typeSymbol{spec.typeSymbol()};
const Scope *typeScope{typeSymbol.scope()};
CHECK(typeScope != nullptr);
CHECK(typeScope);
for (const Symbol &symbol : OrderParameterDeclarations(typeSymbol)) {
const SourceName &name{symbol.name()};
if (typeScope->find(symbol.name()) != typeScope->end()) {
@ -795,7 +795,7 @@ void InstantiateDerivedType(DerivedTypeSpec &spec, Scope &containingScope,
if (auto maybeDynamicType{expr->GetType()}) {
if (expr->Rank() == 0 &&
maybeDynamicType->category() == TypeCategory::Integer) {
if (!evaluate::ToInt64(*expr).has_value()) {
if (!evaluate::ToInt64(*expr)) {
std::stringstream fortran;
fortran << *expr;
if (auto *msg{
@ -869,13 +869,13 @@ void ProcessParameterExpressions(
const TypeParamDetails &details{symbol.get<TypeParamDetails>()};
MaybeIntExpr expr;
ParamValue *paramValue{spec.FindParameter(name)};
if (paramValue == nullptr) {
if (!paramValue) {
expr = evaluate::Fold(foldingContext, common::Clone(details.init()));
} else if (paramValue->isExplicit()) {
expr = paramValue->GetExplicit();
}
if (expr.has_value()) {
if (paramValue != nullptr) {
if (expr) {
if (paramValue) {
paramValue->SetExplicit(std::move(*expr));
} else {
spec.AddParamValue(
@ -933,7 +933,7 @@ static Symbol &InstantiateSymbol(
}
details->ReplaceType(FindOrInstantiateDerivedType(
scope, std::move(newSpec), semanticsContext, origType->category()));
} else if (origType->AsIntrinsic() != nullptr) {
} else if (origType->AsIntrinsic()) {
details->ReplaceType(
InstantiateIntrinsicType(scope, *origType, semanticsContext));
} else if (origType->category() != DeclTypeSpec::ClassStar) {
@ -1160,7 +1160,7 @@ const Symbol *FindImmediateComponent(const DerivedTypeSpec &type,
parent = symbol;
}
}
if (parent != nullptr) {
if (parent) {
if (const auto *object{parent->detailsIf<ObjectEntityDetails>()}) {
if (const auto *type{object->type()}) {
if (const auto *derived{type->AsDerived()}) {

View file

@ -214,7 +214,7 @@ struct GetExprHelper {
return Get(x.value());
}
template<typename T> const SomeExpr *Get(const std::optional<T> &x) {
return x.has_value() ? Get(x.value()) : nullptr;
return x ? Get(*x) : nullptr;
}
template<typename T> const SomeExpr *Get(const T &x) {
if constexpr (ConstraintTrait<T>) {

View file

@ -1,4 +1,4 @@
// Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -41,7 +41,7 @@ void *CFI_address(
int CFI_allocate(CFI_cdesc_t *descriptor, const CFI_index_t lower_bounds[],
const CFI_index_t upper_bounds[], std::size_t elem_len) {
if (descriptor == nullptr) {
if (!descriptor) {
return CFI_INVALID_DESCRIPTOR;
}
if (descriptor->version != CFI_VERSION) {
@ -53,7 +53,7 @@ int CFI_allocate(CFI_cdesc_t *descriptor, const CFI_index_t lower_bounds[],
return CFI_INVALID_ATTRIBUTE;
}
if (descriptor->attribute == CFI_attribute_allocatable &&
descriptor->base_addr != nullptr) {
descriptor->base_addr) {
return CFI_ERROR_BASE_ADDR_NOT_NULL;
}
if (descriptor->rank > CFI_MAX_RANK) {
@ -82,7 +82,7 @@ int CFI_allocate(CFI_cdesc_t *descriptor, const CFI_index_t lower_bounds[],
byteSize *= extent;
}
void *p{new char[byteSize]};
if (p == nullptr) {
if (!p) {
return CFI_ERROR_MEM_ALLOCATION;
}
descriptor->base_addr = p;
@ -91,7 +91,7 @@ int CFI_allocate(CFI_cdesc_t *descriptor, const CFI_index_t lower_bounds[],
}
int CFI_deallocate(CFI_cdesc_t *descriptor) {
if (descriptor == nullptr) {
if (!descriptor) {
return CFI_INVALID_DESCRIPTOR;
}
if (descriptor->version != CFI_VERSION) {
@ -102,7 +102,7 @@ int CFI_deallocate(CFI_cdesc_t *descriptor) {
// Non-interoperable object
return CFI_INVALID_DESCRIPTOR;
}
if (descriptor->base_addr == nullptr) {
if (!descriptor->base_addr) {
return CFI_ERROR_BASE_ADDR_NULL;
}
delete[] static_cast<char *>(descriptor->base_addr);
@ -162,16 +162,16 @@ int CFI_establish(CFI_cdesc_t *descriptor, void *base_addr,
if (rank > CFI_MAX_RANK) {
return CFI_INVALID_RANK;
}
if (base_addr != nullptr && attribute == CFI_attribute_allocatable) {
if (base_addr && attribute == CFI_attribute_allocatable) {
return CFI_ERROR_BASE_ADDR_NOT_NULL;
}
if (rank > 0 && base_addr != nullptr && extents == nullptr) {
if (rank > 0 && base_addr && !extents) {
return CFI_INVALID_EXTENT;
}
if (type < CFI_type_signed_char || type > CFI_type_struct) {
return CFI_INVALID_TYPE;
}
if (descriptor == nullptr) {
if (!descriptor) {
return CFI_INVALID_DESCRIPTOR;
}
std::size_t minElemLen{MinElemLen(type)};
@ -189,7 +189,7 @@ int CFI_establish(CFI_cdesc_t *descriptor, void *base_addr,
descriptor->f18Addendum = 0;
std::size_t byteSize{elem_len};
constexpr std::size_t lower_bound{0};
if (base_addr != nullptr) {
if (base_addr) {
for (std::size_t j{0}; j < rank; ++j) {
descriptor->dim[j].lower_bound = lower_bound;
descriptor->dim[j].extent = extents[j];
@ -218,13 +218,13 @@ int CFI_section(CFI_cdesc_t *result, const CFI_cdesc_t *source,
CFI_index_t actualStride[CFI_MAX_RANK];
CFI_rank_t resRank{0};
if (result == nullptr || source == nullptr) {
if (!result || !source) {
return CFI_INVALID_DESCRIPTOR;
}
if (source->rank == 0) {
return CFI_INVALID_RANK;
}
if (IsAssumedSize(source) && upper_bounds == nullptr) {
if (IsAssumedSize(source) && !upper_bounds) {
return CFI_INVALID_DESCRIPTOR;
}
if ((result->type != source->type) ||
@ -234,7 +234,7 @@ int CFI_section(CFI_cdesc_t *result, const CFI_cdesc_t *source,
if (result->attribute == CFI_attribute_allocatable) {
return CFI_INVALID_ATTRIBUTE;
}
if (source->base_addr == nullptr) {
if (!source->base_addr) {
return CFI_ERROR_BASE_ADDR_NULL;
}
@ -244,9 +244,9 @@ int CFI_section(CFI_cdesc_t *result, const CFI_cdesc_t *source,
const CFI_dim_t &dim{source->dim[j]};
const CFI_index_t srcLB{dim.lower_bound};
const CFI_index_t srcUB{srcLB + dim.extent - 1};
const CFI_index_t lb{lower_bounds != nullptr ? lower_bounds[j] : srcLB};
const CFI_index_t ub{upper_bounds != nullptr ? upper_bounds[j] : srcUB};
const CFI_index_t stride{strides != nullptr ? strides[j] : 1};
const CFI_index_t lb{lower_bounds ? lower_bounds[j] : srcLB};
const CFI_index_t ub{upper_bounds ? upper_bounds[j] : srcUB};
const CFI_index_t stride{strides ? strides[j] : 1};
if (stride == 0 && lb != ub) {
return CFI_ERROR_OUT_OF_BOUNDS;
@ -285,7 +285,7 @@ int CFI_section(CFI_cdesc_t *result, const CFI_cdesc_t *source,
int CFI_select_part(CFI_cdesc_t *result, const CFI_cdesc_t *source,
std::size_t displacement, std::size_t elem_len) {
if (result == nullptr || source == nullptr) {
if (!result || !source) {
return CFI_INVALID_DESCRIPTOR;
}
if (result->rank != source->rank) {
@ -294,7 +294,7 @@ int CFI_select_part(CFI_cdesc_t *result, const CFI_cdesc_t *source,
if (result->attribute == CFI_attribute_allocatable) {
return CFI_INVALID_ATTRIBUTE;
}
if (source->base_addr == nullptr) {
if (!source->base_addr) {
return CFI_ERROR_BASE_ADDR_NULL;
}
if (IsAssumedSize(source)) {
@ -320,13 +320,13 @@ int CFI_select_part(CFI_cdesc_t *result, const CFI_cdesc_t *source,
int CFI_setpointer(CFI_cdesc_t *result, const CFI_cdesc_t *source,
const CFI_index_t lower_bounds[]) {
if (result == nullptr) {
if (!result) {
return CFI_INVALID_DESCRIPTOR;
}
if (result->attribute != CFI_attribute_pointer) {
return CFI_INVALID_ATTRIBUTE;
}
if (source == nullptr) {
if (!source) {
result->base_addr = nullptr;
return CFI_SUCCESS;
}
@ -339,17 +339,16 @@ int CFI_setpointer(CFI_cdesc_t *result, const CFI_cdesc_t *source,
if (source->elem_len != result->elem_len) {
return CFI_INVALID_ELEM_LEN;
}
if (source->base_addr == nullptr &&
source->attribute != CFI_attribute_pointer) {
if (!source->base_addr && source->attribute != CFI_attribute_pointer) {
return CFI_ERROR_BASE_ADDR_NULL;
}
if (IsAssumedSize(source)) {
return CFI_INVALID_DESCRIPTOR;
}
const bool copySrcLB{lower_bounds == nullptr};
const bool copySrcLB{!lower_bounds};
result->base_addr = source->base_addr;
if (source->base_addr != nullptr) {
if (source->base_addr) {
for (int j{0}; j < result->rank; ++j) {
result->dim[j].extent = source->dim[j].extent;
result->dim[j].sm = source->dim[j].sm;

View file

@ -1,4 +1,4 @@
// Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -86,7 +86,7 @@ public:
}
const Descriptor *GetDescriptor(const char *dtInstance) const {
if (staticDescriptor_ != nullptr) {
if (staticDescriptor_) {
return staticDescriptor_;
} else if (IsDescriptor()) {
return Locate<const Descriptor>(dtInstance);

View file

@ -1,4 +1,4 @@
// Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -61,7 +61,7 @@ void Descriptor::Establish(const DerivedType &dt, void *p, int rank,
dt.SizeInBytes(), rank, extent) == CFI_SUCCESS);
raw_.f18Addendum = true;
DescriptorAddendum *a{Addendum()};
CHECK(a != nullptr);
CHECK(a);
new (a) DescriptorAddendum{&dt};
}
@ -70,7 +70,7 @@ std::unique_ptr<Descriptor> Descriptor::Create(TypeCode t,
ISO::CFI_attribute_t attribute) {
std::size_t bytes{SizeInBytes(rank, true)};
Descriptor *result{reinterpret_cast<Descriptor *>(new char[bytes])};
CHECK(result != nullptr);
CHECK(result);
result->Establish(t, elementBytes, p, rank, extent, attribute, true);
return std::unique_ptr<Descriptor>{result};
}
@ -80,7 +80,7 @@ std::unique_ptr<Descriptor> Descriptor::Create(TypeCategory c, int kind,
ISO::CFI_attribute_t attribute) {
std::size_t bytes{SizeInBytes(rank, true)};
Descriptor *result{reinterpret_cast<Descriptor *>(new char[bytes])};
CHECK(result != nullptr);
CHECK(result);
result->Establish(c, kind, p, rank, extent, attribute, true);
return std::unique_ptr<Descriptor>{result};
}
@ -89,7 +89,7 @@ std::unique_ptr<Descriptor> Descriptor::Create(const DerivedType &dt, void *p,
int rank, const SubscriptValue *extent, ISO::CFI_attribute_t attribute) {
std::size_t bytes{SizeInBytes(rank, true, dt.lenParameters())};
Descriptor *result{reinterpret_cast<Descriptor *>(new char[bytes])};
CHECK(result != nullptr);
CHECK(result);
result->Establish(dt, p, rank, extent, attribute);
return std::unique_ptr<Descriptor>{result};
}
@ -119,14 +119,14 @@ int Descriptor::Allocate(
}
int Descriptor::Deallocate(bool finalize) {
if (raw_.base_addr != nullptr) {
if (raw_.base_addr) {
Destroy(static_cast<char *>(raw_.base_addr), finalize);
}
return ISO::CFI_deallocate(&raw_);
}
void Descriptor::Destroy(char *data, bool finalize) const {
if (data != nullptr) {
if (data) {
if (const DescriptorAddendum * addendum{Addendum()}) {
if (addendum->flags() & DescriptorAddendum::DoNotFinalize) {
finalize = false;

View file

@ -1,4 +1,4 @@
// Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -82,7 +82,7 @@ public:
const std::uint64_t &flags() const { return flags_; }
std::size_t LenParameters() const {
if (derivedType_ != nullptr) {
if (derivedType_) {
return derivedType_->lenParameters();
}
return 0;

View file

@ -1,4 +1,4 @@
// Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -74,7 +74,7 @@ std::unique_ptr<Descriptor> RESHAPE(const Descriptor &source,
// Extract and check the optional ORDER= argument, which must be a
// permutation of [1..resultRank].
int dimOrder[maxRank];
if (order != nullptr) {
if (order) {
CHECK(order->rank() == 1);
CHECK(order->type().IsInteger());
CHECK(order->GetDimension(0).Extent() == resultRank);
@ -97,7 +97,7 @@ std::unique_ptr<Descriptor> RESHAPE(const Descriptor &source,
const DerivedType *sourceDerivedType{
sourceAddendum ? sourceAddendum->derivedType() : nullptr};
std::unique_ptr<Descriptor> result;
if (sourceDerivedType != nullptr) {
if (sourceDerivedType) {
result = Descriptor::Create(*sourceDerivedType, nullptr, resultRank,
resultExtent, CFI_attribute_allocatable);
} else {
@ -106,9 +106,9 @@ std::unique_ptr<Descriptor> RESHAPE(const Descriptor &source,
CFI_attribute_allocatable); // TODO rearrange these arguments
}
DescriptorAddendum *resultAddendum{result->Addendum()};
CHECK(resultAddendum != nullptr);
CHECK(resultAddendum);
resultAddendum->flags() |= DescriptorAddendum::DoNotFinalize;
if (sourceDerivedType != nullptr) {
if (sourceDerivedType) {
std::size_t lenParameters{sourceDerivedType->lenParameters()};
for (std::size_t j{0}; j < lenParameters; ++j) {
resultAddendum->SetLenParameterValue(

View file

@ -213,7 +213,7 @@ std::string CompileFortran(
}
if ((!parsing.messages().empty() &&
(driver.warningsAreErrors || parsing.messages().AnyFatalError())) ||
!parsing.parseTree().has_value()) {
!parsing.parseTree()) {
std::cerr << driver.prefix << "could not parse " << path << '\n';
exitStatus = EXIT_FAILURE;
return {};

View file

@ -222,7 +222,7 @@ std::string CompileFortran(std::string path, Fortran::parser::Options options,
}
if ((!parsing.messages().empty() &&
(driver.warningsAreErrors || parsing.messages().AnyFatalError())) ||
!parsing.parseTree().has_value()) {
!parsing.parseTree()) {
std::cerr << driver.prefix << "could not parse " << path << '\n';
exitStatus = EXIT_FAILURE;
return {};
@ -291,7 +291,7 @@ std::string CompileFortran(std::string path, Fortran::parser::Options options,
Fortran::parser::TypedExprAsFortran unparseExpression{
[](std::ostream &o, const Fortran::evaluate::GenericExprWrapper &x) {
if (x.v.has_value()) {
if (x.v) {
o << *x.v;
} else {
o << "(bad expression)";