FLANG
Fortran-features.h
1//===-- include/flang/Support/Fortran-features.h ----------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef FORTRAN_SUPPORT_FORTRAN_FEATURES_H_
10#define FORTRAN_SUPPORT_FORTRAN_FEATURES_H_
11
12#include "Fortran.h"
13#include "flang/Common/enum-set.h"
14#include <string_view>
15#include <vector>
16
17namespace Fortran::common {
18
19// Non-conforming extensions & legacies
20ENUM_CLASS(LanguageFeature, BackslashEscapes, OldDebugLines,
21 FixedFormContinuationWithColumn1Ampersand, LogicalAbbreviations,
22 XOROperator, PunctuationInNames, OptionalFreeFormSpace, BOZExtensions,
23 EmptyStatement, AlternativeNE, ExecutionPartNamelist, DECStructures,
24 DoubleComplex, Byte, StarKind, ExponentMatchingKindParam, QuadPrecision,
25 SlashInitialization, TripletInArrayConstructor, MissingColons,
26 SignedComplexLiteral, OldStyleParameter, ComplexConstructor, PercentLOC,
27 SignedMultOperand, FileName, Carriagecontrol, Convert, Dispose,
28 IOListLeadingComma, AbbreviatedEditDescriptor, ProgramParentheses,
29 PercentRefAndVal, OmitFunctionDummies, CrayPointer, Hollerith, ArithmeticIF,
30 Assign, AssignedGOTO, Pause, OpenACC, OpenMP, CUDA, CruftAfterAmpersand,
31 ClassicCComments, AdditionalFormats, BigIntLiterals, RealDoControls,
32 EquivalenceNumericWithCharacter, EquivalenceNonDefaultNumeric,
33 EquivalenceSameNonSequence, AdditionalIntrinsics, AnonymousParents,
34 OldLabelDoEndStatements, LogicalIntegerAssignment, EmptySourceFile,
35 ProgramReturn, ImplicitNoneTypeNever, ImplicitNoneTypeAlways,
36 ImplicitNoneExternal, ForwardRefImplicitNone, OpenAccessAppend,
37 BOZAsDefaultInteger, DistinguishableSpecifics, DefaultSave,
38 PointerInSeqType, NonCharacterFormat, SaveMainProgram,
39 SaveBigMainProgramVariables, DistinctArrayConstructorLengths, PPCVector,
40 RelaxedIntentInChecking, ForwardRefImplicitNoneData,
41 NullActualForAllocatable, ActualIntegerConvertedToSmallerKind,
42 HollerithOrCharacterAsBOZ, BindingAsProcedure, StatementFunctionExtensions,
43 UseGenericIntrinsicWhenSpecificDoesntMatch, DataStmtExtensions,
44 RedundantContiguous, RedundantAttribute, InitBlankCommon,
45 EmptyBindCDerivedType, MiscSourceExtensions, AllocateToOtherLength,
46 LongNames, IntrinsicAsSpecific, BenignNameClash, BenignRedundancy,
47 NullMoldAllocatableComponentValue, NopassScalarBase, MiscUseExtensions,
48 ImpliedDoIndexScope, DistinctCommonSizes, OddIndexVariableRestrictions,
49 IndistinguishableSpecifics, SubroutineAndFunctionSpecifics,
50 EmptySequenceType, NonSequenceCrayPointee, BranchIntoConstruct,
51 BadBranchTarget, HollerithPolymorphic, ListDirectedSize,
52 NonBindCInteroperability, CudaManaged, CudaUnified,
53 PolymorphicActualAllocatableOrPointerToMonomorphicDummy, RelaxedPureDummy,
54 UndefinableAsynchronousOrVolatileActual, AutomaticInMainProgram, PrintCptr,
55 SavedLocalInSpecExpr, PrintNamelist, AssumedRankPassedToNonAssumedRank,
56 IgnoreIrrelevantAttributes, Unsigned, ContiguousOkForSeqAssociation,
57 ForwardRefExplicitTypeDummy, InaccessibleDeferredOverride,
58 CudaWarpMatchFunction, DoConcurrentOffload, TransferBOZ, Coarray,
59 PointerPassObject, MultipleIdenticalDATA,
60 DefaultStructConstructorNullPointer, AssumedRankIoItem,
61 MultipleProgramUnitsOnSameLine, AllocatedForAssociated,
62 OpenMPThreadprivateEquivalence, RelaxedCLocChecks, CudaPinned,
63 OpenAccDefaultNoneScalarsStrict, OpenACCMultipleNamesInRoutine,
64 EnumerationType, CUDAInit, PreferIntrinsicModuleUseAssociation,
65 MultipleCommonBlockInit, OutOfBoundsSubscripts)
66
67// Portability and suspicious usage warnings
68ENUM_CLASS(UsageWarning, Portability, PointerToUndefinable,
69 NonTargetPassedToTarget, PointerToPossibleNoncontiguous,
70 ShortCharacterActual, ShortArrayActual, ImplicitInterfaceActual,
71 PolymorphicTransferArg, PointerComponentTransferArg, TransferSizePresence,
72 F202XAllocatableBreakingChange, OptionalMustBePresent, CommonBlockPadding,
73 LogicalVsCBool, BindCCharLength, ProcDummyArgShapes, ExternalNameConflict,
74 FoldingException, FoldingAvoidsRuntimeCrash, FoldingValueChecks,
75 FoldingFailure, FoldingLimit, Interoperability, CharacterInteroperability,
76 Bounds, Preprocessing, Scanning, OpenAccUsage, ProcPointerCompatibility,
77 VoidMold, KnownBadImplicitInterface, EmptyCase, CaseOverflow, CUDAUsage,
78 IgnoreTKRUsage, ExternalInterfaceMismatch, DefinedOperatorArgs, Final,
79 ZeroDoStep, UnusedForallIndex, OpenMPUsage, DataLength, IgnoredDirective,
80 HomonymousSpecific, HomonymousResult, IgnoredIntrinsicFunctionType,
81 PreviousScalarUse, RedeclaredInaccessibleComponent, ImplicitShared,
82 IndexVarRedefinition, IncompatibleImplicitInterfaces,
83 VectorSubscriptFinalization, UndefinedFunctionResult, UselessIomsg,
84 MismatchingDummyProcedure, SubscriptedEmptyArray, UnsignedLiteralTruncation,
85 CompatibleDeclarationsFromDistinctModules, ConstantIsContiguous,
86 NullActualForDefaultIntentAllocatable, UseAssociationIntoSameNameSubprogram,
87 HostAssociatedIntentOutInSpecExpr, NonVolatilePointerToVolatile,
88 RealConstantWidening, VolatileOrAsynchronousTemporary, UnusedVariable,
89 UsedUndefinedVariable, BadValueInDeadCode, AssumedTypeSizeDummy,
90 MisplacedIgnoreTKR, NamelistParameter, ImpureFinalInPure,
91 IgnoredNoReallocateLHS, ExperimentalOption, IoImpliedDoIndexConflict,
92 BOZLiteralTruncation, IntentInActualForDefaultIntent)
93
96using LanguageFeatureOrWarning = std::variant<LanguageFeature, UsageWarning>;
97using LanguageControlFlag =
98 std::pair<LanguageFeatureOrWarning, /*shouldEnable=*/bool>;
99
100class LanguageFeatureControl {
101public:
102 LanguageFeatureControl();
103 LanguageFeatureControl(const LanguageFeatureControl &) = default;
104
105 void Enable(LanguageFeature f, bool yes = true) { disable_.set(f, !yes); }
106 void EnableWarning(LanguageFeature f, bool yes = true) {
107 warnLanguage_.set(f, yes);
108 }
109 void EnableWarning(UsageWarning w, bool yes = true) {
110 warnUsage_.set(w, yes);
111 }
112 void EnableWarning(LanguageFeatureOrWarning flag, bool yes = true) {
113 if (std::holds_alternative<LanguageFeature>(flag)) {
114 EnableWarning(std::get<LanguageFeature>(flag), yes);
115 } else {
116 EnableWarning(std::get<UsageWarning>(flag), yes);
117 }
118 }
119 void WarnOnAllNonstandard(bool yes = true);
120 bool IsWarnOnAllNonstandard() const { return warnAllLanguage_; }
121 void WarnOnAllUsage(bool yes = true);
122 bool IsWarnOnAllUsage() const { return warnAllUsage_; }
123 void DisableAllNonstandardWarnings() {
124 warnAllLanguage_ = false;
125 warnLanguage_.clear();
126 }
127 void DisableAllUsageWarnings() {
128 warnAllUsage_ = false;
129 warnUsage_.clear();
130 }
131 void DisableAllWarnings() {
132 disableAllWarnings_ = true;
133 DisableAllNonstandardWarnings();
134 DisableAllUsageWarnings();
135 }
136 bool AreWarningsDisabled() const { return disableAllWarnings_; }
137 bool IsEnabled(LanguageFeature f) const { return !disable_.test(f); }
138 bool ShouldWarn(LanguageFeature f) const { return warnLanguage_.test(f); }
139 bool ShouldWarn(UsageWarning w) const { return warnUsage_.test(w); }
140 // Cli options
141 // Find a warning by its Cli spelling, i.e. '[no-]warning-name'.
142 std::optional<LanguageControlFlag> FindWarning(std::string_view input);
143 // Take a string from the Cli and apply it to the LanguageFeatureControl.
144 // Return true if the option was recognized (and hence applied).
145 bool EnableWarning(std::string_view input);
146 // The add and replace functions are not currently used but are provided
147 // to allow a flexible many-to-one mapping from Cli spellings to enum values.
148 // Taking a string by value because the functions own this string after the
149 // call.
150 void AddAlternativeCliSpelling(LanguageFeature f, std::string input) {
151 cliOptions_.insert({input, {f}});
152 }
153 void AddAlternativeCliSpelling(UsageWarning w, std::string input) {
154 cliOptions_.insert({input, {w}});
155 }
156 void AddDeprecatedCliSpelling(LanguageFeature f,
157 const std::string &deprecated, const std::string &canonical) {
158 cliOptions_.insert({deprecated, {f}});
159 deprecatedCliOptions_.insert({deprecated, canonical});
160 }
161 void AddDeprecatedCliSpelling(UsageWarning w, const std::string &deprecated,
162 const std::string &canonical) {
163 cliOptions_.insert({deprecated, {w}});
164 deprecatedCliOptions_.insert({deprecated, canonical});
165 }
166 // Returns the canonical spelling if the input is a deprecated spelling.
167 std::optional<std::string_view> CheckDeprecatedSpelling(
168 std::string_view input) const;
169 void ReplaceCliCanonicalSpelling(LanguageFeature f, std::string input);
170 void ReplaceCliCanonicalSpelling(UsageWarning w, std::string input);
171 std::string_view getDefaultCliSpelling(LanguageFeature f) const {
172 return languageFeatureCliCanonicalSpelling_[EnumToInt(f)];
173 };
174 std::string_view getDefaultCliSpelling(UsageWarning w) const {
175 return usageWarningCliCanonicalSpelling_[EnumToInt(w)];
176 };
177 // Return all spellings of operators names, depending on features enabled
178 std::vector<const char *> GetNames(LogicalOperator) const;
179 std::vector<const char *> GetNames(RelationalOperator) const;
180
181private:
182 // Map from Cli syntax of language features and usage warnings to their enum
183 // values.
184 std::unordered_map<std::string, LanguageFeatureOrWarning> cliOptions_;
185 // Map from deprecated Cli spellings to their canonical replacements.
186 std::unordered_map<std::string, std::string> deprecatedCliOptions_;
187 // These two arrays map the enum values to their cannonical Cli spellings.
188 // Since each of the CanonicalSpelling is a string in the domain of the map
189 // above we just use a view of the string instead of another copy.
190 std::array<std::string, LanguageFeature_enumSize>
191 languageFeatureCliCanonicalSpelling_;
192 std::array<std::string, UsageWarning_enumSize>
193 usageWarningCliCanonicalSpelling_;
194 LanguageFeatures disable_;
195 LanguageFeatures warnLanguage_;
196 bool warnAllLanguage_{false};
197 UsageWarnings warnUsage_;
198 bool warnAllUsage_{false};
199 bool disableAllWarnings_{false};
200};
201} // namespace Fortran::common
202#endif // FORTRAN_SUPPORT_FORTRAN_FEATURES_H_
Definition enum-set.h:28
Definition bit-population-count.h:20