Coverage Report

Created: 2018-07-22 10:17

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Lex/Lexer.h
Line
Count
Source (jump to first uncovered line)
1
//===- Lexer.h - C Language Family Lexer ------------------------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
//  This file defines the Lexer interface.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_LEX_LEXER_H
15
#define LLVM_CLANG_LEX_LEXER_H
16
17
#include "clang/Basic/LangOptions.h"
18
#include "clang/Basic/SourceLocation.h"
19
#include "clang/Basic/TokenKinds.h"
20
#include "clang/Lex/PreprocessorLexer.h"
21
#include "clang/Lex/Token.h"
22
#include "llvm/ADT/Optional.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/StringRef.h"
25
#include <cassert>
26
#include <cstdint>
27
#include <string>
28
29
namespace llvm {
30
31
class MemoryBuffer;
32
33
} // namespace llvm
34
35
namespace clang {
36
37
class DiagnosticBuilder;
38
class Preprocessor;
39
class SourceManager;
40
41
/// ConflictMarkerKind - Kinds of conflict marker which the lexer might be
42
/// recovering from.
43
enum ConflictMarkerKind {
44
  /// Not within a conflict marker.
45
  CMK_None,
46
47
  /// A normal or diff3 conflict marker, initiated by at least 7 "<"s,
48
  /// separated by at least 7 "="s or "|"s, and terminated by at least 7 ">"s.
49
  CMK_Normal,
50
51
  /// A Perforce-style conflict marker, initiated by 4 ">"s,
52
  /// separated by 4 "="s, and terminated by 4 "<"s.
53
  CMK_Perforce
54
};
55
56
/// Describes the bounds (start, size) of the preamble and a flag required by
57
/// PreprocessorOptions::PrecompiledPreambleBytes.
58
/// The preamble includes the BOM, if any.
59
struct PreambleBounds {
60
  /// Size of the preamble in bytes.
61
  unsigned Size;
62
63
  /// Whether the preamble ends at the start of a new line.
64
  ///
65
  /// Used to inform the lexer as to whether it's starting at the beginning of
66
  /// a line after skipping the preamble.
67
  bool PreambleEndsAtStartOfLine;
68
69
  PreambleBounds(unsigned Size, bool PreambleEndsAtStartOfLine)
70
1.33k
      : Size(Size), PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
71
};
72
73
/// Lexer - This provides a simple interface that turns a text buffer into a
74
/// stream of tokens.  This provides no support for file reading or buffering,
75
/// or buffering/seeking of tokens, only forward lexing is supported.  It relies
76
/// on the specified Preprocessor object to handle preprocessor directives, etc.
77
class Lexer : public PreprocessorLexer {
78
  friend class Preprocessor;
79
80
  void anchor() override;
81
82
  //===--------------------------------------------------------------------===//
83
  // Constant configuration values for this lexer.
84
85
  // Start of the buffer.
86
  const char *BufferStart;
87
88
  // End of the buffer.
89
  const char *BufferEnd;
90
91
  // Location for start of file.
92
  SourceLocation FileLoc;
93
94
  // LangOpts enabled by this language (cache).
95
  LangOptions LangOpts;
96
97
  // True if lexer for _Pragma handling.
98
  bool Is_PragmaLexer;
99
100
  //===--------------------------------------------------------------------===//
101
  // Context-specific lexing flags set by the preprocessor.
102
  //
103
104
  /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace
105
  /// and return them as tokens.  This is used for -C and -CC modes, and
106
  /// whitespace preservation can be useful for some clients that want to lex
107
  /// the file in raw mode and get every character from the file.
108
  ///
109
  /// When this is set to 2 it returns comments and whitespace.  When set to 1
110
  /// it returns comments, when it is set to 0 it returns normal tokens only.
111
  unsigned char ExtendedTokenMode;
112
113
  //===--------------------------------------------------------------------===//
114
  // Context that changes as the file is lexed.
115
  // NOTE: any state that mutates when in raw mode must have save/restore code
116
  // in Lexer::isNextPPTokenLParen.
117
118
  // BufferPtr - Current pointer into the buffer.  This is the next character
119
  // to be lexed.
120
  const char *BufferPtr;
121
122
  // IsAtStartOfLine - True if the next lexed token should get the "start of
123
  // line" flag set on it.
124
  bool IsAtStartOfLine;
125
126
  bool IsAtPhysicalStartOfLine;
127
128
  bool HasLeadingSpace;
129
130
  bool HasLeadingEmptyMacro;
131
132
  // CurrentConflictMarkerState - The kind of conflict marker we are handling.
133
  ConflictMarkerKind CurrentConflictMarkerState;
134
135
  void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
136
137
public:
138
  /// Lexer constructor - Create a new lexer object for the specified buffer
139
  /// with the specified preprocessor managing the lexing process.  This lexer
140
  /// assumes that the associated file buffer and Preprocessor objects will
141
  /// outlive it, so it doesn't take ownership of either of them.
142
  Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, Preprocessor &PP);
143
144
  /// Lexer constructor - Create a new raw lexer object.  This object is only
145
  /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the
146
  /// text range will outlive it, so it doesn't take ownership of it.
147
  Lexer(SourceLocation FileLoc, const LangOptions &LangOpts,
148
        const char *BufStart, const char *BufPtr, const char *BufEnd);
149
150
  /// Lexer constructor - Create a new raw lexer object.  This object is only
151
  /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the
152
  /// text range will outlive it, so it doesn't take ownership of it.
153
  Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer,
154
        const SourceManager &SM, const LangOptions &LangOpts);
155
156
  Lexer(const Lexer &) = delete;
157
  Lexer &operator=(const Lexer &) = delete;
158
159
  /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
160
  /// _Pragma expansion.  This has a variety of magic semantics that this method
161
  /// sets up.  It returns a new'd Lexer that must be delete'd when done.
162
  static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc,
163
                                   SourceLocation ExpansionLocStart,
164
                                   SourceLocation ExpansionLocEnd,
165
                                   unsigned TokLen, Preprocessor &PP);
166
167
  /// getLangOpts - Return the language features currently enabled.
168
  /// NOTE: this lexer modifies features as a file is parsed!
169
5.25M
  const LangOptions &getLangOpts() const { return LangOpts; }
170
171
  /// getFileLoc - Return the File Location for the file we are lexing out of.
172
  /// The physical location encodes the location where the characters come from,
173
  /// the virtual location encodes where we should *claim* the characters came
174
  /// from.  Currently this is only used by _Pragma handling.
175
1.07M
  SourceLocation getFileLoc() const { return FileLoc; }
176
177
private:
178
  /// Lex - Return the next token in the file.  If this is the end of file, it
179
  /// return the tok::eof token.  This implicitly involves the preprocessor.
180
  bool Lex(Token &Result);
181
182
public:
183
  /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
184
1.64M
  bool isPragmaLexer() const { return Is_PragmaLexer; }
185
186
private:
187
  /// IndirectLex - An indirect call to 'Lex' that can be invoked via
188
  ///  the PreprocessorLexer interface.
189
1
  void IndirectLex(Token &Result) override { Lex(Result); }
190
191
public:
192
  /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no
193
  /// associated preprocessor object.  Return true if the 'next character to
194
  /// read' pointer points at the end of the lexer buffer, false otherwise.
195
10.1M
  bool LexFromRawLexer(Token &Result) {
196
10.1M
    assert(LexingRawMode && "Not already in raw mode!");
197
10.1M
    Lex(Result);
198
10.1M
    // Note that lexing to the end of the buffer doesn't implicitly delete the
199
10.1M
    // lexer when in raw mode.
200
10.1M
    return BufferPtr == BufferEnd;
201
10.1M
  }
202
203
  /// isKeepWhitespaceMode - Return true if the lexer should return tokens for
204
  /// every character in the file, including whitespace and comments.  This
205
  /// should only be used in raw mode, as the preprocessor is not prepared to
206
  /// deal with the excess tokens.
207
493M
  bool isKeepWhitespaceMode() const {
208
493M
    return ExtendedTokenMode > 1;
209
493M
  }
210
211
  /// SetKeepWhitespaceMode - This method lets clients enable or disable
212
  /// whitespace retention mode.
213
124M
  void SetKeepWhitespaceMode(bool Val) {
214
124M
    assert((!Val || LexingRawMode || LangOpts.TraditionalCPP) &&
215
124M
           "Can only retain whitespace in raw mode or -traditional-cpp");
216
124M
    ExtendedTokenMode = Val ? 
275.7k
:
0124M
;
217
124M
  }
218
219
  /// inKeepCommentMode - Return true if the lexer should return comments as
220
  /// tokens.
221
24.2M
  bool inKeepCommentMode() const {
222
24.2M
    return ExtendedTokenMode > 0;
223
24.2M
  }
224
225
  /// SetCommentRetentionMode - Change the comment retention mode of the lexer
226
  /// to the specified mode.  This is really only useful when lexing in raw
227
  /// mode, because otherwise the lexer needs to manage this.
228
155M
  void SetCommentRetentionState(bool Mode) {
229
155M
    assert(!isKeepWhitespaceMode() &&
230
155M
           "Can't play with comment retention state when retaining whitespace");
231
155M
    ExtendedTokenMode = Mode ? 
1999k
:
0154M
;
232
155M
  }
233
234
  /// Sets the extended token mode back to its initial value, according to the
235
  /// language options and preprocessor. This controls whether the lexer
236
  /// produces comment and whitespace tokens.
237
  ///
238
  /// This requires the lexer to have an associated preprocessor. A standalone
239
  /// lexer has nothing to reset to.
240
  void resetExtendedTokenMode();
241
242
  /// Gets source code buffer.
243
4.26k
  StringRef getBuffer() const {
244
4.26k
    return StringRef(BufferStart, BufferEnd - BufferStart);
245
4.26k
  }
246
247
  /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
248
  /// uninterpreted string.  This switches the lexer out of directive mode.
249
  void ReadToEndOfLine(SmallVectorImpl<char> *Result = nullptr);
250
251
252
  /// Diag - Forwarding function for diagnostics.  This translate a source
253
  /// position in the current buffer into a SourceLocation object for rendering.
254
  DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const;
255
256
  /// getSourceLocation - Return a source location identifier for the specified
257
  /// offset in the current file.
258
  SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const;
259
260
  /// getSourceLocation - Return a source location for the next character in
261
  /// the current file.
262
11.7M
  SourceLocation getSourceLocation() override {
263
11.7M
    return getSourceLocation(BufferPtr);
264
11.7M
  }
265
266
  /// Return the current location in the buffer.
267
44.4k
  const char *getBufferLocation() const { return BufferPtr; }
268
269
  /// Stringify - Convert the specified string into a C string by i) escaping
270
  /// '\\' and " characters and ii) replacing newline character(s) with "\\n".
271
  /// If Charify is true, this escapes the ' character instead of ".
272
  static std::string Stringify(StringRef Str, bool Charify = false);
273
274
  /// Stringify - Convert the specified string into a C string by i) escaping
275
  /// '\\' and " characters and ii) replacing newline character(s) with "\\n".
276
  static void Stringify(SmallVectorImpl<char> &Str);
277
278
  /// getSpelling - This method is used to get the spelling of a token into a
279
  /// preallocated buffer, instead of as an std::string.  The caller is required
280
  /// to allocate enough space for the token, which is guaranteed to be at least
281
  /// Tok.getLength() bytes long.  The length of the actual result is returned.
282
  ///
283
  /// Note that this method may do two possible things: it may either fill in
284
  /// the buffer specified with characters, or it may *change the input pointer*
285
  /// to point to a constant buffer with the data already in it (avoiding a
286
  /// copy).  The caller is not allowed to modify the returned buffer pointer
287
  /// if an internal buffer is returned.
288
  static unsigned getSpelling(const Token &Tok, const char *&Buffer,
289
                              const SourceManager &SourceMgr,
290
                              const LangOptions &LangOpts,
291
                              bool *Invalid = nullptr);
292
293
  /// getSpelling() - Return the 'spelling' of the Tok token.  The spelling of a
294
  /// token is the characters used to represent the token in the source file
295
  /// after trigraph expansion and escaped-newline folding.  In particular, this
296
  /// wants to get the true, uncanonicalized, spelling of things like digraphs
297
  /// UCNs, etc.
298
  static std::string getSpelling(const Token &Tok,
299
                                 const SourceManager &SourceMgr,
300
                                 const LangOptions &LangOpts,
301
                                 bool *Invalid = nullptr);
302
303
  /// getSpelling - This method is used to get the spelling of the
304
  /// token at the given source location.  If, as is usually true, it
305
  /// is not necessary to copy any data, then the returned string may
306
  /// not point into the provided buffer.
307
  ///
308
  /// This method lexes at the expansion depth of the given
309
  /// location and does not jump to the expansion or spelling
310
  /// location.
311
  static StringRef getSpelling(SourceLocation loc,
312
                               SmallVectorImpl<char> &buffer,
313
                               const SourceManager &SourceMgr,
314
                               const LangOptions &LangOpts,
315
                               bool *invalid = nullptr);
316
317
  /// MeasureTokenLength - Relex the token at the specified location and return
318
  /// its length in bytes in the input file.  If the token needs cleaning (e.g.
319
  /// includes a trigraph or an escaped newline) then this count includes bytes
320
  /// that are part of that.
321
  static unsigned MeasureTokenLength(SourceLocation Loc,
322
                                     const SourceManager &SM,
323
                                     const LangOptions &LangOpts);
324
325
  /// Relex the token at the specified location.
326
  /// \returns true if there was a failure, false on success.
327
  static bool getRawToken(SourceLocation Loc, Token &Result,
328
                          const SourceManager &SM,
329
                          const LangOptions &LangOpts,
330
                          bool IgnoreWhiteSpace = false);
331
332
  /// Given a location any where in a source buffer, find the location
333
  /// that corresponds to the beginning of the token in which the original
334
  /// source location lands.
335
  static SourceLocation GetBeginningOfToken(SourceLocation Loc,
336
                                            const SourceManager &SM,
337
                                            const LangOptions &LangOpts);
338
339
  /// Get the physical length (including trigraphs and escaped newlines) of the
340
  /// first \p Characters characters of the token starting at TokStart.
341
  static unsigned getTokenPrefixLength(SourceLocation TokStart,
342
                                       unsigned Characters,
343
                                       const SourceManager &SM,
344
                                       const LangOptions &LangOpts);
345
346
  /// AdvanceToTokenCharacter - If the current SourceLocation specifies a
347
  /// location at the start of a token, return a new location that specifies a
348
  /// character within the token.  This handles trigraphs and escaped newlines.
349
  static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
350
                                                unsigned Characters,
351
                                                const SourceManager &SM,
352
189k
                                                const LangOptions &LangOpts) {
353
189k
    return TokStart.getLocWithOffset(
354
189k
        getTokenPrefixLength(TokStart, Characters, SM, LangOpts));
355
189k
  }
356
357
  /// Computes the source location just past the end of the
358
  /// token at this source location.
359
  ///
360
  /// This routine can be used to produce a source location that
361
  /// points just past the end of the token referenced by \p Loc, and
362
  /// is generally used when a diagnostic needs to point just after a
363
  /// token where it expected something different that it received. If
364
  /// the returned source location would not be meaningful (e.g., if
365
  /// it points into a macro), this routine returns an invalid
366
  /// source location.
367
  ///
368
  /// \param Offset an offset from the end of the token, where the source
369
  /// location should refer to. The default offset (0) produces a source
370
  /// location pointing just past the end of the token; an offset of 1 produces
371
  /// a source location pointing to the last character in the token, etc.
372
  static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
373
                                            const SourceManager &SM,
374
                                            const LangOptions &LangOpts);
375
376
  /// Given a token range, produce a corresponding CharSourceRange that
377
  /// is not a token range. This allows the source range to be used by
378
  /// components that don't have access to the lexer and thus can't find the
379
  /// end of the range for themselves.
380
  static CharSourceRange getAsCharRange(SourceRange Range,
381
                                        const SourceManager &SM,
382
5.80k
                                        const LangOptions &LangOpts) {
383
5.80k
    SourceLocation End = getLocForEndOfToken(Range.getEnd(), 0, SM, LangOpts);
384
5.80k
    return End.isInvalid() ? 
CharSourceRange()0
385
5.80k
                           : CharSourceRange::getCharRange(
386
5.80k
                                 Range.getBegin(), End.getLocWithOffset(-1));
387
5.80k
  }
388
  static CharSourceRange getAsCharRange(CharSourceRange Range,
389
                                        const SourceManager &SM,
390
1.77k
                                        const LangOptions &LangOpts) {
391
1.77k
    return Range.isTokenRange()
392
1.77k
               ? getAsCharRange(Range.getAsRange(), SM, LangOpts)
393
1.77k
               : 
Range0
;
394
1.77k
  }
395
396
  /// Returns true if the given MacroID location points at the first
397
  /// token of the macro expansion.
398
  ///
399
  /// \param MacroBegin If non-null and function returns true, it is set to
400
  /// begin location of the macro.
401
  static bool isAtStartOfMacroExpansion(SourceLocation loc,
402
                                        const SourceManager &SM,
403
                                        const LangOptions &LangOpts,
404
                                        SourceLocation *MacroBegin = nullptr);
405
406
  /// Returns true if the given MacroID location points at the last
407
  /// token of the macro expansion.
408
  ///
409
  /// \param MacroEnd If non-null and function returns true, it is set to
410
  /// end location of the macro.
411
  static bool isAtEndOfMacroExpansion(SourceLocation loc,
412
                                      const SourceManager &SM,
413
                                      const LangOptions &LangOpts,
414
                                      SourceLocation *MacroEnd = nullptr);
415
416
  /// Accepts a range and returns a character range with file locations.
417
  ///
418
  /// Returns a null range if a part of the range resides inside a macro
419
  /// expansion or the range does not reside on the same FileID.
420
  ///
421
  /// This function is trying to deal with macros and return a range based on
422
  /// file locations. The cases where it can successfully handle macros are:
423
  ///
424
  /// -begin or end range lies at the start or end of a macro expansion, in
425
  ///  which case the location will be set to the expansion point, e.g:
426
  ///    \#define M 1 2
427
  ///    a M
428
  /// If you have a range [a, 2] (where 2 came from the macro), the function
429
  /// will return a range for "a M"
430
  /// if you have range [a, 1], the function will fail because the range
431
  /// overlaps with only a part of the macro
432
  ///
433
  /// -The macro is a function macro and the range can be mapped to the macro
434
  ///  arguments, e.g:
435
  ///    \#define M 1 2
436
  ///    \#define FM(x) x
437
  ///    FM(a b M)
438
  /// if you have range [b, 2], the function will return the file range "b M"
439
  /// inside the macro arguments.
440
  /// if you have range [a, 2], the function will return the file range
441
  /// "FM(a b M)" since the range includes all of the macro expansion.
442
  static CharSourceRange makeFileCharRange(CharSourceRange Range,
443
                                           const SourceManager &SM,
444
                                           const LangOptions &LangOpts);
445
446
  /// Returns a string for the source that the range encompasses.
447
  static StringRef getSourceText(CharSourceRange Range,
448
                                 const SourceManager &SM,
449
                                 const LangOptions &LangOpts,
450
                                 bool *Invalid = nullptr);
451
452
  /// Retrieve the name of the immediate macro expansion.
453
  ///
454
  /// This routine starts from a source location, and finds the name of the macro
455
  /// responsible for its immediate expansion. It looks through any intervening
456
  /// macro argument expansions to compute this. It returns a StringRef which
457
  /// refers to the SourceManager-owned buffer of the source where that macro
458
  /// name is spelled. Thus, the result shouldn't out-live that SourceManager.
459
  static StringRef getImmediateMacroName(SourceLocation Loc,
460
                                         const SourceManager &SM,
461
                                         const LangOptions &LangOpts);
462
463
  /// Retrieve the name of the immediate macro expansion.
464
  ///
465
  /// This routine starts from a source location, and finds the name of the
466
  /// macro responsible for its immediate expansion. It looks through any
467
  /// intervening macro argument expansions to compute this. It returns a
468
  /// StringRef which refers to the SourceManager-owned buffer of the source
469
  /// where that macro name is spelled. Thus, the result shouldn't out-live
470
  /// that SourceManager.
471
  ///
472
  /// This differs from Lexer::getImmediateMacroName in that any macro argument
473
  /// location will result in the topmost function macro that accepted it.
474
  /// e.g.
475
  /// \code
476
  ///   MAC1( MAC2(foo) )
477
  /// \endcode
478
  /// for location of 'foo' token, this function will return "MAC1" while
479
  /// Lexer::getImmediateMacroName will return "MAC2".
480
  static StringRef getImmediateMacroNameForDiagnostics(
481
      SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts);
482
483
  /// Compute the preamble of the given file.
484
  ///
485
  /// The preamble of a file contains the initial comments, include directives,
486
  /// and other preprocessor directives that occur before the code in this
487
  /// particular file actually begins. The preamble of the main source file is
488
  /// a potential prefix header.
489
  ///
490
  /// \param Buffer The memory buffer containing the file's contents.
491
  ///
492
  /// \param MaxLines If non-zero, restrict the length of the preamble
493
  /// to fewer than this number of lines.
494
  ///
495
  /// \returns The offset into the file where the preamble ends and the rest
496
  /// of the file begins along with a boolean value indicating whether
497
  /// the preamble ends at the beginning of a new line.
498
  static PreambleBounds ComputePreamble(StringRef Buffer,
499
                                        const LangOptions &LangOpts,
500
                                        unsigned MaxLines = 0);
501
502
  /// Finds the token that comes right after the given location.
503
  ///
504
  /// Returns the next token, or none if the location is inside a macro.
505
  static Optional<Token> findNextToken(SourceLocation Loc,
506
                                       const SourceManager &SM,
507
                                       const LangOptions &LangOpts);
508
509
  /// Checks that the given token is the first token that occurs after
510
  /// the given location (this excludes comments and whitespace). Returns the
511
  /// location immediately after the specified token. If the token is not found
512
  /// or the location is inside a macro, the returned source location will be
513
  /// invalid.
514
  static SourceLocation findLocationAfterToken(SourceLocation loc,
515
                                         tok::TokenKind TKind,
516
                                         const SourceManager &SM,
517
                                         const LangOptions &LangOpts,
518
                                         bool SkipTrailingWhitespaceAndNewLine);
519
520
  /// Returns true if the given character could appear in an identifier.
521
  static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts);
522
523
  /// Checks whether new line pointed by Str is preceded by escape
524
  /// sequence.
525
  static bool isNewLineEscaped(const char *BufferStart, const char *Str);
526
527
  /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
528
  /// emit a warning.
529
  static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
530
288k
                                          const LangOptions &LangOpts) {
531
288k
    // If this is not a trigraph and not a UCN or escaped newline, return
532
288k
    // quickly.
533
288k
    if (isObviouslySimpleCharacter(Ptr[0])) {
534
271k
      Size = 1;
535
271k
      return *Ptr;
536
271k
    }
537
17.5k
538
17.5k
    Size = 0;
539
17.5k
    return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
540
17.5k
  }
541
542
  /// Returns the leading whitespace for line that corresponds to the given
543
  /// location \p Loc.
544
  static StringRef getIndentationForLine(SourceLocation Loc,
545
                                         const SourceManager &SM);
546
547
private:
548
  //===--------------------------------------------------------------------===//
549
  // Internal implementation interfaces.
550
551
  /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
552
  /// by Lex.
553
  ///
554
  bool LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine);
555
556
  bool CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr);
557
558
  /// Given that a token begins with the Unicode character \p C, figure out
559
  /// what kind of token it is and dispatch to the appropriate lexing helper
560
  /// function.
561
  bool LexUnicode(Token &Result, uint32_t C, const char *CurPtr);
562
563
  /// FormTokenWithChars - When we lex a token, we have identified a span
564
  /// starting at BufferPtr, going to TokEnd that forms the token.  This method
565
  /// takes that range and assigns it to the token as its location and size.  In
566
  /// addition, since tokens cannot overlap, this also updates BufferPtr to be
567
  /// TokEnd.
568
  void FormTokenWithChars(Token &Result, const char *TokEnd,
569
1.13G
                          tok::TokenKind Kind) {
570
1.13G
    unsigned TokLen = TokEnd-BufferPtr;
571
1.13G
    Result.setLength(TokLen);
572
1.13G
    Result.setLocation(getSourceLocation(BufferPtr, TokLen));
573
1.13G
    Result.setKind(Kind);
574
1.13G
    BufferPtr = TokEnd;
575
1.13G
  }
576
577
  /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
578
  /// tok::l_paren token, 0 if it is something else and 2 if there are no more
579
  /// tokens in the buffer controlled by this lexer.
580
  unsigned isNextPPTokenLParen();
581
582
  //===--------------------------------------------------------------------===//
583
  // Lexer character reading interfaces.
584
585
  // This lexer is built on two interfaces for reading characters, both of which
586
  // automatically provide phase 1/2 translation.  getAndAdvanceChar is used
587
  // when we know that we will be reading a character from the input buffer and
588
  // that this character will be part of the result token. This occurs in (f.e.)
589
  // string processing, because we know we need to read until we find the
590
  // closing '"' character.
591
  //
592
  // The second interface is the combination of getCharAndSize with
593
  // ConsumeChar.  getCharAndSize reads a phase 1/2 translated character,
594
  // returning it and its size.  If the lexer decides that this character is
595
  // part of the current token, it calls ConsumeChar on it.  This two stage
596
  // approach allows us to emit diagnostics for characters (e.g. warnings about
597
  // trigraphs), knowing that they only are emitted if the character is
598
  // consumed.
599
600
  /// isObviouslySimpleCharacter - Return true if the specified character is
601
  /// obviously the same in translation phase 1 and translation phase 3.  This
602
  /// can return false for characters that end up being the same, but it will
603
  /// never return true for something that needs to be mapped.
604
1.70G
  static bool isObviouslySimpleCharacter(char C) {
605
1.70G
    return C != '?' && 
C != '\\'1.70G
;
606
1.70G
  }
607
608
  /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
609
  /// advance over it, and return it.  This is tricky in several cases.  Here we
610
  /// just handle the trivial case and fall-back to the non-inlined
611
  /// getCharAndSizeSlow method to handle the hard case.
612
1.34G
  inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
613
1.34G
    // If this is not a trigraph and not a UCN or escaped newline, return
614
1.34G
    // quickly.
615
1.34G
    if (isObviouslySimpleCharacter(Ptr[0])) 
return *Ptr++1.34G
;
616
3.82M
617
3.82M
    unsigned Size = 0;
618
3.82M
    char C = getCharAndSizeSlow(Ptr, Size, &Tok);
619
3.82M
    Ptr += Size;
620
3.82M
    return C;
621
3.82M
  }
622
623
  /// ConsumeChar - When a character (identified by getCharAndSize) is consumed
624
  /// and added to a given token, check to see if there are diagnostics that
625
  /// need to be emitted or flags that need to be set on the token.  If so, do
626
  /// it.
627
116M
  const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
628
116M
    // Normal case, we consumed exactly one token.  Just return it.
629
116M
    if (Size == 1)
630
116M
      return Ptr+Size;
631
85
632
85
    // Otherwise, re-lex the character with a current token, allowing
633
85
    // diagnostics to be emitted and flags to be set.
634
85
    Size = 0;
635
85
    getCharAndSizeSlow(Ptr, Size, &Tok);
636
85
    return Ptr+Size;
637
85
  }
638
639
  /// getCharAndSize - Peek a single 'character' from the specified buffer,
640
  /// get its size, and return it.  This is tricky in several cases.  Here we
641
  /// just handle the trivial case and fall-back to the non-inlined
642
  /// getCharAndSizeSlow method to handle the hard case.
643
355M
  inline char getCharAndSize(const char *Ptr, unsigned &Size) {
644
355M
    // If this is not a trigraph and not a UCN or escaped newline, return
645
355M
    // quickly.
646
355M
    if (isObviouslySimpleCharacter(Ptr[0])) {
647
355M
      Size = 1;
648
355M
      return *Ptr;
649
355M
    }
650
7.11k
651
7.11k
    Size = 0;
652
7.11k
    return getCharAndSizeSlow(Ptr, Size);
653
7.11k
  }
654
655
  /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
656
  /// method.
657
  char getCharAndSizeSlow(const char *Ptr, unsigned &Size,
658
                          Token *Tok = nullptr);
659
660
  /// getEscapedNewLineSize - Return the size of the specified escaped newline,
661
  /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
662
  /// to this function.
663
  static unsigned getEscapedNewLineSize(const char *P);
664
665
  /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
666
  /// them), skip over them and return the first non-escaped-newline found,
667
  /// otherwise return P.
668
  static const char *SkipEscapedNewLines(const char *P);
669
670
  /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
671
  /// diagnostic.
672
  static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
673
                                       const LangOptions &LangOpts);
674
675
  //===--------------------------------------------------------------------===//
676
  // Other lexer functions.
677
678
  void SetByteOffset(unsigned Offset, bool StartOfLine);
679
680
  void PropagateLineStartLeadingSpaceInfo(Token &Result);
681
682
  const char *LexUDSuffix(Token &Result, const char *CurPtr,
683
                          bool IsStringLiteral);
684
685
  // Helper functions to lex the remainder of a token of the specific type.
686
  bool LexIdentifier         (Token &Result, const char *CurPtr);
687
  bool LexNumericConstant    (Token &Result, const char *CurPtr);
688
  bool LexStringLiteral      (Token &Result, const char *CurPtr,
689
                              tok::TokenKind Kind);
690
  bool LexRawStringLiteral   (Token &Result, const char *CurPtr,
691
                              tok::TokenKind Kind);
692
  bool LexAngledStringLiteral(Token &Result, const char *CurPtr);
693
  bool LexCharConstant       (Token &Result, const char *CurPtr,
694
                              tok::TokenKind Kind);
695
  bool LexEndOfFile          (Token &Result, const char *CurPtr);
696
  bool SkipWhitespace        (Token &Result, const char *CurPtr,
697
                              bool &TokAtPhysicalStartOfLine);
698
  bool SkipLineComment       (Token &Result, const char *CurPtr,
699
                              bool &TokAtPhysicalStartOfLine);
700
  bool SkipBlockComment      (Token &Result, const char *CurPtr,
701
                              bool &TokAtPhysicalStartOfLine);
702
  bool SaveLineComment       (Token &Result, const char *CurPtr);
703
704
  bool IsStartOfConflictMarker(const char *CurPtr);
705
  bool HandleEndOfConflictMarker(const char *CurPtr);
706
707
  bool lexEditorPlaceholder(Token &Result, const char *CurPtr);
708
709
  bool isCodeCompletionPoint(const char *CurPtr) const;
710
48
  void cutOffLexing() { BufferPtr = BufferEnd; }
711
712
  bool isHexaLiteral(const char *Start, const LangOptions &LangOpts);
713
714
715
  /// Read a universal character name.
716
  ///
717
  /// \param CurPtr The position in the source buffer after the initial '\'.
718
  ///               If the UCN is syntactically well-formed (but not necessarily
719
  ///               valid), this parameter will be updated to point to the
720
  ///               character after the UCN.
721
  /// \param SlashLoc The position in the source buffer of the '\'.
722
  /// \param Tok The token being formed. Pass \c nullptr to suppress diagnostics
723
  ///            and handle token formation in the caller.
724
  ///
725
  /// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is
726
  ///         invalid.
727
  uint32_t tryReadUCN(const char *&CurPtr, const char *SlashLoc, Token *Tok);
728
729
  /// Try to consume a UCN as part of an identifier at the current
730
  /// location.
731
  /// \param CurPtr Initially points to the range of characters in the source
732
  ///               buffer containing the '\'. Updated to point past the end of
733
  ///               the UCN on success.
734
  /// \param Size The number of characters occupied by the '\' (including
735
  ///             trigraphs and escaped newlines).
736
  /// \param Result The token being produced. Marked as containing a UCN on
737
  ///               success.
738
  /// \return \c true if a UCN was lexed and it produced an acceptable
739
  ///         identifier character, \c false otherwise.
740
  bool tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
741
                               Token &Result);
742
743
  /// Try to consume an identifier character encoded in UTF-8.
744
  /// \param CurPtr Points to the start of the (potential) UTF-8 code unit
745
  ///        sequence. On success, updated to point past the end of it.
746
  /// \return \c true if a UTF-8 sequence mapping to an acceptable identifier
747
  ///         character was lexed, \c false otherwise.
748
  bool tryConsumeIdentifierUTF8Char(const char *&CurPtr);
749
};
750
751
} // namespace clang
752
753
#endif // LLVM_CLANG_LEX_LEXER_H