Debian Codegraph @

flang/lib/Parser/preprocessor.cpp

raw
1 //===-- lib/Parser/preprocessor.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "flang/Parser/preprocessor.h"
10
11 #include "prescan.h"
12 #include "flang/Common/idioms.h"
13 #include "flang/Parser/characters.h"
14 #include "flang/Parser/message.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include <algorithm>
18 #include <cinttypes>
19 #include <cstddef>
20 #include <ctime>
21 #include <map>
22 #include <memory>
23 #include <optional>
24 #include <set>
25 #include <utility>
26 #include <vector>
27
28 namespace Fortran::parser {
29
30 Definition::Definition(
31 const TokenSequence &repl, std::size_t firstToken, std::size_t tokens)
32 : replacement_{Tokenize({}, repl, firstToken, tokens)} {}
33
34 Definition::Definition(const std::vector<std::string> &argNames,
35 const TokenSequence &repl, std::size_t firstToken, std::size_t tokens,
36 bool isVariadic)
37 : isFunctionLike_{true}, isVariadic_{isVariadic}, argNames_{argNames},
38 replacement_{Tokenize(argNames, repl, firstToken, tokens)} {}
39
40 Definition::Definition(const std::string &predefined, AllSources &sources)
41 : isPredefined_{true},
42 replacement_{
43 predefined, sources.AddCompilerInsertion(predefined).start()} {}
44
45 bool Definition::set_isDisabled(bool disable) {
46 bool was{isDisabled_};
47 isDisabled_ = disable;
48 return was;
49 }
50
51 void Definition::Print(llvm::raw_ostream &out, const char *macroName) const {
52 if (!isFunctionLike_) {
53 // If it's not a function-like macro, then just print the replacement.
54 out << ' ' << replacement_.ToString();
55 return;
56 }
57
58 size_t argCount{argumentCount()};
59
60 out << '(';
61 for (size_t i{0}; i != argCount; ++i) {
62 if (i != 0) {
63 out << ", ";
64 }
65 out << argNames_[i];
66 }
67 if (isVariadic_) {
68 out << ", ...";
69 }
70 out << ") ";
71
72 for (size_t i{0}, e{replacement_.SizeInTokens()}; i != e; ++i) {
73 std::string tok{replacement_.TokenAt(i).ToString()};
74 if (size_t idx{GetArgumentIndex(tok)}; idx < argCount) {
75 out << argNames_[idx];
76 } else {
77 out << tok;
78 }
79 }
80 }
81
82 static bool IsLegalIdentifierStart(const CharBlock &cpl) {
83 return cpl.size() > 0 && IsLegalIdentifierStart(cpl[0]);
84 }
85
86 TokenSequence Definition::Tokenize(const std::vector<std::string> &argNames,
87 const TokenSequence &token, std::size_t firstToken, std::size_t tokens) {
88 std::map<std::string, std::string> args;
89 char argIndex{'A'};
90 for (const std::string &arg : argNames) {
91 CHECK(args.find(arg) == args.end());
92 args[arg] = "~"s + argIndex++;
93 }
94 TokenSequence result;
95 for (std::size_t j{0}; j < tokens; ++j) {
96 CharBlock tok{token.TokenAt(firstToken + j)};
97 if (IsLegalIdentifierStart(tok)) {
98 auto it{args.find(tok.ToString())};
99 if (it != args.end()) {
100 result.Put(it->second, token.GetTokenProvenance(j));
101 continue;
102 }
103 }
104 result.Put(token, firstToken + j, 1);
105 }
106 return result;
107 }
108
109 std::size_t Definition::GetArgumentIndex(const CharBlock &token) const {
110 if (token.size() >= 2 && token[0] == '~') {
111 return static_cast<size_t>(token[1] - 'A');
112 }
113 return argumentCount();
114 }
115
116 static TokenSequence Stringify(
117 const TokenSequence &tokens, AllSources &allSources) {
118 TokenSequence result;
119 Provenance quoteProvenance{allSources.CompilerInsertionProvenance('"')};
120 result.PutNextTokenChar('"', quoteProvenance);
121 for (std::size_t j{0}; j < tokens.SizeInTokens(); ++j) {
122 const CharBlock &token{tokens.TokenAt(j)};
123 std::size_t bytes{token.size()};
124 for (std::size_t k{0}; k < bytes; ++k) {
125 char ch{token[k]};
126 Provenance from{tokens.GetTokenProvenance(j, k)};
127 if (ch == '"' || ch == '\\') {
128 result.PutNextTokenChar(ch, from);
129 }
130 result.PutNextTokenChar(ch, from);
131 }
132 }
133 result.PutNextTokenChar('"', quoteProvenance);
134 result.CloseToken();
135 return result;
136 }
137
138 constexpr bool IsTokenPasting(CharBlock opr) {
139 return opr.size() == 2 && opr[0] == '#' && opr[1] == '#';
140 }
141
142 static bool AnyTokenPasting(const TokenSequence &text) {
143 std::size_t tokens{text.SizeInTokens()};
144 for (std::size_t j{0}; j < tokens; ++j) {
145 if (IsTokenPasting(text.TokenAt(j))) {
146 return true;
147 }
148 }
149 return false;
150 }
151
152 static TokenSequence TokenPasting(TokenSequence &&text) {
153 if (!AnyTokenPasting(text)) {
154 return std::move(text);
155 }
156 TokenSequence result;
157 std::size_t tokens{text.SizeInTokens()};
158 bool pasting{false};
159 for (std::size_t j{0}; j < tokens; ++j) {
160 if (IsTokenPasting(text.TokenAt(j))) {
161 if (!pasting) {
162 while (!result.empty() &&
163 result.TokenAt(result.SizeInTokens() - 1).IsBlank()) {
164 result.pop_back();
165 }
166 if (!result.empty()) {
167 result.ReopenLastToken();
168 pasting = true;
169 }
170 }
171 } else if (pasting && text.TokenAt(j).IsBlank()) {
172 } else {
173 result.Put(text, j, 1);
174 pasting = false;
175 }
176 }
177 return result;
178 }
179
180 TokenSequence Definition::Apply(
181 const std::vector<TokenSequence> &args, Prescanner &prescanner) {
182 TokenSequence result;
183 bool skipping{false};
184 int parenthesesNesting{0};
185 std::size_t tokens{replacement_.SizeInTokens()};
186 for (std::size_t j{0}; j < tokens; ++j) {
187 CharBlock token{replacement_.TokenAt(j)};
188 std::size_t bytes{token.size()};
189 if (skipping) {
190 char ch{token.OnlyNonBlank()};
191 if (ch == '(') {
192 ++parenthesesNesting;
193 } else if (ch == ')') {
194 if (parenthesesNesting > 0) {
195 --parenthesesNesting;
196 }
197 skipping = parenthesesNesting > 0;
198 }
199 continue;
200 }
201 if (bytes == 2 && token[0] == '~') { // argument substitution
202 std::size_t index{GetArgumentIndex(token)};
203 if (index >= args.size()) {
204 continue;
205 }
206 std::size_t prev{j};
207 while (prev > 0 && replacement_.TokenAt(prev - 1).IsBlank()) {
208 --prev;
209 }
210 if (prev > 0 && replacement_.TokenAt(prev - 1).size() == 1 &&
211 replacement_.TokenAt(prev - 1)[0] ==
212 '#') { // stringify argument without macro replacement
213 std::size_t resultSize{result.SizeInTokens()};
214 while (resultSize > 0 && result.TokenAt(resultSize - 1).IsBlank()) {
215 result.pop_back();
216 --resultSize;
217 }
218 CHECK(resultSize > 0 &&
219 result.TokenAt(resultSize - 1) == replacement_.TokenAt(prev - 1));
220 result.pop_back();
221 result.Put(Stringify(args[index], prescanner.allSources()));
222 } else {
223 const TokenSequence *arg{&args[index]};
224 std::optional<TokenSequence> replaced;
225 // Don't replace macros in the actual argument if it is preceded or
226 // followed by the token-pasting operator ## in the replacement text.
227 if (prev == 0 || !IsTokenPasting(replacement_.TokenAt(prev - 1))) {
228 auto next{replacement_.SkipBlanks(j + 1)};
229 if (next >= tokens || !IsTokenPasting(replacement_.TokenAt(next))) {
230 // Apply macro replacement to the actual argument
231 replaced =
232 prescanner.preprocessor().MacroReplacement(*arg, prescanner);
233 if (replaced) {
234 arg = &*replaced;
235 }
236 }
237 }
238 result.Put(DEREF(arg));
239 }
240 } else if (bytes == 11 && isVariadic_ &&
241 token.ToString() == "__VA_ARGS__") {
242 Provenance commaProvenance{
243 prescanner.preprocessor().allSources().CompilerInsertionProvenance(
244 ',')};
245 for (std::size_t k{argumentCount()}; k < args.size(); ++k) {
246 if (k > argumentCount()) {
247 result.Put(","s, commaProvenance);
248 }
249 result.Put(args[k]);
250 }
251 } else if (bytes == 10 && isVariadic_ && token.ToString() == "__VA_OPT__" &&
252 j + 2 < tokens && replacement_.TokenAt(j + 1).OnlyNonBlank() == '(' &&
253 parenthesesNesting == 0) {
254 parenthesesNesting = 1;
255 skipping = args.size() == argumentCount();
256 ++j;
257 } else {
258 if (parenthesesNesting > 0) {
259 char ch{token.OnlyNonBlank()};
260 if (ch == '(') {
261 ++parenthesesNesting;
262 } else if (ch == ')') {
263 if (--parenthesesNesting == 0) {
264 skipping = false;
265 continue;
266 }
267 }
268 }
269 result.Put(replacement_, j);
270 }
271 }
272 return TokenPasting(std::move(result));
273 }
274
275 static std::string FormatTime(const std::time_t &now, const char *format) {
276 char buffer[16];
277 return {buffer,
278 std::strftime(buffer, sizeof buffer, format, std::localtime(&now))};
279 }
280
281 Preprocessor::Preprocessor(AllSources &allSources) : allSources_{allSources} {}
282
283 void Preprocessor::DefineStandardMacros() {
284 // Capture current local date & time once now to avoid having the values
285 // of __DATE__ or __TIME__ change during compilation.
286 std::time_t now;
287 std::time(&now);
288 Define("__DATE__"s, FormatTime(now, "\"%h %e %Y\"")); // e.g., "Jun 16 1904"
289 Define("__TIME__"s, FormatTime(now, "\"%T\"")); // e.g., "23:59:60"
290 // The values of these predefined macros depend on their invocation sites.
291 Define("__FILE__"s, "__FILE__"s);
292 Define("__LINE__"s, "__LINE__"s);
293 Define("__TIMESTAMP__"s, "__TIMESTAMP__"s);
294 }
295
296 void Preprocessor::Define(const std::string &macro, const std::string &value) {
297 definitions_.emplace(SaveTokenAsName(macro), Definition{value, allSources_});
298 }
299
300 void Preprocessor::Undefine(std::string macro) { definitions_.erase(macro); }
301
302 std::optional<TokenSequence> Preprocessor::MacroReplacement(
303 const TokenSequence &input, Prescanner &prescanner,
304 std::optional<std::size_t> *partialFunctionLikeMacro) {
305 // Do quick scan for any use of a defined name.
306 if (definitions_.empty()) {
307 return std::nullopt;
308 }
309 std::size_t tokens{input.SizeInTokens()};
310 std::size_t j{0};
311 for (; j < tokens; ++j) {
312 CharBlock token{input.TokenAt(j)};
313 if (!token.empty() && IsLegalIdentifierStart(token[0]) &&
314 IsNameDefined(token)) {
315 break;
316 }
317 }
318 if (j == tokens) {
319 return std::nullopt; // input contains nothing that would be replaced
320 }
321 TokenSequence result{input, 0, j};
322
323 // After rescanning after macro replacement has failed due to an unclosed
324 // function-like macro call (no left parenthesis yet, or no closing
325 // parenthesis), if tokens remain in the input, append them to the
326 // replacement text and attempt to proceed. Otherwise, return, so that
327 // the caller may try again with remaining tokens in its input.
328 auto CompleteFunctionLikeMacro{
329 [this, &input, &prescanner, &result, &partialFunctionLikeMacro](
330 std::size_t after, const TokenSequence &replacement,
331 std::size_t pFLMOffset) {
332 if (after < input.SizeInTokens()) {
333 result.Put(replacement, 0, pFLMOffset);
334 TokenSequence suffix;
335 suffix.Put(
336 replacement, pFLMOffset, replacement.SizeInTokens() - pFLMOffset);
337 suffix.Put(input, after, input.SizeInTokens() - after);
338 auto further{
339 ReplaceMacros(suffix, prescanner, partialFunctionLikeMacro)};
340 if (partialFunctionLikeMacro && *partialFunctionLikeMacro) {
341 // still not closed
342 **partialFunctionLikeMacro += result.SizeInTokens();
343 }
344 result.Put(further);
345 return true;
346 } else {
347 if (partialFunctionLikeMacro) {
348 *partialFunctionLikeMacro = pFLMOffset + result.SizeInTokens();
349 }
350 return false;
351 }
352 }};
353
354 for (; j < tokens; ++j) {
355 CharBlock token{input.TokenAt(j)};
356 if (token.IsBlank() || !IsLegalIdentifierStart(token[0])) {
357 result.Put(input, j);
358 continue;
359 }
360 auto it{definitions_.find(token)};
361 if (it == definitions_.end()) {
362 result.Put(input, j);
363 continue;
364 }
365 Definition *def{&it->second};
366 if (def->isDisabled()) {
367 result.Put(input, j);
368 continue;
369 }
370 if (!def->isFunctionLike()) {
371 if (def->isPredefined() && !def->replacement().empty()) {
372 std::string repl;
373 std::string name{def->replacement().TokenAt(0).ToString()};
374 if (name == "__FILE__") {
375 repl = "\""s +
376 allSources_.GetPath(prescanner.GetCurrentProvenance()) + '"';
377 } else if (name == "__LINE__") {
378 std::string buf;
379 llvm::raw_string_ostream ss{buf};
380 ss << allSources_.GetLineNumber(prescanner.GetCurrentProvenance());
381 repl = ss.str();
382 } else if (name == "__TIMESTAMP__") {
383 auto path{allSources_.GetPath(
384 prescanner.GetCurrentProvenance(), /*topLevel=*/true)};
385 llvm::sys::fs::file_status status;
386 repl = "??? ??? ?? ??:??:?? ????";
387 if (!llvm::sys::fs::status(path, status)) {
388 auto modTime{llvm::sys::toTimeT(status.getLastModificationTime())};
389 if (std::string time{std::asctime(std::localtime(&modTime))};
390 time.size() > 1 && time[time.size() - 1] == '\n') {
391 time.erase(time.size() - 1); // clip terminal '\n'
392 repl = "\""s + time + '"';
393 }
394 }
395 }
396 if (!repl.empty()) {
397 ProvenanceRange insert{allSources_.AddCompilerInsertion(repl)};
398 ProvenanceRange call{allSources_.AddMacroCall(
399 insert, input.GetTokenProvenanceRange(j), repl)};
400 result.Put(repl, call.start());
401 continue;
402 }
403 }
404 std::optional<std::size_t> partialFLM;
405 def->set_isDisabled(true);
406 TokenSequence replaced{TokenPasting(
407 ReplaceMacros(def->replacement(), prescanner, &partialFLM))};
408 def->set_isDisabled(false);
409 if (partialFLM &&
410 CompleteFunctionLikeMacro(j + 1, replaced, *partialFLM)) {
411 return result;
412 }
413 if (!replaced.empty()) {
414 ProvenanceRange from{def->replacement().GetProvenanceRange()};
415 ProvenanceRange use{input.GetTokenProvenanceRange(j)};
416 ProvenanceRange newRange{
417 allSources_.AddMacroCall(from, use, replaced.ToString())};
418 result.Put(replaced, newRange);
419 }
420 } else {
421 // Possible function-like macro call. Skip spaces and newlines to see
422 // whether '(' is next.
423 std::size_t k{j};
424 bool leftParen{false};
425 while (++k < tokens) {
426 const CharBlock &lookAhead{input.TokenAt(k)};
427 if (!lookAhead.IsBlank() && lookAhead[0] != '\n') {
428 leftParen = lookAhead[0] == '(' && lookAhead.size() == 1;
429 break;
430 }
431 }
432 if (!leftParen) {
433 if (partialFunctionLikeMacro) {
434 *partialFunctionLikeMacro = result.SizeInTokens();
435 result.Put(input, j, tokens - j);
436 return result;
437 } else {
438 result.Put(input, j);
439 continue;
440 }
441 }
442 std::vector<std::size_t> argStart{++k};
443 for (int nesting{0}; k < tokens; ++k) {
444 CharBlock token{input.TokenAt(k)};
445 char ch{token.OnlyNonBlank()};
446 if (ch == '(') {
447 ++nesting;
448 } else if (ch == ')') {
449 if (nesting == 0) {
450 break;
451 }
452 --nesting;
453 } else if (ch == ',' && nesting == 0) {
454 argStart.push_back(k + 1);
455 }
456 }
457 if (argStart.size() == 1 && k == argStart[0] &&
458 def->argumentCount() == 0) {
459 // Subtle: () is zero arguments, not one empty argument,
460 // unless one argument was expected.
461 argStart.clear();
462 }
463 if (k >= tokens && partialFunctionLikeMacro) {
464 *partialFunctionLikeMacro = result.SizeInTokens();
465 result.Put(input, j, tokens - j);
466 return result;
467 } else if (k >= tokens || argStart.size() < def->argumentCount() ||
468 (argStart.size() > def->argumentCount() && !def->isVariadic())) {
469 result.Put(input, j);
470 continue;
471 }
472 std::vector<TokenSequence> args;
473 for (std::size_t n{0}; n < argStart.size(); ++n) {
474 std::size_t at{argStart[n]};
475 std::size_t count{
476 (n + 1 == argStart.size() ? k : argStart[n + 1] - 1) - at};
477 args.emplace_back(TokenSequence(input, at, count));
478 }
479 TokenSequence applied{def->Apply(args, prescanner)};
480 std::optional<std::size_t> partialFLM;
481 def->set_isDisabled(true);
482 TokenSequence replaced{
483 ReplaceMacros(std::move(applied), prescanner, &partialFLM)};
484 def->set_isDisabled(false);
485 if (partialFLM &&
486 CompleteFunctionLikeMacro(k + 1, replaced, *partialFLM)) {
487 return result;
488 }
489 if (!replaced.empty()) {
490 ProvenanceRange from{def->replacement().GetProvenanceRange()};
491 ProvenanceRange use{input.GetIntervalProvenanceRange(j, k - j)};
492 ProvenanceRange newRange{
493 allSources_.AddMacroCall(from, use, replaced.ToString())};
494 result.Put(replaced, newRange);
495 }
496 j = k; // advance to the terminal ')'
497 }
498 }
499 return result;
500 }
501
502 TokenSequence Preprocessor::ReplaceMacros(const TokenSequence &tokens,
503 Prescanner &prescanner,
504 std::optional<std::size_t> *partialFunctionLikeMacro) {
505 if (std::optional<TokenSequence> repl{
506 MacroReplacement(tokens, prescanner, partialFunctionLikeMacro)}) {
507 return std::move(*repl);
508 }
509 return tokens;
510 }
511
512 void Preprocessor::Directive(const TokenSequence &dir, Prescanner &prescanner) {
513 std::size_t tokens{dir.SizeInTokens()};
514 std::size_t j{dir.SkipBlanks(0)};
515 if (j == tokens) {
516 return;
517 }
518 if (dir.TokenAt(j).ToString() != "#") {
519 prescanner.Say(dir.GetTokenProvenanceRange(j), "missing '#'"_err_en_US);
520 return;
521 }
522 j = dir.SkipBlanks(j + 1);
523 while (tokens > 0 && dir.TokenAt(tokens - 1).IsBlank()) {
524 --tokens;
525 }
526 if (j == tokens) {
527 return;
528 }
529 if (IsDecimalDigit(dir.TokenAt(j)[0]) || dir.TokenAt(j)[0] == '"') {
530 LineDirective(dir, j, prescanner);
531 return;
532 }
533 std::size_t dirOffset{j};
534 std::string dirName{ToLowerCaseLetters(dir.TokenAt(dirOffset).ToString())};
535 j = dir.SkipBlanks(j + 1);
536 CharBlock nameToken;
537 if (j < tokens && IsLegalIdentifierStart(dir.TokenAt(j)[0])) {
538 nameToken = dir.TokenAt(j);
539 }
540 if (dirName == "line") {
541 LineDirective(dir, j, prescanner);
542 } else if (dirName == "define") {
543 if (nameToken.empty()) {
544 prescanner.Say(dir.GetTokenProvenanceRange(j < tokens ? j : tokens - 1),
545 "#define: missing or invalid name"_err_en_US);
546 return;
547 }
548 nameToken = SaveTokenAsName(nameToken);
549 definitions_.erase(nameToken);
550 if (++j < tokens && dir.TokenAt(j).OnlyNonBlank() == '(') {
551 j = dir.SkipBlanks(j + 1);
552 std::vector<std::string> argName;
553 bool isVariadic{false};
554 if (dir.TokenAt(j).OnlyNonBlank() != ')') {
555 while (true) {
556 std::string an{dir.TokenAt(j).ToString()};
557 if (an == "...") {
558 isVariadic = true;
559 } else {
560 if (an.empty() || !IsLegalIdentifierStart(an[0])) {
561 prescanner.Say(dir.GetTokenProvenanceRange(j),
562 "#define: missing or invalid argument name"_err_en_US);
563 return;
564 }
565 argName.push_back(an);
566 }
567 j = dir.SkipBlanks(j + 1);
568 if (j == tokens) {
569 prescanner.Say(dir.GetTokenProvenanceRange(tokens - 1),
570 "#define: malformed argument list"_err_en_US);
571 return;
572 }
573 char punc{dir.TokenAt(j).OnlyNonBlank()};
574 if (punc == ')') {
575 break;
576 }
577 if (isVariadic || punc != ',') {
578 prescanner.Say(dir.GetTokenProvenanceRange(j),
579 "#define: malformed argument list"_err_en_US);
580 return;
581 }
582 j = dir.SkipBlanks(j + 1);
583 if (j == tokens) {
584 prescanner.Say(dir.GetTokenProvenanceRange(tokens - 1),
585 "#define: malformed argument list"_err_en_US);
586 return;
587 }
588 }
589 if (std::set<std::string>(argName.begin(), argName.end()).size() !=
590 argName.size()) {
591 prescanner.Say(dir.GetTokenProvenance(dirOffset),
592 "#define: argument names are not distinct"_err_en_US);
593 return;
594 }
595 }
596 j = dir.SkipBlanks(j + 1);
597 definitions_.emplace(std::make_pair(
598 nameToken, Definition{argName, dir, j, tokens - j, isVariadic}));
599 } else {
600 j = dir.SkipBlanks(j + 1);
601 definitions_.emplace(
602 std::make_pair(nameToken, Definition{dir, j, tokens - j}));
603 }
604 } else if (dirName == "undef") {
605 if (nameToken.empty()) {
606 prescanner.Say(
607 dir.GetIntervalProvenanceRange(dirOffset, tokens - dirOffset),
608 "# missing or invalid name"_err_en_US);
609 } else {
610 if (dir.IsAnythingLeft(++j)) {
611 if (prescanner.features().ShouldWarn(
612 common::UsageWarning::Portability)) {
613 prescanner.Say(dir.GetIntervalProvenanceRange(j, tokens - j),
614 "#undef: excess tokens at end of directive"_port_en_US);
615 }
616 } else {
617 definitions_.erase(nameToken);
618 }
619 }
620 } else if (dirName == "ifdef" || dirName == "ifndef") {
621 bool doThen{false};
622 if (nameToken.empty()) {
623 prescanner.Say(
624 dir.GetIntervalProvenanceRange(dirOffset, tokens - dirOffset),
625 "#%s: missing name"_err_en_US, dirName);
626 } else {
627 if (dir.IsAnythingLeft(++j)) {
628 if (prescanner.features().ShouldWarn(
629 common::UsageWarning::Portability)) {
630 prescanner.Say(dir.GetIntervalProvenanceRange(j, tokens - j),
631 "#%s: excess tokens at end of directive"_port_en_US, dirName);
632 }
633 }
634 doThen = IsNameDefined(nameToken) == (dirName == "ifdef");
635 }
636 if (doThen) {
637 ifStack_.push(CanDeadElseAppear::Yes);
638 } else {
639 SkipDisabledConditionalCode(dirName, IsElseActive::Yes, prescanner,
640 dir.GetTokenProvenance(dirOffset));
641 }
642 } else if (dirName == "if") {
643 if (IsIfPredicateTrue(dir, j, tokens - j, prescanner)) {
644 ifStack_.push(CanDeadElseAppear::Yes);
645 } else {
646 SkipDisabledConditionalCode(dirName, IsElseActive::Yes, prescanner,
647 dir.GetTokenProvenanceRange(dirOffset));
648 }
649 } else if (dirName == "else") {
650 if (dir.IsAnythingLeft(j)) {
651 if (prescanner.features().ShouldWarn(common::UsageWarning::Portability)) {
652 prescanner.Say(dir.GetIntervalProvenanceRange(j, tokens - j),
653 "#else: excess tokens at end of directive"_port_en_US);
654 }
655 } else if (ifStack_.empty()) {
656 prescanner.Say(dir.GetTokenProvenanceRange(dirOffset),
657 "#else: not nested within #if, #ifdef, or #ifndef"_err_en_US);
658 } else if (ifStack_.top() != CanDeadElseAppear::Yes) {
659 prescanner.Say(dir.GetTokenProvenanceRange(dirOffset),
660 "#else: already appeared within this #if, #ifdef, or #ifndef"_err_en_US);
661 } else {
662 ifStack_.pop();
663 SkipDisabledConditionalCode("else", IsElseActive::No, prescanner,
664 dir.GetTokenProvenanceRange(dirOffset));
665 }
666 } else if (dirName == "elif") {
667 if (ifStack_.empty()) {
668 prescanner.Say(dir.GetTokenProvenanceRange(dirOffset),
669 "#elif: not nested within #if, #ifdef, or #ifndef"_err_en_US);
670 } else if (ifStack_.top() != CanDeadElseAppear::Yes) {
671 prescanner.Say(dir.GetTokenProvenanceRange(dirOffset),
672 "#elif: #else previously appeared within this #if, #ifdef, or #ifndef"_err_en_US);
673 } else {
674 ifStack_.pop();
675 SkipDisabledConditionalCode("elif", IsElseActive::No, prescanner,
676 dir.GetTokenProvenanceRange(dirOffset));
677 }
678 } else if (dirName == "endif") {
679 if (dir.IsAnythingLeft(j)) {
680 if (prescanner.features().ShouldWarn(common::UsageWarning::Portability)) {
681 prescanner.Say(dir.GetIntervalProvenanceRange(j, tokens - j),
682 "#endif: excess tokens at end of directive"_port_en_US);
683 }
684 } else if (ifStack_.empty()) {
685 prescanner.Say(dir.GetTokenProvenanceRange(dirOffset),
686 "#endif: no #if, #ifdef, or #ifndef"_err_en_US);
687 } else {
688 ifStack_.pop();
689 }
690 } else if (dirName == "error") {
691 prescanner.Say(
692 dir.GetIntervalProvenanceRange(dirOffset, tokens - dirOffset),
693 "%s"_err_en_US, dir.ToString());
694 } else if (dirName == "warning") {
695 prescanner.Say(
696 dir.GetIntervalProvenanceRange(dirOffset, tokens - dirOffset),
697 "%s"_warn_en_US, dir.ToString());
698 } else if (dirName == "comment" || dirName == "note") {
699 prescanner.Say(
700 dir.GetIntervalProvenanceRange(dirOffset, tokens - dirOffset),
701 "%s"_en_US, dir.ToString());
702 } else if (dirName == "include") {
703 if (j == tokens) {
704 prescanner.Say(
705 dir.GetIntervalProvenanceRange(dirOffset, tokens - dirOffset),
706 "#include: missing name of file to include"_err_en_US);
707 return;
708 }
709 std::optional<std::string> prependPath;
710 TokenSequence path{dir, j, tokens - j};
711 std::string include{path.TokenAt(0).ToString()};
712 if (include != "<" && include.substr(0, 1) != "\"" &&
713 include.substr(0, 1) != "'") {
714 path = ReplaceMacros(path, prescanner);
715 include = path.empty() ? ""s : path.TokenAt(0).ToString();
716 }
717 auto pathTokens{path.SizeInTokens()};
718 std::size_t k{0};
719 if (include == "<") { // #include <foo>
720 k = 1;
721 if (k >= pathTokens) {
722 prescanner.Say(dir.GetIntervalProvenanceRange(j, pathTokens),
723 "#include: file name missing"_err_en_US);
724 return;
725 }
726 while (k < pathTokens && path.TokenAt(k) != ">") {
727 ++k;
728 }
729 if (k >= pathTokens) {
730 if (prescanner.features().ShouldWarn(
731 common::UsageWarning::Portability)) {
732 prescanner.Say(dir.GetIntervalProvenanceRange(j, tokens - j),
733 "#include: expected '>' at end of included file"_port_en_US);
734 }
735 }
736 TokenSequence braced{path, 1, k - 1};
737 include = braced.ToString();
738 } else if ((include.substr(0, 1) == "\"" || include.substr(0, 1) == "'") &&
739 include.front() == include.back()) {
740 // #include "foo" and #include 'foo'
741 include = include.substr(1, include.size() - 2);
742 // Start search in directory of file containing the directive
743 auto prov{dir.GetTokenProvenanceRange(dirOffset).start()};
744 if (const auto *currentFile{allSources_.GetSourceFile(prov)}) {
745 prependPath = DirectoryName(currentFile->path());
746 }
747 } else {
748 prescanner.Say(dir.GetTokenProvenanceRange(j < tokens ? j : tokens - 1),
749 "#include %s: expected name of file to include"_err_en_US,
750 path.ToString());
751 return;
752 }
753 if (include.empty()) {
754 prescanner.Say(dir.GetTokenProvenanceRange(dirOffset),
755 "#include %s: empty include file name"_err_en_US, path.ToString());
756 return;
757 }
758 k = path.SkipBlanks(k + 1);
759 if (k < pathTokens && path.TokenAt(k).ToString() != "!") {
760 if (prescanner.features().ShouldWarn(common::UsageWarning::Portability)) {
761 prescanner.Say(dir.GetIntervalProvenanceRange(j, tokens - j),
762 "#include: extra stuff ignored after file name"_port_en_US);
763 }
764 }
765 std::string buf;
766 llvm::raw_string_ostream error{buf};
767 if (const SourceFile *
768 included{allSources_.Open(include, error, std::move(prependPath))}) {
769 if (included->bytes() > 0) {
770 ProvenanceRange fileRange{
771 allSources_.AddIncludedFile(*included, dir.GetProvenanceRange())};
772 Prescanner{prescanner, /*isNestedInIncludeDirective=*/true}
773 .set_encoding(included->encoding())
774 .Prescan(fileRange);
775 }
776 } else {
777 prescanner.Say(dir.GetTokenProvenanceRange(j), "#include: %s"_err_en_US,
778 error.str());
779 }
780 } else {
781 prescanner.Say(dir.GetTokenProvenanceRange(dirOffset),
782 "#%s: unknown or unimplemented directive"_err_en_US, dirName);
783 }
784 }
785
786 void Preprocessor::PrintMacros(llvm::raw_ostream &out) const {
787 // std::set is ordered. Use that to print the macros in an
788 // alphabetical order.
789 std::set<std::string> macroNames;
790 for (const auto &[name, _] : definitions_) {
791 macroNames.insert(name.ToString());
792 }
793
794 for (const std::string &name : macroNames) {
795 out << "#define " << name;
796 definitions_.at(name).Print(out, name.c_str());
797 out << '\n';
798 }
799 }
800
801 CharBlock Preprocessor::SaveTokenAsName(const CharBlock &t) {
802 names_.push_back(t.ToString());
803 return {names_.back().data(), names_.back().size()};
804 }
805
806 bool Preprocessor::IsNameDefined(const CharBlock &token) {
807 return definitions_.find(token) != definitions_.end();
808 }
809
810 bool Preprocessor::IsFunctionLikeDefinition(const CharBlock &token) {
811 auto it{definitions_.find(token)};
812 return it != definitions_.end() && it->second.isFunctionLike();
813 }
814
815 static std::string GetDirectiveName(
816 const TokenSequence &line, std::size_t *rest) {
817 std::size_t tokens{line.SizeInTokens()};
818 std::size_t j{line.SkipBlanks(0)};
819 if (j == tokens || line.TokenAt(j).ToString() != "#") {
820 *rest = tokens;
821 return "";
822 }
823 j = line.SkipBlanks(j + 1);
824 if (j == tokens) {
825 *rest = tokens;
826 return "";
827 }
828 *rest = line.SkipBlanks(j + 1);
829 return ToLowerCaseLetters(line.TokenAt(j).ToString());
830 }
831
832 void Preprocessor::SkipDisabledConditionalCode(const std::string &dirName,
833 IsElseActive isElseActive, Prescanner &prescanner,
834 ProvenanceRange provenanceRange) {
835 int nesting{0};
836 while (!prescanner.IsAtEnd()) {
837 if (!prescanner.IsNextLinePreprocessorDirective()) {
838 prescanner.NextLine();
839 continue;
840 }
841 TokenSequence line{prescanner.TokenizePreprocessorDirective()};
842 std::size_t rest{0};
843 std::string dn{GetDirectiveName(line, &rest)};
844 if (dn == "ifdef" || dn == "ifndef" || dn == "if") {
845 ++nesting;
846 } else if (dn == "endif") {
847 if (nesting-- == 0) {
848 return;
849 }
850 } else if (isElseActive == IsElseActive::Yes && nesting == 0) {
851 if (dn == "else") {
852 ifStack_.push(CanDeadElseAppear::No);
853 return;
854 }
855 if (dn == "elif" &&
856 IsIfPredicateTrue(
857 line, rest, line.SizeInTokens() - rest, prescanner)) {
858 ifStack_.push(CanDeadElseAppear::Yes);
859 return;
860 }
861 }
862 }
863 prescanner.Say(provenanceRange, "#%s: missing #endif"_err_en_US, dirName);
864 }
865
866 // Precedence level codes used here to accommodate mixed Fortran and C:
867 // 15: parentheses and constants, logical !, bitwise ~
868 // 14: unary + and -
869 // 13: **
870 // 12: *, /, % (modulus)
871 // 11: + and -
872 // 10: << and >>
873 // 9: bitwise &
874 // 8: bitwise ^
875 // 7: bitwise |
876 // 6: relations (.EQ., ==, &c.)
877 // 5: .NOT.
878 // 4: .AND., &&
879 // 3: .OR., ||
880 // 2: .EQV. and .NEQV. / .XOR.
881 // 1: ? :
882 // 0: ,
883 static std::int64_t ExpressionValue(const TokenSequence &token,
884 int minimumPrecedence, std::size_t *atToken,
885 std::optional<Message> *error) {
886 enum Operator {
887 PARENS,
888 CONST,
889 NOTZERO, // !
890 COMPLEMENT, // ~
891 UPLUS,
892 UMINUS,
893 POWER,
894 TIMES,
895 DIVIDE,
896 MODULUS,
897 ADD,
898 SUBTRACT,
899 LEFTSHIFT,
900 RIGHTSHIFT,
901 BITAND,
902 BITXOR,
903 BITOR,
904 LT,
905 LE,
906 EQ,
907 NE,
908 GE,
909 GT,
910 NOT,
911 AND,
912 OR,
913 EQV,
914 NEQV,
915 SELECT,
916 COMMA
917 };
918 static const int precedence[]{
919 15, 15, 15, 15, // (), 6, !, ~
920 14, 14, // unary +, -
921 13, 12, 12, 12, 11, 11, 10, 10, // **, *, /, %, +, -, <<, >>
922 9, 8, 7, // &, ^, |
923 6, 6, 6, 6, 6, 6, // relations .LT. to .GT.
924 5, 4, 3, 2, 2, // .NOT., .AND., .OR., .EQV., .NEQV.
925 1, 0 // ?: and ,
926 };
927 static const int operandPrecedence[]{0, -1, 15, 15, 15, 15, 13, 12, 12, 12,
928 11, 11, 11, 11, 9, 8, 7, 7, 7, 7, 7, 7, 7, 6, 4, 3, 3, 3, 1, 0};
929
930 static std::map<std::string, enum Operator> opNameMap;
931 if (opNameMap.empty()) {
932 opNameMap["("] = PARENS;
933 opNameMap["!"] = NOTZERO;
934 opNameMap["~"] = COMPLEMENT;
935 opNameMap["**"] = POWER;
936 opNameMap["*"] = TIMES;
937 opNameMap["/"] = DIVIDE;
938 opNameMap["%"] = MODULUS;
939 opNameMap["+"] = ADD;
940 opNameMap["-"] = SUBTRACT;
941 opNameMap["<<"] = LEFTSHIFT;
942 opNameMap[">>"] = RIGHTSHIFT;
943 opNameMap["&"] = BITAND;
944 opNameMap["^"] = BITXOR;
945 opNameMap["|"] = BITOR;
946 opNameMap[".lt."] = opNameMap["<"] = LT;
947 opNameMap[".le."] = opNameMap["<="] = LE;
948 opNameMap[".eq."] = opNameMap["=="] = EQ;
949 opNameMap[".ne."] = opNameMap["/="] = opNameMap["!="] = NE;
950 opNameMap[".ge."] = opNameMap[">="] = GE;
951 opNameMap[".gt."] = opNameMap[">"] = GT;
952 opNameMap[".not."] = NOT;
953 opNameMap[".and."] = opNameMap[".a."] = opNameMap["&&"] = AND;
954 opNameMap[".or."] = opNameMap[".o."] = opNameMap["||"] = OR;
955 opNameMap[".eqv."] = EQV;
956 opNameMap[".neqv."] = opNameMap[".xor."] = opNameMap[".x."] = NEQV;
957 opNameMap["?"] = SELECT;
958 opNameMap[","] = COMMA;
959 }
960
961 std::size_t tokens{token.SizeInTokens()};
962 CHECK(tokens > 0);
963 if (*atToken >= tokens) {
964 *error =
965 Message{token.GetProvenanceRange(), "incomplete expression"_err_en_US};
966 return 0;
967 }
968
969 // Parse and evaluate a primary or a unary operator and its operand.
970 std::size_t opAt{*atToken};
971 std::string t{token.TokenAt(opAt).ToString()};
972 enum Operator op;
973 std::int64_t left{0};
974 if (t == "(") {
975 op = PARENS;
976 } else if (IsDecimalDigit(t[0])) {
977 op = CONST;
978 std::size_t consumed{0};
979 left = std::stoll(t, &consumed, 0 /*base to be detected*/);
980 if (consumed < t.size()) {
981 *error = Message{token.GetTokenProvenanceRange(opAt),
982 "Uninterpretable numeric constant '%s'"_err_en_US, t};
983 return 0;
984 }
985 } else if (IsLegalIdentifierStart(t[0])) {
986 // undefined macro name -> zero
987 // TODO: BOZ constants?
988 op = CONST;
989 } else if (t == "+") {
990 op = UPLUS;
991 } else if (t == "-") {
992 op = UMINUS;
993 } else if (t == "." && *atToken + 2 < tokens &&
994 ToLowerCaseLetters(token.TokenAt(*atToken + 1).ToString()) == "not" &&
995 token.TokenAt(*atToken + 2).ToString() == ".") {
996 op = NOT;
997 *atToken += 2;
998 } else {
999 auto it{opNameMap.find(t)};
1000 if (it != opNameMap.end()) {
1001 op = it->second;
1002 } else {
1003 *error = Message{token.GetTokenProvenanceRange(opAt),
1004 "operand expected in expression"_err_en_US};
1005 return 0;
1006 }
1007 }
1008 if (precedence[op] < minimumPrecedence) {
1009 *error = Message{token.GetTokenProvenanceRange(opAt),
1010 "operator precedence error"_err_en_US};
1011 return 0;
1012 }
1013 ++*atToken;
1014 if (op != CONST) {
1015 left = ExpressionValue(token, operandPrecedence[op], atToken, error);
1016 if (*error) {
1017 return 0;
1018 }
1019 switch (op) {
1020 case PARENS:
1021 if (*atToken < tokens && token.TokenAt(*atToken).OnlyNonBlank() == ')') {
1022 ++*atToken;
1023 break;
1024 }
1025 if (*atToken >= tokens) {
1026 *error = Message{token.GetProvenanceRange(),
1027 "')' missing from expression"_err_en_US};
1028 } else {
1029 *error = Message{
1030 token.GetTokenProvenanceRange(*atToken), "expected ')'"_err_en_US};
1031 }
1032 return 0;
1033 case NOTZERO:
1034 left = !left;
1035 break;
1036 case COMPLEMENT:
1037 left = ~left;
1038 break;
1039 case UPLUS:
1040 break;
1041 case UMINUS:
1042 left = -left;
1043 break;
1044 case NOT:
1045 left = -!left;
1046 break;
1047 default:
1048 CRASH_NO_CASE;
1049 }
1050 }
1051
1052 // Parse and evaluate binary operators and their second operands, if present.
1053 while (*atToken < tokens) {
1054 int advance{1};
1055 t = token.TokenAt(*atToken).ToString();
1056 if (t == "." && *atToken + 2 < tokens &&
1057 token.TokenAt(*atToken + 2).ToString() == ".") {
1058 t += ToLowerCaseLetters(token.TokenAt(*atToken + 1).ToString()) + '.';
1059 advance = 3;
1060 }
1061 auto it{opNameMap.find(t)};
1062 if (it == opNameMap.end()) {
1063 break;
1064 }
1065 op = it->second;
1066 if (op < POWER || precedence[op] < minimumPrecedence) {
1067 break;
1068 }
1069 opAt = *atToken;
1070 *atToken += advance;
1071
1072 std::int64_t right{
1073 ExpressionValue(token, operandPrecedence[op], atToken, error)};
1074 if (*error) {
1075 return 0;
1076 }
1077
1078 switch (op) {
1079 case POWER:
1080 if (left == 0) {
1081 if (right < 0) {
1082 *error = Message{token.GetTokenProvenanceRange(opAt),
1083 "0 ** negative power"_err_en_US};
1084 }
1085 } else if (left != 1 && right != 1) {
1086 if (right <= 0) {
1087 left = !right;
1088 } else {
1089 std::int64_t power{1};
1090 for (; right > 0; --right) {
1091 if ((power * left) / left != power) {
1092 *error = Message{token.GetTokenProvenanceRange(opAt),
1093 "overflow in exponentation"_err_en_US};
1094 left = 1;
1095 }
1096 power *= left;
1097 }
1098 left = power;
1099 }
1100 }
1101 break;
1102 case TIMES:
1103 if (left != 0 && right != 0 && ((left * right) / left) != right) {
1104 *error = Message{token.GetTokenProvenanceRange(opAt),
1105 "overflow in multiplication"_err_en_US};
1106 }
1107 left = left * right;
1108 break;
1109 case DIVIDE:
1110 if (right == 0) {
1111 *error = Message{
1112 token.GetTokenProvenanceRange(opAt), "division by zero"_err_en_US};
1113 left = 0;
1114 } else {
1115 left = left / right;
1116 }
1117 break;
1118 case MODULUS:
1119 if (right == 0) {
1120 *error = Message{
1121 token.GetTokenProvenanceRange(opAt), "modulus by zero"_err_en_US};
1122 left = 0;
1123 } else {
1124 left = left % right;
1125 }
1126 break;
1127 case ADD:
1128 if ((left < 0) == (right < 0) && (left < 0) != (left + right < 0)) {
1129 *error = Message{token.GetTokenProvenanceRange(opAt),
1130 "overflow in addition"_err_en_US};
1131 }
1132 left = left + right;
1133 break;
1134 case SUBTRACT:
1135 if ((left < 0) != (right < 0) && (left < 0) == (left - right < 0)) {
1136 *error = Message{token.GetTokenProvenanceRange(opAt),
1137 "overflow in subtraction"_err_en_US};
1138 }
1139 left = left - right;
1140 break;
1141 case LEFTSHIFT:
1142 if (right < 0 || right > 64) {
1143 *error = Message{token.GetTokenProvenanceRange(opAt),
1144 "bad left shift count"_err_en_US};
1145 }
1146 left = right >= 64 ? 0 : left << right;
1147 break;
1148 case RIGHTSHIFT:
1149 if (right < 0 || right > 64) {
1150 *error = Message{token.GetTokenProvenanceRange(opAt),
1151 "bad right shift count"_err_en_US};
1152 }
1153 left = right >= 64 ? 0 : left >> right;
1154 break;
1155 case BITAND:
1156 case AND:
1157 left = left & right;
1158 break;
1159 case BITXOR:
1160 left = left ^ right;
1161 break;
1162 case BITOR:
1163 case OR:
1164 left = left | right;
1165 break;
1166 case LT:
1167 left = -(left < right);
1168 break;
1169 case LE:
1170 left = -(left <= right);
1171 break;
1172 case EQ:
1173 left = -(left == right);
1174 break;
1175 case NE:
1176 left = -(left != right);
1177 break;
1178 case GE:
1179 left = -(left >= right);
1180 break;
1181 case GT:
1182 left = -(left > right);
1183 break;
1184 case EQV:
1185 left = -(!left == !right);
1186 break;
1187 case NEQV:
1188 left = -(!left != !right);
1189 break;
1190 case SELECT:
1191 if (*atToken >= tokens || token.TokenAt(*atToken).ToString() != ":") {
1192 *error = Message{token.GetTokenProvenanceRange(opAt),
1193 "':' required in selection expression"_err_en_US};
1194 return 0;
1195 } else {
1196 ++*atToken;
1197 std::int64_t third{
1198 ExpressionValue(token, operandPrecedence[op], atToken, error)};
1199 left = left != 0 ? right : third;
1200 }
1201 break;
1202 case COMMA:
1203 left = right;
1204 break;
1205 default:
1206 CRASH_NO_CASE;
1207 }
1208 }
1209 return left;
1210 }
1211
1212 bool Preprocessor::IsIfPredicateTrue(const TokenSequence &expr,
1213 std::size_t first, std::size_t exprTokens, Prescanner &prescanner) {
1214 TokenSequence expr1{expr, first, exprTokens};
1215 if (expr1.HasBlanks()) {
1216 expr1.RemoveBlanks();
1217 }
1218 TokenSequence expr2;
1219 for (std::size_t j{0}; j < expr1.SizeInTokens(); ++j) {
1220 if (ToLowerCaseLetters(expr1.TokenAt(j).ToString()) == "defined") {
1221 CharBlock name;
1222 if (j + 3 < expr1.SizeInTokens() &&
1223 expr1.TokenAt(j + 1).OnlyNonBlank() == '(' &&
1224 expr1.TokenAt(j + 3).OnlyNonBlank() == ')') {
1225 name = expr1.TokenAt(j + 2);
1226 j += 3;
1227 } else if (j + 1 < expr1.SizeInTokens() &&
1228 IsLegalIdentifierStart(expr1.TokenAt(j + 1))) {
1229 name = expr1.TokenAt(++j);
1230 }
1231 if (!name.empty()) {
1232 char truth{IsNameDefined(name) ? '1' : '0'};
1233 expr2.Put(&truth, 1, allSources_.CompilerInsertionProvenance(truth));
1234 continue;
1235 }
1236 }
1237 expr2.Put(expr1, j);
1238 }
1239 TokenSequence expr3{ReplaceMacros(expr2, prescanner)};
1240 if (expr3.HasBlanks()) {
1241 expr3.RemoveBlanks();
1242 }
1243 if (expr3.empty()) {
1244 prescanner.Say(expr.GetProvenanceRange(), "empty expression"_err_en_US);
1245 return false;
1246 }
1247 std::size_t atToken{0};
1248 std::optional<Message> error;
1249 bool result{ExpressionValue(expr3, 0, &atToken, &error) != 0};
1250 if (error) {
1251 prescanner.Say(std::move(*error));
1252 } else if (atToken < expr3.SizeInTokens() &&
1253 expr3.TokenAt(atToken).ToString() != "!") {
1254 prescanner.Say(expr3.GetIntervalProvenanceRange(
1255 atToken, expr3.SizeInTokens() - atToken),
1256 atToken == 0 ? "could not parse any expression"_err_en_US
1257 : "excess characters after expression"_err_en_US);
1258 }
1259 return result;
1260 }
1261
1262 void Preprocessor::LineDirective(
1263 const TokenSequence &dir, std::size_t j, Prescanner &prescanner) {
1264 std::size_t tokens{dir.SizeInTokens()};
1265 const std::string *linePath{nullptr};
1266 std::optional<int> lineNumber;
1267 SourceFile *sourceFile{nullptr};
1268 std::optional<SourcePosition> pos;
1269 for (; j < tokens; j = dir.SkipBlanks(j + 1)) {
1270 std::string tstr{dir.TokenAt(j).ToString()};
1271 Provenance provenance{dir.GetTokenProvenance(j)};
1272 if (!pos) {
1273 pos = allSources_.GetSourcePosition(provenance);
1274 }
1275 if (!sourceFile && pos) {
1276 sourceFile = const_cast<SourceFile *>(&*pos->sourceFile);
1277 }
1278 if (tstr.front() == '"' && tstr.back() == '"') {
1279 tstr = tstr.substr(1, tstr.size() - 2);
1280 if (!tstr.empty() && sourceFile) {
1281 linePath = &sourceFile->SavePath(std::move(tstr));
1282 }
1283 } else if (IsDecimalDigit(tstr[0])) {
1284 if (!lineNumber) { // ignore later column number
1285 int ln{0};
1286 for (char c : tstr) {
1287 if (IsDecimalDigit(c)) {
1288 int nln{10 * ln + c - '0'};
1289 if (nln / 10 == ln && nln % 10 == c - '0') {
1290 ln = nln;
1291 continue;
1292 }
1293 }
1294 prescanner.Say(provenance,
1295 "bad line number '%s' in #line directive"_err_en_US, tstr);
1296 return;
1297 }
1298 lineNumber = ln;
1299 }
1300 } else {
1301 prescanner.Say(
1302 provenance, "bad token '%s' in #line directive"_err_en_US, tstr);
1303 return;
1304 }
1305 }
1306 if (lineNumber && sourceFile) {
1307 CHECK(pos);
1308 if (!linePath) {
1309 linePath = &*pos->path;
1310 }
1311 sourceFile->LineDirective(pos->trueLineNumber + 1, *linePath, *lineNumber);
1312 }
1313 }
1314
1315 } // namespace Fortran::parser