FLANG
prescan.h
1//===-- lib/Parser/prescan.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_PARSER_PRESCAN_H_
10#define FORTRAN_PARSER_PRESCAN_H_
11
12// Defines a fast Fortran source prescanning phase that implements some
13// character-level features of the language that can be inefficient to
14// support directly in a backtracking parser. This phase handles Fortran
15// line continuation, comment removal, card image margins, padding out
16// fixed form character literals on truncated card images, file
17// inclusion, and driving the Fortran source preprocessor.
18
19#include "flang/Parser/characters.h"
20#include "flang/Parser/message.h"
21#include "flang/Parser/provenance.h"
22#include "flang/Parser/token-sequence.h"
23#include "flang/Support/Fortran-features.h"
24#include <bitset>
25#include <optional>
26#include <string>
27#include <unordered_set>
28
29namespace Fortran::parser {
30
31class Messages;
32class Preprocessor;
33
34class Prescanner {
35public:
36 Prescanner(Messages &, CookedSource &, Preprocessor &,
38 Prescanner(
39 const Prescanner &, Preprocessor &, bool isNestedInIncludeDirective);
40 Prescanner(const Prescanner &) = delete;
41 Prescanner(Prescanner &&) = delete;
42
43 const AllSources &allSources() const { return allSources_; }
44 AllSources &allSources() { return allSources_; }
45 const Messages &messages() const { return messages_; }
46 Messages &messages() { return messages_; }
47 const Preprocessor &preprocessor() const { return preprocessor_; }
48 Preprocessor &preprocessor() { return preprocessor_; }
49 common::LanguageFeatureControl &features() { return features_; }
50
51 Prescanner &set_preprocessingOnly(bool yes) {
52 preprocessingOnly_ = yes;
53 return *this;
54 }
55 Prescanner &set_expandIncludeLines(bool yes) {
56 expandIncludeLines_ = yes;
57 return *this;
58 }
59 Prescanner &set_fixedForm(bool yes) {
60 inFixedForm_ = yes;
61 return *this;
62 }
63 Prescanner &set_encoding(Encoding code) {
64 encoding_ = code;
65 return *this;
66 }
67 Prescanner &set_fixedFormColumnLimit(int limit) {
68 fixedFormColumnLimit_ = limit;
69 return *this;
70 }
71
72 Prescanner &AddCompilerDirectiveSentinel(const std::string &);
73
74 void Prescan(ProvenanceRange);
75 void Statement();
76 void NextLine();
77
78 // Callbacks for use by Preprocessor.
79 bool IsAtEnd() const { return nextLine_ >= limit_; }
80 bool IsNextLinePreprocessorDirective() const;
81 TokenSequence TokenizePreprocessorDirective();
82 Provenance GetCurrentProvenance() const { return GetProvenance(at_); }
83
84 const char *IsCompilerDirectiveSentinel(const char *, std::size_t) const;
85 const char *IsCompilerDirectiveSentinel(CharBlock) const;
86 // 'first' is the sentinel, 'second' is beginning of payload
87 std::optional<std::pair<const char *, const char *>>
88 IsCompilerDirectiveSentinel(const char *p) const;
89
90 template <typename... A> Message &Say(A &&...a) {
91 return messages_.Say(std::forward<A>(a)...);
92 }
93 template <typename... A>
94 Message *Warn(common::UsageWarning warning, A &&...a) {
95 return messages_.Warn(false, features_, warning, std::forward<A>(a)...);
96 }
97 template <typename... A>
98 Message *Warn(common::LanguageFeature feature, A &&...a) {
99 return messages_.Warn(false, features_, feature, std::forward<A>(a)...);
100 }
101
102private:
103 struct LineClassification {
104 enum class Kind {
105 Comment,
106 ConditionalCompilationDirective,
107 IncludeDirective, // #include
108 DefinitionDirective, // #define & #undef
109 PreprocessorDirective,
110 IncludeLine, // Fortran INCLUDE
112 Source
113 };
114 LineClassification(Kind k, std::size_t po = 0, const char *s = nullptr)
115 : kind{k}, payloadOffset{po}, sentinel{s} {}
116 LineClassification(LineClassification &&) = default;
117 LineClassification &operator=(LineClassification &&) = default;
118 Kind kind;
119 std::size_t payloadOffset; // byte offset of content
120 const char *sentinel; // if it's a compiler directive
121 };
122
123 void BeginSourceLine(const char *at) {
124 at_ = at;
125 column_ = 1;
126 tabInCurrentLine_ = false;
127 }
128
129 void BeginSourceLineAndAdvance() {
130 BeginSourceLine(nextLine_);
131 NextLine();
132 }
133
134 void BeginStatementAndAdvance() {
135 BeginSourceLineAndAdvance();
136 slashInCurrentStatement_ = false;
137 preventHollerith_ = false;
138 parenthesisNesting_ = 0;
139 continuationLines_ = 0;
140 isPossibleMacroCall_ = false;
141 disableSourceContinuation_ = false;
142 }
143
144 Provenance GetProvenance(const char *sourceChar) const {
145 return startProvenance_ + (sourceChar - start_);
146 }
147
148 ProvenanceRange GetProvenanceRange(
149 const char *first, const char *afterLast) const {
150 std::size_t bytes = afterLast - first;
151 return {startProvenance_ + (first - start_), bytes};
152 }
153
154 void EmitChar(TokenSequence &tokens, char ch) {
155 tokens.PutNextTokenChar(ch, GetCurrentProvenance());
156 }
157
158 void EmitInsertedChar(TokenSequence &tokens, char ch) {
159 Provenance provenance{allSources_.CompilerInsertionProvenance(ch)};
160 tokens.PutNextTokenChar(ch, provenance);
161 }
162
163 char EmitCharAndAdvance(TokenSequence &tokens, char ch) {
164 EmitChar(tokens, ch);
165 NextChar();
166 return *at_;
167 }
168
169 bool InCompilerDirective() const { return directiveSentinel_ != nullptr; }
170 bool InOpenMPConditionalLine() const {
171 return directiveSentinel_ && directiveSentinel_[0] == '$' &&
172 !directiveSentinel_[1];
173 }
174 bool InOpenACCOrCUDAConditionalLine() const {
175 return directiveSentinel_ && directiveSentinel_[0] == '@' &&
176 ((directiveSentinel_[1] == 'a' && directiveSentinel_[2] == 'c' &&
177 directiveSentinel_[3] == 'c') ||
178 (directiveSentinel_[1] == 'c' && directiveSentinel_[2] == 'u' &&
179 directiveSentinel_[3] == 'f')) &&
180 directiveSentinel_[4] == '\0';
181 }
182 bool InConditionalLine() const {
183 return InOpenMPConditionalLine() || InOpenACCOrCUDAConditionalLine();
184 }
185 bool IsOpenMPDirective() const {
186 return directiveSentinel_ && std::strcmp(directiveSentinel_, "$omp") == 0;
187 }
188 bool InFixedFormSource() const {
189 return inFixedForm_ && !inPreprocessorDirective_ && !InCompilerDirective();
190 }
191
192 bool IsCComment(const char *p) const {
193 return p[0] == '/' && p[1] == '*' &&
194 (inPreprocessorDirective_ ||
195 (!inCharLiteral_ &&
196 features_.IsEnabled(
197 common::LanguageFeature::ClassicCComments)));
198 }
199
200 void CheckAndEmitLine(TokenSequence &, Provenance newlineProvenance);
201 void LabelField(TokenSequence &);
202 void EnforceStupidEndStatementRules(const TokenSequence &);
203 void SkipToEndOfLine();
204 bool MustSkipToEndOfLine() const;
205 void NextChar();
206 // True when input flowed to a continuation line
207 bool SkipToNextSignificantCharacter();
208 void SkipCComments();
209 void SkipSpaces();
210 static const char *SkipWhiteSpace(const char *);
211 const char *SkipWhiteSpaceIncludingEmptyMacros(const char *) const;
212 const char *SkipWhiteSpaceAndCComments(const char *) const;
213 const char *SkipCComment(const char *) const;
214 bool NextToken(TokenSequence &);
215 bool HandleExponent(TokenSequence &);
216 bool HandleKindSuffix(TokenSequence &);
217 bool HandleExponentAndOrKindSuffix(TokenSequence &);
218 void QuotedCharacterLiteral(TokenSequence &, const char *start);
219 void Hollerith(TokenSequence &, int count, const char *start);
220 bool PadOutCharacterLiteral(TokenSequence &);
221 bool SkipCommentLine(bool afterAmpersand);
222 bool IsFixedFormCommentLine(const char *) const;
223 const char *IsFreeFormComment(const char *) const;
224 std::optional<std::size_t> IsIncludeLine(const char *) const;
225 void FortranInclude(const char *quote);
226 const char *IsPreprocessorDirectiveLine(const char *) const;
227 const char *FixedFormContinuationLine(bool atNewline);
228 const char *FreeFormContinuationLine(bool ampersand);
229 bool IsImplicitContinuation() const;
230 bool FixedFormContinuation(bool atNewline);
231 bool FreeFormContinuation();
232 bool Continuation(bool mightNeedFixedFormSpace);
233 std::optional<LineClassification> IsFixedFormCompilerDirectiveLine(
234 const char *) const;
235 std::optional<LineClassification> IsFreeFormCompilerDirectiveLine(
236 const char *) const;
237 LineClassification ClassifyLine(const char *) const;
238 LineClassification ClassifyLine(
239 TokenSequence &, Provenance newlineProvenance) const;
240 bool SourceFormChange(std::string &&);
241 bool CompilerDirectiveContinuation(TokenSequence &, const char *sentinel);
242 bool SourceLineContinuation(TokenSequence &);
243
244 Messages &messages_;
245 CookedSource &cooked_;
246 Preprocessor &preprocessor_;
247 AllSources &allSources_;
249 bool preprocessingOnly_{false};
250 bool expandIncludeLines_{true};
251 bool isNestedInIncludeDirective_{false};
252 bool backslashFreeFormContinuation_{false};
253 bool inFixedForm_{false};
254 int fixedFormColumnLimit_{72};
255 Encoding encoding_{Encoding::UTF_8};
256 int parenthesisNesting_{0};
257 int prescannerNesting_{0};
258 int continuationLines_{0};
259 bool isPossibleMacroCall_{false};
260 bool afterPreprocessingDirective_{false};
261 bool disableSourceContinuation_{false};
262
263 Provenance startProvenance_;
264 const char *start_{nullptr}; // beginning of current source file content
265 const char *limit_{nullptr}; // first address after end of current source
266 const char *nextLine_{nullptr}; // next line to process; <= limit_
267 const char *directiveSentinel_{nullptr}; // current compiler directive
268
269 // These data members are state for processing the source line containing
270 // "at_", which goes to up to the newline character before "nextLine_".
271 const char *at_{nullptr}; // next character to process; < nextLine_
272 int column_{1}; // card image column position of next character
273 bool tabInCurrentLine_{false};
274 bool slashInCurrentStatement_{false};
275 bool preventHollerith_{false}; // CHARACTER*4HIMOM not Hollerith
276 bool inCharLiteral_{false};
277 bool continuationInCharLiteral_{false};
278 bool inPreprocessorDirective_{false};
279
280 // True after processing a continuation that can't be allowed
281 // to appear in the middle of an identifier token, but is fixed form,
282 // or is free form and doesn't have a space character handy to use as
283 // a separator when:
284 // a) (standard) doesn't begin with a leading '&' on the continuation
285 // line, but has a non-blank in column 1, or
286 // b) (extension) does have a leading '&', but didn't have one
287 // on the continued line.
288 bool brokenToken_{false};
289
290 // When a free form continuation marker (&) appears at the end of a line
291 // before a INCLUDE or #include, we delete it and omit the newline, so
292 // that the first line of the included file is truly a continuation of
293 // the line before. Also used when the & appears at the end of the last
294 // line in an include file.
295 bool omitNewline_{false};
296 bool skipLeadingAmpersand_{false};
297
298 const std::size_t firstCookedCharacterOffset_{cooked_.BufferedBytes()};
299
300 const Provenance spaceProvenance_{
301 allSources_.CompilerInsertionProvenance(' ')};
302 const Provenance backslashProvenance_{
303 allSources_.CompilerInsertionProvenance('\\')};
304
305 // To avoid probing the set of active compiler directive sentinel strings
306 // on every comment line, they're checked first with a cheap Bloom filter.
307 static const int prime1{1019}, prime2{1021};
308 std::bitset<prime2> compilerDirectiveBloomFilter_; // 128 bytes
309 std::unordered_set<std::string> compilerDirectiveSentinels_;
310};
311} // namespace Fortran::parser
312#endif // FORTRAN_PARSER_PRESCAN_H_
Definition Fortran-features.h:91
Definition provenance.h:139
Definition char-block.h:28
Definition provenance.h:233
Definition message.h:200
Definition message.h:332
Definition preprocessor.h:74
Definition provenance.h:52
Definition token-sequence.h:35
Definition check-expression.h:19
Definition parse-tree.h:3350