clang 23.0.0git
LiteralSupport.h
Go to the documentation of this file.
1//===--- LiteralSupport.h ---------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the NumericLiteralParser, CharLiteralParser, and
10// StringLiteralParser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_LITERALSUPPORT_H
15#define LLVM_CLANG_LEX_LITERALSUPPORT_H
16
18#include "clang/Basic/LLVM.h"
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Support/DataTypes.h"
26#include "llvm/Support/TextEncoding.h"
27
28namespace clang {
29
31class Preprocessor;
32class Token;
33class SourceLocation;
34class TargetInfo;
35class SourceManager;
36class LangOptions;
37
38/// Copy characters from Input to Buf, expanding any UCNs.
39void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input);
40
41/// Return true if the token corresponds to a function local predefined macro,
42/// which expands to a string literal, that can be concatenated with other
43/// string literals (only in Microsoft mode).
45
46/// Return true if the token is a string literal, or a function local
47/// predefined macro, which expands to a string literal.
48bool tokenIsLikeStringLiteral(const Token &Tok, const LangOptions &LO);
49
50/// NumericLiteralParser - This performs strict semantic analysis of the content
51/// of a ppnumber, classifying it as either integer, floating, or erroneous,
52/// determines the radix of the value and can convert it to a useful value.
54 const SourceManager &SM;
55 const LangOptions &LangOpts;
56 DiagnosticsEngine &Diags;
57
58 const char *const ThisTokBegin;
59 const char *const ThisTokEnd;
60 const char *DigitsBegin, *SuffixBegin; // markers
61 const char *s; // cursor
62
63 unsigned radix;
64
65 bool saw_exponent, saw_period, saw_ud_suffix, saw_fixed_point_suffix;
66
67 SmallString<32> UDSuffixBuf;
68
69public:
70 NumericLiteralParser(StringRef TokSpelling, SourceLocation TokLoc,
71 const SourceManager &SM, const LangOptions &LangOpts,
72 const TargetInfo &Target, DiagnosticsEngine &Diags);
73 bool hadError : 1;
74 bool isUnsigned : 1;
75 bool isLong : 1; // This is *not* set for long long.
76 bool isLongLong : 1;
77 bool isSizeT : 1; // 1z, 1uz (C++23)
78 bool isHalf : 1; // 1.0h
79 bool isFloat : 1; // 1.0f
80 bool isImaginary : 1; // 1.0i
81 bool isFloat16 : 1; // 1.0f16
82 bool isFloat128 : 1; // 1.0q
83 bool isFract : 1; // 1.0hr/r/lr/uhr/ur/ulr
84 bool isAccum : 1; // 1.0hk/k/lk/uhk/uk/ulk
85 bool isBitInt : 1; // 1wb, 1uwb (C23) or 1__wb, 1__uwb (Clang extension in C++
86 // mode)
87 uint8_t MicrosoftInteger; // Microsoft suffix extension i8, i16, i32, i64, or
88 // i128.
89
90 bool isFixedPointLiteral() const {
91 return (saw_period || saw_exponent) && saw_fixed_point_suffix;
92 }
93
94 bool isIntegerLiteral() const {
95 return !saw_period && !saw_exponent && !isFixedPointLiteral();
96 }
97 bool isFloatingLiteral() const {
98 return (saw_period || saw_exponent) && !isFixedPointLiteral();
99 }
100
101 bool hasUDSuffix() const {
102 return saw_ud_suffix;
103 }
104 StringRef getUDSuffix() const {
105 assert(saw_ud_suffix);
106 return UDSuffixBuf;
107 }
108 unsigned getUDSuffixOffset() const {
109 assert(saw_ud_suffix);
110 return SuffixBegin - ThisTokBegin;
111 }
112
113 static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix);
114
115 unsigned getRadix() const { return radix; }
116
117 /// GetIntegerValue - Convert this numeric literal value to an APInt that
118 /// matches Val's input width. If there is an overflow (i.e., if the unsigned
119 /// value read is larger than the APInt's bits will hold), set Val to the low
120 /// bits of the result and return true. Otherwise, return false.
121 bool GetIntegerValue(llvm::APInt &Val);
122
123 /// Convert this numeric literal to a floating value, using the specified
124 /// APFloat fltSemantics (specifying float, double, etc) and rounding mode.
125 llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result,
126 llvm::RoundingMode RM);
127
128 /// GetFixedPointValue - Convert this numeric literal value into a
129 /// scaled integer that represents this value. Returns true if an overflow
130 /// occurred when calculating the integral part of the scaled integer or
131 /// calculating the digit sequence of the exponent.
132 bool GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale);
133
134 /// Get the digits that comprise the literal. This excludes any prefix or
135 /// suffix associated with the literal.
136 StringRef getLiteralDigits() const {
137 assert(!hadError && "cannot reliably get the literal digits with an error");
138 return StringRef(DigitsBegin, SuffixBegin - DigitsBegin);
139 }
140
141private:
142
143 void ParseNumberStartingWithZero(SourceLocation TokLoc);
144 void ParseDecimalOrOctalCommon(SourceLocation TokLoc);
145
146 static bool isDigitSeparator(char C) { return C == '\''; }
147
148 /// Determine whether the sequence of characters [Start, End) contains
149 /// any real digits (not digit separators).
150 bool containsDigits(const char *Start, const char *End) {
151 return Start != End && (Start + 1 != End || !isDigitSeparator(Start[0]));
152 }
153
154 enum CheckSeparatorKind { CSK_BeforeDigits, CSK_AfterDigits };
155
156 /// Ensure that we don't have a digit separator here.
157 void checkSeparator(SourceLocation TokLoc, const char *Pos,
158 CheckSeparatorKind IsAfterDigits);
159
160 /// SkipHexDigits - Read and skip over any hex digits, up to End.
161 /// Return a pointer to the first non-hex digit or End.
162 const char *SkipHexDigits(const char *ptr) {
163 while (ptr != ThisTokEnd && (isHexDigit(*ptr) || isDigitSeparator(*ptr)))
164 ptr++;
165 return ptr;
166 }
167
168 /// SkipOctalDigits - Read and skip over any octal digits, up to End.
169 /// Return a pointer to the first non-hex digit or End.
170 const char *SkipOctalDigits(const char *ptr) {
171 while (ptr != ThisTokEnd &&
172 ((*ptr >= '0' && *ptr <= '7') || isDigitSeparator(*ptr)))
173 ptr++;
174 return ptr;
175 }
176
177 /// SkipDigits - Read and skip over any digits, up to End.
178 /// Return a pointer to the first non-hex digit or End.
179 const char *SkipDigits(const char *ptr) {
180 while (ptr != ThisTokEnd && (isDigit(*ptr) || isDigitSeparator(*ptr)))
181 ptr++;
182 return ptr;
183 }
184
185 /// SkipBinaryDigits - Read and skip over any binary digits, up to End.
186 /// Return a pointer to the first non-binary digit or End.
187 const char *SkipBinaryDigits(const char *ptr) {
188 while (ptr != ThisTokEnd &&
189 (*ptr == '0' || *ptr == '1' || isDigitSeparator(*ptr)))
190 ptr++;
191 return ptr;
192 }
193
194};
195
196/// CharLiteralParser - Perform interpretation and semantic analysis of a
197/// character literal.
199 uint64_t Value;
200 tok::TokenKind Kind;
201 bool IsMultiChar;
202 bool HadError;
203 SmallString<32> UDSuffixBuf;
204 unsigned UDSuffixOffset;
205public:
206 CharLiteralParser(const char *begin, const char *end,
209
210 bool hadError() const { return HadError; }
211 bool isOrdinary() const { return Kind == tok::char_constant; }
212 bool isWide() const { return Kind == tok::wide_char_constant; }
213 bool isUTF8() const { return Kind == tok::utf8_char_constant; }
214 bool isUTF16() const { return Kind == tok::utf16_char_constant; }
215 bool isUTF32() const { return Kind == tok::utf32_char_constant; }
216 bool isMultiChar() const { return IsMultiChar; }
217 uint64_t getValue() const { return Value; }
218 StringRef getUDSuffix() const { return UDSuffixBuf; }
219 unsigned getUDSuffixOffset() const {
220 assert(!UDSuffixBuf.empty() && "no ud-suffix");
221 return UDSuffixOffset;
222 }
223};
224
229
230/// StringLiteralParser - This decodes string escape characters and performs
231/// wide string analysis and Translation Phase #6 (concatenation of string
232/// literals) (C99 5.1.1.2p1).
234 const SourceManager &SM;
235 const LangOptions &Features;
236 const TargetInfo &Target;
237 DiagnosticsEngine *Diags;
238 TextEncoding *TE;
239
240 unsigned MaxTokenLength;
241 unsigned SizeBound;
242 unsigned CharByteWidth;
243 tok::TokenKind Kind;
244 SmallString<512> ResultBuf;
245 char *ResultPtr; // cursor
246 SmallString<32> UDSuffixBuf;
247 unsigned UDSuffixToken;
248 unsigned UDSuffixOffset;
249 StringLiteralEvalMethod EvalMethod;
250
251public:
253 ArrayRef<Token> StringToks, Preprocessor &PP,
257 const LangOptions &features, const TargetInfo &target,
258 DiagnosticsEngine *diags = nullptr)
259 : SM(sm), Features(features), Target(target), Diags(diags), TE(nullptr),
260 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
261 ResultPtr(ResultBuf.data()),
263 Pascal(false) {
264 init(StringToks, CA_NoConversion);
265 }
266
268 bool Pascal;
269
270 StringRef GetString() const {
271 return StringRef(ResultBuf.data(), GetStringLength());
272 }
273 unsigned GetStringLength() const { return ResultPtr-ResultBuf.data(); }
274
275 unsigned GetNumStringChars() const {
276 return GetStringLength() / CharByteWidth;
277 }
278 /// getOffsetOfStringByte - This function returns the offset of the
279 /// specified byte of the string data represented by Token. This handles
280 /// advancing over escape sequences in the string.
281 ///
282 /// If the Diagnostics pointer is non-null, then this will do semantic
283 /// checking of the string literal and emit errors and warnings.
284 unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) const;
285
286 bool isOrdinary() const { return Kind == tok::string_literal; }
287 bool isWide() const { return Kind == tok::wide_string_literal; }
288 bool isUTF8() const { return Kind == tok::utf8_string_literal; }
289 bool isUTF16() const { return Kind == tok::utf16_string_literal; }
290 bool isUTF32() const { return Kind == tok::utf32_string_literal; }
291 bool isPascal() const { return Pascal; }
292 bool isUnevaluated() const {
293 return EvalMethod == StringLiteralEvalMethod::Unevaluated;
294 }
295
296 StringRef getUDSuffix() const { return UDSuffixBuf; }
297
298 /// Get the index of a token containing a ud-suffix.
299 unsigned getUDSuffixToken() const {
300 assert(!UDSuffixBuf.empty() && "no ud-suffix");
301 return UDSuffixToken;
302 }
303 /// Get the spelling offset of the first byte of the ud-suffix.
304 unsigned getUDSuffixOffset() const {
305 assert(!UDSuffixBuf.empty() && "no ud-suffix");
306 return UDSuffixOffset;
307 }
308
309 static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix);
310
311private:
312 void init(ArrayRef<Token> StringToks, ConversionAction Action);
313 bool CopyStringFragment(const Token &Tok, const char *TokBegin,
314 StringRef Fragment,
315 llvm::TextEncodingConverter *Converter);
316 void DiagnoseLexingError(SourceLocation Loc);
317};
318
319} // end namespace clang
320
321#endif
Token Tok
The Token.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the clang::TokenKind enum and support functions.
unsigned getUDSuffixOffset() const
StringRef getUDSuffix() const
uint64_t getValue() const
CharLiteralParser(const char *begin, const char *end, SourceLocation Loc, Preprocessor &PP, tok::TokenKind kind)
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
NumericLiteralParser(StringRef TokSpelling, SourceLocation TokLoc, const SourceManager &SM, const LangOptions &LangOpts, const TargetInfo &Target, DiagnosticsEngine &Diags)
integer-constant: [C99 6.4.4.1] decimal-constant integer-suffix octal-constant integer-suffix hexadec...
StringRef getUDSuffix() const
llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result, llvm::RoundingMode RM)
Convert this numeric literal to a floating value, using the specified APFloat fltSemantics (specifyin...
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
bool GetIntegerValue(llvm::APInt &Val)
GetIntegerValue - Convert this numeric literal value to an APInt that matches Val's input width.
unsigned getUDSuffixOffset() const
StringRef getLiteralDigits() const
Get the digits that comprise the literal.
bool GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale)
GetFixedPointValue - Convert this numeric literal value into a scaled integer that represents this va...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
unsigned getUDSuffixToken() const
Get the index of a token containing a ud-suffix.
unsigned getUDSuffixOffset() const
Get the spelling offset of the first byte of the ud-suffix.
unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) const
getOffsetOfStringByte - This function returns the offset of the specified byte of the string data rep...
StringRef getUDSuffix() const
StringLiteralParser(ArrayRef< Token > StringToks, Preprocessor &PP, StringLiteralEvalMethod StringMethod=StringLiteralEvalMethod::Evaluated, ConversionAction Action=CA_NoConversion)
unsigned GetStringLength() const
StringLiteralParser(ArrayRef< Token > StringToks, const SourceManager &sm, const LangOptions &features, const TargetInfo &target, DiagnosticsEngine *diags=nullptr)
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
unsigned GetNumStringChars() const
StringRef GetString() const
Exposes information about the current target.
Definition TargetInfo.h:227
Token - This structure provides full information about a lexed token.
Definition Token.h:36
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:27
The JSON file list parser is used to communicate input to InstallAPI.
void expandUCNs(SmallVectorImpl< char > &Buf, StringRef Input)
Copy characters from Input to Buf, expanding any UCNs.
bool tokenIsLikeStringLiteral(const Token &Tok, const LangOptions &LO)
Return true if the token is a string literal, or a function local predefined macro,...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:905
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition CharInfo.h:114
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
Definition CharInfo.h:144
ConversionAction
@ CA_NoConversion
StringLiteralEvalMethod
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
#define false
Definition stdbool.h:26