DependencyDirectivesScanner.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. //===- DependencyDirectivesScanner.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. /// \file
  10. /// This is the interface for scanning header and source files to get the
  11. /// minimum necessary preprocessor directives for evaluating includes. It
  12. /// reduces the source down to #define, #include, #import, @import, and any
  13. /// conditional preprocessor logic that contains one of those.
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #include "clang/Lex/DependencyDirectivesScanner.h"
  17. #include "clang/Basic/CharInfo.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Lex/LexDiagnostic.h"
  20. #include "clang/Lex/Lexer.h"
  21. #include "llvm/ADT/ScopeExit.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/StringMap.h"
  24. #include "llvm/ADT/StringSwitch.h"
  25. #include <optional>
  26. using namespace clang;
  27. using namespace clang::dependency_directives_scan;
  28. using namespace llvm;
  29. namespace {
  30. struct DirectiveWithTokens {
  31. DirectiveKind Kind;
  32. unsigned NumTokens;
  33. DirectiveWithTokens(DirectiveKind Kind, unsigned NumTokens)
  34. : Kind(Kind), NumTokens(NumTokens) {}
  35. };
  36. /// Does an efficient "scan" of the sources to detect the presence of
  37. /// preprocessor (or module import) directives and collects the raw lexed tokens
  38. /// for those directives so that the \p Lexer can "replay" them when the file is
  39. /// included.
  40. ///
  41. /// Note that the behavior of the raw lexer is affected by the language mode,
  42. /// while at this point we want to do a scan and collect tokens once,
  43. /// irrespective of the language mode that the file will get included in. To
  44. /// compensate for that the \p Lexer, while "replaying", will adjust a token
  45. /// where appropriate, when it could affect the preprocessor's state.
  46. /// For example in a directive like
  47. ///
  48. /// \code
  49. /// #if __has_cpp_attribute(clang::fallthrough)
  50. /// \endcode
  51. ///
  52. /// The preprocessor needs to see '::' as 'tok::coloncolon' instead of 2
  53. /// 'tok::colon'. The \p Lexer will adjust if it sees consecutive 'tok::colon'
  54. /// while in C++ mode.
  55. struct Scanner {
  56. Scanner(StringRef Input,
  57. SmallVectorImpl<dependency_directives_scan::Token> &Tokens,
  58. DiagnosticsEngine *Diags, SourceLocation InputSourceLoc)
  59. : Input(Input), Tokens(Tokens), Diags(Diags),
  60. InputSourceLoc(InputSourceLoc), LangOpts(getLangOptsForDepScanning()),
  61. TheLexer(InputSourceLoc, LangOpts, Input.begin(), Input.begin(),
  62. Input.end()) {}
  63. static LangOptions getLangOptsForDepScanning() {
  64. LangOptions LangOpts;
  65. // Set the lexer to use 'tok::at' for '@', instead of 'tok::unknown'.
  66. LangOpts.ObjC = true;
  67. LangOpts.LineComment = true;
  68. return LangOpts;
  69. }
  70. /// Lex the provided source and emit the directive tokens.
  71. ///
  72. /// \returns True on error.
  73. bool scan(SmallVectorImpl<Directive> &Directives);
  74. private:
  75. /// Lexes next token and advances \p First and the \p Lexer.
  76. [[nodiscard]] dependency_directives_scan::Token &
  77. lexToken(const char *&First, const char *const End);
  78. dependency_directives_scan::Token &lexIncludeFilename(const char *&First,
  79. const char *const End);
  80. void skipLine(const char *&First, const char *const End);
  81. void skipDirective(StringRef Name, const char *&First, const char *const End);
  82. /// Lexes next token and if it is identifier returns its string, otherwise
  83. /// it skips the current line and returns \p std::nullopt.
  84. ///
  85. /// In any case (whatever the token kind) \p First and the \p Lexer will
  86. /// advance beyond the token.
  87. [[nodiscard]] std::optional<StringRef>
  88. tryLexIdentifierOrSkipLine(const char *&First, const char *const End);
  89. /// Used when it is certain that next token is an identifier.
  90. [[nodiscard]] StringRef lexIdentifier(const char *&First,
  91. const char *const End);
  92. /// Lexes next token and returns true iff it is an identifier that matches \p
  93. /// Id, otherwise it skips the current line and returns false.
  94. ///
  95. /// In any case (whatever the token kind) \p First and the \p Lexer will
  96. /// advance beyond the token.
  97. [[nodiscard]] bool isNextIdentifierOrSkipLine(StringRef Id,
  98. const char *&First,
  99. const char *const End);
  100. [[nodiscard]] bool scanImpl(const char *First, const char *const End);
  101. [[nodiscard]] bool lexPPLine(const char *&First, const char *const End);
  102. [[nodiscard]] bool lexAt(const char *&First, const char *const End);
  103. [[nodiscard]] bool lexModule(const char *&First, const char *const End);
  104. [[nodiscard]] bool lexDefine(const char *HashLoc, const char *&First,
  105. const char *const End);
  106. [[nodiscard]] bool lexPragma(const char *&First, const char *const End);
  107. [[nodiscard]] bool lexEndif(const char *&First, const char *const End);
  108. [[nodiscard]] bool lexDefault(DirectiveKind Kind, const char *&First,
  109. const char *const End);
  110. [[nodiscard]] bool lexModuleDirectiveBody(DirectiveKind Kind,
  111. const char *&First,
  112. const char *const End);
  113. void lexPPDirectiveBody(const char *&First, const char *const End);
  114. DirectiveWithTokens &pushDirective(DirectiveKind Kind) {
  115. Tokens.append(CurDirToks);
  116. DirsWithToks.emplace_back(Kind, CurDirToks.size());
  117. CurDirToks.clear();
  118. return DirsWithToks.back();
  119. }
  120. void popDirective() {
  121. Tokens.pop_back_n(DirsWithToks.pop_back_val().NumTokens);
  122. }
  123. DirectiveKind topDirective() const {
  124. return DirsWithToks.empty() ? pp_none : DirsWithToks.back().Kind;
  125. }
  126. unsigned getOffsetAt(const char *CurPtr) const {
  127. return CurPtr - Input.data();
  128. }
  129. /// Reports a diagnostic if the diagnostic engine is provided. Always returns
  130. /// true at the end.
  131. bool reportError(const char *CurPtr, unsigned Err);
  132. StringMap<char> SplitIds;
  133. StringRef Input;
  134. SmallVectorImpl<dependency_directives_scan::Token> &Tokens;
  135. DiagnosticsEngine *Diags;
  136. SourceLocation InputSourceLoc;
  137. const char *LastTokenPtr = nullptr;
  138. /// Keeps track of the tokens for the currently lexed directive. Once a
  139. /// directive is fully lexed and "committed" then the tokens get appended to
  140. /// \p Tokens and \p CurDirToks is cleared for the next directive.
  141. SmallVector<dependency_directives_scan::Token, 32> CurDirToks;
  142. /// The directives that were lexed along with the number of tokens that each
  143. /// directive contains. The tokens of all the directives are kept in \p Tokens
  144. /// vector, in the same order as the directives order in \p DirsWithToks.
  145. SmallVector<DirectiveWithTokens, 64> DirsWithToks;
  146. LangOptions LangOpts;
  147. Lexer TheLexer;
  148. };
  149. } // end anonymous namespace
  150. bool Scanner::reportError(const char *CurPtr, unsigned Err) {
  151. if (!Diags)
  152. return true;
  153. assert(CurPtr >= Input.data() && "invalid buffer ptr");
  154. Diags->Report(InputSourceLoc.getLocWithOffset(getOffsetAt(CurPtr)), Err);
  155. return true;
  156. }
  157. static void skipOverSpaces(const char *&First, const char *const End) {
  158. while (First != End && isHorizontalWhitespace(*First))
  159. ++First;
  160. }
  161. [[nodiscard]] static bool isRawStringLiteral(const char *First,
  162. const char *Current) {
  163. assert(First <= Current);
  164. // Check if we can even back up.
  165. if (*Current != '"' || First == Current)
  166. return false;
  167. // Check for an "R".
  168. --Current;
  169. if (*Current != 'R')
  170. return false;
  171. if (First == Current || !isAsciiIdentifierContinue(*--Current))
  172. return true;
  173. // Check for a prefix of "u", "U", or "L".
  174. if (*Current == 'u' || *Current == 'U' || *Current == 'L')
  175. return First == Current || !isAsciiIdentifierContinue(*--Current);
  176. // Check for a prefix of "u8".
  177. if (*Current != '8' || First == Current || *Current-- != 'u')
  178. return false;
  179. return First == Current || !isAsciiIdentifierContinue(*--Current);
  180. }
  181. static void skipRawString(const char *&First, const char *const End) {
  182. assert(First[0] == '"');
  183. assert(First[-1] == 'R');
  184. const char *Last = ++First;
  185. while (Last != End && *Last != '(')
  186. ++Last;
  187. if (Last == End) {
  188. First = Last; // Hit the end... just give up.
  189. return;
  190. }
  191. StringRef Terminator(First, Last - First);
  192. for (;;) {
  193. // Move First to just past the next ")".
  194. First = Last;
  195. while (First != End && *First != ')')
  196. ++First;
  197. if (First == End)
  198. return;
  199. ++First;
  200. // Look ahead for the terminator sequence.
  201. Last = First;
  202. while (Last != End && size_t(Last - First) < Terminator.size() &&
  203. Terminator[Last - First] == *Last)
  204. ++Last;
  205. // Check if we hit it (or the end of the file).
  206. if (Last == End) {
  207. First = Last;
  208. return;
  209. }
  210. if (size_t(Last - First) < Terminator.size())
  211. continue;
  212. if (*Last != '"')
  213. continue;
  214. First = Last + 1;
  215. return;
  216. }
  217. }
  218. // Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
  219. static unsigned isEOL(const char *First, const char *const End) {
  220. if (First == End)
  221. return 0;
  222. if (End - First > 1 && isVerticalWhitespace(First[0]) &&
  223. isVerticalWhitespace(First[1]) && First[0] != First[1])
  224. return 2;
  225. return !!isVerticalWhitespace(First[0]);
  226. }
  227. static void skipString(const char *&First, const char *const End) {
  228. assert(*First == '\'' || *First == '"' || *First == '<');
  229. const char Terminator = *First == '<' ? '>' : *First;
  230. for (++First; First != End && *First != Terminator; ++First) {
  231. // String and character literals don't extend past the end of the line.
  232. if (isVerticalWhitespace(*First))
  233. return;
  234. if (*First != '\\')
  235. continue;
  236. // Skip past backslash to the next character. This ensures that the
  237. // character right after it is skipped as well, which matters if it's
  238. // the terminator.
  239. if (++First == End)
  240. return;
  241. if (!isWhitespace(*First))
  242. continue;
  243. // Whitespace after the backslash might indicate a line continuation.
  244. const char *FirstAfterBackslashPastSpace = First;
  245. skipOverSpaces(FirstAfterBackslashPastSpace, End);
  246. if (unsigned NLSize = isEOL(FirstAfterBackslashPastSpace, End)) {
  247. // Advance the character pointer to the next line for the next
  248. // iteration.
  249. First = FirstAfterBackslashPastSpace + NLSize - 1;
  250. }
  251. }
  252. if (First != End)
  253. ++First; // Finish off the string.
  254. }
  255. // Returns the length of the skipped newline
  256. static unsigned skipNewline(const char *&First, const char *End) {
  257. if (First == End)
  258. return 0;
  259. assert(isVerticalWhitespace(*First));
  260. unsigned Len = isEOL(First, End);
  261. assert(Len && "expected newline");
  262. First += Len;
  263. return Len;
  264. }
  265. static bool wasLineContinuation(const char *First, unsigned EOLLen) {
  266. return *(First - (int)EOLLen - 1) == '\\';
  267. }
  268. static void skipToNewlineRaw(const char *&First, const char *const End) {
  269. for (;;) {
  270. if (First == End)
  271. return;
  272. unsigned Len = isEOL(First, End);
  273. if (Len)
  274. return;
  275. do {
  276. if (++First == End)
  277. return;
  278. Len = isEOL(First, End);
  279. } while (!Len);
  280. if (First[-1] != '\\')
  281. return;
  282. First += Len;
  283. // Keep skipping lines...
  284. }
  285. }
  286. static void skipLineComment(const char *&First, const char *const End) {
  287. assert(First[0] == '/' && First[1] == '/');
  288. First += 2;
  289. skipToNewlineRaw(First, End);
  290. }
  291. static void skipBlockComment(const char *&First, const char *const End) {
  292. assert(First[0] == '/' && First[1] == '*');
  293. if (End - First < 4) {
  294. First = End;
  295. return;
  296. }
  297. for (First += 3; First != End; ++First)
  298. if (First[-1] == '*' && First[0] == '/') {
  299. ++First;
  300. return;
  301. }
  302. }
  303. /// \returns True if the current single quotation mark character is a C++ 14
  304. /// digit separator.
  305. static bool isQuoteCppDigitSeparator(const char *const Start,
  306. const char *const Cur,
  307. const char *const End) {
  308. assert(*Cur == '\'' && "expected quotation character");
  309. // skipLine called in places where we don't expect a valid number
  310. // body before `start` on the same line, so always return false at the start.
  311. if (Start == Cur)
  312. return false;
  313. // The previous character must be a valid PP number character.
  314. // Make sure that the L, u, U, u8 prefixes don't get marked as a
  315. // separator though.
  316. char Prev = *(Cur - 1);
  317. if (Prev == 'L' || Prev == 'U' || Prev == 'u')
  318. return false;
  319. if (Prev == '8' && (Cur - 1 != Start) && *(Cur - 2) == 'u')
  320. return false;
  321. if (!isPreprocessingNumberBody(Prev))
  322. return false;
  323. // The next character should be a valid identifier body character.
  324. return (Cur + 1) < End && isAsciiIdentifierContinue(*(Cur + 1));
  325. }
  326. void Scanner::skipLine(const char *&First, const char *const End) {
  327. for (;;) {
  328. assert(First <= End);
  329. if (First == End)
  330. return;
  331. if (isVerticalWhitespace(*First)) {
  332. skipNewline(First, End);
  333. return;
  334. }
  335. const char *Start = First;
  336. while (First != End && !isVerticalWhitespace(*First)) {
  337. // Iterate over strings correctly to avoid comments and newlines.
  338. if (*First == '"' ||
  339. (*First == '\'' && !isQuoteCppDigitSeparator(Start, First, End))) {
  340. LastTokenPtr = First;
  341. if (isRawStringLiteral(Start, First))
  342. skipRawString(First, End);
  343. else
  344. skipString(First, End);
  345. continue;
  346. }
  347. // Iterate over comments correctly.
  348. if (*First != '/' || End - First < 2) {
  349. LastTokenPtr = First;
  350. ++First;
  351. continue;
  352. }
  353. if (First[1] == '/') {
  354. // "//...".
  355. skipLineComment(First, End);
  356. continue;
  357. }
  358. if (First[1] != '*') {
  359. LastTokenPtr = First;
  360. ++First;
  361. continue;
  362. }
  363. // "/*...*/".
  364. skipBlockComment(First, End);
  365. }
  366. if (First == End)
  367. return;
  368. // Skip over the newline.
  369. unsigned Len = skipNewline(First, End);
  370. if (!wasLineContinuation(First, Len)) // Continue past line-continuations.
  371. break;
  372. }
  373. }
  374. void Scanner::skipDirective(StringRef Name, const char *&First,
  375. const char *const End) {
  376. if (llvm::StringSwitch<bool>(Name)
  377. .Case("warning", true)
  378. .Case("error", true)
  379. .Default(false))
  380. // Do not process quotes or comments.
  381. skipToNewlineRaw(First, End);
  382. else
  383. skipLine(First, End);
  384. }
  385. static void skipWhitespace(const char *&First, const char *const End) {
  386. for (;;) {
  387. assert(First <= End);
  388. skipOverSpaces(First, End);
  389. if (End - First < 2)
  390. return;
  391. if (First[0] == '\\' && isVerticalWhitespace(First[1])) {
  392. skipNewline(++First, End);
  393. continue;
  394. }
  395. // Check for a non-comment character.
  396. if (First[0] != '/')
  397. return;
  398. // "// ...".
  399. if (First[1] == '/') {
  400. skipLineComment(First, End);
  401. return;
  402. }
  403. // Cannot be a comment.
  404. if (First[1] != '*')
  405. return;
  406. // "/*...*/".
  407. skipBlockComment(First, End);
  408. }
  409. }
  410. bool Scanner::lexModuleDirectiveBody(DirectiveKind Kind, const char *&First,
  411. const char *const End) {
  412. const char *DirectiveLoc = Input.data() + CurDirToks.front().Offset;
  413. for (;;) {
  414. const dependency_directives_scan::Token &Tok = lexToken(First, End);
  415. if (Tok.is(tok::eof))
  416. return reportError(
  417. DirectiveLoc,
  418. diag::err_dep_source_scanner_missing_semi_after_at_import);
  419. if (Tok.is(tok::semi))
  420. break;
  421. }
  422. pushDirective(Kind);
  423. skipWhitespace(First, End);
  424. if (First == End)
  425. return false;
  426. if (!isVerticalWhitespace(*First))
  427. return reportError(
  428. DirectiveLoc, diag::err_dep_source_scanner_unexpected_tokens_at_import);
  429. skipNewline(First, End);
  430. return false;
  431. }
  432. dependency_directives_scan::Token &Scanner::lexToken(const char *&First,
  433. const char *const End) {
  434. clang::Token Tok;
  435. TheLexer.LexFromRawLexer(Tok);
  436. First = Input.data() + TheLexer.getCurrentBufferOffset();
  437. assert(First <= End);
  438. unsigned Offset = TheLexer.getCurrentBufferOffset() - Tok.getLength();
  439. CurDirToks.emplace_back(Offset, Tok.getLength(), Tok.getKind(),
  440. Tok.getFlags());
  441. return CurDirToks.back();
  442. }
  443. dependency_directives_scan::Token &
  444. Scanner::lexIncludeFilename(const char *&First, const char *const End) {
  445. clang::Token Tok;
  446. TheLexer.LexIncludeFilename(Tok);
  447. First = Input.data() + TheLexer.getCurrentBufferOffset();
  448. assert(First <= End);
  449. unsigned Offset = TheLexer.getCurrentBufferOffset() - Tok.getLength();
  450. CurDirToks.emplace_back(Offset, Tok.getLength(), Tok.getKind(),
  451. Tok.getFlags());
  452. return CurDirToks.back();
  453. }
  454. void Scanner::lexPPDirectiveBody(const char *&First, const char *const End) {
  455. while (true) {
  456. const dependency_directives_scan::Token &Tok = lexToken(First, End);
  457. if (Tok.is(tok::eod))
  458. break;
  459. }
  460. }
  461. [[nodiscard]] std::optional<StringRef>
  462. Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) {
  463. const dependency_directives_scan::Token &Tok = lexToken(First, End);
  464. if (Tok.isNot(tok::raw_identifier)) {
  465. if (!Tok.is(tok::eod))
  466. skipLine(First, End);
  467. return std::nullopt;
  468. }
  469. bool NeedsCleaning = Tok.Flags & clang::Token::NeedsCleaning;
  470. if (LLVM_LIKELY(!NeedsCleaning))
  471. return Input.slice(Tok.Offset, Tok.getEnd());
  472. SmallString<64> Spelling;
  473. Spelling.resize(Tok.Length);
  474. unsigned SpellingLength = 0;
  475. const char *BufPtr = Input.begin() + Tok.Offset;
  476. const char *AfterIdent = Input.begin() + Tok.getEnd();
  477. while (BufPtr < AfterIdent) {
  478. unsigned Size;
  479. Spelling[SpellingLength++] =
  480. Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
  481. BufPtr += Size;
  482. }
  483. return SplitIds.try_emplace(StringRef(Spelling.begin(), SpellingLength), 0)
  484. .first->first();
  485. }
  486. StringRef Scanner::lexIdentifier(const char *&First, const char *const End) {
  487. std::optional<StringRef> Id = tryLexIdentifierOrSkipLine(First, End);
  488. assert(Id && "expected identifier token");
  489. return *Id;
  490. }
  491. bool Scanner::isNextIdentifierOrSkipLine(StringRef Id, const char *&First,
  492. const char *const End) {
  493. if (std::optional<StringRef> FoundId =
  494. tryLexIdentifierOrSkipLine(First, End)) {
  495. if (*FoundId == Id)
  496. return true;
  497. skipLine(First, End);
  498. }
  499. return false;
  500. }
  501. bool Scanner::lexAt(const char *&First, const char *const End) {
  502. // Handle "@import".
  503. // Lex '@'.
  504. const dependency_directives_scan::Token &AtTok = lexToken(First, End);
  505. assert(AtTok.is(tok::at));
  506. (void)AtTok;
  507. if (!isNextIdentifierOrSkipLine("import", First, End))
  508. return false;
  509. return lexModuleDirectiveBody(decl_at_import, First, End);
  510. }
  511. bool Scanner::lexModule(const char *&First, const char *const End) {
  512. StringRef Id = lexIdentifier(First, End);
  513. bool Export = false;
  514. if (Id == "export") {
  515. Export = true;
  516. std::optional<StringRef> NextId = tryLexIdentifierOrSkipLine(First, End);
  517. if (!NextId)
  518. return false;
  519. Id = *NextId;
  520. }
  521. if (Id != "module" && Id != "import") {
  522. skipLine(First, End);
  523. return false;
  524. }
  525. skipWhitespace(First, End);
  526. // Ignore this as a module directive if the next character can't be part of
  527. // an import.
  528. switch (*First) {
  529. case ':':
  530. case '<':
  531. case '"':
  532. break;
  533. default:
  534. if (!isAsciiIdentifierContinue(*First)) {
  535. skipLine(First, End);
  536. return false;
  537. }
  538. }
  539. TheLexer.seek(getOffsetAt(First), /*IsAtStartOfLine*/ false);
  540. DirectiveKind Kind;
  541. if (Id == "module")
  542. Kind = Export ? cxx_export_module_decl : cxx_module_decl;
  543. else
  544. Kind = Export ? cxx_export_import_decl : cxx_import_decl;
  545. return lexModuleDirectiveBody(Kind, First, End);
  546. }
  547. bool Scanner::lexPragma(const char *&First, const char *const End) {
  548. std::optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End);
  549. if (!FoundId)
  550. return false;
  551. StringRef Id = *FoundId;
  552. auto Kind = llvm::StringSwitch<DirectiveKind>(Id)
  553. .Case("once", pp_pragma_once)
  554. .Case("push_macro", pp_pragma_push_macro)
  555. .Case("pop_macro", pp_pragma_pop_macro)
  556. .Case("include_alias", pp_pragma_include_alias)
  557. .Default(pp_none);
  558. if (Kind != pp_none) {
  559. lexPPDirectiveBody(First, End);
  560. pushDirective(Kind);
  561. return false;
  562. }
  563. if (Id != "clang") {
  564. skipLine(First, End);
  565. return false;
  566. }
  567. // #pragma clang.
  568. if (!isNextIdentifierOrSkipLine("module", First, End))
  569. return false;
  570. // #pragma clang module.
  571. if (!isNextIdentifierOrSkipLine("import", First, End))
  572. return false;
  573. // #pragma clang module import.
  574. lexPPDirectiveBody(First, End);
  575. pushDirective(pp_pragma_import);
  576. return false;
  577. }
  578. bool Scanner::lexEndif(const char *&First, const char *const End) {
  579. // Strip out "#else" if it's empty.
  580. if (topDirective() == pp_else)
  581. popDirective();
  582. // If "#ifdef" is empty, strip it and skip the "#endif".
  583. //
  584. // FIXME: Once/if Clang starts disallowing __has_include in macro expansions,
  585. // we can skip empty `#if` and `#elif` blocks as well after scanning for a
  586. // literal __has_include in the condition. Even without that rule we could
  587. // drop the tokens if we scan for identifiers in the condition and find none.
  588. if (topDirective() == pp_ifdef || topDirective() == pp_ifndef) {
  589. popDirective();
  590. skipLine(First, End);
  591. return false;
  592. }
  593. return lexDefault(pp_endif, First, End);
  594. }
  595. bool Scanner::lexDefault(DirectiveKind Kind, const char *&First,
  596. const char *const End) {
  597. lexPPDirectiveBody(First, End);
  598. pushDirective(Kind);
  599. return false;
  600. }
  601. static bool isStartOfRelevantLine(char First) {
  602. switch (First) {
  603. case '#':
  604. case '@':
  605. case 'i':
  606. case 'e':
  607. case 'm':
  608. return true;
  609. }
  610. return false;
  611. }
  612. bool Scanner::lexPPLine(const char *&First, const char *const End) {
  613. assert(First != End);
  614. skipWhitespace(First, End);
  615. assert(First <= End);
  616. if (First == End)
  617. return false;
  618. if (!isStartOfRelevantLine(*First)) {
  619. skipLine(First, End);
  620. assert(First <= End);
  621. return false;
  622. }
  623. LastTokenPtr = First;
  624. TheLexer.seek(getOffsetAt(First), /*IsAtStartOfLine*/ true);
  625. auto ScEx1 = make_scope_exit([&]() {
  626. /// Clear Scanner's CurDirToks before returning, in case we didn't push a
  627. /// new directive.
  628. CurDirToks.clear();
  629. });
  630. // Handle "@import".
  631. if (*First == '@')
  632. return lexAt(First, End);
  633. if (*First == 'i' || *First == 'e' || *First == 'm')
  634. return lexModule(First, End);
  635. // Handle preprocessing directives.
  636. TheLexer.setParsingPreprocessorDirective(true);
  637. auto ScEx2 = make_scope_exit(
  638. [&]() { TheLexer.setParsingPreprocessorDirective(false); });
  639. // Lex '#'.
  640. const dependency_directives_scan::Token &HashTok = lexToken(First, End);
  641. if (HashTok.is(tok::hashhash)) {
  642. // A \p tok::hashhash at this location is passed by the preprocessor to the
  643. // parser to interpret, like any other token. So for dependency scanning
  644. // skip it like a normal token not affecting the preprocessor.
  645. skipLine(First, End);
  646. assert(First <= End);
  647. return false;
  648. }
  649. assert(HashTok.is(tok::hash));
  650. (void)HashTok;
  651. std::optional<StringRef> FoundId = tryLexIdentifierOrSkipLine(First, End);
  652. if (!FoundId)
  653. return false;
  654. StringRef Id = *FoundId;
  655. if (Id == "pragma")
  656. return lexPragma(First, End);
  657. auto Kind = llvm::StringSwitch<DirectiveKind>(Id)
  658. .Case("include", pp_include)
  659. .Case("__include_macros", pp___include_macros)
  660. .Case("define", pp_define)
  661. .Case("undef", pp_undef)
  662. .Case("import", pp_import)
  663. .Case("include_next", pp_include_next)
  664. .Case("if", pp_if)
  665. .Case("ifdef", pp_ifdef)
  666. .Case("ifndef", pp_ifndef)
  667. .Case("elif", pp_elif)
  668. .Case("elifdef", pp_elifdef)
  669. .Case("elifndef", pp_elifndef)
  670. .Case("else", pp_else)
  671. .Case("endif", pp_endif)
  672. .Default(pp_none);
  673. if (Kind == pp_none) {
  674. skipDirective(Id, First, End);
  675. return false;
  676. }
  677. if (Kind == pp_endif)
  678. return lexEndif(First, End);
  679. switch (Kind) {
  680. case pp_include:
  681. case pp___include_macros:
  682. case pp_include_next:
  683. case pp_import:
  684. lexIncludeFilename(First, End);
  685. break;
  686. default:
  687. break;
  688. }
  689. // Everything else.
  690. return lexDefault(Kind, First, End);
  691. }
  692. static void skipUTF8ByteOrderMark(const char *&First, const char *const End) {
  693. if ((End - First) >= 3 && First[0] == '\xef' && First[1] == '\xbb' &&
  694. First[2] == '\xbf')
  695. First += 3;
  696. }
  697. bool Scanner::scanImpl(const char *First, const char *const End) {
  698. skipUTF8ByteOrderMark(First, End);
  699. while (First != End)
  700. if (lexPPLine(First, End))
  701. return true;
  702. return false;
  703. }
  704. bool Scanner::scan(SmallVectorImpl<Directive> &Directives) {
  705. bool Error = scanImpl(Input.begin(), Input.end());
  706. if (!Error) {
  707. // Add an EOF on success.
  708. if (LastTokenPtr &&
  709. (Tokens.empty() || LastTokenPtr > Input.begin() + Tokens.back().Offset))
  710. pushDirective(tokens_present_before_eof);
  711. pushDirective(pp_eof);
  712. }
  713. ArrayRef<dependency_directives_scan::Token> RemainingTokens = Tokens;
  714. for (const DirectiveWithTokens &DirWithToks : DirsWithToks) {
  715. assert(RemainingTokens.size() >= DirWithToks.NumTokens);
  716. Directives.emplace_back(DirWithToks.Kind,
  717. RemainingTokens.take_front(DirWithToks.NumTokens));
  718. RemainingTokens = RemainingTokens.drop_front(DirWithToks.NumTokens);
  719. }
  720. assert(RemainingTokens.empty());
  721. return Error;
  722. }
  723. bool clang::scanSourceForDependencyDirectives(
  724. StringRef Input, SmallVectorImpl<dependency_directives_scan::Token> &Tokens,
  725. SmallVectorImpl<Directive> &Directives, DiagnosticsEngine *Diags,
  726. SourceLocation InputSourceLoc) {
  727. return Scanner(Input, Tokens, Diags, InputSourceLoc).scan(Directives);
  728. }
  729. void clang::printDependencyDirectivesAsSource(
  730. StringRef Source,
  731. ArrayRef<dependency_directives_scan::Directive> Directives,
  732. llvm::raw_ostream &OS) {
  733. // Add a space separator where it is convenient for testing purposes.
  734. auto needsSpaceSeparator =
  735. [](tok::TokenKind Prev,
  736. const dependency_directives_scan::Token &Tok) -> bool {
  737. if (Prev == Tok.Kind)
  738. return !Tok.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
  739. tok::r_square);
  740. if (Prev == tok::raw_identifier &&
  741. Tok.isOneOf(tok::hash, tok::numeric_constant, tok::string_literal,
  742. tok::char_constant, tok::header_name))
  743. return true;
  744. if (Prev == tok::r_paren &&
  745. Tok.isOneOf(tok::raw_identifier, tok::hash, tok::string_literal,
  746. tok::char_constant, tok::unknown))
  747. return true;
  748. if (Prev == tok::comma &&
  749. Tok.isOneOf(tok::l_paren, tok::string_literal, tok::less))
  750. return true;
  751. return false;
  752. };
  753. for (const dependency_directives_scan::Directive &Directive : Directives) {
  754. if (Directive.Kind == tokens_present_before_eof)
  755. OS << "<TokBeforeEOF>";
  756. std::optional<tok::TokenKind> PrevTokenKind;
  757. for (const dependency_directives_scan::Token &Tok : Directive.Tokens) {
  758. if (PrevTokenKind && needsSpaceSeparator(*PrevTokenKind, Tok))
  759. OS << ' ';
  760. PrevTokenKind = Tok.Kind;
  761. OS << Source.slice(Tok.Offset, Tok.getEnd());
  762. }
  763. }
  764. }